RCNRemoteConfigTest.m 96 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998
  1. /*
  2. * Copyright 2019 Google
  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 <OCMock/OCMStubRecorder.h>
  17. #import <OCMock/OCMock.h>
  18. #import <XCTest/XCTest.h>
  19. #import "FirebaseRemoteConfig/Sources/FIRRemoteConfigComponent.h"
  20. #import "FirebaseRemoteConfig/Sources/Private/FIRRemoteConfig_Private.h"
  21. #import "FirebaseRemoteConfig/Sources/Private/RCNConfigFetch.h"
  22. #import "FirebaseRemoteConfig/Sources/Public/FirebaseRemoteConfig/FIRRemoteConfig.h"
  23. #import "FirebaseRemoteConfig/Sources/RCNConfigConstants.h"
  24. #import "FirebaseRemoteConfig/Sources/RCNConfigDBManager.h"
  25. #import "FirebaseRemoteConfig/Sources/RCNConfigExperiment.h"
  26. #import "FirebaseRemoteConfig/Sources/RCNConfigRealtime.h"
  27. #import "FirebaseRemoteConfig/Sources/RCNUserDefaultsManager.h"
  28. #import "FirebaseRemoteConfig/Tests/Unit/RCNTestUtilities.h"
  29. #import <GoogleUtilities/GULNSData+zlib.h>
  30. #import "FirebaseCore/Extension/FirebaseCoreInternal.h"
  31. @import FirebaseRemoteConfigInterop;
  32. @protocol FIRRolloutsStateSubscriber;
  33. @interface RCNConfigFetch (ForTest)
  34. - (instancetype)initWithContent:(RCNConfigContent *)content
  35. DBManager:(RCNConfigDBManager *)DBManager
  36. settings:(RCNConfigSettings *)settings
  37. experiment:(RCNConfigExperiment *)experiment
  38. queue:(dispatch_queue_t)queue
  39. namespace:firebaseNamespace
  40. app:firebaseApp;
  41. /// Skip fetching user properties from analytics because we cannot mock the action here. Instead
  42. /// overriding the method to skip.
  43. - (void)fetchWithUserPropertiesCompletionHandler:(NSString *)fetchTypeHeader
  44. completionHandler:(FIRAInteropUserPropertiesCallback)block;
  45. - (NSURLSessionDataTask *)URLSessionDataTaskWithContent:(NSData *)content
  46. fetchTypeHeader:(NSString *)fetchTypeHeader
  47. completionHandler:
  48. (RCNConfigFetcherCompletion)fetcherCompletion;
  49. - (void)fetchConfigWithExpirationDuration:(NSTimeInterval)expirationDuration
  50. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler;
  51. - (void)realtimeFetchConfigWithNoExpirationDuration:(NSInteger)fetchAttemptNumber
  52. completionHandler:(RCNConfigFetchCompletion)completionHandler;
  53. - (void)fetchWithUserProperties:(NSDictionary *)userProperties
  54. fetchTypeHeader:(NSString *)fetchTypeHeader
  55. completionHandler:(FIRRemoteConfigFetchCompletion)completionHandler
  56. updateCompletionHandler:(RCNConfigFetchCompletion)updateCompletionHandler;
  57. - (NSString *)constructServerURL;
  58. - (NSURLSession *)currentNetworkSession;
  59. @end
  60. @interface RCNConfigRealtime (ForTest)
  61. - (instancetype _Nonnull)init:(RCNConfigFetch *_Nonnull)configFetch
  62. settings:(RCNConfigSettings *_Nonnull)settings
  63. namespace:(NSString *_Nonnull)namespace
  64. options:(FIROptions *_Nonnull)options;
  65. - (void)fetchLatestConfig:(NSInteger)remainingAttempts targetVersion:(NSInteger)targetVersion;
  66. - (void)scheduleFetch:(NSInteger)remainingAttempts targetVersion:(NSInteger)targetVersion;
  67. - (void)autoFetch:(NSInteger)remainingAttempts targetVersion:(NSInteger)targetVersion;
  68. - (void)beginRealtimeStream;
  69. - (void)pauseRealtimeStream;
  70. - (void)createRequestBodyWithCompletion:(void (^)(NSData *_Nonnull requestBody))completion;
  71. - (FIRConfigUpdateListenerRegistration *_Nonnull)addConfigUpdateListener:
  72. (RCNConfigUpdateCompletion _Nonnull)listener;
  73. - (void)removeConfigUpdateListener:(RCNConfigUpdateCompletion _Nonnull)listener;
  74. - (void)evaluateStreamResponse:(NSDictionary *)response error:(NSError *)dataError;
  75. @end
  76. @interface FIRRemoteConfig (ForTest)
  77. - (void)updateWithNewInstancesForConfigFetch:(RCNConfigFetch *)configFetch
  78. configContent:(RCNConfigContent *)configContent
  79. configSettings:(RCNConfigSettings *)configSettings
  80. configExperiment:(RCNConfigExperiment *)configExperiment;
  81. - (void)updateWithNewInstancesForConfigRealtime:(RCNConfigRealtime *)configRealtime;
  82. @end
  83. @implementation FIRRemoteConfig (ForTest)
  84. - (void)updateWithNewInstancesForConfigFetch:(RCNConfigFetch *)configFetch
  85. configContent:(RCNConfigContent *)configContent
  86. configSettings:(RCNConfigSettings *)configSettings
  87. configExperiment:(RCNConfigExperiment *)configExperiment {
  88. [self setValue:configFetch forKey:@"_configFetch"];
  89. [self setValue:configContent forKey:@"_configContent"];
  90. [self setValue:configSettings forKey:@"_settings"];
  91. [self setValue:configExperiment forKey:@"_configExperiment"];
  92. }
  93. - (void)updateWithNewInstancesForConfigRealtime:(RCNConfigRealtime *)configRealtime {
  94. [self setValue:configRealtime forKey:@"_configRealtime"];
  95. }
  96. @end
  97. @interface RCNConfigDBManager (Test)
  98. - (void)removeDatabaseOnDatabaseQueueAtPath:(NSString *)path;
  99. @end
  100. @interface RCNUserDefaultsManager (Test)
  101. + (NSUserDefaults *)sharedUserDefaultsForBundleIdentifier:(NSString *)bundleIdentifier;
  102. @end
  103. @interface RCNConfigSettings (Test)
  104. - (NSString *)nextRequestWithUserProperties:(NSDictionary *)userProperties;
  105. @end
  106. typedef NS_ENUM(NSInteger, RCNTestRCInstance) {
  107. RCNTestRCInstanceDefault,
  108. RCNTestRCInstanceSecondNamespace,
  109. RCNTestRCInstanceSecondApp,
  110. RCNTestRCNumTotalInstances
  111. };
  112. @interface RCNRemoteConfigTest : XCTestCase {
  113. NSTimeInterval _expectationTimeout;
  114. NSTimeInterval _checkCompletionTimeout;
  115. NSMutableArray<FIRRemoteConfig *> *_configInstances;
  116. NSMutableArray<NSDictionary<NSString *, NSString *> *> *_entries;
  117. NSArray<NSDictionary *> *_rolloutMetadata;
  118. NSMutableArray<NSDictionary<NSString *, id> *> *_response;
  119. NSMutableArray<NSData *> *_responseData;
  120. NSMutableArray<NSURLResponse *> *_URLResponse;
  121. NSMutableArray<id> *_configFetch;
  122. NSMutableArray<id> *_configRealtime;
  123. RCNConfigDBManager *_DBManager;
  124. NSUserDefaults *_userDefaults;
  125. NSString *_userDefaultsSuiteName;
  126. NSString *_DBPath;
  127. id _DBManagerMock;
  128. id _experimentMock;
  129. id _userDefaultsMock;
  130. NSString *_fullyQualifiedNamespace;
  131. RCNConfigSettings *_settings;
  132. dispatch_queue_t _queue;
  133. NSString *_namespaceGoogleMobilePlatform;
  134. }
  135. @end
  136. @implementation RCNRemoteConfigTest
  137. - (void)setUp {
  138. [super setUp];
  139. FIRSetLoggerLevel(FIRLoggerLevelMax);
  140. _expectationTimeout = 5;
  141. _checkCompletionTimeout = 1.0;
  142. // Always remove the database at the start of testing.
  143. _DBPath = [RCNTestUtilities remoteConfigPathForTestDatabase];
  144. _DBManagerMock = OCMClassMock([RCNConfigDBManager class]);
  145. OCMStub([_DBManagerMock remoteConfigPathForDatabase]).andReturn(_DBPath);
  146. _DBManager = [[RCNConfigDBManager alloc] init];
  147. _userDefaultsSuiteName = [RCNTestUtilities userDefaultsSuiteNameForTestSuite];
  148. _userDefaults = [[NSUserDefaults alloc] initWithSuiteName:_userDefaultsSuiteName];
  149. _userDefaultsMock = OCMClassMock([RCNUserDefaultsManager class]);
  150. OCMStub([_userDefaultsMock sharedUserDefaultsForBundleIdentifier:[OCMArg any]])
  151. .andReturn(_userDefaults);
  152. _experimentMock = OCMClassMock([RCNConfigExperiment class]);
  153. OCMStub([_experimentMock
  154. updateExperimentsWithHandler:([OCMArg invokeBlockWithArgs:[NSNull null], nil])]);
  155. RCNConfigContent *configContent = [[RCNConfigContent alloc] initWithDBManager:_DBManager];
  156. _configInstances = [[NSMutableArray alloc] initWithCapacity:3];
  157. _entries = [[NSMutableArray alloc] initWithCapacity:3];
  158. _response = [[NSMutableArray alloc] initWithCapacity:3];
  159. _responseData = [[NSMutableArray alloc] initWithCapacity:3];
  160. _URLResponse = [[NSMutableArray alloc] initWithCapacity:3];
  161. _configFetch = [[NSMutableArray alloc] initWithCapacity:3];
  162. _configRealtime = [[NSMutableArray alloc] initWithCapacity:3];
  163. _namespaceGoogleMobilePlatform = FIRRemoteConfigConstants.FIRNamespaceGoogleMobilePlatform;
  164. // Populate the default, second app, second namespace instances.
  165. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  166. // Fake a response for default instance.
  167. NSMutableDictionary<NSString *, NSString *> *valuesDict = [[NSMutableDictionary alloc] init];
  168. for (int count = 1; count <= 100; count++) {
  169. NSString *key = [NSString stringWithFormat:@"key%d-%d", count, i];
  170. NSString *value = [NSString stringWithFormat:@"value%d-%d", count, i];
  171. valuesDict[key] = value;
  172. }
  173. _entries[i] = valuesDict;
  174. NSString *currentAppName = nil;
  175. FIROptions *currentOptions = nil;
  176. NSString *currentNamespace = nil;
  177. switch (i) {
  178. case RCNTestRCInstanceSecondNamespace:
  179. currentAppName = RCNTestsDefaultFIRAppName;
  180. currentOptions = [self firstAppOptions];
  181. currentNamespace = RCNTestsPerfNamespace;
  182. break;
  183. case RCNTestRCInstanceSecondApp:
  184. currentAppName = RCNTestsSecondFIRAppName;
  185. currentOptions = [self secondAppOptions];
  186. currentNamespace = _namespaceGoogleMobilePlatform;
  187. break;
  188. case RCNTestRCInstanceDefault:
  189. default:
  190. currentAppName = RCNTestsDefaultFIRAppName;
  191. currentOptions = [self firstAppOptions];
  192. currentNamespace = RCNTestsFIRNamespace;
  193. break;
  194. }
  195. _fullyQualifiedNamespace =
  196. [NSString stringWithFormat:@"%@:%@", currentNamespace, currentAppName];
  197. FIRRemoteConfig *config =
  198. OCMPartialMock([[FIRRemoteConfig alloc] initWithAppName:currentAppName
  199. FIROptions:currentOptions
  200. namespace:currentNamespace
  201. DBManager:_DBManager
  202. configContent:configContent
  203. analytics:nil]);
  204. _configInstances[i] = config;
  205. _settings = [[RCNConfigSettings alloc] initWithDatabaseManager:_DBManager
  206. namespace:_fullyQualifiedNamespace
  207. firebaseAppName:currentAppName
  208. googleAppID:currentOptions.googleAppID];
  209. _queue = dispatch_queue_create(
  210. [[NSString stringWithFormat:@"testqueue: %d", i] cStringUsingEncoding:NSUTF8StringEncoding],
  211. DISPATCH_QUEUE_SERIAL);
  212. _configFetch[i] =
  213. OCMPartialMock([[RCNConfigFetch alloc] initWithContent:configContent
  214. DBManager:_DBManager
  215. settings:_settings
  216. analytics:nil
  217. experiment:_experimentMock
  218. queue:_queue
  219. namespace:_fullyQualifiedNamespace
  220. options:currentOptions]);
  221. _configRealtime[i] = OCMPartialMock([[RCNConfigRealtime alloc] init:_configFetch[i]
  222. settings:_settings
  223. namespace:_fullyQualifiedNamespace
  224. options:currentOptions]);
  225. _settings.configInstallationsIdentifier = @"iid";
  226. OCMStubRecorder *mock = OCMStub([_configFetch[i] fetchConfigWithExpirationDuration:0
  227. completionHandler:OCMOCK_ANY]);
  228. mock = [mock ignoringNonObjectArgs];
  229. mock.andDo(^(NSInvocation *invocation) {
  230. __unsafe_unretained void (^handler)(FIRRemoteConfigFetchStatus status,
  231. NSError *_Nullable error) = nil;
  232. [invocation getArgument:&handler atIndex:3];
  233. [self->_configFetch[i] fetchWithUserProperties:[[NSDictionary alloc] init]
  234. fetchTypeHeader:@"Base/1"
  235. completionHandler:handler
  236. updateCompletionHandler:nil];
  237. });
  238. _rolloutMetadata = @[ @{
  239. RCNFetchResponseKeyRolloutID : @"1",
  240. RCNFetchResponseKeyVariantID : @"0",
  241. RCNFetchResponseKeyAffectedParameterKeys : @[ _entries[i].allKeys[0] ]
  242. } ];
  243. _response[i] = @{
  244. @"state" : @"UPDATE",
  245. @"entries" : _entries[i],
  246. RCNFetchResponseKeyRolloutMetadata : _rolloutMetadata
  247. };
  248. _responseData[i] = [NSJSONSerialization dataWithJSONObject:_response[i] options:0 error:nil];
  249. _URLResponse[i] = [[NSHTTPURLResponse alloc]
  250. initWithURL:[NSURL URLWithString:@"https://firebase.com"]
  251. statusCode:200
  252. HTTPVersion:nil
  253. headerFields:@{@"etag" : [NSString stringWithFormat:@"etag1-%d", i]}];
  254. id completionBlock =
  255. [OCMArg invokeBlockWithArgs:_responseData[i], _URLResponse[i], [NSNull null], nil];
  256. OCMStub([_configFetch[i] URLSessionDataTaskWithContent:[OCMArg any]
  257. fetchTypeHeader:[OCMArg any]
  258. completionHandler:completionBlock])
  259. .andReturn(nil);
  260. [_configInstances[i] updateWithNewInstancesForConfigFetch:_configFetch[i]
  261. configContent:configContent
  262. configSettings:_settings
  263. configExperiment:_experimentMock];
  264. [_configInstances[i] updateWithNewInstancesForConfigRealtime:_configRealtime[i]];
  265. }
  266. }
  267. - (void)tearDown {
  268. [_DBManager removeDatabaseOnDatabaseQueueAtPath:_DBPath];
  269. [FIRRemoteConfigComponent clearAllComponentInstances];
  270. [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:_userDefaultsSuiteName];
  271. [_DBManagerMock stopMocking];
  272. _DBManagerMock = nil;
  273. [_userDefaultsMock stopMocking];
  274. _userDefaultsMock = nil;
  275. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  276. [(id)_configInstances[i] stopMocking];
  277. [(id)_configFetch[i] stopMocking];
  278. }
  279. [_configInstances removeAllObjects];
  280. [_configFetch removeAllObjects];
  281. [_configRealtime removeAllObjects];
  282. _configInstances = nil;
  283. _configFetch = nil;
  284. [super tearDown];
  285. }
  286. - (void)testFetchConfigWithNilCallback {
  287. NSMutableArray<XCTestExpectation *> *expectations =
  288. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  289. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  290. expectations[i] = [self
  291. expectationWithDescription:
  292. [NSString stringWithFormat:@"Set defaults no callback expectation - instance %d", i]];
  293. XCTAssertEqual(_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusNoFetchYet);
  294. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:nil];
  295. dispatch_after(
  296. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  297. dispatch_get_main_queue(), ^{
  298. XCTAssertEqual(self->_configInstances[i].lastFetchStatus,
  299. FIRRemoteConfigFetchStatusSuccess);
  300. [expectations[i] fulfill];
  301. });
  302. }
  303. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  304. }
  305. - (void)testFetchConfigsSuccessfully {
  306. NSMutableArray<XCTestExpectation *> *expectations =
  307. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  308. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  309. expectations[i] =
  310. [self expectationWithDescription:
  311. [NSString stringWithFormat:@"Test fetch configs successfully - instance %d", i]];
  312. XCTAssertEqual(_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusNoFetchYet);
  313. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  314. NSError *error) {
  315. XCTAssertEqual(self->_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusSuccess);
  316. XCTAssertNil(error);
  317. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  318. XCTAssertTrue(changed);
  319. NSString *key1 = [NSString stringWithFormat:@"key1-%d", i];
  320. NSString *key2 = [NSString stringWithFormat:@"key2-%d", i];
  321. NSString *value1 = [NSString stringWithFormat:@"value1-%d", i];
  322. NSString *value2 = [NSString stringWithFormat:@"value2-%d", i];
  323. XCTAssertEqualObjects(self->_configInstances[i][key1].stringValue, value1);
  324. XCTAssertEqualObjects(self->_configInstances[i][key2].stringValue, value2);
  325. OCMVerify([self->_configInstances[i] objectForKeyedSubscript:key1]);
  326. XCTAssertEqual(status, FIRRemoteConfigFetchStatusSuccess,
  327. @"Callback of first successful config "
  328. @"fetch. Status must equal to FIRRemoteConfigFetchStatusSuccessFresh.");
  329. XCTAssertNotNil(self->_configInstances[i].lastFetchTime);
  330. XCTAssertGreaterThan(self->_configInstances[i].lastFetchTime.timeIntervalSince1970, 0,
  331. @"last fetch time interval should be set.");
  332. [expectations[i] fulfill];
  333. }];
  334. };
  335. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  336. }
  337. [self waitForExpectationsWithTimeout:_expectationTimeout
  338. handler:^(NSError *error) {
  339. XCTAssertNil(error);
  340. }];
  341. }
  342. - (void)testFetchAndActivate {
  343. NSMutableArray<XCTestExpectation *> *expectations =
  344. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  345. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  346. expectations[i] =
  347. [self expectationWithDescription:
  348. [NSString stringWithFormat:@"Test fetch configs successfully - instance %d", i]];
  349. XCTAssertEqual(_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusNoFetchYet);
  350. FIRRemoteConfigFetchAndActivateCompletion fetchAndActivateCompletion = ^void(
  351. FIRRemoteConfigFetchAndActivateStatus status, NSError *error) {
  352. XCTAssertEqual(self->_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusSuccess);
  353. XCTAssertNil(error);
  354. NSString *key1 = [NSString stringWithFormat:@"key1-%d", i];
  355. NSString *key2 = [NSString stringWithFormat:@"key2-%d", i];
  356. NSString *value1 = [NSString stringWithFormat:@"value1-%d", i];
  357. NSString *value2 = [NSString stringWithFormat:@"value2-%d", i];
  358. XCTAssertEqualObjects(self->_configInstances[i][key1].stringValue, value1);
  359. XCTAssertEqualObjects(self->_configInstances[i][key2].stringValue, value2);
  360. OCMVerify([self->_configInstances[i] objectForKeyedSubscript:key1]);
  361. XCTAssertEqual(
  362. status, FIRRemoteConfigFetchAndActivateStatusSuccessFetchedFromRemote,
  363. @"Callback of first successful config "
  364. @"fetchAndActivate status must equal to FIRRemoteConfigFetchAndStatusSuccessFromRemote.");
  365. XCTAssertNotNil(self->_configInstances[i].lastFetchTime);
  366. XCTAssertGreaterThan(self->_configInstances[i].lastFetchTime.timeIntervalSince1970, 0,
  367. @"last fetch time interval should be set.");
  368. [expectations[i] fulfill];
  369. };
  370. // Update the minimum fetch interval to 0. This disables the cache and forces a remote fetch
  371. // request.
  372. FIRRemoteConfigSettings *settings = [[FIRRemoteConfigSettings alloc] init];
  373. settings.minimumFetchInterval = 0;
  374. [_configInstances[i] setConfigSettings:settings];
  375. [_configInstances[i] fetchAndActivateWithCompletionHandler:fetchAndActivateCompletion];
  376. }
  377. [self waitForExpectationsWithTimeout:_expectationTimeout
  378. handler:^(NSError *error) {
  379. XCTAssertNil(error);
  380. }];
  381. }
  382. // TODO: Try splitting into smaller tests.
  383. - (void)testFetchConfigsSuccessfullyWithNewActivateMethodSignature {
  384. NSMutableArray<XCTestExpectation *> *expectations =
  385. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  386. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  387. expectations[i] =
  388. [self expectationWithDescription:
  389. [NSString stringWithFormat:@"Test fetch configs successfully - instance %d", i]];
  390. XCTAssertEqual(_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusNoFetchYet);
  391. FIRRemoteConfigFetchCompletion fetchCompletion = ^(FIRRemoteConfigFetchStatus status,
  392. NSError *error) {
  393. XCTAssertEqual(self->_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusSuccess);
  394. XCTAssertNil(error);
  395. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  396. XCTAssertTrue(changed);
  397. XCTAssertNil(error);
  398. NSString *key1 = [NSString stringWithFormat:@"key1-%d", i];
  399. NSString *key2 = [NSString stringWithFormat:@"key2-%d", i];
  400. NSString *value1 = [NSString stringWithFormat:@"value1-%d", i];
  401. NSString *value2 = [NSString stringWithFormat:@"value2-%d", i];
  402. XCTAssertEqualObjects(self->_configInstances[i][key1].stringValue, value1);
  403. XCTAssertEqualObjects(self->_configInstances[i][key2].stringValue, value2);
  404. OCMVerify([self->_configInstances[i] objectForKeyedSubscript:key1]);
  405. XCTAssertEqual(status, FIRRemoteConfigFetchStatusSuccess,
  406. @"Callback of first successful config "
  407. @"fetch. Status must equal to FIRRemoteConfigFetchStatusSuccessFresh.");
  408. XCTAssertNotNil(self->_configInstances[i].lastFetchTime);
  409. XCTAssertGreaterThan(self->_configInstances[i].lastFetchTime.timeIntervalSince1970, 0,
  410. @"last fetch time interval should be set.");
  411. // A second activate should have no effect.
  412. [self->_configInstances[i]
  413. activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  414. XCTAssertFalse(changed);
  415. XCTAssertNil(error);
  416. }];
  417. [expectations[i] fulfill];
  418. }];
  419. };
  420. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  421. }
  422. [self waitForExpectationsWithTimeout:_expectationTimeout
  423. handler:^(NSError *error) {
  424. XCTAssertNil(error);
  425. }];
  426. }
  427. - (void)testEnumeratingConfigResults {
  428. NSMutableArray<XCTestExpectation *> *expectations =
  429. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  430. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  431. expectations[i] = [self
  432. expectationWithDescription:
  433. [NSString stringWithFormat:@"Test enumerating configs successfully - instance %d", i]];
  434. XCTAssertEqual(_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusNoFetchYet);
  435. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  436. NSError *error) {
  437. XCTAssertEqual(self->_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusSuccess);
  438. XCTAssertNil(error);
  439. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  440. XCTAssertTrue(changed);
  441. NSString *key5 = [NSString stringWithFormat:@"key5-%d", i];
  442. NSString *key19 = [NSString stringWithFormat:@"key19-%d", i];
  443. NSString *value5 = [NSString stringWithFormat:@"value5-%d", i];
  444. NSString *value19 = [NSString stringWithFormat:@"value19-%d", i];
  445. XCTAssertEqualObjects(self->_configInstances[i][key5].stringValue, value5);
  446. XCTAssertEqualObjects(self->_configInstances[i][key19].stringValue, value19);
  447. // Test enumerating config values.
  448. for (NSString *key in self->_configInstances[i]) {
  449. if ([key isEqualToString:key5]) {
  450. XCTAssertEqualObjects(self->_configInstances[i][key5].stringValue, value5);
  451. }
  452. if ([key isEqualToString:key19]) {
  453. XCTAssertEqualObjects(self->_configInstances[i][key19].stringValue, value19);
  454. }
  455. }
  456. XCTAssertEqual(status, FIRRemoteConfigFetchStatusSuccess,
  457. @"Callback of first successful config "
  458. @"fetch. Status must equal to FIRRemoteConfigFetchStatusSuccessFresh.");
  459. XCTAssertNotNil(self->_configInstances[i].lastFetchTime);
  460. XCTAssertGreaterThan(self->_configInstances[i].lastFetchTime.timeIntervalSince1970, 0,
  461. @"last fetch time interval should be set.");
  462. [expectations[i] fulfill];
  463. }];
  464. };
  465. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  466. }
  467. [self waitForExpectationsWithTimeout:_expectationTimeout
  468. handler:^(NSError *error) {
  469. XCTAssertNil(error);
  470. }];
  471. }
  472. - (void)testFetchAndActivate3pNamespaceUpdatesExperiments {
  473. [[_experimentMock expect] updateExperimentsWithResponse:[OCMArg any]];
  474. XCTestExpectation *expectation = [self
  475. expectationWithDescription:[NSString stringWithFormat:@"FetchAndActivate call for 'firebase' "
  476. @"namespace updates experiment data"]];
  477. XCTAssertEqual(_configInstances[RCNTestRCInstanceDefault].lastFetchStatus,
  478. FIRRemoteConfigFetchStatusNoFetchYet);
  479. FIRRemoteConfigFetchAndActivateCompletion fetchAndActivateCompletion =
  480. ^void(FIRRemoteConfigFetchAndActivateStatus status, NSError *error) {
  481. XCTAssertEqual(status, FIRRemoteConfigFetchAndActivateStatusSuccessFetchedFromRemote);
  482. XCTAssertNil(error);
  483. XCTAssertEqual(self->_configInstances[RCNTestRCInstanceDefault].lastFetchStatus,
  484. FIRRemoteConfigFetchStatusSuccess);
  485. XCTAssertNotNil(self->_configInstances[RCNTestRCInstanceDefault].lastFetchTime);
  486. XCTAssertGreaterThan(
  487. self->_configInstances[RCNTestRCInstanceDefault].lastFetchTime.timeIntervalSince1970, 0,
  488. @"last fetch time interval should be set.");
  489. [expectation fulfill];
  490. };
  491. [_configInstances[RCNTestRCInstanceDefault]
  492. fetchAndActivateWithCompletionHandler:fetchAndActivateCompletion];
  493. [self waitForExpectationsWithTimeout:_expectationTimeout
  494. handler:^(NSError *error) {
  495. XCTAssertNil(error);
  496. }];
  497. }
  498. - (void)testFetchAndActivateOtherNamespaceDoesntUpdateExperiments {
  499. [[_experimentMock reject] updateExperimentsWithResponse:[OCMArg any]];
  500. XCTestExpectation *expectation = [self
  501. expectationWithDescription:
  502. [NSString stringWithFormat:@"FetchAndActivate call for namespace other than 'firebase' "
  503. @"doesn't update experiment data"]];
  504. XCTAssertEqual(_configInstances[RCNTestRCInstanceSecondNamespace].lastFetchStatus,
  505. FIRRemoteConfigFetchStatusNoFetchYet);
  506. FIRRemoteConfigFetchAndActivateCompletion fetchAndActivateCompletion =
  507. ^void(FIRRemoteConfigFetchAndActivateStatus status, NSError *error) {
  508. XCTAssertEqual(status, FIRRemoteConfigFetchAndActivateStatusSuccessFetchedFromRemote);
  509. XCTAssertNil(error);
  510. XCTAssertEqual(self->_configInstances[RCNTestRCInstanceSecondNamespace].lastFetchStatus,
  511. FIRRemoteConfigFetchStatusSuccess);
  512. XCTAssertNotNil(self->_configInstances[RCNTestRCInstanceSecondNamespace].lastFetchTime);
  513. XCTAssertGreaterThan(self->_configInstances[RCNTestRCInstanceSecondNamespace]
  514. .lastFetchTime.timeIntervalSince1970,
  515. 0, @"last fetch time interval should be set.");
  516. [expectation fulfill];
  517. };
  518. [_configInstances[RCNTestRCInstanceSecondNamespace]
  519. fetchAndActivateWithCompletionHandler:fetchAndActivateCompletion];
  520. [self waitForExpectationsWithTimeout:_expectationTimeout
  521. handler:^(NSError *error) {
  522. XCTAssertNil(error);
  523. }];
  524. }
  525. - (void)testFetchConfigsFailed {
  526. // Override the setup values to return back an error status.
  527. RCNConfigContent *configContent = [[RCNConfigContent alloc] initWithDBManager:_DBManager];
  528. // Populate the default, second app, second namespace instances.
  529. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  530. NSString *currentAppName = nil;
  531. FIROptions *currentOptions = nil;
  532. NSString *currentNamespace = nil;
  533. switch (i) {
  534. case RCNTestRCInstanceSecondNamespace:
  535. currentAppName = RCNTestsDefaultFIRAppName;
  536. currentOptions = [self firstAppOptions];
  537. currentNamespace = RCNTestsPerfNamespace;
  538. break;
  539. case RCNTestRCInstanceSecondApp:
  540. currentAppName = RCNTestsSecondFIRAppName;
  541. currentOptions = [self secondAppOptions];
  542. currentNamespace = _namespaceGoogleMobilePlatform;
  543. break;
  544. case RCNTestRCInstanceDefault:
  545. default:
  546. currentAppName = RCNTestsDefaultFIRAppName;
  547. currentOptions = [self firstAppOptions];
  548. currentNamespace = RCNTestsFIRNamespace;
  549. break;
  550. }
  551. RCNUserDefaultsManager *userDefaultsManager =
  552. [[RCNUserDefaultsManager alloc] initWithAppName:currentAppName
  553. bundleID:[NSBundle mainBundle].bundleIdentifier
  554. namespace:_fullyQualifiedNamespace];
  555. userDefaultsManager.lastFetchTime = 0;
  556. FIRRemoteConfig *config =
  557. OCMPartialMock([[FIRRemoteConfig alloc] initWithAppName:currentAppName
  558. FIROptions:currentOptions
  559. namespace:currentNamespace
  560. DBManager:_DBManager
  561. configContent:configContent
  562. analytics:nil]);
  563. _configInstances[i] = config;
  564. _configFetch[i] =
  565. OCMPartialMock([[RCNConfigFetch alloc] initWithContent:configContent
  566. DBManager:_DBManager
  567. settings:_settings
  568. analytics:nil
  569. experiment:nil
  570. queue:_queue
  571. namespace:_fullyQualifiedNamespace
  572. options:currentOptions]);
  573. _configRealtime[i] = OCMPartialMock([[RCNConfigRealtime alloc] init:_configFetch[i]
  574. settings:_settings
  575. namespace:_fullyQualifiedNamespace
  576. options:currentOptions]);
  577. OCMStub([_configFetch[i] fetchConfigWithExpirationDuration:43200 completionHandler:OCMOCK_ANY])
  578. .andDo(^(NSInvocation *invocation) {
  579. __unsafe_unretained void (^handler)(FIRRemoteConfigFetchStatus status,
  580. NSError *_Nullable error) = nil;
  581. [invocation getArgument:&handler atIndex:3];
  582. [self->_configFetch[i] fetchWithUserProperties:[[NSDictionary alloc] init]
  583. fetchTypeHeader:@"Base/1"
  584. completionHandler:handler
  585. updateCompletionHandler:nil];
  586. });
  587. _response[i] = @{};
  588. _responseData[i] = [NSJSONSerialization dataWithJSONObject:_response[i] options:0 error:nil];
  589. _URLResponse[i] =
  590. [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"https://firebase.com"]
  591. statusCode:500
  592. HTTPVersion:nil
  593. headerFields:@{@"etag" : @"etag1"}];
  594. [_configInstances[i] updateWithNewInstancesForConfigFetch:_configFetch[i]
  595. configContent:configContent
  596. configSettings:_settings
  597. configExperiment:nil];
  598. }
  599. // Make the fetch calls for all instances.
  600. NSMutableArray<XCTestExpectation *> *expectations =
  601. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  602. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  603. expectations[i] = [self
  604. expectationWithDescription:
  605. [NSString stringWithFormat:@"Test enumerating configs successfully - instance %d", i]];
  606. XCTAssertEqual(_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusNoFetchYet);
  607. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  608. NSError *error) {
  609. XCTAssertEqual(self->_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusFailure);
  610. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  611. XCTAssertFalse(changed);
  612. XCTAssertNil(error);
  613. FIRRemoteConfigValue *value = self->_configInstances[RCNTestRCInstanceDefault][@"key1"];
  614. XCTAssertEqual((int)value.source, (int)FIRRemoteConfigSourceStatic);
  615. XCTAssertEqualObjects(value.stringValue, @"");
  616. XCTAssertEqual(value.boolValue, NO);
  617. [expectations[i] fulfill];
  618. }];
  619. };
  620. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  621. }
  622. [self waitForExpectationsWithTimeout:_expectationTimeout
  623. handler:^(NSError *error) {
  624. XCTAssertNil(error);
  625. }];
  626. }
  627. // TODO(mandard): Break up test with helper methods.
  628. - (void)testFetchConfigsFailedErrorNoNetwork {
  629. // Override the setup values to return back an error status.
  630. RCNConfigContent *configContent = [[RCNConfigContent alloc] initWithDBManager:_DBManager];
  631. // Populate the default, second app, second namespace instances.
  632. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  633. NSString *currentAppName = nil;
  634. FIROptions *currentOptions = nil;
  635. NSString *currentNamespace = nil;
  636. switch (i) {
  637. case RCNTestRCInstanceSecondNamespace:
  638. currentAppName = RCNTestsDefaultFIRAppName;
  639. currentOptions = [self firstAppOptions];
  640. currentNamespace = RCNTestsPerfNamespace;
  641. break;
  642. case RCNTestRCInstanceSecondApp:
  643. currentAppName = RCNTestsSecondFIRAppName;
  644. currentOptions = [self secondAppOptions];
  645. currentNamespace = _namespaceGoogleMobilePlatform;
  646. break;
  647. case RCNTestRCInstanceDefault:
  648. default:
  649. currentAppName = RCNTestsDefaultFIRAppName;
  650. currentOptions = [self firstAppOptions];
  651. currentNamespace = RCNTestsFIRNamespace;
  652. break;
  653. }
  654. NSString *fullyQualifiedNamespace =
  655. [NSString stringWithFormat:@"%@:%@", currentNamespace, currentAppName];
  656. RCNUserDefaultsManager *userDefaultsManager =
  657. [[RCNUserDefaultsManager alloc] initWithAppName:currentAppName
  658. bundleID:[NSBundle mainBundle].bundleIdentifier
  659. namespace:fullyQualifiedNamespace];
  660. userDefaultsManager.lastFetchTime = 0;
  661. FIRRemoteConfig *config =
  662. OCMPartialMock([[FIRRemoteConfig alloc] initWithAppName:currentAppName
  663. FIROptions:currentOptions
  664. namespace:currentNamespace
  665. DBManager:_DBManager
  666. configContent:configContent
  667. analytics:nil]);
  668. _configInstances[i] = config;
  669. RCNConfigSettings *settings =
  670. [[RCNConfigSettings alloc] initWithDatabaseManager:_DBManager
  671. namespace:fullyQualifiedNamespace
  672. firebaseAppName:currentAppName
  673. googleAppID:currentOptions.googleAppID];
  674. dispatch_queue_t queue = dispatch_queue_create(
  675. [[NSString stringWithFormat:@"testqueue: %d", i] cStringUsingEncoding:NSUTF8StringEncoding],
  676. DISPATCH_QUEUE_SERIAL);
  677. _configFetch[i] = OCMPartialMock([[RCNConfigFetch alloc] initWithContent:configContent
  678. DBManager:_DBManager
  679. settings:settings
  680. analytics:nil
  681. experiment:nil
  682. queue:queue
  683. namespace:fullyQualifiedNamespace
  684. options:currentOptions]);
  685. _configRealtime[i] = OCMPartialMock([[RCNConfigRealtime alloc] init:_configFetch[i]
  686. settings:settings
  687. namespace:fullyQualifiedNamespace
  688. options:currentOptions]);
  689. OCMStub([_configFetch[i] fetchConfigWithExpirationDuration:43200 completionHandler:OCMOCK_ANY])
  690. .andDo(^(NSInvocation *invocation) {
  691. __unsafe_unretained void (^handler)(FIRRemoteConfigFetchStatus status,
  692. NSError *_Nullable error) = nil;
  693. [invocation getArgument:&handler atIndex:3];
  694. [self->_configFetch[i] fetchWithUserProperties:[[NSDictionary alloc] init]
  695. fetchTypeHeader:@"Base/1"
  696. completionHandler:handler
  697. updateCompletionHandler:nil];
  698. });
  699. _response[i] = @{};
  700. _responseData[i] = [NSJSONSerialization dataWithJSONObject:_response[i] options:0 error:nil];
  701. // A no network error is accompanied with an HTTP status code of 0.
  702. _URLResponse[i] =
  703. [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"https://firebase.com"]
  704. statusCode:0
  705. HTTPVersion:nil
  706. headerFields:@{@"etag" : @"etag1"}];
  707. [_configInstances[i] updateWithNewInstancesForConfigFetch:_configFetch[i]
  708. configContent:configContent
  709. configSettings:settings
  710. configExperiment:nil];
  711. }
  712. // Make the fetch calls for all instances.
  713. NSMutableArray<XCTestExpectation *> *expectations =
  714. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  715. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  716. expectations[i] = [self
  717. expectationWithDescription:
  718. [NSString stringWithFormat:@"Test enumerating configs successfully - instance %d", i]];
  719. XCTAssertEqual(_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusNoFetchYet);
  720. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  721. NSError *error) {
  722. XCTAssertEqual(self->_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusFailure);
  723. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  724. XCTAssertFalse(changed);
  725. XCTAssertNil(error);
  726. // No such key, still return a static value.
  727. FIRRemoteConfigValue *value = self->_configInstances[RCNTestRCInstanceDefault][@"key1"];
  728. XCTAssertEqual((int)value.source, (int)FIRRemoteConfigSourceStatic);
  729. XCTAssertEqualObjects(value.stringValue, @"");
  730. XCTAssertEqual(value.boolValue, NO);
  731. [expectations[i] fulfill];
  732. }];
  733. };
  734. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  735. }
  736. [self waitForExpectationsWithTimeout:_expectationTimeout
  737. handler:^(NSError *error) {
  738. XCTAssertNil(error);
  739. }];
  740. }
  741. - (void)testFetchFailedNoNetworkErrorDoesNotThrottle {
  742. RCNConfigContent *configContent = [[RCNConfigContent alloc] initWithDBManager:_DBManager];
  743. NSString *currentAppName = RCNTestsDefaultFIRAppName;
  744. FIROptions *currentOptions = [self firstAppOptions];
  745. NSString *currentNamespace = RCNTestsFIRNamespace;
  746. NSString *fullyQualifiedNamespace =
  747. [NSString stringWithFormat:@"%@:%@", currentNamespace, currentAppName];
  748. RCNUserDefaultsManager *userDefaultsManager =
  749. [[RCNUserDefaultsManager alloc] initWithAppName:currentAppName
  750. bundleID:[NSBundle mainBundle].bundleIdentifier
  751. namespace:fullyQualifiedNamespace];
  752. userDefaultsManager.lastFetchTime = 0;
  753. FIRRemoteConfig *config = OCMPartialMock([[FIRRemoteConfig alloc] initWithAppName:currentAppName
  754. FIROptions:currentOptions
  755. namespace:currentNamespace
  756. DBManager:_DBManager
  757. configContent:configContent
  758. analytics:nil]);
  759. RCNConfigSettings *settings =
  760. [[RCNConfigSettings alloc] initWithDatabaseManager:_DBManager
  761. namespace:fullyQualifiedNamespace
  762. firebaseAppName:currentAppName
  763. googleAppID:currentOptions.googleAppID];
  764. dispatch_queue_t queue = dispatch_queue_create(
  765. [[NSString stringWithFormat:@"testqueue"] cStringUsingEncoding:NSUTF8StringEncoding],
  766. DISPATCH_QUEUE_SERIAL);
  767. RCNConfigFetch *configFetch =
  768. OCMPartialMock([[RCNConfigFetch alloc] initWithContent:configContent
  769. DBManager:_DBManager
  770. settings:settings
  771. analytics:nil
  772. experiment:nil
  773. queue:queue
  774. namespace:fullyQualifiedNamespace
  775. options:currentOptions]);
  776. OCMStub([configFetch fetchConfigWithExpirationDuration:43200 completionHandler:OCMOCK_ANY])
  777. .andDo(^(NSInvocation *invocation) {
  778. __unsafe_unretained void (^handler)(FIRRemoteConfigFetchStatus status,
  779. NSError *_Nullable error) = nil;
  780. [invocation getArgument:&handler atIndex:3];
  781. [configFetch fetchWithUserProperties:[[NSDictionary alloc] init]
  782. fetchTypeHeader:@"Base/1"
  783. completionHandler:handler
  784. updateCompletionHandler:nil];
  785. });
  786. _responseData[0] = [NSJSONSerialization dataWithJSONObject:@{} options:0 error:nil];
  787. // A no network error is accompanied with an HTTP status code of 0.
  788. _URLResponse[0] =
  789. [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"https://firebase.com"]
  790. statusCode:0
  791. HTTPVersion:nil
  792. headerFields:@{@"etag" : @"etag1"}];
  793. [config updateWithNewInstancesForConfigFetch:configFetch
  794. configContent:configContent
  795. configSettings:settings
  796. configExperiment:nil];
  797. XCTestExpectation *expectation =
  798. [self expectationWithDescription:@"Network error doesn't increase throttle interval"];
  799. XCTAssertEqual(config.lastFetchStatus, FIRRemoteConfigFetchStatusNoFetchYet);
  800. FIRRemoteConfigFetchCompletion fetchCompletion =
  801. ^void(FIRRemoteConfigFetchStatus status, NSError *error) {
  802. XCTAssertEqual(config.lastFetchStatus, FIRRemoteConfigFetchStatusFailure);
  803. XCTAssertEqual(settings.exponentialBackoffRetryInterval, 0);
  804. [expectation fulfill];
  805. };
  806. [config fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  807. [self waitForExpectationsWithTimeout:_expectationTimeout
  808. handler:^(NSError *error) {
  809. XCTAssertNil(error);
  810. }];
  811. }
  812. // Activate should return false if a fetch response returns 200 with NO_CHANGE as the response body.
  813. - (void)testActivateOnFetchNoChangeStatus {
  814. // Override the setup values to return back an error status.
  815. RCNConfigContent *configContent = [[RCNConfigContent alloc] initWithDBManager:_DBManager];
  816. // Populate the default, second app, second namespace instances.
  817. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  818. NSString *currentAppName = nil;
  819. FIROptions *currentOptions = nil;
  820. NSString *currentNamespace = nil;
  821. switch (i) {
  822. case RCNTestRCInstanceSecondNamespace:
  823. currentAppName = RCNTestsDefaultFIRAppName;
  824. currentOptions = [self firstAppOptions];
  825. currentNamespace = RCNTestsPerfNamespace;
  826. break;
  827. case RCNTestRCInstanceSecondApp:
  828. currentAppName = RCNTestsSecondFIRAppName;
  829. currentOptions = [self secondAppOptions];
  830. currentNamespace = _namespaceGoogleMobilePlatform;
  831. break;
  832. case RCNTestRCInstanceDefault:
  833. default:
  834. currentAppName = RCNTestsDefaultFIRAppName;
  835. currentOptions = [self firstAppOptions];
  836. currentNamespace = RCNTestsFIRNamespace;
  837. break;
  838. }
  839. NSString *fullyQualifiedNamespace =
  840. [NSString stringWithFormat:@"%@:%@", currentNamespace, currentAppName];
  841. RCNUserDefaultsManager *userDefaultsManager =
  842. [[RCNUserDefaultsManager alloc] initWithAppName:currentAppName
  843. bundleID:[NSBundle mainBundle].bundleIdentifier
  844. namespace:fullyQualifiedNamespace];
  845. userDefaultsManager.lastFetchTime = 10;
  846. FIRRemoteConfig *config =
  847. OCMPartialMock([[FIRRemoteConfig alloc] initWithAppName:currentAppName
  848. FIROptions:currentOptions
  849. namespace:currentNamespace
  850. DBManager:_DBManager
  851. configContent:configContent
  852. analytics:nil]);
  853. _configInstances[i] = config;
  854. RCNConfigSettings *settings =
  855. [[RCNConfigSettings alloc] initWithDatabaseManager:_DBManager
  856. namespace:fullyQualifiedNamespace
  857. firebaseAppName:currentAppName
  858. googleAppID:currentOptions.googleAppID];
  859. // Start the test with the assumption that we have some data that was fetched and activated.
  860. settings.lastETag = @"etag1";
  861. settings.lastETagUpdateTime = 100;
  862. settings.lastApplyTimeInterval = 101;
  863. dispatch_queue_t queue =
  864. dispatch_queue_create([[NSString stringWithFormat:@"testNoStatusFetchQueue: %d", i]
  865. cStringUsingEncoding:NSUTF8StringEncoding],
  866. DISPATCH_QUEUE_SERIAL);
  867. _configFetch[i] = OCMPartialMock([[RCNConfigFetch alloc] initWithContent:configContent
  868. DBManager:_DBManager
  869. settings:settings
  870. analytics:nil
  871. experiment:nil
  872. queue:queue
  873. namespace:fullyQualifiedNamespace
  874. options:currentOptions]);
  875. _configRealtime[i] = OCMPartialMock([[RCNConfigRealtime alloc] init:_configFetch[i]
  876. settings:settings
  877. namespace:fullyQualifiedNamespace
  878. options:currentOptions]);
  879. OCMStub([_configFetch[i] fetchConfigWithExpirationDuration:43200 completionHandler:OCMOCK_ANY])
  880. .andDo(^(NSInvocation *invocation) {
  881. __unsafe_unretained void (^handler)(FIRRemoteConfigFetchStatus status,
  882. NSError *_Nullable error) = nil;
  883. [invocation getArgument:&handler atIndex:3];
  884. [self->_configFetch[i] fetchWithUserProperties:[[NSDictionary alloc] init]
  885. fetchTypeHeader:@"Base/1"
  886. completionHandler:handler
  887. updateCompletionHandler:nil];
  888. });
  889. _response[i] = @{@"state" : @"NO_CHANGE"};
  890. _responseData[i] = [NSJSONSerialization dataWithJSONObject:_response[i] options:0 error:nil];
  891. _URLResponse[i] =
  892. [[NSHTTPURLResponse alloc] initWithURL:[NSURL URLWithString:@"https://firebase.com"]
  893. statusCode:200
  894. HTTPVersion:nil
  895. headerFields:@{@"etag" : @"etag1"}];
  896. id completionBlock =
  897. [OCMArg invokeBlockWithArgs:_responseData[i], _URLResponse[i], [NSNull null], nil];
  898. OCMStub([_configFetch[i] URLSessionDataTaskWithContent:[OCMArg any]
  899. fetchTypeHeader:@"Base/1"
  900. completionHandler:completionBlock])
  901. .andReturn(nil);
  902. [_configInstances[i] updateWithNewInstancesForConfigFetch:_configFetch[i]
  903. configContent:configContent
  904. configSettings:settings
  905. configExperiment:nil];
  906. }
  907. // Make the fetch calls for all instances.
  908. NSMutableArray<XCTestExpectation *> *expectations =
  909. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  910. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  911. expectations[i] = [self
  912. expectationWithDescription:
  913. [NSString stringWithFormat:@"Test enumerating configs successfully - instance %d", i]];
  914. XCTAssertEqual(_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusNoFetchYet);
  915. // Make sure activate returns false in fetch completion.
  916. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  917. NSError *error) {
  918. XCTAssertEqual(self->_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusSuccess);
  919. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  920. XCTAssertFalse(changed);
  921. XCTAssertNil(error);
  922. [expectations[i] fulfill];
  923. }];
  924. };
  925. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  926. }
  927. [self waitForExpectationsWithTimeout:_expectationTimeout
  928. handler:^(NSError *error) {
  929. XCTAssertNil(error);
  930. }];
  931. }
  932. - (void)testConfigValueForKey {
  933. NSMutableArray<XCTestExpectation *> *expectations =
  934. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  935. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  936. expectations[i] =
  937. [self expectationWithDescription:
  938. [NSString stringWithFormat:@"Test configValueForKey: method - instance %d", i]];
  939. XCTAssertEqual(_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusNoFetchYet);
  940. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  941. NSError *error) {
  942. XCTAssertEqual(status, FIRRemoteConfigFetchStatusSuccess);
  943. XCTAssertNil(error);
  944. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  945. XCTAssertTrue(changed);
  946. NSString *key1 = [NSString stringWithFormat:@"key1-%d", i];
  947. NSString *key2 = [NSString stringWithFormat:@"key2-%d", i];
  948. NSString *key3 = [NSString stringWithFormat:@"key3-%d", i];
  949. NSString *key7 = [NSString stringWithFormat:@"key7-%d", i];
  950. NSString *value1 = [NSString stringWithFormat:@"value1-%d", i];
  951. NSString *value2 = [NSString stringWithFormat:@"value2-%d", i];
  952. NSString *value3 = [NSString stringWithFormat:@"value3-%d", i];
  953. NSString *value7 = [NSString stringWithFormat:@"value7-%d", i];
  954. XCTAssertEqualObjects(self->_configInstances[i][key1].stringValue, value1);
  955. XCTAssertEqualObjects(self->_configInstances[i][key2].stringValue, value2);
  956. OCMVerify([self->_configInstances[i] objectForKeyedSubscript:key1]);
  957. XCTAssertEqualObjects([self->_configInstances[i] configValueForKey:key3].stringValue,
  958. value3);
  959. if (i == RCNTestRCInstanceDefault) {
  960. XCTAssertEqualObjects([self->_configInstances[i] configValueForKey:key7].stringValue,
  961. value7);
  962. }
  963. XCTAssertEqualObjects([self->_configInstances[i] configValueForKey:key7].stringValue,
  964. value7);
  965. XCTAssertNotNil([self->_configInstances[i] configValueForKey:nil]);
  966. XCTAssertEqual([self->_configInstances[i] configValueForKey:nil].source,
  967. FIRRemoteConfigSourceStatic);
  968. XCTAssertEqual([self->_configInstances[i] configValueForKey:nil].source,
  969. FIRRemoteConfigSourceStatic);
  970. XCTAssertEqual([self->_configInstances[i] configValueForKey:nil source:-1].source,
  971. FIRRemoteConfigSourceStatic);
  972. [expectations[i] fulfill];
  973. }];
  974. };
  975. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  976. }
  977. [self waitForExpectationsWithTimeout:_expectationTimeout
  978. handler:^(NSError *error) {
  979. XCTAssertNil(error);
  980. }];
  981. }
  982. - (void)testFetchConfigWithDefaultSets {
  983. NSMutableArray<XCTestExpectation *> *fetchConfigsExpectation =
  984. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  985. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  986. fetchConfigsExpectation[i] = [self
  987. expectationWithDescription:
  988. [NSString stringWithFormat:@"Test fetch configs with defaults set - instance %d", i]];
  989. NSString *key1 = [NSString stringWithFormat:@"key1-%d", i];
  990. NSString *key2 = [NSString stringWithFormat:@"key2-%d", i];
  991. NSString *key0 = [NSString stringWithFormat:@"key0-%d", i];
  992. NSString *value1 = [NSString stringWithFormat:@"value1-%d", i];
  993. NSString *value2 = [NSString stringWithFormat:@"value2-%d", i];
  994. NSDictionary<NSString *, NSString *> *defaults = @{key1 : @"default key1", key0 : @"value0-0"};
  995. [_configInstances[i] setDefaults:defaults];
  996. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  997. NSError *error) {
  998. XCTAssertEqual(self->_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusSuccess);
  999. XCTAssertNil(error);
  1000. XCTAssertEqualObjects(self->_configInstances[i][key1].stringValue, @"default key1");
  1001. XCTAssertEqual(self->_configInstances[i][key1].source, FIRRemoteConfigSourceDefault);
  1002. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  1003. XCTAssertTrue(changed);
  1004. XCTAssertEqualObjects(self->_configInstances[i][key1].stringValue, value1);
  1005. XCTAssertEqual(self->_configInstances[i][key1].source, FIRRemoteConfigSourceRemote);
  1006. XCTAssertEqualObjects([self->_configInstances[i] defaultValueForKey:key1].stringValue,
  1007. @"default key1");
  1008. XCTAssertEqualObjects(self->_configInstances[i][key2].stringValue, value2);
  1009. XCTAssertEqualObjects(self->_configInstances[i][key0].stringValue, @"value0-0");
  1010. XCTAssertNil([self->_configInstances[i] defaultValueForKey:nil]);
  1011. OCMVerify([self->_configInstances[i] objectForKeyedSubscript:key1]);
  1012. XCTAssertEqual(status, FIRRemoteConfigFetchStatusSuccess,
  1013. @"Callback of first successful config "
  1014. @"fetch. Status must equal to FIRRemoteConfigFetchStatusSuccess.");
  1015. [fetchConfigsExpectation[i] fulfill];
  1016. }];
  1017. };
  1018. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  1019. }
  1020. [self waitForExpectationsWithTimeout:_expectationTimeout
  1021. handler:^(NSError *error) {
  1022. XCTAssertNil(error);
  1023. }];
  1024. }
  1025. - (void)testDefaultsSetsOnly {
  1026. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1027. NSString *key1 = [NSString stringWithFormat:@"key1-%d", i];
  1028. NSString *key2 = [NSString stringWithFormat:@"key2-%d", i];
  1029. NSString *key3 = [NSString stringWithFormat:@"key3-%d", i];
  1030. NSString *key4 = [NSString stringWithFormat:@"key4-%d", i];
  1031. NSString *key5 = [NSString stringWithFormat:@"key5-%d", i];
  1032. NSString *defaultValue1 = @"default value1";
  1033. NSData *defaultValue2 = [defaultValue1 dataUsingEncoding:NSUTF8StringEncoding];
  1034. NSNumber *defaultValue3 = [NSNumber numberWithFloat:3.1415926];
  1035. NSDate *defaultValue4 = [NSDate date];
  1036. BOOL defaultValue5 = NO;
  1037. NSMutableDictionary<NSString *, id> *defaults = [NSMutableDictionary dictionaryWithDictionary:@{
  1038. key1 : defaultValue1,
  1039. key2 : defaultValue2,
  1040. key3 : defaultValue3,
  1041. key4 : defaultValue4,
  1042. key5 : @(defaultValue5),
  1043. }];
  1044. [_configInstances[i] setDefaults:defaults];
  1045. if (i == RCNTestRCInstanceSecondNamespace) {
  1046. [defaults setObject:@"2860" forKey:@"experience"];
  1047. [_configInstances[i] setDefaults:defaults];
  1048. }
  1049. // Remove objects right away to make sure dispatch_async gets the copy.
  1050. [defaults removeAllObjects];
  1051. FIRRemoteConfig *config = _configInstances[i];
  1052. XCTAssertEqualObjects(config[key1].stringValue, defaultValue1, @"Should support string format");
  1053. XCTAssertEqualObjects(config[key2].dataValue, defaultValue2, @"Should support data format");
  1054. XCTAssertEqual(config[key3].numberValue.longValue, defaultValue3.longValue,
  1055. @"Should support number format");
  1056. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  1057. [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  1058. NSString *strValueOfDate = [dateFormatter stringFromDate:(NSDate *)defaultValue4];
  1059. XCTAssertEqualObjects(
  1060. config[key4].stringValue, strValueOfDate,
  1061. @"Date format can be set as an input from plist, but output coming out of "
  1062. @"defaultConfig as string.");
  1063. XCTAssertEqual(config[key5].boolValue, defaultValue5, @"Should support bool format");
  1064. if (i == RCNTestRCInstanceSecondNamespace) {
  1065. XCTAssertEqualObjects(
  1066. [_configInstances[i] configValueForKey:@"experience"].stringValue, @"2860",
  1067. @"Only default config has the key, must equal to default config value.");
  1068. }
  1069. // Reset default sets
  1070. [_configInstances[i] setDefaults:nil];
  1071. XCTAssertEqual([_configInstances[i] allKeysFromSource:FIRRemoteConfigSourceDefault].count, 0);
  1072. }
  1073. }
  1074. - (void)testSetDefaultsWithNilParams {
  1075. NSMutableArray<XCTestExpectation *> *expectations =
  1076. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1077. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1078. expectations[i] = [self
  1079. expectationWithDescription:
  1080. [NSString stringWithFormat:@"Set defaults no callback expectation - instance %d", i]];
  1081. // Should work when passing nil.
  1082. [_configInstances[i] setDefaults:nil];
  1083. [_configInstances[i] setDefaults:nil];
  1084. dispatch_after(
  1085. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  1086. dispatch_get_main_queue(), ^{
  1087. XCTAssertEqual(
  1088. [self->_configInstances[i] allKeysFromSource:FIRRemoteConfigSourceDefault].count, 0);
  1089. [expectations[i] fulfill];
  1090. });
  1091. }
  1092. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1093. }
  1094. - (void)testFetchConfigOverwriteDefaultSet {
  1095. NSMutableArray<XCTestExpectation *> *fetchConfigsExpectation =
  1096. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1097. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1098. fetchConfigsExpectation[i] = [self
  1099. expectationWithDescription:
  1100. [NSString stringWithFormat:@"Test fetch configs with defaults set - instance %d", i]];
  1101. NSString *key1 = [NSString stringWithFormat:@"key1-%d", i];
  1102. NSString *value1 = [NSString stringWithFormat:@"value1-%d", i];
  1103. [_configInstances[i] setDefaults:@{key1 : @"default key1"}];
  1104. FIRRemoteConfigValue *value = _configInstances[i][key1];
  1105. XCTAssertEqualObjects(value.stringValue, @"default key1");
  1106. XCTAssertEqual(value.source, FIRRemoteConfigSourceDefault);
  1107. value = _configInstances[i][@"A key doesn't exist"];
  1108. XCTAssertEqual(value.source, FIRRemoteConfigSourceStatic);
  1109. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  1110. NSError *error) {
  1111. XCTAssertEqual(self->_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusSuccess);
  1112. XCTAssertNil(error);
  1113. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  1114. XCTAssertTrue(changed);
  1115. XCTAssertEqualObjects(self->_configInstances[i][key1].stringValue, value1);
  1116. XCTAssertEqual(self->_configInstances[i][key1].source, FIRRemoteConfigSourceRemote);
  1117. XCTAssertEqualObjects([self->_configInstances[i] defaultValueForKey:key1].stringValue,
  1118. @"default key1");
  1119. OCMVerify([self->_configInstances[i] objectForKeyedSubscript:key1]);
  1120. XCTAssertEqual(status, FIRRemoteConfigFetchStatusSuccess,
  1121. @"Callback of first successful config "
  1122. @"fetch. Status must equal to FIRRemoteConfigFetchStatusSuccess.");
  1123. [fetchConfigsExpectation[i] fulfill];
  1124. }];
  1125. };
  1126. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  1127. }
  1128. [self waitForExpectationsWithTimeout:_expectationTimeout
  1129. handler:^(NSError *error) {
  1130. XCTAssertNil(error);
  1131. }];
  1132. }
  1133. - (void)testGetConfigValueBySource {
  1134. NSMutableArray<XCTestExpectation *> *fetchConfigsExpectation =
  1135. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1136. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1137. fetchConfigsExpectation[i] =
  1138. [self expectationWithDescription:
  1139. [NSString stringWithFormat:@"Test get config value by source - instance %d", i]];
  1140. NSString *key1 = [NSString stringWithFormat:@"key1-%d", i];
  1141. NSString *value1 = [NSString stringWithFormat:@"value1-%d", i];
  1142. NSDictionary<NSString *, NSString *> *defaults = @{key1 : @"default value1"};
  1143. [_configInstances[i] setDefaults:defaults];
  1144. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  1145. NSError *error) {
  1146. XCTAssertEqual(self->_configInstances[i].lastFetchStatus, FIRRemoteConfigFetchStatusSuccess);
  1147. XCTAssertNil(error);
  1148. XCTAssertEqualObjects(self->_configInstances[i][key1].stringValue, @"default value1");
  1149. XCTAssertEqual(self->_configInstances[i][key1].source, FIRRemoteConfigSourceDefault);
  1150. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  1151. XCTAssertTrue(changed);
  1152. XCTAssertEqualObjects(self->_configInstances[i][key1].stringValue, value1);
  1153. XCTAssertEqual(self->_configInstances[i][key1].source, FIRRemoteConfigSourceRemote);
  1154. FIRRemoteConfigValue *value;
  1155. if (i == RCNTestRCInstanceDefault) {
  1156. value = [self->_configInstances[i] configValueForKey:key1
  1157. source:FIRRemoteConfigSourceRemote];
  1158. XCTAssertEqualObjects(value.stringValue, value1);
  1159. value = [self->_configInstances[i] configValueForKey:key1
  1160. source:FIRRemoteConfigSourceDefault];
  1161. XCTAssertEqualObjects(value.stringValue, @"default value1");
  1162. value = [self->_configInstances[i] configValueForKey:key1
  1163. source:FIRRemoteConfigSourceStatic];
  1164. } else {
  1165. value = [self->_configInstances[i] configValueForKey:key1
  1166. source:FIRRemoteConfigSourceRemote];
  1167. XCTAssertEqualObjects(value.stringValue, value1);
  1168. value = [self->_configInstances[i] configValueForKey:key1
  1169. source:FIRRemoteConfigSourceDefault];
  1170. XCTAssertEqualObjects(value.stringValue, @"default value1");
  1171. value = [self->_configInstances[i] configValueForKey:key1
  1172. source:FIRRemoteConfigSourceStatic];
  1173. }
  1174. XCTAssertEqualObjects(value.stringValue, @"");
  1175. XCTAssertEqualObjects(value.numberValue, @(0));
  1176. XCTAssertEqual(value.boolValue, NO);
  1177. XCTAssertEqual(status, FIRRemoteConfigFetchStatusSuccess,
  1178. @"Callback of first successful config "
  1179. @"fetch. Status must equal to FIRRemoteConfigFetchStatusSuccess.");
  1180. [fetchConfigsExpectation[i] fulfill];
  1181. }];
  1182. };
  1183. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  1184. }
  1185. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1186. }
  1187. - (void)testInvalidKeyOrNamespace {
  1188. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1189. FIRRemoteConfigValue *value = [_configInstances[i] configValueForKey:nil];
  1190. XCTAssertNotNil(value);
  1191. XCTAssertEqual(value.source, FIRRemoteConfigSourceStatic);
  1192. value = [_configInstances[i] configValueForKey:nil];
  1193. XCTAssertNotNil(value);
  1194. XCTAssertEqual(value.source, FIRRemoteConfigSourceStatic);
  1195. value = [_configInstances[i] configValueForKey:nil source:5];
  1196. XCTAssertNotNil(value);
  1197. XCTAssertEqual(value.source, FIRRemoteConfigSourceStatic);
  1198. }
  1199. }
  1200. // Remote Config converts UTC times in the plists to local times. This utility function makes it
  1201. // possible to check the times when running the tests in any timezone.
  1202. static NSString *UTCToLocal(NSString *utcTime) {
  1203. // Create a UTC dateFormatter.
  1204. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
  1205. [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
  1206. [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
  1207. NSDate *date = [dateFormatter dateFromString:utcTime];
  1208. [dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
  1209. return [dateFormatter stringFromDate:date];
  1210. }
  1211. // Manage different bundle locations for Swift Package Manager, CocoaPods static, CocoaPods dynamic.
  1212. - (void)setDefaultsFor:(FIRRemoteConfig *)config {
  1213. #if SWIFT_PACKAGE
  1214. NSBundle *bundle = SWIFTPM_MODULE_BUNDLE;
  1215. NSString *plistFile = [bundle pathForResource:@"Defaults-testInfo" ofType:@"plist"];
  1216. #else
  1217. NSBundle *bundle = [NSBundle mainBundle];
  1218. NSString *plistFile = [bundle pathForResource:@"Defaults-testInfo" ofType:@"plist"];
  1219. if (plistFile != nil) {
  1220. [config setDefaultsFromPlistFileName:@"Defaults-testInfo"];
  1221. return;
  1222. }
  1223. // We've linked dynamically and the plist file is in the test's bundle.
  1224. for (bundle in [NSBundle allBundles]) {
  1225. plistFile = [bundle pathForResource:@"Defaults-testInfo" ofType:@"plist"];
  1226. if (plistFile != nil) {
  1227. break;
  1228. }
  1229. }
  1230. #endif
  1231. NSDictionary *defaults = [[NSDictionary alloc] initWithContentsOfFile:plistFile];
  1232. [config setDefaults:defaults];
  1233. }
  1234. - (void)testSetDefaultsFromPlist {
  1235. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1236. FIRRemoteConfig *config = _configInstances[i];
  1237. [self setDefaultsFor:config];
  1238. XCTAssertEqualObjects(_configInstances[i][@"lastCheckTime"].stringValue,
  1239. UTCToLocal(@"2016-02-28 18:33:31"));
  1240. XCTAssertEqual(_configInstances[i][@"isPaidUser"].boolValue, YES);
  1241. XCTAssertEqualObjects(_configInstances[i][@"dataValue"].stringValue, @"2.4");
  1242. XCTAssertEqualObjects(_configInstances[i][@"New item"].numberValue, @(2.4));
  1243. XCTAssertEqualObjects(_configInstances[i][@"Languages"].stringValue, @"English");
  1244. XCTAssertEqualObjects(_configInstances[i][@"FileInfo"].stringValue,
  1245. @"To setup default config.");
  1246. XCTAssertEqualObjects(_configInstances[i][@"format"].stringValue, @"key to value.");
  1247. XCTAssertEqualObjects(_configInstances[i][@"arrayValue"].JSONValue,
  1248. ((id) @[ @"foo", @"bar", @"baz" ]));
  1249. XCTAssertEqualObjects(_configInstances[i][@"dictValue"].JSONValue,
  1250. ((id) @{@"foo" : @"foo", @"bar" : @"bar", @"baz" : @"baz"}));
  1251. // If given a wrong file name, the default will not be set and kept as previous results.
  1252. [_configInstances[i] setDefaultsFromPlistFileName:@""];
  1253. XCTAssertEqualObjects(_configInstances[i][@"lastCheckTime"].stringValue,
  1254. UTCToLocal(@"2016-02-28 18:33:31"));
  1255. [_configInstances[i] setDefaultsFromPlistFileName:@"non-existed_file"];
  1256. XCTAssertEqualObjects(_configInstances[i][@"dataValue"].stringValue, @"2.4");
  1257. [_configInstances[i] setDefaultsFromPlistFileName:nil];
  1258. XCTAssertEqualObjects(_configInstances[i][@"New item"].numberValue, @(2.4));
  1259. [_configInstances[i] setDefaultsFromPlistFileName:@""];
  1260. XCTAssertEqualObjects(_configInstances[i][@"Languages"].stringValue, @"English");
  1261. }
  1262. }
  1263. - (void)testAllKeysFromSource {
  1264. NSMutableArray<XCTestExpectation *> *fetchConfigsExpectation =
  1265. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1266. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1267. fetchConfigsExpectation[i] = [self
  1268. expectationWithDescription:[NSString
  1269. stringWithFormat:@"Test allKeys methods - instance %d", i]];
  1270. NSString *key1 = [NSString stringWithFormat:@"key1-%d", i];
  1271. NSString *key0 = [NSString stringWithFormat:@"key0-%d", i];
  1272. NSDictionary<NSString *, NSString *> *defaults = @{key1 : @"default key1", key0 : @"value0-0"};
  1273. [_configInstances[i] setDefaults:defaults];
  1274. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  1275. NSError *error) {
  1276. XCTAssertEqual(status, FIRRemoteConfigFetchStatusSuccess);
  1277. XCTAssertNil(error);
  1278. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  1279. XCTAssertTrue(changed);
  1280. XCTAssertEqual(
  1281. [self->_configInstances[i] allKeysFromSource:FIRRemoteConfigSourceRemote].count, 100);
  1282. XCTAssertEqual(
  1283. [self->_configInstances[i] allKeysFromSource:FIRRemoteConfigSourceDefault].count, 2);
  1284. XCTAssertEqual(
  1285. [self->_configInstances[i] allKeysFromSource:FIRRemoteConfigSourceStatic].count, 0);
  1286. [fetchConfigsExpectation[i] fulfill];
  1287. }];
  1288. };
  1289. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  1290. }
  1291. [self waitForExpectationsWithTimeout:_expectationTimeout
  1292. handler:^(NSError *error) {
  1293. XCTAssertNil(error);
  1294. }];
  1295. }
  1296. - (void)testAllKeysWithPrefix {
  1297. NSMutableArray<XCTestExpectation *> *fetchConfigsExpectation =
  1298. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1299. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1300. fetchConfigsExpectation[i] = [self
  1301. expectationWithDescription:[NSString
  1302. stringWithFormat:@"Test allKeys methods - instance %d", i]];
  1303. FIRRemoteConfigFetchCompletion fetchCompletion = ^void(FIRRemoteConfigFetchStatus status,
  1304. NSError *error) {
  1305. XCTAssertEqual(status, FIRRemoteConfigFetchStatusSuccess);
  1306. XCTAssertNil(error);
  1307. NSLog(@"Testing _configInstances %d", i);
  1308. [self->_configInstances[i] activateWithCompletion:^(BOOL changed, NSError *_Nullable error) {
  1309. XCTAssertTrue(changed);
  1310. // Test keysWithPrefix: method.
  1311. XCTAssertEqual([self->_configInstances[i] keysWithPrefix:@"key1"].count, 12);
  1312. XCTAssertEqual([self->_configInstances[i] keysWithPrefix:@"key"].count, 100);
  1313. XCTAssertEqual([self->_configInstances[i] keysWithPrefix:@"invalid key"].count, 0);
  1314. XCTAssertEqual([self->_configInstances[i] keysWithPrefix:nil].count, 100);
  1315. XCTAssertEqual([self->_configInstances[i] keysWithPrefix:@""].count, 100);
  1316. [fetchConfigsExpectation[i] fulfill];
  1317. }];
  1318. };
  1319. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  1320. }
  1321. [self waitForExpectationsWithTimeout:_expectationTimeout
  1322. handler:^(NSError *error) {
  1323. XCTAssertNil(error);
  1324. }];
  1325. }
  1326. /// Test the minimum fetch interval is applied and read back correctly.
  1327. - (void)testSetMinimumFetchIntervalConfigSetting {
  1328. NSMutableArray<XCTestExpectation *> *fetchConfigsExpectation =
  1329. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1330. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1331. fetchConfigsExpectation[i] = [self
  1332. expectationWithDescription:
  1333. [NSString stringWithFormat:@"Test minimumFetchInterval expectation - instance %d", i]];
  1334. FIRRemoteConfigSettings *settings = [[FIRRemoteConfigSettings alloc] init];
  1335. settings.minimumFetchInterval = 123;
  1336. [_configInstances[i] setConfigSettings:settings];
  1337. XCTAssertEqual([_configInstances[i] configSettings].minimumFetchInterval, 123);
  1338. FIRRemoteConfigFetchCompletion fetchCompletion =
  1339. ^void(FIRRemoteConfigFetchStatus status, NSError *error) {
  1340. XCTAssertFalse([self->_configInstances[i].settings hasMinimumFetchIntervalElapsed:43200]);
  1341. // Update minimum fetch interval.
  1342. FIRRemoteConfigSettings *settings = [[FIRRemoteConfigSettings alloc] init];
  1343. settings.minimumFetchInterval = 0;
  1344. [self->_configInstances[i] setConfigSettings:settings];
  1345. XCTAssertEqual([self->_configInstances[i] configSettings].minimumFetchInterval, 0);
  1346. XCTAssertTrue([self->_configInstances[i].settings hasMinimumFetchIntervalElapsed:0]);
  1347. [fetchConfigsExpectation[i] fulfill];
  1348. };
  1349. [_configInstances[i] fetchWithExpirationDuration:43200 completionHandler:fetchCompletion];
  1350. }
  1351. [self waitForExpectationsWithTimeout:_expectationTimeout
  1352. handler:^(NSError *error) {
  1353. XCTAssertNil(error);
  1354. }];
  1355. }
  1356. /// Test the fetch timeout is properly set and read back.
  1357. - (void)testSetFetchTimeoutConfigSetting {
  1358. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1359. FIRRemoteConfigSettings *settings = [[FIRRemoteConfigSettings alloc] init];
  1360. settings.fetchTimeout = 1;
  1361. [_configInstances[i] setConfigSettings:settings];
  1362. XCTAssertEqual([_configInstances[i] configSettings].fetchTimeout, 1);
  1363. NSURLSession *networkSession = [_configFetch[i] currentNetworkSession];
  1364. XCTAssertNotNil(networkSession);
  1365. XCTAssertEqual(networkSession.configuration.timeoutIntervalForResource, 1);
  1366. XCTAssertEqual(networkSession.configuration.timeoutIntervalForRequest, 1);
  1367. }
  1368. }
  1369. - (void)testFetchRequestWithUserPropertiesOnly {
  1370. NSDictionary *userProperties = @{@"user_key" : @"user_value"};
  1371. NSString *req = [_settings nextRequestWithUserProperties:userProperties];
  1372. XCTAssertTrue([req containsString:@"analytics_user_properties:{\"user_key\":\"user_value\"}"]);
  1373. XCTAssertFalse([req containsString:@"first_open_time"]);
  1374. }
  1375. - (void)testFetchRequestWithFirstOpenTimeAndUserProperties {
  1376. NSDictionary *userProperties = @{@"_fot" : @1649116800000, @"user_key" : @"user_value"};
  1377. NSString *req = [_settings nextRequestWithUserProperties:userProperties];
  1378. XCTAssertTrue([req containsString:@"first_open_time:'2022-04-05T00:00:00Z'"]);
  1379. XCTAssertTrue([req containsString:@"analytics_user_properties:{\"user_key\":\"user_value\"}"]);
  1380. }
  1381. - (void)testFetchRequestFirstOpenTimeOnly {
  1382. NSDictionary *userProperties = @{@"_fot" : @1650315600000};
  1383. NSString *req = [_settings nextRequestWithUserProperties:userProperties];
  1384. XCTAssertTrue([req containsString:@"first_open_time:'2022-04-18T21:00:00Z'"]);
  1385. XCTAssertFalse([req containsString:@"analytics_user_properties"]);
  1386. }
  1387. #pragma mark - Public Factory Methods
  1388. - (void)testConfigureConfigWithValidInput {
  1389. // Configure the default app with our options and ensure the Remote Config instance is set up
  1390. // properly.
  1391. if (![FIRApp isDefaultAppConfigured]) {
  1392. XCTAssertNoThrow([FIRApp configureWithOptions:[self firstAppOptions]]);
  1393. }
  1394. XCTAssertNoThrow([FIRRemoteConfig remoteConfig]);
  1395. FIRRemoteConfig *config = [FIRRemoteConfig remoteConfig];
  1396. XCTAssertNotNil(config);
  1397. // Ensure the same instance is returned from the singleton.
  1398. FIRRemoteConfig *sameConfig = [FIRRemoteConfig remoteConfig];
  1399. XCTAssertNotNil(sameConfig);
  1400. XCTAssertEqual(config, sameConfig);
  1401. // Ensure the app name is stored properly.
  1402. XCTAssertEqual([config valueForKey:@"_appName"], kFIRDefaultAppName);
  1403. }
  1404. #pragma mark - Realtime tests
  1405. - (void)testRealtimeAddConfigUpdateListenerWithValidListener {
  1406. NSMutableArray<XCTestExpectation *> *expectations =
  1407. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1408. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1409. expectations[i] = [self
  1410. expectationWithDescription:
  1411. [NSString
  1412. stringWithFormat:@"Test Realtime add listener successfully - instance %d", i]];
  1413. OCMStub([_configRealtime[i] beginRealtimeStream]).andDo(nil);
  1414. id completion = ^void(FIRRemoteConfigUpdate *_Nullable configUpdate, NSError *_Nullable error) {
  1415. if (error != nil) {
  1416. NSLog(@"Callback");
  1417. }
  1418. };
  1419. [_configRealtime[i] addConfigUpdateListener:completion];
  1420. dispatch_after(
  1421. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  1422. dispatch_get_main_queue(), ^{
  1423. OCMVerify([self->_configRealtime[i] beginRealtimeStream]);
  1424. OCMVerify([self->_configRealtime[i] addConfigUpdateListener:completion]);
  1425. [expectations[i] fulfill];
  1426. });
  1427. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1428. }
  1429. }
  1430. - (void)testRealtimeAddConfigUpdateListenerWithInvalidListener {
  1431. NSMutableArray<XCTestExpectation *> *expectations =
  1432. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1433. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1434. expectations[i] = [self
  1435. expectationWithDescription:
  1436. [NSString
  1437. stringWithFormat:@"Test Realtime add listener unsuccessfully - instance %d", i]];
  1438. id completion = nil;
  1439. [_configRealtime[i] addConfigUpdateListener:completion];
  1440. dispatch_after(
  1441. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  1442. dispatch_get_main_queue(), ^{
  1443. OCMVerify(never(), [self->_configRealtime[i] beginRealtimeStream]);
  1444. [expectations[i] fulfill];
  1445. });
  1446. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1447. }
  1448. }
  1449. - (void)testRemoveRealtimeListener {
  1450. NSMutableArray<XCTestExpectation *> *expectations =
  1451. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1452. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1453. expectations[i] = [self
  1454. expectationWithDescription:
  1455. [NSString
  1456. stringWithFormat:@"Test Realtime remove listeners successfully - instance %d", i]];
  1457. id completion = ^void(FIRRemoteConfigUpdate *_Nullable configUpdate, NSError *_Nullable error) {
  1458. if (error != nil) {
  1459. NSLog(@"Callback");
  1460. }
  1461. };
  1462. OCMStub([_configRealtime[i] beginRealtimeStream]).andDo(nil);
  1463. FIRConfigUpdateListenerRegistration *registration =
  1464. [_configRealtime[i] addConfigUpdateListener:completion];
  1465. [registration remove];
  1466. dispatch_after(
  1467. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  1468. dispatch_get_main_queue(), ^{
  1469. OCMVerify([self->_configRealtime[i] addConfigUpdateListener:completion]);
  1470. OCMVerify([self->_configRealtime[i] removeConfigUpdateListener:completion]);
  1471. OCMVerify([self->_configRealtime[i] pauseRealtimeStream]);
  1472. [expectations[i] fulfill];
  1473. });
  1474. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1475. }
  1476. }
  1477. - (void)testRealtimeFetch {
  1478. NSMutableArray<XCTestExpectation *> *expectations =
  1479. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1480. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1481. expectations[i] = [self
  1482. expectationWithDescription:
  1483. [NSString stringWithFormat:@"Test Realtime Autofetch successfully - instance %d", i]];
  1484. OCMStub([_configFetch[i] realtimeFetchConfigWithNoExpirationDuration:1
  1485. completionHandler:OCMOCK_ANY])
  1486. .andDo(nil);
  1487. OCMStub([_configRealtime[i] scheduleFetch:1 targetVersion:1]).andDo(nil);
  1488. [_configRealtime[i] fetchLatestConfig:3 targetVersion:1];
  1489. dispatch_after(
  1490. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  1491. dispatch_get_main_queue(), ^{
  1492. OCMVerify([self->_configFetch[i] realtimeFetchConfigWithNoExpirationDuration:1
  1493. completionHandler:OCMOCK_ANY]);
  1494. [expectations[i] fulfill];
  1495. });
  1496. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1497. }
  1498. }
  1499. - (void)testAutofetch {
  1500. NSMutableArray<XCTestExpectation *> *expectations =
  1501. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1502. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1503. expectations[i] = [self
  1504. expectationWithDescription:
  1505. [NSString stringWithFormat:@"Test Realtime Autofetch successfully - instance %d", i]];
  1506. OCMStub([_configRealtime[i] scheduleFetch:1 targetVersion:1]).andDo(nil);
  1507. [_configRealtime[i] autoFetch:1 targetVersion:1];
  1508. dispatch_after(
  1509. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  1510. dispatch_get_main_queue(), ^{
  1511. OCMVerify([self->_configRealtime[i] scheduleFetch:1 targetVersion:1]);
  1512. [expectations[i] fulfill];
  1513. });
  1514. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1515. }
  1516. }
  1517. - (void)testAddOnConfigUpdateMethodSuccess {
  1518. NSMutableArray<XCTestExpectation *> *expectations =
  1519. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1520. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1521. expectations[i] = [self
  1522. expectationWithDescription:
  1523. [NSString
  1524. stringWithFormat:@"Test public realtime method successfully - instance %d", i]];
  1525. OCMStub([_configRealtime[i] beginRealtimeStream]).andDo(nil);
  1526. id completion = ^void(FIRRemoteConfigUpdate *_Nullable configUpdate, NSError *_Nullable error) {
  1527. if (error != nil) {
  1528. NSLog(@"Callback");
  1529. }
  1530. };
  1531. [_configInstances[i] addOnConfigUpdateListener:completion];
  1532. dispatch_after(
  1533. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  1534. dispatch_get_main_queue(), ^{
  1535. OCMVerify([self->_configRealtime[i] addConfigUpdateListener:completion]);
  1536. [expectations[i] fulfill];
  1537. });
  1538. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1539. }
  1540. }
  1541. - (void)testAddOnConfigUpdateMethodFail {
  1542. NSMutableArray<XCTestExpectation *> *expectations =
  1543. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1544. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1545. expectations[i] = [self
  1546. expectationWithDescription:
  1547. [NSString stringWithFormat:@"Test public realtime method and fails - instance %d", i]];
  1548. id completion = nil;
  1549. [_configInstances[i] addOnConfigUpdateListener:completion];
  1550. dispatch_after(
  1551. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  1552. dispatch_get_main_queue(), ^{
  1553. OCMVerify(never(), [self->_configRealtime[i] beginRealtimeStream]);
  1554. [expectations[i] fulfill];
  1555. });
  1556. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1557. }
  1558. }
  1559. - (void)testRealtimeDisabled {
  1560. NSMutableArray<XCTestExpectation *> *expectations =
  1561. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1562. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1563. expectations[i] = [self
  1564. expectationWithDescription:
  1565. [NSString
  1566. stringWithFormat:@"Test isRealtimeDisabled flag and makes it true - instance %d",
  1567. i]];
  1568. OCMStub([_configRealtime[i] pauseRealtimeStream]).andDo(nil);
  1569. NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
  1570. [dictionary setValue:@"true" forKey:@"featureDisabled"];
  1571. [dictionary setValue:@"1" forKey:@"latestTemplateVersionNumber"];
  1572. [_configRealtime[i] evaluateStreamResponse:dictionary error:nil];
  1573. dispatch_after(
  1574. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  1575. dispatch_get_main_queue(), ^{
  1576. OCMVerify([self->_configRealtime[i] pauseRealtimeStream]);
  1577. OCMVerify(never(), [self->_configRealtime[i] autoFetch:5 targetVersion:1]);
  1578. [expectations[i] fulfill];
  1579. });
  1580. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1581. }
  1582. }
  1583. - (void)testRealtimeStreamRequestBody {
  1584. XCTestExpectation *requestBodyExpectation = [self expectationWithDescription:@"requestBody"];
  1585. __block NSData *requestBody;
  1586. [_configRealtime[0] createRequestBodyWithCompletion:^(NSData *_Nonnull data) {
  1587. requestBody = data;
  1588. [requestBodyExpectation fulfill];
  1589. }];
  1590. [self waitForExpectations:@[ requestBodyExpectation ] timeout:5.0];
  1591. NSError *error;
  1592. NSData *uncompressedRequest = [NSData gul_dataByInflatingGzippedData:requestBody error:&error];
  1593. NSString *strData = [[NSString alloc] initWithData:uncompressedRequest
  1594. encoding:NSUTF8StringEncoding];
  1595. XCTAssertTrue([strData containsString:@"project:'correct_gcm_sender_id'"]);
  1596. XCTAssertTrue([strData containsString:@"namespace:'firebase'"]);
  1597. XCTAssertTrue([strData containsString:@"lastKnownVersionNumber:'0'"]);
  1598. XCTAssertTrue([strData containsString:@"appId:'1:123:ios:123abc'"]);
  1599. XCTAssertTrue([strData containsString:@"sdkVersion:"]);
  1600. XCTAssertTrue([strData containsString:@"appInstanceId:'iid'"]);
  1601. }
  1602. - (void)testFetchAndActivateRolloutsNotifyInterop {
  1603. XCTestExpectation *notificationExpectation =
  1604. [self expectationForNotification:@"FIRRolloutsStateDidChangeNotification"
  1605. object:nil
  1606. handler:nil];
  1607. XCTAssertEqual(_configInstances[RCNTestRCInstanceDefault].lastFetchStatus,
  1608. FIRRemoteConfigFetchStatusNoFetchYet);
  1609. FIRRemoteConfigFetchAndActivateCompletion fetchAndActivateCompletion =
  1610. ^void(FIRRemoteConfigFetchAndActivateStatus status, NSError *error) {
  1611. XCTAssertEqual(status, FIRRemoteConfigFetchAndActivateStatusSuccessFetchedFromRemote);
  1612. XCTAssertNil(error);
  1613. XCTAssertEqual(self->_configInstances[RCNTestRCInstanceDefault].lastFetchStatus,
  1614. FIRRemoteConfigFetchStatusSuccess);
  1615. XCTAssertNotNil(self->_configInstances[RCNTestRCInstanceDefault].lastFetchTime);
  1616. XCTAssertGreaterThan(
  1617. self->_configInstances[RCNTestRCInstanceDefault].lastFetchTime.timeIntervalSince1970, 0,
  1618. @"last fetch time interval should be set.");
  1619. [notificationExpectation fulfill];
  1620. };
  1621. [_configInstances[RCNTestRCInstanceDefault]
  1622. fetchAndActivateWithCompletionHandler:fetchAndActivateCompletion];
  1623. [self waitForExpectations:@[ notificationExpectation ] timeout:_expectationTimeout];
  1624. }
  1625. - (void)testURLSessionDelegateHandlesChunkedJSON {
  1626. NSString *testString = @"} {\"testKey\":\"testValue\"}";
  1627. NSData *testData = [testString dataUsingEncoding:NSUTF8StringEncoding];
  1628. NSMutableArray<XCTestExpectation *> *expectations =
  1629. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1630. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1631. expectations[i] = [self
  1632. expectationWithDescription:
  1633. [NSString
  1634. stringWithFormat:@"Test delegate method handling chunked JSON - instance %d", i]];
  1635. NSURLSession *networkSession = [_configFetch[i] currentNetworkSession];
  1636. NSURLSessionDataTask *dataTask = [_configFetch[i] URLSessionDataTaskWithContent:[OCMArg any]
  1637. fetchTypeHeader:[OCMArg any]
  1638. completionHandler:nil];
  1639. XCTAssertNoThrow([_configRealtime[i] URLSession:networkSession
  1640. dataTask:dataTask
  1641. didReceiveData:testData]);
  1642. [expectations[i] fulfill];
  1643. }
  1644. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1645. }
  1646. - (void)testSetCustomSignals {
  1647. NSMutableArray<XCTestExpectation *> *expectations =
  1648. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1649. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1650. expectations[i] = [self
  1651. expectationWithDescription:[NSString
  1652. stringWithFormat:@"Set custom signals - instance %d", i]];
  1653. NSDictionary<NSString *, NSObject *> *testSignals = @{
  1654. @"signal1" : @"stringValue",
  1655. @"signal2" : @"stringValue2",
  1656. };
  1657. [_configInstances[i] setCustomSignals:testSignals
  1658. withCompletion:^(NSError *_Nullable error) {
  1659. XCTAssertNil(error);
  1660. NSDictionary<NSString *, NSString *> *retrievedSignals =
  1661. self->_configInstances[i].settings.customSignals;
  1662. XCTAssertEqualObjects(retrievedSignals, testSignals);
  1663. [expectations[i] fulfill];
  1664. }];
  1665. }
  1666. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1667. }
  1668. - (void)testSetCustomSignalsMultipleTimes {
  1669. NSMutableArray<XCTestExpectation *> *expectations =
  1670. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1671. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1672. expectations[i] = [self
  1673. expectationWithDescription:
  1674. [NSString stringWithFormat:@"Set custom signals multiple times - instance %d", i]];
  1675. // First set of signals
  1676. NSDictionary<NSString *, NSObject *> *testSignals1 = @{
  1677. @"signal1" : @"stringValue1",
  1678. @"signal2" : @"stringValue2",
  1679. };
  1680. // Second set of signals (overwrites, remove and adds new)
  1681. NSDictionary<NSString *, NSObject *> *testSignals2 = @{
  1682. @"signal1" : @"updatedValue1",
  1683. @"signal2" : [NSNull null],
  1684. @"signal3" : @5,
  1685. };
  1686. // Expected final set of signals
  1687. NSDictionary<NSString *, NSString *> *expectedSignals = @{
  1688. @"signal1" : @"updatedValue1",
  1689. @"signal3" : @"5",
  1690. };
  1691. [_configInstances[i] setCustomSignals:testSignals1
  1692. withCompletion:^(NSError *_Nullable error) {
  1693. XCTAssertNil(error);
  1694. [_configInstances[i]
  1695. setCustomSignals:testSignals2
  1696. withCompletion:^(NSError *_Nullable error) {
  1697. XCTAssertNil(error);
  1698. NSDictionary<NSString *, NSString *> *retrievedSignals =
  1699. self->_configInstances[i].settings.customSignals;
  1700. XCTAssertEqualObjects(retrievedSignals, expectedSignals);
  1701. [expectations[i] fulfill];
  1702. }];
  1703. }];
  1704. }
  1705. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1706. }
  1707. - (void)testSetCustomSignals_invalidInput_throwsException {
  1708. NSMutableArray<XCTestExpectation *> *expectations =
  1709. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1710. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1711. expectations[i] =
  1712. [self expectationWithDescription:
  1713. [NSString stringWithFormat:@"Set custom signals expects error - instance %d", i]];
  1714. // Invalid value type.
  1715. NSDictionary<NSString *, NSObject *> *invalidSignals1 = @{@"name" : [NSDate date]};
  1716. // Key length exceeds limit.
  1717. NSDictionary<NSString *, NSObject *> *invalidSignals2 =
  1718. @{[@"a" stringByPaddingToLength:251 withString:@"a" startingAtIndex:0] : @"value"};
  1719. // Value length exceeds limit.
  1720. NSDictionary<NSString *, NSObject *> *invalidSignals3 =
  1721. @{@"key" : [@"a" stringByPaddingToLength:501 withString:@"a" startingAtIndex:0]};
  1722. [_configInstances[i]
  1723. setCustomSignals:invalidSignals1
  1724. withCompletion:^(NSError *_Nullable error) {
  1725. XCTAssertNotNil(error);
  1726. XCTAssertEqual(error.code, FIRRemoteConfigCustomSignalsErrorInvalidValueType);
  1727. }];
  1728. [_configInstances[i]
  1729. setCustomSignals:invalidSignals2
  1730. withCompletion:^(NSError *_Nullable error) {
  1731. XCTAssertNotNil(error);
  1732. XCTAssertEqual(error.code, FIRRemoteConfigCustomSignalsErrorLimitExceeded);
  1733. }];
  1734. [_configInstances[i]
  1735. setCustomSignals:invalidSignals3
  1736. withCompletion:^(NSError *_Nullable error) {
  1737. XCTAssertNotNil(error);
  1738. XCTAssertEqual(error.code, FIRRemoteConfigCustomSignalsErrorLimitExceeded);
  1739. [expectations[i] fulfill];
  1740. }];
  1741. }
  1742. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1743. }
  1744. #pragma mark - Test Helpers
  1745. - (FIROptions *)firstAppOptions {
  1746. // TODO: Evaluate if we want to hardcode things here instead.
  1747. FIROptions *options = [[FIROptions alloc] initWithGoogleAppID:@"1:123:ios:123abc"
  1748. GCMSenderID:@"correct_gcm_sender_id"];
  1749. options.APIKey = @"AIzaSy-ApiKeyWithValidFormat_0123456789";
  1750. options.projectID = @"abc-xyz-123";
  1751. return options;
  1752. }
  1753. - (FIROptions *)secondAppOptions {
  1754. NSBundle *bundle = [NSBundle bundleForClass:[self class]];
  1755. #if SWIFT_PACKAGE
  1756. bundle = SWIFTPM_MODULE_BUNDLE;
  1757. #endif
  1758. NSString *plistPath = [bundle pathForResource:@"SecondApp-GoogleService-Info" ofType:@"plist"];
  1759. FIROptions *options = [[FIROptions alloc] initWithContentsOfFile:plistPath];
  1760. XCTAssertNotNil(options);
  1761. return options;
  1762. }
  1763. @end