1 //===- Test.h - Simple macros for API unit tests ----------------*- 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 // This file define simple macros for declaring test functions and running them. 10 // The actual checking must be performed on the outputs with FileCheck. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #ifndef MLIR_TEST_TEST_H_ 15 #define MLIR_TEST_TEST_H_ 16 17 #include <functional> 18 #include <vector> 19 20 namespace test_detail { 21 // Returns a mutable list of known test functions. Used internally by test 22 // macros to add and run tests. This function is static to ensure it creates a 23 // new list in each test file. tests()24static std::vector<std::function<void()>> &tests() { 25 static std::vector<std::function<void()>> list; 26 return list; 27 } 28 29 // Test registration class. Used internally by test macros to register tests 30 // during static allocation. 31 struct TestRegistration { TestRegistrationTestRegistration32 explicit TestRegistration(std::function<void()> func) { 33 test_detail::tests().push_back(func); 34 } 35 }; 36 } // end namespace test_detail 37 38 /// Declares a test function with the given name and adds it to the list of 39 /// known tests. The body of the function must follow immediately. Example: 40 /// 41 /// TEST_FUNC(mytest) { 42 /// // CHECK: expected-output-here 43 /// emitSomethingToStdOut(); 44 /// } 45 /// 46 #define TEST_FUNC(name) \ 47 void name(); \ 48 static test_detail::TestRegistration name##Registration(name); \ 49 void name() 50 51 /// Runs all registered tests. Example: 52 /// 53 /// int main() { 54 /// RUN_TESTS(); 55 /// return 0; 56 /// } 57 #define RUN_TESTS \ 58 []() { \ 59 for (auto f : test_detail::tests()) \ 60 f(); \ 61 } 62 63 #endif // MLIR_TEST_TEST_H_ 64