FSTGoogleTestTests.mm 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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;
  74. NSError* error;
  75. if (@available(macOS 10.13, iOS 11, tvOS 11, *)) {
  76. NSData* data = [NSData dataWithContentsOfFile:filePath
  77. options:kNilOptions
  78. error:&error];
  79. if (!data) {
  80. NSLog(@"Failed to fill data with contents of file. %@", error);
  81. return nil;
  82. }
  83. config = [NSKeyedUnarchiver unarchivedObjectOfClass:NSObject.class
  84. fromData:data
  85. error:&error];
  86. } else {
  87. config = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
  88. }
  89. if (!config) {
  90. NSLog(@"Failed to load any configuaration from %@=%@. %@", configEnvVar,
  91. filePath, error);
  92. return nil;
  93. }
  94. SEL testsToRunSelector = NSSelectorFromString(@"testsToRun");
  95. if (![config respondsToSelector:testsToRunSelector]) {
  96. NSLog(@"Invalid configuaration from %@=%@: missing testsToRun",
  97. configEnvVar, filePath);
  98. return nil;
  99. }
  100. // Invoke the testsToRun selector safely. This indirection is required because
  101. // just calling -performSelector: fails to properly retain the NSSet under
  102. // ARC.
  103. typedef NSSet<NSString*>* (*TestsToRunFunction)(id, SEL);
  104. IMP testsToRunMethod = [config methodForSelector:testsToRunSelector];
  105. auto testsToRunFunction =
  106. reinterpret_cast<TestsToRunFunction>(testsToRunMethod);
  107. return testsToRunFunction(config, testsToRunSelector);
  108. }
  109. /**
  110. * Creates a GoogleTest filter specification, suitable for passing to the
  111. * --gtest_filter flag, that limits GoogleTest to running the same set of tests
  112. * that Xcode requested.
  113. *
  114. * Each member of the testsToRun set is mapped as follows:
  115. *
  116. * * Bare class: "ClassTests" => "Class.*"
  117. * * Class and method: "ClassTests/testMethod" => "Class.Method"
  118. *
  119. * These members are then joined with a ":" as googletest requires.
  120. *
  121. * @see
  122. * https://github.com/google/googletest/blob/master/googletest/docs/AdvancedGuide.md
  123. */
  124. NSString* CreateTestFiltersFromTestsToRun(NSSet<NSString*>* testsToRun) {
  125. NSMutableString* result = [[NSMutableString alloc] init];
  126. for (NSString* spec in testsToRun) {
  127. NSArray<NSString*>* parts = [spec componentsSeparatedByString:@"/"];
  128. NSString* gtestCaseName = nil;
  129. if (parts.count > 0) {
  130. NSString* className = parts[0];
  131. if ([className hasSuffix:kTestCaseSuffix]) {
  132. gtestCaseName = [className
  133. substringToIndex:className.length - kTestCaseSuffix.length];
  134. }
  135. }
  136. NSString* gtestMethodName = nil;
  137. if (parts.count > 1) {
  138. NSString* methodName = parts[1];
  139. if ([methodName hasPrefix:kTestMethodPrefix]) {
  140. gtestMethodName =
  141. [methodName substringFromIndex:kTestMethodPrefix.length];
  142. }
  143. }
  144. if (gtestCaseName) {
  145. if (result.length > 0) {
  146. [result appendString:@":"];
  147. }
  148. [result appendString:gtestCaseName];
  149. [result appendString:@"."];
  150. [result appendString:(gtestMethodName ? gtestMethodName : @"*")];
  151. }
  152. }
  153. return result;
  154. }
  155. /** Returns the name of the selector for the test method representing this
  156. * specific test. */
  157. NSString* SelectorNameForTestInfo(const testing::TestInfo* testInfo) {
  158. return
  159. [NSString stringWithFormat:@"%@%s", kTestMethodPrefix, testInfo->name()];
  160. }
  161. /** Returns the name of the class representing the given testing::TestCase. */
  162. NSString* ClassNameForTestCase(const testing::TestCase* testCase) {
  163. return [NSString stringWithFormat:@"%s%@", testCase->name(), kTestCaseSuffix];
  164. }
  165. /**
  166. * Returns a key name for the testInfosByKey dictionary. Each (class, selector)
  167. * pair corresponds to a unique GoogleTest result.
  168. */
  169. NSString* TestInfoKey(Class testClass, SEL testSelector) {
  170. return [NSString stringWithFormat:@"%@.%@", NSStringFromClass(testClass),
  171. NSStringFromSelector(testSelector)];
  172. }
  173. /**
  174. * A function that is the implementation for each generated test method. It
  175. * shouldn't be used directly--instead use it with class_addMethod to define the
  176. * behavior of the generated XCTestCase class.
  177. *
  178. * The first invocation of this method runs all GoogleTest tests. Delaying
  179. * execution this way allows XCTest to register to the test runner that it
  180. * actually has started.
  181. *
  182. * Looks up the testing::TestInfo for this test method and reports on the
  183. * outcome to XCTest, as if the test actually ran in this method.
  184. *
  185. * Note: The parameter names of self and _cmd match up with the implicit
  186. * parameters passed to any Objective-C method. Naming them this way here allows
  187. * XCTAssert and friends to work.
  188. */
  189. void XCTestMethod(XCTestCase* self, SEL _cmd) {
  190. RunGoogleTestTests();
  191. NSString* testInfoKey = TestInfoKey([self class], _cmd);
  192. NSValue* holder = testInfosByKey[testInfoKey];
  193. auto testInfo = static_cast<const testing::TestInfo*>(holder.pointerValue);
  194. if (!testInfo) {
  195. return;
  196. }
  197. if (!testInfo->should_run()) {
  198. // Test was filtered out by gunit; nothing to report.
  199. return;
  200. }
  201. const testing::TestResult* result = testInfo->result();
  202. if (result->Passed()) {
  203. // Let XCode know that the test ran and succeeded.
  204. XCTAssertTrue(true);
  205. return;
  206. } else if (result->Skipped()) {
  207. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 130400 || \
  208. __TV_OS_VERSION_MAX_ALLOWED >= 130400 || \
  209. __MAC_OS_X_VERSION_MAX_ALLOWED >= 101504
  210. // Let XCode know that the test was skipped.
  211. XCTSkip();
  212. #endif
  213. }
  214. // Test failed :-(. Record the failure such that XCode will navigate directly
  215. // to the file:line.
  216. int parts = result->total_part_count();
  217. for (int i = 0; i < parts; i++) {
  218. const testing::TestPartResult& part = result->GetTestPartResult(i);
  219. const char* path = part.file_name() ? part.file_name() : "";
  220. int line = part.line_number() > 0 ? part.line_number() : 0;
  221. #if __IPHONE_OS_VERSION_MAX_ALLOWED >= 140000 || \
  222. __MAC_OS_X_VERSION_MAX_ALLOWED >= 101500
  223. // Xcode 12
  224. auto* location = [[XCTSourceCodeLocation alloc] initWithFilePath:@(path)
  225. lineNumber:line];
  226. auto* context = [[XCTSourceCodeContext alloc] initWithLocation:location];
  227. auto* issue = [[XCTIssue alloc] initWithType:XCTIssueTypeAssertionFailure
  228. compactDescription:@(part.summary())
  229. detailedDescription:@(part.message())
  230. sourceCodeContext:context
  231. associatedError:nil
  232. attachments:@[]];
  233. [self recordIssue:issue];
  234. #else
  235. // Xcode 11 and prior. recordFailureWithDescription:inFile:atLine:expected:
  236. // is deprecated in Xcode 12.
  237. [self recordFailureWithDescription:@(part.message())
  238. inFile:@(path)
  239. atLine:line
  240. expected:true];
  241. #endif
  242. }
  243. }
  244. /**
  245. * Generates a new subclass of XCTestCase for the given GoogleTest TestCase.
  246. * Each TestInfo (which represents an individual test method execution) is
  247. * translated into a method on the test case.
  248. *
  249. * @param testCase The testing::TestCase of interest to translate.
  250. * @param infoMap A map of TestInfoKeys to testing::TestInfos, populated by this
  251. * method.
  252. *
  253. * @return A new Class that's a subclass of XCTestCase, that's been registered
  254. * with the Objective-C runtime.
  255. */
  256. Class CreateXCTestCaseClass(const testing::TestCase* testCase,
  257. NSMutableDictionary<NSString*, NSValue*>* infoMap) {
  258. NSString* testCaseName = ClassNameForTestCase(testCase);
  259. Class testClass =
  260. objc_allocateClassPair([XCTestCase class], [testCaseName UTF8String], 0);
  261. // Create a method for each TestInfo.
  262. int testInfos = testCase->total_test_count();
  263. for (int j = 0; j < testInfos; j++) {
  264. const testing::TestInfo* testInfo = testCase->GetTestInfo(j);
  265. NSString* selectorName = SelectorNameForTestInfo(testInfo);
  266. SEL selector = sel_registerName([selectorName UTF8String]);
  267. // Use the XCTestMethod function as the method implementation. The v@:
  268. // indicates it is a void objective-C method; this must continue to match
  269. // the signature of XCTestMethod.
  270. IMP method = reinterpret_cast<IMP>(XCTestMethod);
  271. class_addMethod(testClass, selector, method, "v@:");
  272. NSString* infoKey = TestInfoKey(testClass, selector);
  273. NSValue* holder = [NSValue valueWithPointer:testInfo];
  274. infoMap[infoKey] = holder;
  275. }
  276. objc_registerClassPair(testClass);
  277. return testClass;
  278. }
  279. /**
  280. * Creates a test suite containing all C++ tests, used when the user starts the
  281. * GoogleTests class.
  282. *
  283. * Note: normally XCTest finds all the XCTestCase classes that are registered
  284. * with the run time and asks them to create suites for themselves. When a user
  285. * focuses on the GoogleTests class, XCTest no longer does this so we have to
  286. * force XCTest to see more tests than it would normally look at so that the
  287. * indicators in the test navigator update properly.
  288. */
  289. XCTestSuite* CreateAllTestsTestSuite() {
  290. XCTestSuite* allTestsSuite =
  291. [[XCTestSuite alloc] initWithName:@"All GoogleTest Tests"];
  292. [allTestsSuite
  293. addTest:[XCTestSuite testSuiteForTestCaseClass:[GoogleTests class]]];
  294. const testing::UnitTest* master = testing::UnitTest::GetInstance();
  295. int testCases = master->total_test_case_count();
  296. for (int i = 0; i < testCases; i++) {
  297. const testing::TestCase* testCase = master->GetTestCase(i);
  298. NSString* testCaseName = ClassNameForTestCase(testCase);
  299. Class testClass = objc_getClass([testCaseName UTF8String]);
  300. [allTestsSuite addTest:[XCTestSuite testSuiteForTestCaseClass:testClass]];
  301. }
  302. return allTestsSuite;
  303. }
  304. /**
  305. * Finds and runs googletest-based tests based on the XCTestConfiguration of the
  306. * current test invocation.
  307. */
  308. void CreateGoogleTestTests() {
  309. NSString* masterTestCaseName = NSStringFromClass([GoogleTests class]);
  310. // Initialize GoogleTest but don't run the tests yet.
  311. int argc = 1;
  312. const char* argv[] = {[masterTestCaseName UTF8String]};
  313. testing::InitGoogleTest(&argc, const_cast<char**>(argv));
  314. // Convert XCTest's testToRun set to the equivalent --gtest_filter flag.
  315. //
  316. // Note that we only set forceAllTests to true if the user specifically
  317. // focused on GoogleTests. This prevents XCTest double-counting test cases
  318. // (and failures) when a user asks for all tests.
  319. NSSet<NSString*>* allTests = [NSSet setWithObject:masterTestCaseName];
  320. NSSet<NSString*>* testsToRun = LoadXCTestConfigurationTestsToRun();
  321. if (testsToRun) {
  322. if ([allTests isEqual:testsToRun]) {
  323. NSLog(@"Forcing all tests to run");
  324. forceAllTests = true;
  325. } else {
  326. NSString* filters = CreateTestFiltersFromTestsToRun(testsToRun);
  327. NSLog(@"Using --gtest_filter=%@", filters);
  328. if (filters) {
  329. testing::GTEST_FLAG(filter) = [filters UTF8String];
  330. }
  331. }
  332. }
  333. // Create XCTestCases and populate the testInfosByKey map
  334. const testing::UnitTest* master = testing::UnitTest::GetInstance();
  335. NSMutableDictionary<NSString*, NSValue*>* infoMap =
  336. [NSMutableDictionary dictionaryWithCapacity:master->total_test_count()];
  337. int testCases = master->total_test_case_count();
  338. for (int i = 0; i < testCases; i++) {
  339. const testing::TestCase* testCase = master->GetTestCase(i);
  340. CreateXCTestCaseClass(testCase, infoMap);
  341. }
  342. testInfosByKey = infoMap;
  343. }
  344. void RunGoogleTestTests() {
  345. static bool firstRun = true;
  346. if (firstRun) {
  347. firstRun = false;
  348. int result = RUN_ALL_TESTS();
  349. // RUN_ALL_TESTS by default doesn't want you to ignore its result, but it's
  350. // safe here. Test failures are already logged by GoogleTest itself (and
  351. // then again by XCTest). Test failures are reported via
  352. // -recordFailureWithDescription:inFile:atLine:expected: which then causes
  353. // XCTest itself to fail the run.
  354. (void)result;
  355. }
  356. }
  357. } // namespace
  358. @implementation GoogleTests
  359. + (XCTestSuite*)defaultTestSuite {
  360. // Only return all tests beyond GoogleTests if the user is focusing on
  361. // GoogleTests.
  362. if (forceAllTests) {
  363. return CreateAllTestsTestSuite();
  364. } else {
  365. // just run the tests that are a part of this class
  366. return [XCTestSuite testSuiteForTestCaseClass:[self class]];
  367. }
  368. }
  369. - (void)testGoogleTestsActuallyRun {
  370. // This whole mechanism is sufficiently tricky that we should verify that the
  371. // build actually plumbed this together correctly.
  372. const testing::UnitTest* master = testing::UnitTest::GetInstance();
  373. XCTAssertGreaterThan(master->total_test_case_count(), 0);
  374. }
  375. @end
  376. /**
  377. * This class is registered as the NSPrincipalClass in the Firestore_Tests
  378. * bundle's Info.plist. XCTest instantiates this class to perform one-time setup
  379. * for the test bundle, as documented here:
  380. *
  381. * https://developer.apple.com/documentation/xctest/xctestobservationcenter
  382. */
  383. @interface FSTGoogleTestsPrincipal : NSObject
  384. @end
  385. @implementation FSTGoogleTestsPrincipal
  386. - (instancetype)init {
  387. self = [super init];
  388. CreateGoogleTestTests();
  389. return self;
  390. }
  391. @end