FSTGoogleTestTests.mm 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /*
  2. * Copyright 2017 Google LLC
  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. #import <XCTest/XCTest.h>
  17. #import <objc/runtime.h>
  18. #include "gtest/gtest.h"
  19. /**
  20. * An XCTest test case that finds C++ test cases written in the GoogleTest
  21. * framework, runs them, and reports the results back to Xcode. This allows
  22. * tests written in C++ that don't rely on XCTest to coexist in this project.
  23. *
  24. * As an extra feature, you can run all C++ tests by focusing on the GoogleTests
  25. * class.
  26. *
  27. * Each GoogleTest TestCase is mapped to a dynamically generated XCTestCase
  28. * class. Each GoogleTest TEST() is mapped to a test method on that XCTestCase.
  29. */
  30. @interface GoogleTests : XCTestCase
  31. @end
  32. namespace {
  33. // A testing::TestCase named "Foo" corresponds to an XCTestCase named
  34. // "FooTests".
  35. NSString* const kTestCaseSuffix = @"Tests";
  36. // A testing::TestInfo named "Foo" corresponds to test method named "testFoo".
  37. NSString* const kTestMethodPrefix = @"test";
  38. // A map of keys created by TestInfoKey to the corresponding testing::TestInfo
  39. // (wrapped in an NSValue). The generated XCTestCase classes are discovered and
  40. // instantiated by XCTest so this is the only means of plumbing per-test-method
  41. // state into these methods.
  42. NSDictionary<NSString*, NSValue*>* testInfosByKey;
  43. // If the user focuses on GoogleTests itself, this means force all C++ tests to
  44. // run.
  45. bool forceAllTests = false;
  46. void RunGoogleTestTests();
  47. /**
  48. * Loads this XCTest runner's configuration file and figures out which tests to
  49. * run based on the contents of that configuration file.
  50. *
  51. * @return the set of tests to run, or nil if the user asked for all tests or if
  52. * there's any problem loading or parsing the configuration.
  53. */
  54. NSSet<NSString*>* _Nullable LoadXCTestConfigurationTestsToRun() {
  55. // Xcode invokes the test runner with an XCTestConfigurationFilePath
  56. // environment variable set to the path of a configuration file containing,
  57. // among other things, the set of tests to run. The configuration file
  58. // deserializes to a non-public XCTestConfiguration class.
  59. //
  60. // This loads that file and then reflectively pulls out the testsToRun set.
  61. // Just in case any of these private details should change in the future and
  62. // something should fail here, the mechanism complains but fails open. This
  63. // way the worst that can happen is that users end up running more tests than
  64. // they intend, but we never accidentally show a green run that wasn't.
  65. static NSString* const configEnvVar = @"XCTestConfigurationFilePath";
  66. NSDictionary<NSString*, NSString*>* env =
  67. [[NSProcessInfo processInfo] environment];
  68. NSString* filePath = [env objectForKey:configEnvVar];
  69. if (!filePath) {
  70. NSLog(@"Missing %@ environment variable; assuming all tests", configEnvVar);
  71. return nil;
  72. }
  73. id config = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
  74. if (!config) {
  75. NSLog(@"Failed to load any configuaration from %@=%@", configEnvVar,
  76. filePath);
  77. return nil;
  78. }
  79. SEL testsToRunSelector = NSSelectorFromString(@"testsToRun");
  80. if (![config respondsToSelector:testsToRunSelector]) {
  81. NSLog(@"Invalid configuaration from %@=%@: missing testsToRun",
  82. configEnvVar, filePath);
  83. return nil;
  84. }
  85. // Invoke the testsToRun selector safely. This indirection is required because
  86. // just calling -performSelector: fails to properly retain the NSSet under
  87. // ARC.
  88. typedef NSSet<NSString*>* (*TestsToRunFunction)(id, SEL);
  89. IMP testsToRunMethod = [config methodForSelector:testsToRunSelector];
  90. auto testsToRunFunction =
  91. reinterpret_cast<TestsToRunFunction>(testsToRunMethod);
  92. return testsToRunFunction(config, testsToRunSelector);
  93. }
  94. /**
  95. * Creates a GoogleTest filter specification, suitable for passing to the
  96. * --gtest_filter flag, that limits GoogleTest to running the same set of tests
  97. * that Xcode requested.
  98. *
  99. * Each member of the testsToRun set is mapped as follows:
  100. *
  101. * * Bare class: "ClassTests" => "Class.*"
  102. * * Class and method: "ClassTests/testMethod" => "Class.Method"
  103. *
  104. * These members are then joined with a ":" as googletest requires.
  105. *
  106. * @see
  107. * https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md
  108. */
  109. NSString* CreateTestFiltersFromTestsToRun(NSSet<NSString*>* testsToRun) {
  110. NSMutableString* result = [[NSMutableString alloc] init];
  111. for (NSString* spec in testsToRun) {
  112. NSArray<NSString*>* parts = [spec componentsSeparatedByString:@"/"];
  113. NSString* gtestCaseName = nil;
  114. if (parts.count > 0) {
  115. NSString* className = parts[0];
  116. if ([className hasSuffix:kTestCaseSuffix]) {
  117. gtestCaseName = [className
  118. substringToIndex:className.length - kTestCaseSuffix.length];
  119. }
  120. }
  121. NSString* gtestMethodName = nil;
  122. if (parts.count > 1) {
  123. NSString* methodName = parts[1];
  124. if ([methodName hasPrefix:kTestMethodPrefix]) {
  125. gtestMethodName =
  126. [methodName substringFromIndex:kTestMethodPrefix.length];
  127. }
  128. }
  129. if (gtestCaseName) {
  130. if (result.length > 0) {
  131. [result appendString:@":"];
  132. }
  133. [result appendString:gtestCaseName];
  134. [result appendString:@"."];
  135. [result appendString:(gtestMethodName ? gtestMethodName : @"*")];
  136. }
  137. }
  138. return result;
  139. }
  140. /** Returns the name of the selector for the test method representing this
  141. * specific test. */
  142. NSString* SelectorNameForTestInfo(const testing::TestInfo* testInfo) {
  143. return
  144. [NSString stringWithFormat:@"%@%s", kTestMethodPrefix, testInfo->name()];
  145. }
  146. /** Returns the name of the class representing the given testing::TestCase. */
  147. NSString* ClassNameForTestCase(const testing::TestCase* testCase) {
  148. return [NSString stringWithFormat:@"%s%@", testCase->name(), kTestCaseSuffix];
  149. }
  150. /**
  151. * Returns a key name for the testInfosByKey dictionary. Each (class, selector)
  152. * pair corresponds to a unique GoogleTest result.
  153. */
  154. NSString* TestInfoKey(Class testClass, SEL testSelector) {
  155. return [NSString stringWithFormat:@"%@.%@", NSStringFromClass(testClass),
  156. NSStringFromSelector(testSelector)];
  157. }
  158. /**
  159. * A function that is the implementation for each generated test method. It
  160. * shouldn't be used directly--instead use it with class_addMethod to define the
  161. * behavior of the generated XCTestCase class.
  162. *
  163. * The first invocation of this method runs all GoogleTest tests. Delaying
  164. * execution this way allows XCTest to register to the test runner that it
  165. * actually has started.
  166. *
  167. * Looks up the testing::TestInfo for this test method and reports on the
  168. * outcome to XCTest, as if the test actually ran in this method.
  169. *
  170. * Note: The parameter names of self and _cmd match up with the implicit
  171. * parameters passed to any Objective-C method. Naming them this way here allows
  172. * XCTAssert and friends to work.
  173. */
  174. void XCTestMethod(XCTestCase* self, SEL _cmd) {
  175. RunGoogleTestTests();
  176. NSString* testInfoKey = TestInfoKey([self class], _cmd);
  177. NSValue* holder = testInfosByKey[testInfoKey];
  178. auto testInfo = static_cast<const testing::TestInfo*>(holder.pointerValue);
  179. if (!testInfo) {
  180. return;
  181. }
  182. if (!testInfo->should_run()) {
  183. // Test was filtered out by gunit; nothing to report.
  184. return;
  185. }
  186. const testing::TestResult* result = testInfo->result();
  187. if (result->Passed()) {
  188. // Let XCode know that the test ran and succeeded.
  189. XCTAssertTrue(true);
  190. return;
  191. }
  192. // Test failed :-(. Record the failure such that XCode will navigate directly
  193. // to the file:line.
  194. int parts = result->total_part_count();
  195. for (int i = 0; i < parts; i++) {
  196. const testing::TestPartResult& part = result->GetTestPartResult(i);
  197. [self
  198. recordFailureWithDescription:@(part.message())
  199. inFile:@(part.file_name() ? part.file_name() : "")
  200. atLine:(part.line_number() > 0
  201. ? part.line_number()
  202. : 0)
  203. expected:true];
  204. }
  205. }
  206. /**
  207. * Generates a new subclass of XCTestCase for the given GoogleTest TestCase.
  208. * Each TestInfo (which represents an individual test method execution) is
  209. * translated into a method on the test case.
  210. *
  211. * @param testCase The testing::TestCase of interest to translate.
  212. * @param infoMap A map of TestInfoKeys to testing::TestInfos, populated by this
  213. * method.
  214. *
  215. * @return A new Class that's a subclass of XCTestCase, that's been registered
  216. * with the Objective-C runtime.
  217. */
  218. Class CreateXCTestCaseClass(const testing::TestCase* testCase,
  219. NSMutableDictionary<NSString*, NSValue*>* infoMap) {
  220. NSString* testCaseName = ClassNameForTestCase(testCase);
  221. Class testClass =
  222. objc_allocateClassPair([XCTestCase class], [testCaseName UTF8String], 0);
  223. // Create a method for each TestInfo.
  224. int testInfos = testCase->total_test_count();
  225. for (int j = 0; j < testInfos; j++) {
  226. const testing::TestInfo* testInfo = testCase->GetTestInfo(j);
  227. NSString* selectorName = SelectorNameForTestInfo(testInfo);
  228. SEL selector = sel_registerName([selectorName UTF8String]);
  229. // Use the XCTestMethod function as the method implementation. The v@:
  230. // indicates it is a void objective-C method; this must continue to match
  231. // the signature of XCTestMethod.
  232. IMP method = reinterpret_cast<IMP>(XCTestMethod);
  233. class_addMethod(testClass, selector, method, "v@:");
  234. NSString* infoKey = TestInfoKey(testClass, selector);
  235. NSValue* holder = [NSValue valueWithPointer:testInfo];
  236. infoMap[infoKey] = holder;
  237. }
  238. objc_registerClassPair(testClass);
  239. return testClass;
  240. }
  241. /**
  242. * Creates a test suite containing all C++ tests, used when the user starts the
  243. * GoogleTests class.
  244. *
  245. * Note: normally XCTest finds all the XCTestCase classes that are registered
  246. * with the run time and asks them to create suites for themselves. When a user
  247. * focuses on the GoogleTests class, XCTest no longer does this so we have to
  248. * force XCTest to see more tests than it would normally look at so that the
  249. * indicators in the test navigator update properly.
  250. */
  251. XCTestSuite* CreateAllTestsTestSuite() {
  252. XCTestSuite* allTestsSuite =
  253. [[XCTestSuite alloc] initWithName:@"All GoogleTest Tests"];
  254. [allTestsSuite
  255. addTest:[XCTestSuite testSuiteForTestCaseClass:[GoogleTests class]]];
  256. const testing::UnitTest* master = testing::UnitTest::GetInstance();
  257. int testCases = master->total_test_case_count();
  258. for (int i = 0; i < testCases; i++) {
  259. const testing::TestCase* testCase = master->GetTestCase(i);
  260. NSString* testCaseName = ClassNameForTestCase(testCase);
  261. Class testClass = objc_getClass([testCaseName UTF8String]);
  262. [allTestsSuite addTest:[XCTestSuite testSuiteForTestCaseClass:testClass]];
  263. }
  264. return allTestsSuite;
  265. }
  266. /**
  267. * Finds and runs googletest-based tests based on the XCTestConfiguration of the
  268. * current test invocation.
  269. */
  270. void CreateGoogleTestTests() {
  271. NSString* masterTestCaseName = NSStringFromClass([GoogleTests class]);
  272. // Initialize GoogleTest but don't run the tests yet.
  273. int argc = 1;
  274. const char* argv[] = {[masterTestCaseName UTF8String]};
  275. testing::InitGoogleTest(&argc, const_cast<char**>(argv));
  276. // Convert XCTest's testToRun set to the equivalent --gtest_filter flag.
  277. //
  278. // Note that we only set forceAllTests to true if the user specifically
  279. // focused on GoogleTests. This prevents XCTest double-counting test cases
  280. // (and failures) when a user asks for all tests.
  281. NSSet<NSString*>* allTests = [NSSet setWithObject:masterTestCaseName];
  282. NSSet<NSString*>* testsToRun = LoadXCTestConfigurationTestsToRun();
  283. if (testsToRun) {
  284. if ([allTests isEqual:testsToRun]) {
  285. NSLog(@"Forcing all tests to run");
  286. forceAllTests = true;
  287. } else {
  288. NSString* filters = CreateTestFiltersFromTestsToRun(testsToRun);
  289. NSLog(@"Using --gtest_filter=%@", filters);
  290. if (filters) {
  291. testing::GTEST_FLAG(filter) = [filters UTF8String];
  292. }
  293. }
  294. }
  295. // Create XCTestCases and populate the testInfosByKey map
  296. const testing::UnitTest* master = testing::UnitTest::GetInstance();
  297. NSMutableDictionary<NSString*, NSValue*>* infoMap =
  298. [NSMutableDictionary dictionaryWithCapacity:master->total_test_count()];
  299. int testCases = master->total_test_case_count();
  300. for (int i = 0; i < testCases; i++) {
  301. const testing::TestCase* testCase = master->GetTestCase(i);
  302. CreateXCTestCaseClass(testCase, infoMap);
  303. }
  304. testInfosByKey = infoMap;
  305. }
  306. void RunGoogleTestTests() {
  307. static bool firstRun = true;
  308. if (firstRun) {
  309. firstRun = false;
  310. int result = RUN_ALL_TESTS();
  311. // RUN_ALL_TESTS by default doesn't want you to ignore its result, but it's
  312. // safe here. Test failures are already logged by GoogleTest itself (and
  313. // then again by XCTest). Test failures are reported via
  314. // -recordFailureWithDescription:inFile:atLine:expected: which then causes
  315. // XCTest itself to fail the run.
  316. (void)result;
  317. }
  318. }
  319. } // namespace
  320. @implementation GoogleTests
  321. + (XCTestSuite*)defaultTestSuite {
  322. // Only return all tests beyond GoogleTests if the user is focusing on
  323. // GoogleTests.
  324. if (forceAllTests) {
  325. return CreateAllTestsTestSuite();
  326. } else {
  327. // just run the tests that are a part of this class
  328. return [XCTestSuite testSuiteForTestCaseClass:[self class]];
  329. }
  330. }
  331. - (void)testGoogleTestsActuallyRun {
  332. // This whole mechanism is sufficiently tricky that we should verify that the
  333. // build actually plumbed this together correctly.
  334. const testing::UnitTest* master = testing::UnitTest::GetInstance();
  335. XCTAssertGreaterThan(master->total_test_case_count(), 0);
  336. }
  337. @end
  338. /**
  339. * This class is registered as the NSPrincipalClass in the Firestore_Tests
  340. * bundle's Info.plist. XCTest instantiates this class to perform one-time setup
  341. * for the test bundle, as documented here:
  342. *
  343. * https://developer.apple.com/documentation/xctest/xctestobservationcenter
  344. */
  345. @interface FSTGoogleTestsPrincipal : NSObject
  346. @end
  347. @implementation FSTGoogleTestsPrincipal
  348. - (instancetype)init {
  349. self = [super init];
  350. CreateGoogleTestTests();
  351. return self;
  352. }
  353. @end