RCNRemoteConfigTest.m 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029
  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)testRealtimeUpdatesBackoffMetadataWhenRetryIntervalIsProvided {
  1584. NSMutableArray<XCTestExpectation *> *expectations =
  1585. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1586. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1587. expectations[i] =
  1588. [self expectationWithDescription:
  1589. [NSString stringWithFormat:@"Test backoff metadata updates with a provided retry "
  1590. @"interval in the stream response - instance %d",
  1591. i]];
  1592. NSTimeInterval realtimeRetryInterval = 240;
  1593. NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
  1594. [dictionary setValue:@"1" forKey:@"latestTemplateVersionNumber"];
  1595. [dictionary setValue:@(realtimeRetryInterval) forKey:@"retryIntervalSeconds"];
  1596. NSTimeInterval expectedThrottleEndTime =
  1597. [[NSDate date] timeIntervalSince1970] + realtimeRetryInterval;
  1598. [_configRealtime[i] evaluateStreamResponse:dictionary error:nil];
  1599. dispatch_after(
  1600. dispatch_time(DISPATCH_TIME_NOW, (int64_t)(_checkCompletionTimeout * NSEC_PER_SEC)),
  1601. dispatch_get_main_queue(), ^{
  1602. NSTimeInterval retrievedThrottleEndTime =
  1603. self->_configInstances[i].settings.realtimeExponentialBackoffThrottleEndTime;
  1604. XCTAssertEqualWithAccuracy(retrievedThrottleEndTime, expectedThrottleEndTime, 1.0);
  1605. [expectations[i] fulfill];
  1606. });
  1607. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1608. }
  1609. }
  1610. - (void)testRealtimeStreamRequestBody {
  1611. XCTestExpectation *requestBodyExpectation = [self expectationWithDescription:@"requestBody"];
  1612. __block NSData *requestBody;
  1613. [_configRealtime[0] createRequestBodyWithCompletion:^(NSData *_Nonnull data) {
  1614. requestBody = data;
  1615. [requestBodyExpectation fulfill];
  1616. }];
  1617. [self waitForExpectations:@[ requestBodyExpectation ] timeout:5.0];
  1618. NSError *error;
  1619. NSData *uncompressedRequest = [NSData gul_dataByInflatingGzippedData:requestBody error:&error];
  1620. NSString *strData = [[NSString alloc] initWithData:uncompressedRequest
  1621. encoding:NSUTF8StringEncoding];
  1622. XCTAssertTrue([strData containsString:@"project:'correct_gcm_sender_id'"]);
  1623. XCTAssertTrue([strData containsString:@"namespace:'firebase'"]);
  1624. XCTAssertTrue([strData containsString:@"lastKnownVersionNumber:'0'"]);
  1625. XCTAssertTrue([strData containsString:@"appId:'1:123:ios:123abc'"]);
  1626. XCTAssertTrue([strData containsString:@"sdkVersion:"]);
  1627. XCTAssertTrue([strData containsString:@"appInstanceId:'iid'"]);
  1628. }
  1629. - (void)testFetchAndActivateRolloutsNotifyInterop {
  1630. XCTestExpectation *notificationExpectation =
  1631. [self expectationForNotification:@"FIRRolloutsStateDidChangeNotification"
  1632. object:nil
  1633. handler:nil];
  1634. XCTAssertEqual(_configInstances[RCNTestRCInstanceDefault].lastFetchStatus,
  1635. FIRRemoteConfigFetchStatusNoFetchYet);
  1636. FIRRemoteConfigFetchAndActivateCompletion fetchAndActivateCompletion =
  1637. ^void(FIRRemoteConfigFetchAndActivateStatus status, NSError *error) {
  1638. XCTAssertEqual(status, FIRRemoteConfigFetchAndActivateStatusSuccessFetchedFromRemote);
  1639. XCTAssertNil(error);
  1640. XCTAssertEqual(self->_configInstances[RCNTestRCInstanceDefault].lastFetchStatus,
  1641. FIRRemoteConfigFetchStatusSuccess);
  1642. XCTAssertNotNil(self->_configInstances[RCNTestRCInstanceDefault].lastFetchTime);
  1643. XCTAssertGreaterThan(
  1644. self->_configInstances[RCNTestRCInstanceDefault].lastFetchTime.timeIntervalSince1970, 0,
  1645. @"last fetch time interval should be set.");
  1646. [notificationExpectation fulfill];
  1647. };
  1648. [_configInstances[RCNTestRCInstanceDefault]
  1649. fetchAndActivateWithCompletionHandler:fetchAndActivateCompletion];
  1650. [self waitForExpectations:@[ notificationExpectation ] timeout:_expectationTimeout];
  1651. }
  1652. - (void)testURLSessionDelegateHandlesChunkedJSON {
  1653. NSString *testString = @"} {\"testKey\":\"testValue\"}";
  1654. NSData *testData = [testString dataUsingEncoding:NSUTF8StringEncoding];
  1655. NSMutableArray<XCTestExpectation *> *expectations =
  1656. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1657. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1658. expectations[i] = [self
  1659. expectationWithDescription:
  1660. [NSString
  1661. stringWithFormat:@"Test delegate method handling chunked JSON - instance %d", i]];
  1662. NSURLSession *networkSession = [_configFetch[i] currentNetworkSession];
  1663. NSURLSessionDataTask *dataTask = [_configFetch[i] URLSessionDataTaskWithContent:[OCMArg any]
  1664. fetchTypeHeader:[OCMArg any]
  1665. completionHandler:nil];
  1666. XCTAssertNoThrow([_configRealtime[i] URLSession:networkSession
  1667. dataTask:dataTask
  1668. didReceiveData:testData]);
  1669. [expectations[i] fulfill];
  1670. }
  1671. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1672. }
  1673. - (void)testSetCustomSignals {
  1674. NSMutableArray<XCTestExpectation *> *expectations =
  1675. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1676. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1677. expectations[i] = [self
  1678. expectationWithDescription:[NSString
  1679. stringWithFormat:@"Set custom signals - instance %d", i]];
  1680. NSDictionary<NSString *, NSObject *> *testSignals = @{
  1681. @"signal1" : @"stringValue",
  1682. @"signal2" : @"stringValue2",
  1683. };
  1684. [_configInstances[i] setCustomSignals:testSignals
  1685. withCompletion:^(NSError *_Nullable error) {
  1686. XCTAssertNil(error);
  1687. NSDictionary<NSString *, NSString *> *retrievedSignals =
  1688. self->_configInstances[i].settings.customSignals;
  1689. XCTAssertEqualObjects(retrievedSignals, testSignals);
  1690. [expectations[i] fulfill];
  1691. }];
  1692. }
  1693. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1694. }
  1695. - (void)testSetCustomSignalsMultipleTimes {
  1696. NSMutableArray<XCTestExpectation *> *expectations =
  1697. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1698. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1699. expectations[i] = [self
  1700. expectationWithDescription:
  1701. [NSString stringWithFormat:@"Set custom signals multiple times - instance %d", i]];
  1702. // First set of signals
  1703. NSDictionary<NSString *, NSObject *> *testSignals1 = @{
  1704. @"signal1" : @"stringValue1",
  1705. @"signal2" : @"stringValue2",
  1706. };
  1707. // Second set of signals (overwrites, remove and adds new)
  1708. NSDictionary<NSString *, NSObject *> *testSignals2 = @{
  1709. @"signal1" : @"updatedValue1",
  1710. @"signal2" : [NSNull null],
  1711. @"signal3" : @5,
  1712. };
  1713. // Expected final set of signals
  1714. NSDictionary<NSString *, NSString *> *expectedSignals = @{
  1715. @"signal1" : @"updatedValue1",
  1716. @"signal3" : @"5",
  1717. };
  1718. [_configInstances[i] setCustomSignals:testSignals1
  1719. withCompletion:^(NSError *_Nullable error) {
  1720. XCTAssertNil(error);
  1721. [self->_configInstances[i]
  1722. setCustomSignals:testSignals2
  1723. withCompletion:^(NSError *_Nullable error) {
  1724. XCTAssertNil(error);
  1725. NSDictionary<NSString *, NSString *> *retrievedSignals =
  1726. self->_configInstances[i].settings.customSignals;
  1727. XCTAssertEqualObjects(retrievedSignals, expectedSignals);
  1728. [expectations[i] fulfill];
  1729. }];
  1730. }];
  1731. }
  1732. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1733. }
  1734. - (void)testSetCustomSignals_invalidInput_throwsException {
  1735. NSMutableArray<XCTestExpectation *> *expectations =
  1736. [[NSMutableArray alloc] initWithCapacity:RCNTestRCNumTotalInstances];
  1737. for (int i = 0; i < RCNTestRCNumTotalInstances; i++) {
  1738. expectations[i] =
  1739. [self expectationWithDescription:
  1740. [NSString stringWithFormat:@"Set custom signals expects error - instance %d", i]];
  1741. // Invalid value type.
  1742. NSDictionary<NSString *, NSObject *> *invalidSignals1 = @{@"name" : [NSDate date]};
  1743. // Key length exceeds limit.
  1744. NSDictionary<NSString *, NSObject *> *invalidSignals2 =
  1745. @{[@"a" stringByPaddingToLength:251 withString:@"a" startingAtIndex:0] : @"value"};
  1746. // Value length exceeds limit.
  1747. NSDictionary<NSString *, NSObject *> *invalidSignals3 =
  1748. @{@"key" : [@"a" stringByPaddingToLength:501 withString:@"a" startingAtIndex:0]};
  1749. [_configInstances[i]
  1750. setCustomSignals:invalidSignals1
  1751. withCompletion:^(NSError *_Nullable error) {
  1752. XCTAssertNotNil(error);
  1753. XCTAssertEqual(error.code, FIRRemoteConfigCustomSignalsErrorInvalidValueType);
  1754. }];
  1755. [_configInstances[i]
  1756. setCustomSignals:invalidSignals2
  1757. withCompletion:^(NSError *_Nullable error) {
  1758. XCTAssertNotNil(error);
  1759. XCTAssertEqual(error.code, FIRRemoteConfigCustomSignalsErrorLimitExceeded);
  1760. }];
  1761. [_configInstances[i]
  1762. setCustomSignals:invalidSignals3
  1763. withCompletion:^(NSError *_Nullable error) {
  1764. XCTAssertNotNil(error);
  1765. XCTAssertEqual(error.code, FIRRemoteConfigCustomSignalsErrorLimitExceeded);
  1766. [expectations[i] fulfill];
  1767. }];
  1768. }
  1769. [self waitForExpectationsWithTimeout:_expectationTimeout handler:nil];
  1770. }
  1771. #pragma mark - Test Helpers
  1772. - (FIROptions *)firstAppOptions {
  1773. // TODO: Evaluate if we want to hardcode things here instead.
  1774. FIROptions *options = [[FIROptions alloc] initWithGoogleAppID:@"1:123:ios:123abc"
  1775. GCMSenderID:@"correct_gcm_sender_id"];
  1776. options.APIKey = @"AIzaSy-ApiKeyWithValidFormat_0123456789";
  1777. options.projectID = @"abc-xyz-123";
  1778. return options;
  1779. }
  1780. - (FIROptions *)secondAppOptions {
  1781. NSBundle *bundle = [NSBundle bundleForClass:[self class]];
  1782. #if SWIFT_PACKAGE
  1783. bundle = SWIFTPM_MODULE_BUNDLE;
  1784. #endif
  1785. NSString *plistPath = [bundle pathForResource:@"SecondApp-GoogleService-Info" ofType:@"plist"];
  1786. FIROptions *options = [[FIROptions alloc] initWithContentsOfFile:plistPath];
  1787. XCTAssertNotNil(options);
  1788. return options;
  1789. }
  1790. @end