blob: 55939d1738fbd9521bf1e4f7e63a558254b03064 [file] [log] [blame]
Josh Gaoeb9b9252015-11-03 18:46:02 -08001/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef _GNU_SOURCE
18 #define _GNU_SOURCE 1
19#endif
20
21#include <string.h>
22
23#if defined(basename)
24 #error basename should not be defined at this point
25#endif
26
27static const char* gnu_basename(const char* in) {
28 return basename(in);
29}
30
31#include <libgen.h>
32
33#if !defined(basename)
34 #error basename should be defined at this point
35#endif
36
37static char* posix_basename(char* in) {
38 return basename(in);
39}
40
41#include <errno.h>
42#include <gtest/gtest.h>
43
44static void __TestGnuBasename(const char* in, const char* expected_out, int line) {
45 const char* out = gnu_basename(in);
46 ASSERT_STREQ(expected_out, out) << "(" << line << "): " << in << std::endl;
47 ASSERT_EQ(0, errno) << "(" << line << "): " << in << std::endl;
48}
49
50static void __TestPosixBasename(const char* in, const char* expected_out, int line) {
51 char* writable_in = (in != NULL) ? strdup(in) : NULL;
52 errno = 0;
53 const char* out = posix_basename(&writable_in[0]);
54 ASSERT_STREQ(expected_out, out) << "(" << line << "): " << in << std::endl;
55 ASSERT_EQ(0, errno) << "(" << line << "): " << in << std::endl;
56 free(writable_in);
57}
58
59#define TestGnuBasename(in, expected) __TestGnuBasename(in, expected, __LINE__)
60#define TestPosixBasename(in, expected) __TestPosixBasename(in, expected, __LINE__)
61
62TEST(libgen_basename, gnu_basename) {
63 // GNU's basename doesn't accept NULL
64 // TestGnuBasename(NULL, ".");
65 TestGnuBasename("", "");
66 TestGnuBasename("/usr/lib", "lib");
67 TestGnuBasename("/system/bin/sh/", "");
68 TestGnuBasename("/usr/", "");
69 TestGnuBasename("usr", "usr");
70 TestGnuBasename("/", "");
71 TestGnuBasename(".", ".");
72 TestGnuBasename("..", "..");
73 TestGnuBasename("///", "");
74 TestGnuBasename("//usr//lib//", "");
75}
76
77TEST(libgen_basename, posix_basename) {
78 TestPosixBasename(NULL, ".");
79 TestPosixBasename("", ".");
80 TestPosixBasename("/usr/lib", "lib");
81 TestPosixBasename("/system/bin/sh/", "sh");
82 TestPosixBasename("/usr/", "usr");
83 TestPosixBasename("usr", "usr");
84 TestPosixBasename("/", "/");
85 TestPosixBasename(".", ".");
86 TestPosixBasename("..", "..");
87 TestPosixBasename("///", "/");
88 TestPosixBasename("//usr//lib//", "lib");
89}