1 // Copyright (C) 2024 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // This file is included when gtestifier.py rewrites a source file for a standalone test that is
16 // normally run as main() to turn it into a gtest.
17
18 #pragma once
19
20 #include <stdbool.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <sys/cdefs.h>
24
25 #define GTESTIFIER_STRINGIFY(x) GTESTIFIER_STRINGIFY2(x)
26 #define GTESTIFIER_STRINGIFY2(x) #x
27
28 #define GTESTIFIER_CONCAT(x, y) GTESTIFIER_CONCAT2(x, y)
29 #define GTESTIFIER_CONCAT2(x, y) x##y
30
31 // Create unique names for main() and gtestifierWrapper() so that multiple standalone tests
32 // can be linked together.
33 #define main GTESTIFIER_CONCAT(GTESTIFIER_TEST, _main)
34 #define gtestifierWrapper GTESTIFIER_CONCAT(GTESTIFIER_TEST, _wrapper)
35
36 __BEGIN_DECLS
37 void registerGTestifierTest(const char* test_suite_name, const char* test_name, const char* file,
38 int line, int (*func)(), bool (*predicate)(int));
39
40 // The signature of main() needs to match the definition used in the standalone test. If
41 // the standalone test uses main() with no arguments then the code will need to be compiled
42 // with -DGTESTIFIER_MAIN_NO_ARGUMENTS.
43 #if GTESTIFIER_MAIN_NO_ARGUMENTS
44 int main(void);
45 #else
46 int main(int argc, char** argv);
47 #endif
48 __END_DECLS
49
50 // gtestifierWrapper wraps the standalone main() function.
gtestifierWrapper(void)51 static int gtestifierWrapper(void) {
52 #if GTESTIFIER_MAIN_NO_ARGUMENTS
53 return main();
54 #else
55 char* argv[] = {strdup(GTESTIFIER_STRINGIFY(GTESTIFIER_TEST)), NULL};
56 return main(1, argv);
57 #endif
58 }
59
60 // Use a static constructor to register this wrapped test as a gtest.
registerGTestifier()61 __attribute__((constructor)) static void registerGTestifier() {
62 registerGTestifierTest(GTESTIFIER_STRINGIFY(GTESTIFIER_SUITE),
63 GTESTIFIER_STRINGIFY(GTESTIFIER_TEST), __FILE__, __LINE__,
64 gtestifierWrapper, GTESTIFIER_PREDICATE);
65 };
66