Skip to content

Commit

Permalink
prepare 3.1.6 release (#175)
Browse files Browse the repository at this point in the history
* Add support for TLS 1.2 on API 16+

* Add back final keyword

* Bumping the minSdkVersion from 15 to 16

* Circle CI 2.0

* Created new branch for multi-environment sdk feature

* Stub out new LDConfig and LDConfig.Builder code for multi-environment.

* Added overloaded init method in LDClient for creating secondary instances

* Added getForMobileKey methods

* Added LDClient init test for secondary environment, added exception to getForMobileKeys, added multi-environment support to setOffline and setOnlineStatus (seems naive, needs testing), and added exceptions to LDConfig setSecondaryMobileKeys

* Move primary instance into general instances map. Begin on methods effecting all instances.

* Removed incorrect LDClient test

* Fixed 1 failing test in LDClient, added multi-environment test file, fixed some linter issues

* 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`

Co-authored-by: Farhan Khan <farhan.khan@robotsandpencils.com>
Co-authored-by: Arun Bhalla <arun@launchdarkly.com>
Co-authored-by: nejifresh <nejifresh@gmail.com>
Co-authored-by: torchhound <unknownmasayoshi@gmail.com>
Co-authored-by: Gavin Whelan <gavwhela@gmail.com>
Co-authored-by: torchhound <jcieslik@umail.iu.edu>
Co-authored-by: jamesthacker <Nametaker40@live.com>
Co-authored-by: Gavin Whelan <gwhelan@launchdarkly.com>
Co-authored-by: torchhound <jcieslik@launchdarkly.com>
Co-authored-by: Eli Bishop <eli@launchdarkly.com>
Co-authored-by: Ben Woskow <48036130+bwoskow-ld@users.noreply.github.com>
Co-authored-by: Ben Woskow <bwoskow@launchdarkly.com>
Co-authored-by: Elliot <35050275+Apache-HB@users.noreply.github.com>
Co-authored-by: Robert J. Neal <robertjneal@users.noreply.github.com>
Co-authored-by: Louis Chan <lchan@launchdarkly.com>
Co-authored-by: Louis Chan <91093020+louis-launchdarkly@users.noreply.github.com>
Co-authored-by: Alex Engelberg <aengelberg@launchdarkly.com>
  • Loading branch information
18 people committed Aug 1, 2022
1 parent ee80d9f commit 879c21b
Show file tree
Hide file tree
Showing 41 changed files with 1,445 additions and 167 deletions.
205 changes: 120 additions & 85 deletions .circleci/config.yml
Original file line number Diff line number Diff line change
@@ -1,105 +1,140 @@
version: 2.1
orbs:
android: circleci/android@1.0
jobs:
build:
executor:
name: android/android-machine
resource-class: large

orbs:
android: circleci/android@2.1.2

workflows:
test:
jobs:
- package
- unit-tests
- instrumented-tests:
matrix:
parameters:
api-level:
# - 21 - TODO: EasyMock makes our tests fail
- 25
# - 29 - TODO: offline tests fail
# - 31 - https://github.com/CircleCI-Public/android-orb/issues/52
- contract-tests:
matrix:
parameters:
api-level:
- 21
- 25
- 30

commands:
check-emulator-available:
steps:
- checkout

# Create and start emulator
- android/create-avd:
avd-name: ci-android-avd
system-image: system-images;android-25;default;x86
install: true

- android/start-emulator:
avd-name: ci-android-avd
wait-for-emulator: false

# Perform tasks we can do while waiting for emulator to start

# Restore caches
- android/restore-gradle-cache
- android/restore-build-cache

- run:
name: Build local tests
command: ./gradlew :launchdarkly-android-client-sdk:assembleDebugUnitTest

- run:
name: Build connected tests
command: ./gradlew :launchdarkly-android-client-sdk:assembleDebugAndroidTest

# Save caches
- android/save-build-cache
- android/save-gradle-cache

# Run unit tests that do not require the emulator
- run:
name: Run local tests
command: ./gradlew :launchdarkly-android-client-sdk:testDebugUnitTest

# Now wait for emulator to fully start
- android/wait-for-emulator

# Additional validation that emulator is fully started and will accept adb
# commands
- run:
name: Validate retrieving emulator SDK version
name: Check emulator is available
command: |
while ! adb shell getprop ro.build.version.sdk; do
sleep 1
done
# Necessary for test mocking to disable network access through WiFi
# configuration, allowing testing of behavior when device is offline
- run:
name: Disable mobile data for network tests
command: adb shell svc data disable

- run:
name: Fetch logcat and props
background: true
command: |
mkdir -p ~/artifacts
adb shell getprop | tee -a ~/artifacts/props.txt
adb logcat | tee -a ~/artifacts/logcat.txt
- android/run-tests:
max-tries: 1

- android/kill-emulators

jobs:
package:
docker:
- image: cimg/android:2022.06
steps:
- checkout
- android/restore-gradle-cache:
cache-prefix: package
- run:
name: Validate package creation
command: ./gradlew packageRelease --console=plain -PdisablePreDex

- run:
name: Validate Javadoc
command: ./gradlew Javadoc

- run:
name: Save test results
command: |
mkdir -p ~/test-results
cp -r ./launchdarkly-android-client-sdk/build/test-results/testDebugUnitTest ~/test-results/
cp -r ./launchdarkly-android-client-sdk/build/outputs/androidTest-results/* ~/test-results/
when: always
- store_artifacts:
path: ./launchdarkly-android-client-sdk/build/reports/
- android/save-gradle-cache:
cache-prefix: package

unit-tests:
docker:
- image: cimg/android:2022.06
steps:
- checkout
- android/restore-gradle-cache:
cache-prefix: unit
- run:
name: Save artifacts
command: |
mv ./launchdarkly-android-client-sdk/build/test-results ~/artifacts
mv ./launchdarkly-android-client-sdk/build/reports ~/artifacts
mv ./launchdarkly-android-client-sdk/build/outputs ~/artifacts
mv ./launchdarkly-android-client-sdk/build/docs ~/artifacts
when: always

name: Build unit tests
command: ./gradlew :launchdarkly-android-client-sdk:assembleDebugUnitTest
- run:
name: Run local tests
command: ./gradlew :launchdarkly-android-client-sdk:testDebugUnitTest
- android/save-gradle-cache:
cache-prefix: unit
- store_test_results:
path: ~/test-results
- store_artifacts:
path: ~/artifacts
path: ./launchdarkly-android-client-sdk/build/test-results/testDebugUnitTest

instrumented-tests:
parameters:
api-level:
type: integer

executor:
name: android/android-machine
tag: 202102-01
resource-class: large

steps:
- checkout
- android/start-emulator-and-run-tests:
avd-name: ci-android-avd
system-image: system-images;android-<< parameters.api-level >>;default;x86_64
run-logcat: true
restore-gradle-cache-prefix: instrumented-v1
post-emulator-launch-assemble-command: ./gradlew :launchdarkly-android-client-sdk:assembleDebugAndroidTest
pre-run-tests-steps:
- check-emulator-available
# Necessary for test mocking to disable network access through WiFi
# configuration, allowing testing of behavior when device is offline
- run:
name: Disable mobile data for network tests
command: adb shell svc data disable
test-command: ./gradlew connectedDebugAndroidTest
max-tries: 1
post-run-tests-steps:
- store_test_results:
path: ./launchdarkly-android-client-sdk/build/outputs/androidTest-results/
- store_artifacts:
path: ./launchdarkly-android-client-sdk/build/reports/

contract-tests:
parameters:
api-level:
type: integer

executor:
name: android/android-machine
tag: 202102-01
resource-class: large

environment:
TEST_HARNESS_PARAMS: -junit /home/circleci/junit/contract-tests-junit.xml

steps:
- checkout
- android/start-emulator-and-run-tests:
avd-name: ci-android-avd
system-image: system-images;android-<< parameters.api-level >>;default;x86_64
run-logcat: true
restore-gradle-cache-prefix: contract-v1
post-emulator-launch-assemble-command: make build-contract-tests
pre-run-tests-steps:
- check-emulator-available
- run: mkdir -p ~/junit
- run: make start-contract-test-service
test-command: make run-contract-tests
max-tries: 1
post-run-tests-steps:
- store_test_results:
path: ~/junit
- store_artifacts:
path: ./launchdarkly-android-client-sdk/build/reports/
16 changes: 16 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
build-contract-tests:
@cd contract-tests && ../gradlew --no-daemon -s assembleDebug -PdisablePreDex

start-emulator:
@scripts/start-emulator.sh

start-contract-test-service:
@scripts/start-test-service.sh

run-contract-tests:
@curl -s https://raw.githubusercontent.com/launchdarkly/sdk-test-harness/v1.0.0/downloader/run.sh \
| VERSION=v1 PARAMS="-url http://localhost:8001 -host 10.0.2.2 -skip-from testharness-suppressions.txt -debug $(TEST_HARNESS_PARAMS)" sh

contract-tests: build-contract-tests start-emulator start-contract-test-service run-contract-tests

.PHONY: build-contract-tests start-emulator start-contract-test-service run-contract-tests contract-tests
5 changes: 1 addition & 4 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,7 @@ subprojects {
nexusPublishing {
packageGroup = "com.launchdarkly"
repositories {
sonatype {
nexusUrl.set(uri("https://oss.sonatype.org/service/local/staging/deploy/maven2/"))
snapshotRepositoryUrl.set(uri("https://oss.sonatype.org/content/repositories/snapshots/"))
}
sonatype()
}

transitionCheckOptions {
Expand Down
66 changes: 66 additions & 0 deletions contract-tests/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# contract-tests service

A test service that runs inside an Android emulator, that follows the [contract-tests specification](https://github.com/launchdarkly/sdk-test-harness/blob/main/docs/service_spec.md).

## Running locally

You can run the contract tests locally via the `Makefile`, which will:
* start up an emulator
* run the contract-test service APK in the emulator
* forward port 8001 (using `adb forward`) so that we can hit the HTTP server running inside the emulator
* important: this part is something you can't do with Android Studio, which is why I don't use Android Studio to run the contract tests
* run the [SDK test harness](https://github.com/launchdarkly/sdk-test-harness) against the service

To run the contract tests and all its dependencies at once:
```sh
$ make contract-tests
```

For a pseudo-interactive dev flow, I use [watchexec](https://github.com/watchexec/watchexec):
```sh
# start up the emulator once
$ make start-emulator
# anytime code changes, rebuild and restart the test service
$ watchexec make build-contract-tests start-contract-test-service
# meanwhile, run the test harness whenever you want
$ make run-contract-tests
```

For this to work, there are some prerequisites that must be on your machine:

### Install Android Studio

Even though we won't use it to run the contract tests, installing Android Studio will give us all the ingredients necessary for things to work.

### [Android command-line tools](https://developer.android.com/studio/command-line)

The following programs should already be present thanks to Android Studio, but need to be
available on your `$PATH` to be run at the command line:

* `adb`
* `avdmanager`
* `emulator`
* `sdkmanager`

This is what my `~/.zshrc` looks like, to make that happen:

```sh
export PATH="/Users/alex/Library/Android/sdk/cmdline-tools/latest/bin:$PATH" # avdmanager, sdkmanager
export PATH="/Users/alex/Library/Android/sdk/platform-tools/:$PATH" # adb
export PATH="/Users/alex/Library/Android/sdk/emulator/:$PATH" # emulator
```

### System images

The contract-tests scripts expect at least one Android system image (i.e. an image of Android OS that can be run as an emulator)
to be installed. If you've done any Android development already, there should be at least one that works. `start-emulator.sh`
will automatically pick the latest applicable image when creating the emulator.

You can verify by calling `sdkmanager --list_installed`. You're looking for something like:
```
Path | Version | Description | Location
------- | ------- | ------- | -------
... ... ... ...
system-images;android-32;google_apis;arm64-v8a | 3 | Google APIs ARM 64 v8a System Image | system-images/android-32/google_apis/arm64-v8a
```
but swap `arm64-v8a` with `x86` if you aren't on an M1 machine.
35 changes: 35 additions & 0 deletions contract-tests/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
plugins {
id("com.android.application")
// make sure this line comes *after* you apply the Android plugin
id("com.getkeepsafe.dexcount")
}

android {
compileSdkVersion(30)
buildToolsVersion = "30.0.3"

defaultConfig {
applicationId = "com.launchdarkly.sdktest"
minSdkVersion(21)
targetSdkVersion(30)
versionCode = 1
versionName = "1.0"
}

buildTypes {
release {
minifyEnabled = true
proguardFiles(getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro")
}
}
}

dependencies {
implementation("com.jakewharton.timber:timber:5.0.1")
// https://mvnrepository.com/artifact/org.nanohttpd/nanohttpd
implementation("org.nanohttpd:nanohttpd:2.3.1")
implementation("com.google.code.gson:gson:2.8.9")
implementation(project(":launchdarkly-android-client-sdk"))
// Comment the previous line and uncomment this one to depend on the published artifact:
//implementation("com.launchdarkly:launchdarkly-android-client-sdk:3.1.5")
}
26 changes: 26 additions & 0 deletions contract-tests/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.launchdarkly.sdktest">

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
Loading

0 comments on commit 879c21b

Please sign in to comment.