Skip to content

Commit 27e0703

Browse files
LaunchDarklyReleaseBottorchhoundgavwhelatorchhoundarun251
authored
prepare 3.1.8 release (#184)
* Removed unnecessary ListenableFuture in LDClient init, changed identify method for multi-environment, not sure about SettableFuture null vs null for return type of Future<Void>, both type check and pass tests * Added setOnlineStatus multi-environment changes * Moved primaryEnvironmentName to LDConfig, simplifying by removing primaryKey separation everywhere but the builder. Add getRequestBuilderFor a specific environment. Add static method to LDClient to get all environment names so that environments can be iterated over. Add accessor to retrieve LDClient specific UserManager. Iterate over all environments in PollingUpdater. Add environment argument to UserManager constructor, removing singleton and creating replacing init with newInstance static method. * Add back in constructor without environment to UserManager * Specialize HttpFeatureFlagFetcher to the environment, looks like UserManager may not be able to do the same so removed the environment from the constructor. * Added SharedPreferences migration strategy * All tests pass, fixed migration strategy to conform to spec, fixed primaryInstance null when offline in init, fixed primaryEnvironmentName being added to secondaryMobileKeys * Update StreamUpdateProcessor construct to take an environment for the authorization header key. * Fix issue with LDConfig mobileKeys hashmap creation. * Combine futures so LDClient init future waits on all online instances of LDClient. * Propagate IOException on closing instances to caller. * Merge futures for identify call. * Some changes from code review. * Removed static from instanceId and now old SharedPreferences will only cleared once all environments have a copy in LDClient * Fixed instanceId * Updates from PR review. * Added version and flagVersion, if available * refactor(LDClient, LDConfig): changes for PR * refactor(LDClient): changed isInternetConnected behavior for PR * refactor(LDClient): removed async getForMobileKeys and wait seconds version, replaced with method that returns requested instance * Bugfix/timber cleanup (#92) Relates to #60 Cleaned up timber logging messages to use string formatting rather than concatenation. Log messages should remain the same as before. Also replaced Log with Timber in the example app. * Fix crash when example app is backgrounded twice. * Add security provider update mechanism using Google Play Services to attempt a provider update when TLSv1.2 is not available. * Shared Preferences Fix for Multi Environment (#94) * fix(SharedPreferences): added more SharedPreferences first time migration and differentiated SharedPreferences by mobile key * fix(UserLocalSharePreference.java): added missing mobileKey additions to getSharedPreferences, cleaned up debugging code * Fix edge cases in how multi-environment handles connection changes. * fix(UserManagerTest.java): incorrect number of arguments to UserManager instantiation in unit test * Remove line of testing code accidentally left in and refactor shared preferences migration to make future migrations easier. * Final fixes to store migration. Should be fairly future proof. * Fix issue with primitive variation calls always returning null if fallback is null. * Remove CircleCI V1 config file. (#97) * Remove getting/comparing versions as floats (#99) To prevent floating point errors in flag version comparisons. * Include values in unknown summary events and compare values for (#100) equality when creating new summary counters. * simplify flag property deserialization * rm debugging * misc cleanup * rm debugging * add eval reason data model classes * misc fixes * serialize reason * add ability to receive evaluation reasons from LD * Changed shared preferences store system to user a single FlagStore system that holds all the information on a flag to prevent issues arising from unsynchronized separate stores for flag meta-data and values. * add methods to get value with explanation; refactor existing variation methods * Abstract FlagStoreManager from FlagStore, new FlagStoreFactory class so manager can construct FlagStores of unknown type. Reformatted interfaces. Removed unused imports. * Handle null case in allFlags, actually commit changes to UserManager. * Hopefully fix edge cases in summary event reporting to pass testing. * Hopefully fix edge cases in summary event reporting to pass testing. * Simplify getFeaturesJsonObject as no longer using -1 as placeholder for null for variations. * Make Flag non-mutable. Move GsonCache to gson package, move custom serializer/deserializers to classes in gson package and create one for PUT responses. Removed BaseUserSharedPreferences. * Send summary event even if stored flag doesn't exist. * Move sendSummaryEvent update code to UserSummaryEventSharedPreferences to synchronize to prevent data race on sending, updating, and clearing event store. Move SummaryEventSharedPreferences and UserSummaryEventSharedPreferences out of response package. * Update SharedPrefsFlagStore to hold StoreUpdatedListener in weak reference. Fix various warnings. * Migration code for upcoming flagstore. * Remove couple of debug messages. * Handle todos. * Revert to old String behavior for allFlags, initialize WeakReference in SharedPrefsFlagStore. * Better implementation of EvaluationReason serialization type adapter. * Revert "Better implementation of EvaluationReason serialization type adapter." Wrong branch... This reverts commit 69c1c9b. * Gw/ch29266/flagstore (#105) * Changed shared preferences store system to user a single FlagStore system that holds all the information on a flag to prevent issues arising from unsynchronized separate stores for flag meta-data and values. * Abstract FlagStoreManager from FlagStore, new FlagStoreFactory class so manager can construct FlagStores of unknown type. Reformatted interfaces. Removed unused imports. * Handle null case in allFlags, actually commit changes to UserManager. * Hopefully fix edge cases in summary event reporting to pass testing. * Hopefully fix edge cases in summary event reporting to pass testing. * Simplify getFeaturesJsonObject as no longer using -1 as placeholder for null for variations. * Make Flag non-mutable. Move GsonCache to gson package, move custom serializer/deserializers to classes in gson package and create one for PUT responses. Removed BaseUserSharedPreferences. * Send summary event even if stored flag doesn't exist. * Move sendSummaryEvent update code to UserSummaryEventSharedPreferences to synchronize to prevent data race on sending, updating, and clearing event store. Move SummaryEventSharedPreferences and UserSummaryEventSharedPreferences out of response package. * Update SharedPrefsFlagStore to hold StoreUpdatedListener in weak reference. Fix various warnings. * Migration code for upcoming flagstore. * Remove couple of debug messages. * Handle todos. * Revert to old String behavior for allFlags, initialize WeakReference in SharedPrefsFlagStore. * Better implementation of EvaluationReason serialization type adapter. * Remove isUnknown argument from SummaryEventSharedPreferences methods. Use Runnable instead of Callable in UserManager to avoid useless return nulls. Rename FlagStoreFactoryInterface to FlagStoreFactory. * Statically initialize Gson instance in GsonCache. * Make Gson instance in GsonCache final on principle. * Return json flags as JsonElement in allFlags map. (#106) * Bump ok-http version to 3.9.1 (#107) * fix annotations so eval reasons are serialized in events * fix/expand doc comments for public methods * typo * typo * add version string getter method * Check for null key before file comparison check. (#110) * [ch33658] Add unsafeReset() for LDClient testing re-initialization (#111) Add `unsafeReset()` method to close and clear instances for re-initializing client between tests. Update LDClientTest to call `unsafeReset()` before tests. * [ch33846] Rename tests to not start with capitals and general refactoring (#112) * Rename tests to not start with capitals * Reindent MultiEnvironmentLDClientTest to be consistent * Optimize imports * Move TLS patch into TLSUtils * Make setModernTlsVersionsOnSocket private and remove redundant null check * Remove code duplication in LDClient track overloaded methods. * Remove validateParameter in LDClient that was using a NullPointerException as a null test. * Simplify Debounce to use listener instead of callback. * Add documentation for flagstore implementation (#113) * [ch35150] Unit tests and bug fixes (#114) - Use android test orchestrator to run tests isolated from each other. This prevents the issues testing singletons. Also enabled option to clear package data between runs allowing more extensive flagstore testing. - Remove unsafe reset as it was added only for allowing testing the LDClient singleton. - Tests for new FlagStore code. - Convenience test FlagBuilder - Fix Migration to not turn all flags into Strings - Fix issue with clearAndApplyFlagUpdates not generating correct events for listeners. * Add compatibility behavior to stringVariation and allFlags methods. (#115) If a Json flag is requested with stringVariation it will serialize it to a String. Json flags will also be serialized to Strings for the map returned by allFlags() * Update LDUser not to store all fields as Json. (#116) Add testing rule to setup and teardown Timber trees for debug logging. Add additional LDUser tests. Fixed a bit of flakiness in deletesOlderThanLastFiveStoredUsers test that showed up all of a sudden. * Add metricValue field to CustomEvent, add overloaded track method for (#118) creating custom events with metricValues. * [ch37794] Run connected emulator tests in CircleCI (#120) * [ch34533] connection status, removing guava, network restructuring. (#117) * Add ConnectionInformation class. * Remove all internal uses of Guava. * Update StreamUpdateProcessor to only debounce ping events. * Add a connection state monitor to the example app. * rename repo and package name and apply markdown templates (#121) * Fix issue that stream could be started before stopping when calling identify. (#122) * Revert "Fix issue that stream could be started before stopping when calling identify. (#122)" This reverts commit fdede38. * Revert "rename repo and package name and apply markdown templates (#121)" This reverts commit 2215275. * Revert "Revert "Fix issue that stream could be started before stopping when calling identify. (#122)"" This reverts commit 0849812. * Revert "Revert "rename repo and package name and apply markdown templates (#121)"" This reverts commit bbbeb81. * Fix thread leak on identify call from restarting EventProcessor without shutting it down first. (#123) * Add top level try/catch to migration methods. Check flag version SharedPreferences object for String type before cast. (#124) * Update Throttler to call runnable on background thread. (#125) * Fix ConcurrentModificationException of instance map (#126) Move iteration over client instances for ConnectivityReceiver and PollingUpdater to within LDClient to allow synchronizing on initialization. * adding a circleci badge to the readme (#127) * Fix bug where `stop` in StreamUpdateProcessor could not call it's listener when the stream is already closed. This caused a race condition in repeated stream restarts that could put the SDK in a bad state. * Change LDAwaitFuture to not treat zero timeout as unlimited timeout Treating a timeout of zero as unlimited caused a change in behavior when initializing the SDK. This update restores the behavior init had when zero was passed as the timeout argument from pre-2.8.0. Also improves handling of spurious wakeups, and includes test cases for LDAwaitFuture. * Revert "Merge remote-tracking branch 'remotes/origin/experiment' into next-release" This reverts commit 3ac167f, reversing changes made to d26e006. * CircleCI fixes (#131) * Better ci fix (#132) * Speedup tests by building on macOS (#137) * Background identify fixes (#133) Add new testing controllers for network and foreground states. For network control, mobile data must be disabled on recent Android versions, updated circleci config to do this. Add new connectivity manager tests. Made EventProcessor and UserManager minimal interfaces for mocking, with actual implementations moved to DefaultEventProcessor and DefaultUserManager. Fixed issue with blocking in background modes. * Experimentation 1.5 updates (#134) * add entire compile-time classpath to javadoc classpath * javadoc fixes: <p/> is not a thing * do fail on javadoc errors * add javadoc step, misc CI cleanup * misc javadoc fixes * remove unintentional(?) immediate event flush; clean up event tests * remove unreliable test assumption about elapsed time * [ch57098] Deprecate LDCountryCode (#141) Deprecate LDCountryCode class and LDUser setters that take LDCountryCode as an argument. * Catch `SecurityException` when setting alarm in case there are already (#143) the maximum allowed number of alarms on Samsung devices. * Revert "[ch57098] Deprecate LDCountryCode (#141)" so we can do a patch release first. This reverts commit c0e71ae. * Revert "Revert "[ch57098] Deprecate LDCountryCode (#141)" so we can do a patch release" This reverts commit 23b930f. * Deprecate public classes (#145) * Deprecate some unnecessarily public classes, duplicate classes as non-public to avoid using the deprecated classes. * [ch61092] Add event payload ID. (#147) * Add event retry. (#149) * Fix javadoc comment for release. * Fix broken merge. * [ch65133] Deprecate classes (#150) * Deprecate UserSummaryEventSharedPreferences, SummaryEventSharedPreferences, FeatureFlagFetcher, Util, Debounce. * Improve Javadoc and reduce interface clutter. (#152) * Save Javadoc artifact and include logcat in circle output with tee. (#153) * Save Javadoc artifact on circleci. * Add step to kill emulator after tests, and tee output of logcat for visibility during run. * [ch62120] Background during identify callback (#154) * Adding more connectivity manager tests. * Updated internal `Foreground` class to call listeners on a background thread. * Add some comments explaining the behavior of test controllers. * Adding fixes for cases where the completion callback may not be called. * [ch65914] Diagnostic events (#156) * [ch65352] Expose LDValue rather than Gson types (#158) * Remove SET_ALARM permission. The comment that this was required for background updating is incorrect, this permission is only for sending broadcasts to an alarm clock application, something we do not do, and should never do. (#159) * Fix minimum diagnostic recording interval comment. (#160) * Data since date was not getting reset after each periodic diagnostic event. (#161) * [ch75315] Add maxCachedUsers configuration option (#162) Adds maxCachedUsers configuration option for configuring the limit on how many users have their flags cached locally. * Configure okhttp cache for polling requests to be stored in a subdirectory of the application cache directory. (#164) * Fixes ch76614 and add test of null fallback unknown flag event generation. Also some finishing touches to LDValue changes, including LDClientInterface updates, more tests, and improvements to null behavior handling. (#163) * Removing ldvalue changes before release (#165) * Revert "[ch65352] Expose LDValue rather than Gson types (#158)" This reverts commit 1e29a82 * Fixes after revert. * [ch69437] Support for setting additional headers to be included in requests. (#166) * [ch89933] Improve resiliency of store for summary events. (#167) See #105 for the original issue. * [ch94053] Improve throttler behavior. (#169) * Add doubleVariation, doubleVariationDetail. (#171) Deprecates floatVariation, floatVariationDetail. * Provide pollUri configuration and deprecate baseUri. (#172) * Fix throttler behavior to ensure attempt count resets are not cancelled (#178) * [ch98336] Broaden catch statement on scheduling polling alarm (#181) This is to handle more than just the SecurityException that Samsung throws, as we've gotten an issue report that some devices throw a IllegalStateException instead. * Removed the guides link * Include flag key in warning message when converting a json flag to a string (#185) * (2.x) Prevent NullPointerException when diagnostic processor shut down before starting. (#210) * Release 2.14.2 (#130) ## [2.14.2] - 2021-06-02 ### Fixed - Added check to prevent `NullPointerException` in `DiagnosticEventProcessor.stopScheduler` when `LDClient.close` is called before the application is foregrounded when the SDK was initialized in the background. ([#127](#127)) - Log message warning that JSON flag was requested as a String has been updated to include the key of the flag requested to assist in discovering which flag is being requested with an unexpected type. ([#116](#116)) * Bump version and update changelog for release. * Explicitly specify android:exported attribute on manifest receivers. (#211) * Update java common (#212) * Flag PendingIntent on new enough platforms as the flag is required on Android S+ (#213) * Add try for getting network capabilities (#214) * ch103537 bump java-sdk-common to 1.2 to support inExperiment on eval reason (#215) * Remove `allowBackup` manifest attribute that can conflict with the application's (#217) * Update the version to 2.8.9 * Add explicit proguard directives for keeping BroadcastReceivers. (#219) * Using the version that still support Java 8 but pin the grgit core behind the scene * Remove Android Appcompat dependency (#222) * Bump dependencies and reorganize Gradle file somewhat. (#223) * Add the null check to prevent multiple allocation of the DiagnosticEventProcessor * Fix sonatype release plugin (#226) * Add .ldrelease configuration (#227) * Add contract test service (#228) * Fix test service failing on later API versions (#229) * Add usesCleartextTraffic=true to contract-tests AndroidManifest This allows the contract tests to work on API level 28 and above * Fix start-emulator.sh to pick the newest image instead of the oldest * Refactor CI config into separate jobs with a matrix (#230) * Don't auto-retry emulator tests (#231) * Add contract tests for API level 21 (#232) * Remove unnecessary locking in LDClient (#233) * Remove `synchronized` keywords from every `LDClient` method * Treat `instances` as immutable, and swap out the whole map after constructing all the clients * Use a lock to ensure we don't try to init twice * Update `ConnectivityManager` so it now manages `DiagnosticEventManager` * Run contract tests on Android 31, 33 (#234) * Unsuppress streaming/requests and polling/requests (#236) * don't create a new executor just to trigger a flush * remove short publishing timeout, use defaults of 60 retries & 10 seconds * Serialize null values of `anonymous` as null (#237) * fix URL path concatenation to avoid double slashes * fix NPE in edge case where variation is null but value isn't * use SecureRandom instead of Random, just to make scanners happier * rm unused * fix deletion versioning logic, implement tombstones (#244) * disable contract tests for API 31/33 * use okhttp-eventsource 1.11.3 * ensure timed-out clients get closed in contract tests * clean up instances map on close (#247) * clean up instances map on close * improve atomicity of access to instances, ensure they can't be modified via closed clients * update more methods that iterate over instances * rm unnecessary LDClientControl Co-authored-by: torchhound <[email protected]> Co-authored-by: Gavin Whelan <[email protected]> Co-authored-by: torchhound <[email protected]> Co-authored-by: Arun Bhalla <[email protected]> Co-authored-by: jamesthacker <[email protected]> Co-authored-by: Gavin Whelan <[email protected]> Co-authored-by: torchhound <[email protected]> Co-authored-by: Eli Bishop <[email protected]> Co-authored-by: Ben Woskow <[email protected]> Co-authored-by: Ben Woskow <[email protected]> Co-authored-by: Elliot <[email protected]> Co-authored-by: Robert J. Neal <[email protected]> Co-authored-by: Louis Chan <[email protected]> Co-authored-by: Louis Chan <[email protected]> Co-authored-by: Alex Engelberg <[email protected]> Co-authored-by: LaunchDarklyReleaseBot <[email protected]>
1 parent 6c28e9b commit 27e0703

File tree

22 files changed

+206
-237
lines changed

22 files changed

+206
-237
lines changed

.circleci/config.yml

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -15,26 +15,31 @@ workflows:
1515
# - 21 - TODO: EasyMock makes our tests fail
1616
- 25
1717
# - 29 - TODO: offline tests fail
18+
# Contract tests are temporarily disabled for API 31 and API 33 due to a degree of
19+
# test instability that impedes development. Currently there are two common failure
20+
# modes: SDK initialization times out, or SDK initialization completes immediately
21+
# without acquiring any data because the emulator reports no network availability.
22+
# These do not appear correlated to any actual SDK logic flaw.
1823
- contract-tests:
1924
matrix:
2025
parameters:
2126
api-level:
2227
- 21
2328
- 25
2429
- 30
25-
- 31
26-
# "default" images are faster than "google_apis" images, but are otherwise equivalent for our purposes.
27-
# however, there are no "default" images for Android 32+, so as a workaround we have a separate matrix
28-
# for Android 32+
29-
- contract-tests:
30-
matrix:
31-
parameters:
32-
api-level:
33-
- 33
34-
system-image-type:
35-
- google_apis
36-
resource-class:
37-
- xlarge
30+
# - 31
31+
# # "default" images are faster than "google_apis" images, but are otherwise equivalent for our purposes.
32+
# # however, there are no "default" images for Android 32+, so as a workaround we have a separate matrix
33+
# # for Android 32+
34+
# - contract-tests:
35+
# matrix:
36+
# parameters:
37+
# api-level:
38+
# - 33
39+
# system-image-type:
40+
# - google_apis
41+
# resource-class:
42+
# - xlarge
3843

3944
commands:
4045
check-emulator-available:

build.gradle

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -64,9 +64,4 @@ nexusPublishing {
6464
repositories {
6565
sonatype()
6666
}
67-
68-
transitionCheckOptions {
69-
maxRetries.set(20)
70-
delayBetween.set(Duration.ofMillis(3000))
71-
}
72-
}
67+
}

contract-tests/src/main/java/com/launchdarkly/sdk/android/LDClientControl.java

Lines changed: 0 additions & 21 deletions
This file was deleted.

contract-tests/src/main/java/com/launchdarkly/sdktest/SdkClientEntity.java

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
import com.launchdarkly.sdk.android.LaunchDarklyException;
77
import com.launchdarkly.sdk.android.LDClient;
88
import com.launchdarkly.sdk.android.LDConfig;
9-
import com.launchdarkly.sdk.android.LDClientControl;
109

1110
import com.launchdarkly.sdktest.Representations.AliasEventParams;
1211
import com.launchdarkly.sdktest.Representations.CommandParams;
@@ -45,8 +44,6 @@ public class SdkClientEntity {
4544

4645
public SdkClientEntity(Application application, CreateInstanceParams params) {
4746
Timber.i("Creating client for %s", params.tag);
48-
LDClientControl.resetInstances();
49-
Timber.i("Reset global state to allow for another client");
5047
LDConfig config = buildSdkConfig(params.configuration);
5148
// Each new client will plant a new Timber tree, so we uproot any existing ones
5249
// to avoid spamming stdout with duplicate log lines
@@ -70,6 +67,9 @@ public SdkClientEntity(Application application, CreateInstanceParams params) {
7067
this.client = LDClient.get();
7168
if (!client.isInitialized() && !params.configuration.initCanFail) {
7269
// If `initCanFail` is true, we can proceed with an uninitialized client
70+
try {
71+
client.close();
72+
} catch (IOException e) {}
7373
throw new RuntimeException("client initialization failed or timed out");
7474
}
7575
} catch (LaunchDarklyException e) {
@@ -171,7 +171,11 @@ private EvaluateAllFlagsResponse doEvaluateAll(EvaluateAllFlagsParams params) {
171171
}
172172

173173
private void doIdentifyEvent(IdentifyEventParams params) {
174-
client.identify(params.user);
174+
try {
175+
client.identify(params.user).get();
176+
} catch (ExecutionException | InterruptedException e) {
177+
throw new RuntimeException("Error waiting for identify", e);
178+
}
175179
}
176180

177181
private void doCustomEvent(CustomEventParams params) {

launchdarkly-android-client-sdk/build.gradle

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ configurations {
5555
ext {}
5656
ext.versions = [
5757
"androidAnnotation": "1.2.0",
58-
"eventsource": "1.11.2",
58+
"eventsource": "1.11.3",
5959
"gson": "2.8.9",
6060
"jacksonCore": "2.10.5",
6161
"jacksonDatabind": "2.10.5.1",

launchdarkly-android-client-sdk/src/androidTest/java/com/launchdarkly/sdk/android/DefaultUserManagerTest.java

Lines changed: 14 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -195,8 +195,11 @@ public void testDeleteFlag() throws ExecutionException {
195195
AwaitableCallback<Void> deleteAwait = new AwaitableCallback<>();
196196
userManager.deleteCurrentUserFlag("{\"key\":\"stringFlag1\",\"version\":16}", deleteAwait);
197197
deleteAwait.await();
198-
assertNull(flagStore.getFlag("stringFlag1"));
199-
assertEquals(true, flagStore.getFlag("boolFlag1").getValue().booleanValue());
198+
Flag updated = flagStore.getFlag("stringFlag1");
199+
assertNotNull(updated);
200+
assertEquals("stringFlag1", updated.getKey());
201+
assertEquals(16, updated.getVersion());
202+
assertTrue(updated.isDeleted());
200203

201204
deleteAwait.reset();
202205
userManager.deleteCurrentUserFlag("{\"key\":\"nonExistentFlag\",\"version\":16,\"value\":false}", deleteAwait);
@@ -274,7 +277,8 @@ public void testDeleteWithVersion() throws ExecutionException {
274277
userManager.deleteCurrentUserFlag("{\"key\":\"stringFlag1\",\"version\":127}", awaitableCallback);
275278
awaitableCallback.await();
276279
awaitableCallback.reset();
277-
assertNull(flagStore.getFlag("stringFlag1"));
280+
assertNotNull(flagStore.getFlag("stringFlag1"));
281+
assertTrue(flagStore.getFlag("stringFlag1").isDeleted());
278282

279283
userManager.deleteCurrentUserFlag("{\"key\":\"nonExistent\",\"version\":1}", awaitableCallback);
280284
awaitableCallback.await();
@@ -323,32 +327,13 @@ public void testPatchSucceedsForMissingVersionInPatch() throws ExecutionExceptio
323327
FlagStore flagStore = userManager.getCurrentUserFlagStore();
324328
AwaitableCallback<Void> awaitableCallback = new AwaitableCallback<>();
325329

326-
// version does not exist in shared preferences and patch.
327-
// ---------------------------
328-
//// case 1: value does not exist in shared preferences.
329-
userManager.patchCurrentUserFlags("{\"key\":\"flag1\",\"value\":\"value-from-patch\"}", awaitableCallback);
330-
awaitableCallback.await();
331-
awaitableCallback.reset();
332-
Flag flag1 = flagStore.getFlag("flag1");
333-
assertEquals("value-from-patch", flag1.getValue().stringValue());
334-
assertNull(flag1.getVersion());
335-
336-
//// case 2: value exists in shared preferences without version.
337-
userManager.putCurrentUserFlags("{\"flag1\": {\"value\": \"value1\"}}", null);
338-
userManager.patchCurrentUserFlags("{\"key\":\"flag1\",\"value\":\"value-from-patch\"}", awaitableCallback);
339-
awaitableCallback.await();
340-
awaitableCallback.reset();
341-
flag1 = flagStore.getFlag("flag1");
342-
assertEquals("value-from-patch", flag1.getValue().stringValue());
343-
assertNull(flag1.getVersion());
344-
345330
// version does not exist in shared preferences but exists in patch.
346331
// ---------------------------
347332
//// case 1: value does not exist in shared preferences.
348333
userManager.patchCurrentUserFlags("{\"key\":\"flag1\",\"version\":558,\"flagVersion\":3,\"value\":\"value-from-patch\",\"variation\":1,\"trackEvents\":false}", awaitableCallback);
349334
awaitableCallback.await();
350335
awaitableCallback.reset();
351-
flag1 = flagStore.getFlag("flag1");
336+
Flag flag1 = flagStore.getFlag("flag1");
352337
assertEquals("value-from-patch", flag1.getValue().stringValue());
353338
assertEquals(558, (int) flag1.getVersion());
354339
assertEquals(3, (int) flag1.getFlagVersion());
@@ -361,21 +346,9 @@ public void testPatchSucceedsForMissingVersionInPatch() throws ExecutionExceptio
361346
awaitableCallback.reset();
362347
flag1 = flagStore.getFlag("flag1");
363348
assertEquals("value-from-patch", flag1.getValue().stringValue());
364-
assertEquals(558, (int) flag1.getVersion());
365-
assertEquals(3, (int) flag1.getFlagVersion());
366-
assertEquals(3, (int) flag1.getVersionForEvents());
367-
368-
// version exists in shared preferences but does not exist in patch.
369-
// ---------------------------
370-
userManager.putCurrentUserFlags("{\"flag1\": {\"version\": 558, \"flagVersion\": 110,\"value\": \"value1\", \"variation\": 1, \"trackEvents\": false}}", null);
371-
userManager.patchCurrentUserFlags("{\"key\":\"flag1\",\"value\":\"value-from-patch\"}", awaitableCallback);
372-
awaitableCallback.await();
373-
awaitableCallback.reset();
374-
flag1 = flagStore.getFlag("flag1");
375-
assertEquals("value-from-patch", flag1.getValue().stringValue());
376-
assertNull(flag1.getVersion());
377-
assertNull(flag1.getFlagVersion());
378-
assertNull(flag1.getVersionForEvents());
349+
assertEquals(558, flag1.getVersion());
350+
assertEquals(Integer.valueOf(3), flag1.getFlagVersion());
351+
assertEquals(3, flag1.getVersionForEvents());
379352

380353
// version exists in shared preferences and patch.
381354
// ---------------------------
@@ -384,9 +357,9 @@ public void testPatchSucceedsForMissingVersionInPatch() throws ExecutionExceptio
384357
awaitableCallback.await();
385358
flag1 = flagStore.getFlag("flag1");
386359
assertEquals("value-from-patch", flag1.getValue().stringValue());
387-
assertEquals(559, (int) flag1.getVersion());
388-
assertEquals(3, (int) flag1.getFlagVersion());
389-
assertEquals(3, (int) flag1.getVersionForEvents());
360+
assertEquals(559, flag1.getVersion());
361+
assertEquals(Integer.valueOf(3), flag1.getFlagVersion());
362+
assertEquals(3, flag1.getVersionForEvents());
390363
}
391364

392365
@Test

launchdarkly-android-client-sdk/src/androidTest/java/com/launchdarkly/sdk/android/FlagBuilder.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ public class FlagBuilder {
1010
@NonNull
1111
private String key;
1212
private LDValue value = null;
13-
private Integer version = null;
13+
private int version;
1414
private Integer flagVersion = null;
1515
private Integer variation = null;
1616
private Boolean trackEvents = null;
@@ -27,7 +27,7 @@ public FlagBuilder value(LDValue value) {
2727
return this;
2828
}
2929

30-
public FlagBuilder version(Integer version) {
30+
public FlagBuilder version(int version) {
3131
this.version = version;
3232
return this;
3333
}

launchdarkly-android-client-sdk/src/androidTest/java/com/launchdarkly/sdk/android/FlagStoreTest.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ public boolean matches(Object argument) {
5151
Objects.equals(flag.getVersion(), received.getVersion()) &&
5252
Objects.equals(flag.getFlagVersion(), received.getFlagVersion()) &&
5353
Objects.equals(flag.getVariation(), received.getVariation()) &&
54-
Objects.equals(flag.getTrackEvents(), received.getTrackEvents()) &&
54+
Objects.equals(flag.isTrackEvents(), received.isTrackEvents()) &&
5555
Objects.equals(flag.isTrackReason(), received.isTrackReason()) &&
5656
Objects.equals(flag.getDebugEventsUntilDate(),
5757
received.getDebugEventsUntilDate()) &&
@@ -79,7 +79,7 @@ private void assertExpectedFlag(Flag expected, Flag received) {
7979
assertEquals(expected.getVersion(), received.getVersion());
8080
assertEquals(expected.getFlagVersion(), received.getFlagVersion());
8181
assertEquals(expected.getVariation(), received.getVariation());
82-
assertEquals(expected.getTrackEvents(), received.getTrackEvents());
82+
assertEquals(expected.isTrackEvents(), received.isTrackEvents());
8383
assertEquals(expected.isTrackReason(), received.isTrackReason());
8484
assertEquals(expected.getDebugEventsUntilDate(), received.getDebugEventsUntilDate());
8585
assertEquals(expected.getReason(), received.getReason());
@@ -204,7 +204,7 @@ public void mockFlagDeleteBehavior() {
204204

205205
@Test
206206
public void testUnregisterStoreUpdate() {
207-
final Flag initialFlag = new FlagBuilder("flag").build();
207+
final Flag initialFlag = new FlagBuilder("flag").version(10).build();
208208

209209
final FlagUpdate mockCreate = strictMock(FlagUpdate.class);
210210
expect(mockCreate.flagToUpdate()).andReturn("flag");

launchdarkly-android-client-sdk/src/androidTest/java/com/launchdarkly/sdk/android/LDClientTest.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -602,7 +602,7 @@ public void variationFlagTrackReasonGeneratesEventWithReason() throws IOExceptio
602602
TestUtil.markMigrationComplete(application);
603603
EvaluationReason testReason = EvaluationReason.off();
604604
FlagStore flagStore = new SharedPrefsFlagStoreFactory(application).createFlagStore(mobileKey + DefaultUserManager.sharedPrefs(ldUser));
605-
flagStore.applyFlagUpdate(new FlagBuilder("track-reason-flag").trackEvents(true).trackReason(true).reason(testReason).build());
605+
flagStore.applyFlagUpdate(new FlagBuilder("track-reason-flag").version(10).trackEvents(true).trackReason(true).reason(testReason).build());
606606

607607
try (LDClient client = LDClient.init(application, ldConfig, ldUser, 0)) {
608608
client.boolVariation("track-reason-flag", false);
@@ -615,7 +615,7 @@ public void variationFlagTrackReasonGeneratesEventWithReason() throws IOExceptio
615615
assertEquals("track-reason-flag", event.key);
616616
assertEquals("userKey", event.userKey);
617617
assertNull(event.variation);
618-
assertNull(event.version);
618+
assertEquals(Integer.valueOf(10), event.version);
619619
assertFalse(event.value.booleanValue());
620620
assertFalse(event.defaultVal.booleanValue());
621621
assertEquals(testReason, event.reason);

launchdarkly-android-client-sdk/src/androidTest/java/com/launchdarkly/sdk/android/SharedPrefsFlagStoreTest.java

Lines changed: 28 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,9 @@
1515
import java.util.Collections;
1616

1717
import static org.junit.Assert.assertEquals;
18+
import static org.junit.Assert.assertFalse;
19+
import static org.junit.Assert.assertNotNull;
20+
import static org.junit.Assert.assertTrue;
1821

1922
@RunWith(AndroidJUnit4.class)
2023
public class SharedPrefsFlagStoreTest extends FlagStoreTest {
@@ -34,51 +37,60 @@ public FlagStore createFlagStore(String identifier) {
3437
}
3538

3639
@Test
37-
public void deletesVersions() {
40+
public void deletesVersionAndStoresDeletedItemPlaceholder() {
3841
final Flag key1 = new FlagBuilder("key1").version(12).build();
3942

4043
final SharedPrefsFlagStore flagStore = new SharedPrefsFlagStore(testApplication, "abc");
4144
flagStore.applyFlagUpdates(Collections.<FlagUpdate>singletonList(key1));
42-
flagStore.applyFlagUpdate(new DeleteFlagResponse(key1.getKey(), null));
45+
flagStore.applyFlagUpdate(new DeleteFlagResponse(key1.getKey(), 13));
4346

44-
Assert.assertNull(flagStore.getFlag(key1.getKey()));
47+
Flag updated = flagStore.getFlag(key1.getKey());
48+
assertNotNull(updated);
49+
assertEquals(key1.getKey(), updated.getKey());
50+
assertEquals(13, updated.getVersion());
51+
assertTrue(updated.isDeleted());
4552
}
4653

4754
@Test
48-
public void updatesVersions() {
55+
public void doesNotDeleteIfDeletionVersionIsLessThanOrEqualToExistingVersion() {
4956
final Flag key1 = new FlagBuilder("key1").version(12).build();
50-
final Flag updatedKey1 = new FlagBuilder(key1.getKey()).version(15).build();
5157

5258
final SharedPrefsFlagStore flagStore = new SharedPrefsFlagStore(testApplication, "abc");
5359
flagStore.applyFlagUpdates(Collections.<FlagUpdate>singletonList(key1));
54-
55-
flagStore.applyFlagUpdate(updatedKey1);
56-
57-
assertEquals(flagStore.getFlag(key1.getKey()).getVersion(), 15, 0);
60+
flagStore.applyFlagUpdate(new DeleteFlagResponse(key1.getKey(), 11));
61+
flagStore.applyFlagUpdate(new DeleteFlagResponse(key1.getKey(), 12));
62+
63+
Flag updated = flagStore.getFlag(key1.getKey());
64+
assertEquals(key1.getKey(), updated.getKey());
65+
assertEquals(key1.getVersion(), updated.getVersion());
66+
assertEquals(key1.getValue(), updated.getValue());
67+
assertFalse(updated.isDeleted());
5868
}
5969

6070
@Test
61-
public void deletesFlagVersions() {
62-
final Flag key1 = new FlagBuilder("key1").flagVersion(12).build();
71+
public void updatesVersions() {
72+
final Flag key1 = new FlagBuilder("key1").version(12).build();
73+
final Flag updatedKey1 = new FlagBuilder(key1.getKey()).version(15).build();
6374

6475
final SharedPrefsFlagStore flagStore = new SharedPrefsFlagStore(testApplication, "abc");
6576
flagStore.applyFlagUpdates(Collections.<FlagUpdate>singletonList(key1));
66-
flagStore.applyFlagUpdate(new DeleteFlagResponse(key1.getKey(), null));
6777

68-
Assert.assertNull(flagStore.getFlag(key1.getKey()));
78+
flagStore.applyFlagUpdate(updatedKey1);
79+
80+
assertEquals(15, flagStore.getFlag(key1.getKey()).getVersion());
6981
}
7082

7183
@Test
7284
public void updatesFlagVersions() {
73-
final Flag key1 = new FlagBuilder("key1").flagVersion(12).build();
74-
final Flag updatedKey1 = new FlagBuilder(key1.getKey()).flagVersion(15).build();
85+
final Flag key1 = new FlagBuilder("key1").version(100).flagVersion(12).build();
86+
final Flag updatedKey1 = new FlagBuilder(key1.getKey()).version(101).flagVersion(15).build();
7587

7688
final SharedPrefsFlagStore flagStore = new SharedPrefsFlagStore(testApplication, "abc");
7789
flagStore.applyFlagUpdates(Collections.<FlagUpdate>singletonList(key1));
7890

7991
flagStore.applyFlagUpdate(updatedKey1);
8092

81-
assertEquals(flagStore.getFlag(key1.getKey()).getFlagVersion(), 15, 0);
93+
assertEquals(Integer.valueOf(15), flagStore.getFlag(key1.getKey()).getFlagVersion());
8294
}
8395

8496
@Test

0 commit comments

Comments
 (0)