blob: 26ae23cf5b0495c8b5781eba5fbd960474bec184 [file] [log] [blame]
John Park33858a32018-09-28 23:05:48 -07001#include "aos/libc/dirname.h"
Brian Silvermanaf784862014-05-13 08:14:55 -07002
3#include <libgen.h>
Stephan Pleines4b02e7b2024-05-30 20:29:39 -07004#include <string.h>
Brian Silvermanaf784862014-05-13 08:14:55 -07005
6#include "gtest/gtest.h"
7
Stephan Pleinesf63bde82024-01-13 15:59:33 -08008namespace aos::libc::testing {
Brian Silvermanaf784862014-05-13 08:14:55 -07009
10// Tests the examples from the Linux man-pages release 3.44 dirname(3).
11TEST(DirnameTest, ManPageExamples) {
12 EXPECT_EQ("/usr", Dirname("/usr/lib"));
13 EXPECT_EQ("/", Dirname("/usr/"));
14 EXPECT_EQ(".", Dirname("usr"));
15 EXPECT_EQ("/", Dirname("/"));
16 EXPECT_EQ(".", Dirname("."));
17 EXPECT_EQ(".", Dirname(".."));
18}
19
20// Tests that it handles multiple '/'s in a row correctly.
21TEST(DirnameTest, MultipleSlashes) {
22 EXPECT_EQ("//usr", Dirname("//usr//lib"));
23 EXPECT_EQ("//usr/lib", Dirname("//usr/lib//bla"));
24 EXPECT_EQ("/", Dirname("//usr//"));
25 EXPECT_EQ(".", Dirname("usr//"));
26 EXPECT_EQ("/", Dirname("//"));
27 EXPECT_EQ(".", Dirname(".//"));
28 EXPECT_EQ(".", Dirname("..//"));
29}
30
31TEST(DirnameTest, WeirdInputs) {
32 EXPECT_EQ(".", Dirname(""));
33 EXPECT_EQ(".", Dirname("..."));
34}
35
36// Runs through a bunch of randomly constructed pathnames and makes sure it
37// gives the same result as dirname(3).
38TEST(DirnameTest, Random) {
39 static const char kTestBytes[] = "a0//.. ";
40 static const size_t kTestBytesSize = sizeof(kTestBytes) - 1;
41 static const size_t kTestPathSize = 6;
42
43 ::std::string test_string(kTestPathSize, '\0');
44 char test_path[kTestPathSize + 1];
45 for (size_t i0 = 0; i0 < kTestBytesSize; ++i0) {
46 test_string[0] = kTestBytes[i0];
47 for (size_t i1 = 0; i1 < kTestBytesSize; ++i1) {
48 // dirname(3) returns "//" in this case which is weird and our Dirname
49 // doesn't.
50 if (test_string[0] == '/' && kTestBytes[i1] == '/') continue;
51
52 test_string[1] = kTestBytes[i1];
53 for (size_t i2 = 0; i2 < kTestBytesSize; ++i2) {
54 test_string[2] = kTestBytes[i2];
55 for (size_t i3 = 0; i3 < kTestBytesSize; ++i3) {
56 test_string[3] = kTestBytes[i3];
57 for (size_t i4 = 0; i4 < kTestBytesSize; ++i4) {
58 test_string[4] = kTestBytes[i4];
59 for (size_t i5 = 0; i5 < kTestBytesSize; ++i5) {
60 test_string[5] = kTestBytes[i5];
61
62 memcpy(test_path, test_string.c_str(), kTestPathSize);
63 test_path[kTestPathSize] = '\0';
64
65 SCOPED_TRACE("path is '" + test_string + "'");
66 EXPECT_EQ(::std::string(dirname(test_path)),
67 Dirname(test_string));
68 }
69 }
70 }
71 }
72 }
73 }
74}
75
Stephan Pleinesf63bde82024-01-13 15:59:33 -080076} // namespace aos::libc::testing