1 //===-- Base class for libc unittests ---------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8
9 #ifndef LLVM_LIBC_TEST_UNITTEST_LIBCTEST_H
10 #define LLVM_LIBC_TEST_UNITTEST_LIBCTEST_H
11
12 // This is defined as a simple macro in test.h so that it exists for platforms
13 // that don't use our test infrastructure. It's defined as a proper function
14 // below.
15 #ifdef libc_make_test_file_path
16 #undef libc_make_test_file_path
17 #endif // libc_make_test_file_path
18
19 // This is defined as a macro here to avoid namespace issues.
20 #define libc_make_test_file_path(file_name) \
21 (LIBC_NAMESPACE::testing::libc_make_test_file_path_func(file_name))
22
23 // This file can only include headers from src/__support/ or test/UnitTest. No
24 // other headers should be included.
25
26 #include "PlatformDefs.h"
27
28 #include "src/__support/CPP/string.h"
29 #include "src/__support/CPP/string_view.h"
30 #include "src/__support/CPP/type_traits.h"
31 #include "src/__support/c_string.h"
32 #include "test/UnitTest/ExecuteFunction.h"
33 #include "test/UnitTest/TestLogger.h"
34
35 namespace LIBC_NAMESPACE {
36 namespace testing {
37
38 // Only the following conditions are supported. Notice that we do not have
39 // a TRUE or FALSE condition. That is because, C library functions do not
40 // return boolean values, but use integral return values to indicate true or
41 // false conditions. Hence, it is more appropriate to use the other comparison
42 // conditions for such cases.
43 enum class TestCond { EQ, NE, LT, LE, GT, GE };
44
45 struct MatcherBase {
~MatcherBaseMatcherBase46 virtual ~MatcherBase() {}
explainErrorMatcherBase47 virtual void explainError() { tlog << "unknown error\n"; }
48 // Override and return true to skip `explainError` step.
is_silentMatcherBase49 virtual bool is_silent() const { return false; }
50 };
51
52 template <typename T> struct Matcher : public MatcherBase {
53 bool match(const T &t);
54 };
55
56 namespace internal {
57
58 // A simple location object to allow consistent passing of __FILE__ and
59 // __LINE__.
60 struct Location {
LocationLocation61 Location(const char *file, int line) : file(file), line(line) {}
62 const char *file;
63 int line;
64 };
65
66 // Supports writing a failing Location to tlog.
67 TestLogger &operator<<(TestLogger &logger, Location Loc);
68
69 #define LIBC_TEST_LOC_() \
70 LIBC_NAMESPACE::testing::internal::Location(__FILE__, __LINE__)
71
72 // Object to forward custom logging after the EXPECT / ASSERT macros.
73 struct Message {
74 template <typename T> Message &operator<<(T value) {
75 tlog << value;
76 return *this;
77 }
78 };
79
80 // A trivial object to catch the Message, this enables custom logging and
81 // returning from the test function, see LIBC_TEST_SCAFFOLDING_ below.
82 struct Failure {
83 void operator=(Message msg) {}
84 };
85
86 struct RunContext {
87 enum class RunResult : bool { Pass, Fail };
88
statusRunContext89 RunResult status() const { return Status; }
90
markFailRunContext91 void markFail() { Status = RunResult::Fail; }
92
93 private:
94 RunResult Status = RunResult::Pass;
95 };
96
97 template <typename ValType>
98 bool test(RunContext *Ctx, TestCond Cond, ValType LHS, ValType RHS,
99 const char *LHSStr, const char *RHSStr, Location Loc);
100
101 } // namespace internal
102
103 struct TestOptions {
104 // If set, then just this one test from the suite will be run.
105 const char *TestFilter = nullptr;
106 // Should the test results print color codes to stdout?
107 bool PrintColor = true;
108 // Should the test results print timing only in milliseconds, as GTest does?
109 bool TimeInMs = false;
110 };
111
112 // NOTE: One should not create instances and call methods on them directly. One
113 // should use the macros TEST or TEST_F to write test cases.
114 class Test {
115 Test *Next = nullptr;
116 internal::RunContext *Ctx = nullptr;
117
setContext(internal::RunContext * C)118 void setContext(internal::RunContext *C) { Ctx = C; }
119 static int getNumTests();
120
121 public:
~Test()122 virtual ~Test() {}
SetUp()123 virtual void SetUp() {}
TearDown()124 virtual void TearDown() {}
125
126 static int runTests(const TestOptions &Options);
127
128 protected:
129 static void addTest(Test *T);
130
131 // We make use of a template function, with |LHS| and |RHS| as explicit
132 // parameters, for enhanced type checking. Other gtest like unittest
133 // frameworks have a similar function which takes a boolean argument
134 // instead of the explicit |LHS| and |RHS| arguments. This boolean argument
135 // is the result of the |Cond| operation on |LHS| and |RHS|. Though not bad,
136 // |Cond| on mismatched |LHS| and |RHS| types can potentially succeed because
137 // of type promotion.
138 template <
139 typename ValType,
140 cpp::enable_if_t<cpp::is_integral_v<ValType> || is_big_int_v<ValType> ||
141 cpp::is_fixed_point_v<ValType>,
142 int> = 0>
test(TestCond Cond,ValType LHS,ValType RHS,const char * LHSStr,const char * RHSStr,internal::Location Loc)143 bool test(TestCond Cond, ValType LHS, ValType RHS, const char *LHSStr,
144 const char *RHSStr, internal::Location Loc) {
145 return internal::test(Ctx, Cond, LHS, RHS, LHSStr, RHSStr, Loc);
146 }
147
148 template <typename ValType,
149 cpp::enable_if_t<cpp::is_enum_v<ValType>, int> = 0>
test(TestCond Cond,ValType LHS,ValType RHS,const char * LHSStr,const char * RHSStr,internal::Location Loc)150 bool test(TestCond Cond, ValType LHS, ValType RHS, const char *LHSStr,
151 const char *RHSStr, internal::Location Loc) {
152 return internal::test(Ctx, Cond, (long long)LHS, (long long)RHS, LHSStr,
153 RHSStr, Loc);
154 }
155
156 template <typename ValType,
157 cpp::enable_if_t<cpp::is_pointer_v<ValType>, ValType> = nullptr>
test(TestCond Cond,ValType LHS,ValType RHS,const char * LHSStr,const char * RHSStr,internal::Location Loc)158 bool test(TestCond Cond, ValType LHS, ValType RHS, const char *LHSStr,
159 const char *RHSStr, internal::Location Loc) {
160 return internal::test(Ctx, Cond, (unsigned long long)LHS,
161 (unsigned long long)RHS, LHSStr, RHSStr, Loc);
162 }
163
164 template <
165 typename ValType,
166 cpp::enable_if_t<
167 cpp::is_same_v<ValType, LIBC_NAMESPACE::cpp::string_view>, int> = 0>
test(TestCond Cond,ValType LHS,ValType RHS,const char * LHSStr,const char * RHSStr,internal::Location Loc)168 bool test(TestCond Cond, ValType LHS, ValType RHS, const char *LHSStr,
169 const char *RHSStr, internal::Location Loc) {
170 return internal::test(Ctx, Cond, LHS, RHS, LHSStr, RHSStr, Loc);
171 }
172
173 template <typename ValType,
174 cpp::enable_if_t<
175 cpp::is_same_v<ValType, LIBC_NAMESPACE::cpp::string>, int> = 0>
test(TestCond Cond,ValType LHS,ValType RHS,const char * LHSStr,const char * RHSStr,internal::Location Loc)176 bool test(TestCond Cond, ValType LHS, ValType RHS, const char *LHSStr,
177 const char *RHSStr, internal::Location Loc) {
178 return internal::test(Ctx, Cond, LHS, RHS, LHSStr, RHSStr, Loc);
179 }
180
181 bool testStrEq(const char *LHS, const char *RHS, const char *LHSStr,
182 const char *RHSStr, internal::Location Loc);
183
184 bool testStrNe(const char *LHS, const char *RHS, const char *LHSStr,
185 const char *RHSStr, internal::Location Loc);
186
187 bool testMatch(bool MatchResult, MatcherBase &Matcher, const char *LHSStr,
188 const char *RHSStr, internal::Location Loc);
189
190 template <typename MatcherT, typename ValType>
matchAndExplain(MatcherT && Matcher,ValType Value,const char * MatcherStr,const char * ValueStr,internal::Location Loc)191 bool matchAndExplain(MatcherT &&Matcher, ValType Value,
192 const char *MatcherStr, const char *ValueStr,
193 internal::Location Loc) {
194 return testMatch(Matcher.match(Value), Matcher, ValueStr, MatcherStr, Loc);
195 }
196
197 bool testProcessExits(testutils::FunctionCaller *Func, int ExitCode,
198 const char *LHSStr, const char *RHSStr,
199 internal::Location Loc);
200
201 bool testProcessKilled(testutils::FunctionCaller *Func, int Signal,
202 const char *LHSStr, const char *RHSStr,
203 internal::Location Loc);
204
createCallable(Func f)205 template <typename Func> testutils::FunctionCaller *createCallable(Func f) {
206 struct Callable : public testutils::FunctionCaller {
207 Func f;
208 Callable(Func f) : f(f) {}
209 void operator()() override { f(); }
210 };
211
212 return new Callable(f);
213 }
214
215 private:
216 virtual void Run() = 0;
217 virtual const char *getName() const = 0;
218
219 static Test *Start;
220 static Test *End;
221 };
222
223 extern int argc;
224 extern char **argv;
225 extern char **envp;
226
227 namespace internal {
228
same_prefix(char const * lhs,char const * rhs,int const len)229 constexpr bool same_prefix(char const *lhs, char const *rhs, int const len) {
230 for (int i = 0; (*lhs || *rhs) && (i < len); ++lhs, ++rhs, ++i)
231 if (*lhs != *rhs)
232 return false;
233 return true;
234 }
235
valid_prefix(char const * lhs)236 constexpr bool valid_prefix(char const *lhs) {
237 return same_prefix(lhs, "LlvmLibc", 8);
238 }
239
240 // 'str' is a null terminated string of the form
241 // "const char *LIBC_NAMESPACE::testing::internal::GetTypeName() [ParamType =
242 // XXX]" We return the substring that start at character '[' or a default
243 // message.
GetPrettyFunctionParamType(char const * str)244 constexpr char const *GetPrettyFunctionParamType(char const *str) {
245 for (const char *ptr = str; *ptr != '\0'; ++ptr)
246 if (*ptr == '[')
247 return ptr;
248 return "UNSET : declare with REGISTER_TYPE_NAME";
249 }
250
251 // This function recovers ParamType at compile time by using __PRETTY_FUNCTION__
252 // It can be customized by using the REGISTER_TYPE_NAME macro below.
GetTypeName()253 template <typename ParamType> static constexpr const char *GetTypeName() {
254 return GetPrettyFunctionParamType(__PRETTY_FUNCTION__);
255 }
256
257 template <typename T>
GenerateName(char * buffer,int buffer_size,const char * prefix)258 static inline void GenerateName(char *buffer, int buffer_size,
259 const char *prefix) {
260 if (buffer_size == 0)
261 return;
262
263 // Make sure string is null terminated.
264 --buffer_size;
265 buffer[buffer_size] = '\0';
266
267 const auto AppendChar = [&](char c) {
268 if (buffer_size > 0) {
269 *buffer = c;
270 ++buffer;
271 --buffer_size;
272 }
273 };
274 const auto AppendStr = [&](const char *str) {
275 for (; str && *str != '\0'; ++str)
276 AppendChar(*str);
277 };
278
279 AppendStr(prefix);
280 AppendChar(' ');
281 AppendStr(GetTypeName<T>());
282 AppendChar('\0');
283 }
284
285 // TestCreator implements a linear hierarchy of test instances, effectively
286 // instanciating all tests with Types in a single object.
287 template <template <typename> class TemplatedTestClass, typename... Types>
288 struct TestCreator;
289
290 template <template <typename> class TemplatedTestClass, typename Head,
291 typename... Tail>
292 struct TestCreator<TemplatedTestClass, Head, Tail...>
293 : private TestCreator<TemplatedTestClass, Tail...> {
294 TemplatedTestClass<Head> instance;
295 };
296
297 template <template <typename> class TemplatedTestClass>
298 struct TestCreator<TemplatedTestClass> {};
299
300 // A type list to declare the set of types to instantiate the tests with.
301 template <typename... Types> struct TypeList {
302 template <template <typename> class TemplatedTestClass> struct Tests {
303 using type = TestCreator<TemplatedTestClass, Types...>;
304 };
305 };
306
307 } // namespace internal
308
309 // Make TypeList visible in LIBC_NAMESPACE::testing.
310 template <typename... Types> using TypeList = internal::TypeList<Types...>;
311
312 CString libc_make_test_file_path_func(const char *file_name);
313
314 } // namespace testing
315 } // namespace LIBC_NAMESPACE
316
317 // For TYPED_TEST and TYPED_TEST_F below we need to display which type was used
318 // to run the test. The default will return the fully qualified canonical type
319 // but it can be difficult to read. We provide the following macro to allow the
320 // client to register the type name as they see it in the code.
321 #define REGISTER_TYPE_NAME(TYPE) \
322 template <> \
323 constexpr const char * \
324 LIBC_NAMESPACE::testing::internal::GetTypeName<TYPE>() { \
325 return "[ParamType = " #TYPE "]"; \
326 }
327
328 #define TYPED_TEST(SuiteName, TestName, TypeList) \
329 static_assert( \
330 LIBC_NAMESPACE::testing::internal::valid_prefix(#SuiteName), \
331 "All LLVM-libc TYPED_TEST suite names must start with 'LlvmLibc'."); \
332 template <typename T> \
333 class SuiteName##_##TestName : public LIBC_NAMESPACE::testing::Test { \
334 public: \
335 using ParamType = T; \
336 char name[256]; \
337 SuiteName##_##TestName() { \
338 addTest(this); \
339 LIBC_NAMESPACE::testing::internal::GenerateName<T>( \
340 name, sizeof(name), #SuiteName "." #TestName); \
341 } \
342 void Run() override; \
343 const char *getName() const override { return name; } \
344 }; \
345 TypeList::Tests<SuiteName##_##TestName>::type \
346 SuiteName##_##TestName##_Instance; \
347 template <typename T> void SuiteName##_##TestName<T>::Run()
348
349 #define TYPED_TEST_F(SuiteClass, TestName, TypeList) \
350 static_assert(LIBC_NAMESPACE::testing::internal::valid_prefix(#SuiteClass), \
351 "All LLVM-libc TYPED_TEST_F suite class names must start " \
352 "with 'LlvmLibc'."); \
353 template <typename T> class SuiteClass##_##TestName : public SuiteClass<T> { \
354 public: \
355 using ParamType = T; \
356 char name[256]; \
357 SuiteClass##_##TestName() { \
358 SuiteClass<T>::addTest(this); \
359 LIBC_NAMESPACE::testing::internal::GenerateName<T>( \
360 name, sizeof(name), #SuiteClass "." #TestName); \
361 } \
362 void Run() override; \
363 const char *getName() const override { return name; } \
364 }; \
365 TypeList::Tests<SuiteClass##_##TestName>::type \
366 SuiteClass##_##TestName##_Instance; \
367 template <typename T> void SuiteClass##_##TestName<T>::Run()
368
369 #define TEST(SuiteName, TestName) \
370 static_assert(LIBC_NAMESPACE::testing::internal::valid_prefix(#SuiteName), \
371 "All LLVM-libc TEST suite names must start with 'LlvmLibc'."); \
372 class SuiteName##_##TestName : public LIBC_NAMESPACE::testing::Test { \
373 public: \
374 SuiteName##_##TestName() { addTest(this); } \
375 void Run() override; \
376 const char *getName() const override { return #SuiteName "." #TestName; } \
377 }; \
378 SuiteName##_##TestName SuiteName##_##TestName##_Instance; \
379 void SuiteName##_##TestName::Run()
380
381 #define TEST_F(SuiteClass, TestName) \
382 static_assert( \
383 LIBC_NAMESPACE::testing::internal::valid_prefix(#SuiteClass), \
384 "All LLVM-libc TEST_F suite class names must start with 'LlvmLibc'."); \
385 class SuiteClass##_##TestName : public SuiteClass { \
386 public: \
387 SuiteClass##_##TestName() { addTest(this); } \
388 void Run() override; \
389 const char *getName() const override { return #SuiteClass "." #TestName; } \
390 }; \
391 SuiteClass##_##TestName SuiteClass##_##TestName##_Instance; \
392 void SuiteClass##_##TestName::Run()
393
394 // If RET_OR_EMPTY is the 'return' keyword we perform an early return which
395 // corresponds to an assert. If it is empty the execution continues, this
396 // corresponds to an expect.
397 //
398 // The 'else' clause must not be enclosed into braces so that the << operator
399 // can be used to fill the Message.
400 //
401 // TEST is usually implemented as a function performing checking logic and
402 // returning a boolean. This expression is responsible for logging the
403 // diagnostic in case of failure.
404 #define LIBC_TEST_SCAFFOLDING_(TEST, RET_OR_EMPTY) \
405 if (TEST) \
406 ; \
407 else \
408 RET_OR_EMPTY LIBC_NAMESPACE::testing::internal::Failure() = \
409 LIBC_NAMESPACE::testing::internal::Message()
410
411 #define LIBC_TEST_BINOP_(COND, LHS, RHS, RET_OR_EMPTY) \
412 LIBC_TEST_SCAFFOLDING_(test(LIBC_NAMESPACE::testing::TestCond::COND, LHS, \
413 RHS, #LHS, #RHS, LIBC_TEST_LOC_()), \
414 RET_OR_EMPTY)
415
416 ////////////////////////////////////////////////////////////////////////////////
417 // Binary operations corresponding to the TestCond enum.
418
419 #define EXPECT_EQ(LHS, RHS) LIBC_TEST_BINOP_(EQ, LHS, RHS, )
420 #define ASSERT_EQ(LHS, RHS) LIBC_TEST_BINOP_(EQ, LHS, RHS, return)
421
422 #define EXPECT_NE(LHS, RHS) LIBC_TEST_BINOP_(NE, LHS, RHS, )
423 #define ASSERT_NE(LHS, RHS) LIBC_TEST_BINOP_(NE, LHS, RHS, return)
424
425 #define EXPECT_LT(LHS, RHS) LIBC_TEST_BINOP_(LT, LHS, RHS, )
426 #define ASSERT_LT(LHS, RHS) LIBC_TEST_BINOP_(LT, LHS, RHS, return)
427
428 #define EXPECT_LE(LHS, RHS) LIBC_TEST_BINOP_(LE, LHS, RHS, )
429 #define ASSERT_LE(LHS, RHS) LIBC_TEST_BINOP_(LE, LHS, RHS, return)
430
431 #define EXPECT_GT(LHS, RHS) LIBC_TEST_BINOP_(GT, LHS, RHS, )
432 #define ASSERT_GT(LHS, RHS) LIBC_TEST_BINOP_(GT, LHS, RHS, return)
433
434 #define EXPECT_GE(LHS, RHS) LIBC_TEST_BINOP_(GE, LHS, RHS, )
435 #define ASSERT_GE(LHS, RHS) LIBC_TEST_BINOP_(GE, LHS, RHS, return)
436
437 ////////////////////////////////////////////////////////////////////////////////
438 // Boolean checks are handled as comparison to the true / false values.
439
440 #define EXPECT_TRUE(VAL) EXPECT_EQ(VAL, true)
441 #define ASSERT_TRUE(VAL) ASSERT_EQ(VAL, true)
442
443 #define EXPECT_FALSE(VAL) EXPECT_EQ(VAL, false)
444 #define ASSERT_FALSE(VAL) ASSERT_EQ(VAL, false)
445
446 ////////////////////////////////////////////////////////////////////////////////
447 // String checks.
448
449 #define LIBC_TEST_STR_(TEST_FUNC, LHS, RHS, RET_OR_EMPTY) \
450 LIBC_TEST_SCAFFOLDING_(TEST_FUNC(LHS, RHS, #LHS, #RHS, LIBC_TEST_LOC_()), \
451 RET_OR_EMPTY)
452
453 #define EXPECT_STREQ(LHS, RHS) LIBC_TEST_STR_(testStrEq, LHS, RHS, )
454 #define ASSERT_STREQ(LHS, RHS) LIBC_TEST_STR_(testStrEq, LHS, RHS, return)
455
456 #define EXPECT_STRNE(LHS, RHS) LIBC_TEST_STR_(testStrNe, LHS, RHS, )
457 #define ASSERT_STRNE(LHS, RHS) LIBC_TEST_STR_(testStrNe, LHS, RHS, return)
458
459 ////////////////////////////////////////////////////////////////////////////////
460 // Subprocess checks.
461
462 #ifdef ENABLE_SUBPROCESS_TESTS
463
464 #define LIBC_TEST_PROCESS_(TEST_FUNC, FUNC, VALUE, RET_OR_EMPTY) \
465 LIBC_TEST_SCAFFOLDING_( \
466 TEST_FUNC(LIBC_NAMESPACE::testing::Test::createCallable(FUNC), VALUE, \
467 #FUNC, #VALUE, LIBC_TEST_LOC_()), \
468 RET_OR_EMPTY)
469
470 #define EXPECT_EXITS(FUNC, EXIT) \
471 LIBC_TEST_PROCESS_(testProcessExits, FUNC, EXIT, )
472 #define ASSERT_EXITS(FUNC, EXIT) \
473 LIBC_TEST_PROCESS_(testProcessExits, FUNC, EXIT, return)
474
475 #define EXPECT_DEATH(FUNC, SIG) \
476 LIBC_TEST_PROCESS_(testProcessKilled, FUNC, SIG, )
477 #define ASSERT_DEATH(FUNC, SIG) \
478 LIBC_TEST_PROCESS_(testProcessKilled, FUNC, SIG, return)
479
480 #endif // ENABLE_SUBPROCESS_TESTS
481
482 ////////////////////////////////////////////////////////////////////////////////
483 // Custom matcher checks.
484
485 #define LIBC_TEST_MATCH_(MATCHER, MATCH, MATCHER_STR, MATCH_STR, RET_OR_EMPTY) \
486 LIBC_TEST_SCAFFOLDING_(matchAndExplain(MATCHER, MATCH, MATCHER_STR, \
487 MATCH_STR, LIBC_TEST_LOC_()), \
488 RET_OR_EMPTY)
489
490 #define EXPECT_THAT(MATCH, MATCHER) \
491 LIBC_TEST_MATCH_(MATCHER, MATCH, #MATCHER, #MATCH, )
492 #define ASSERT_THAT(MATCH, MATCHER) \
493 LIBC_TEST_MATCH_(MATCHER, MATCH, #MATCHER, #MATCH, return)
494
495 #define WITH_SIGNAL(X) X
496
497 #define LIBC_TEST_HAS_MATCHERS() (1)
498
499 #endif // LLVM_LIBC_TEST_UNITTEST_LIBCTEST_H
500