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