diff --git a/.github/workflows/purchase-e2e.yml b/.github/workflows/purchase-e2e.yml new file mode 100644 index 0000000000..5571013dc4 --- /dev/null +++ b/.github/workflows/purchase-e2e.yml @@ -0,0 +1,291 @@ +name: Purchase E2E (IAP) + +# Focused, path-gated check for the In-App-Purchase / ReceiptStore stack. +# Triggers only when the purchase surface changes so it pages reviewers fast +# instead of waiting for the full PR matrix. +# +# Layers: +# - core-tests : JavaSE-simulator unit tests of the cross-platform receipt +# sync state machine (Purchase / ReceiptStore), including the +# #5186 regression guard that the store is shared across the +# fresh Purchase instances every port hands out. +# - native-ios : hosted XCTest + StoreKitTest SKTestSession driving a +# simulated purchase through the real StoreKit observer into +# the recording ReceiptStore. +# - native-android : instrumentation test injecting a fake IBillingSupport and +# asserting the bridge drives the Java Purchase flow. +# +# native-ios / native-android build a DEDICATED minimal IAP app +# (scripts/purchase-test-app/app) rather than the shared hellocodenameone +# sample, so IAP wiring (StoreKit / Play Billing) never ripples into the +# screenshot / notification CI workflows. + +on: + workflow_dispatch: {} + pull_request: + branches: [ master ] + paths: + - 'CodenameOne/src/com/codename1/payment/**' + - 'Ports/iOSPort/nativeSources/CodenameOne_GLViewController.m' + - 'Ports/iOSPort/src/com/codename1/impl/ios/ZoozPurchase.java' + - 'Ports/iOSPort/src/com/codename1/impl/ios/IOSImplementation.java' + - 'Ports/Android/src/com/codename1/impl/android/BillingSupport.java' + - 'Ports/Android/src/com/codename1/impl/android/ZoozPurchase.java' + - 'Ports/Android/src/com/codename1/impl/android/IBillingSupport.java' + - 'Ports/Android/src/com/codename1/impl/android/CodenameOneActivity.java' + - 'maven/core-unittests/src/test/java/com/codename1/payment/**' + - 'maven/core-unittests/src/test/java/com/codename1/testing/TestCodenameOneImplementation.java' + - 'scripts/purchase-test-app/**' + - 'scripts/ios/purchase-tests/**' + - 'scripts/run-ios-purchase-tests.sh' + - 'scripts/build-ios-app.sh' + - 'scripts/build-android-app.sh' + - '.github/workflows/purchase-e2e.yml' + push: + branches: [ master ] + paths: + - 'CodenameOne/src/com/codename1/payment/**' + - 'Ports/iOSPort/nativeSources/CodenameOne_GLViewController.m' + - 'Ports/iOSPort/src/com/codename1/impl/ios/ZoozPurchase.java' + - 'Ports/iOSPort/src/com/codename1/impl/ios/IOSImplementation.java' + - 'Ports/Android/src/com/codename1/impl/android/BillingSupport.java' + - 'Ports/Android/src/com/codename1/impl/android/ZoozPurchase.java' + - 'Ports/Android/src/com/codename1/impl/android/IBillingSupport.java' + - 'Ports/Android/src/com/codename1/impl/android/CodenameOneActivity.java' + - 'maven/core-unittests/src/test/java/com/codename1/payment/**' + - 'maven/core-unittests/src/test/java/com/codename1/testing/TestCodenameOneImplementation.java' + - 'scripts/purchase-test-app/**' + - 'scripts/ios/purchase-tests/**' + - 'scripts/run-ios-purchase-tests.sh' + - 'scripts/build-ios-app.sh' + - 'scripts/build-android-app.sh' + - '.github/workflows/purchase-e2e.yml' + +permissions: + contents: read + # Required to pull the pr-ci-container image from ghcr.io. + packages: read + +concurrency: + group: purchase-e2e-${{ github.workflow }}-${{ github.ref_name }} + cancel-in-progress: true + +jobs: + core-tests: + name: Core receipt-sync unit tests (JavaSE) + runs-on: ubuntu-latest + container: ghcr.io/codenameone/codenameone/pr-ci-container:latest + timeout-minutes: 20 + defaults: + run: + shell: bash + steps: + - uses: actions/checkout@v6 + + - name: Select JDK 8 + run: | + echo "JAVA_HOME=${JAVA_HOME_8}" >> "$GITHUB_ENV" + echo "${JAVA_HOME_8}/bin" >> "$GITHUB_PATH" + + - name: Cache Maven repository + uses: actions/cache@v5 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-m2-purchase-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-m2-purchase- + ${{ runner.os }}-m2- + + - name: Run Purchase / ReceiptStore unit tests + working-directory: maven + run: | + set -euo pipefail + mvn -B -Dmaven.javadoc.skip=true \ + -DunitTests=true \ + -Plocal-dev-javase \ + -P unittests \ + -pl core-unittests -am \ + test \ + -Dtest='PurchaseTest,ProductTest,ApplePromotionalOfferTest' \ + -Dsurefire.failIfNoSpecifiedTests=false + + build-port: + uses: ./.github/workflows/_build-ios-port.yml + + native-ios: + name: iOS StoreKitTest purchase (simulator) + needs: build-port + permissions: + contents: read + runs-on: macos-15 + timeout-minutes: 45 + concurrency: + group: mac-ci-${{ github.workflow }}-${{ github.ref_name }} + cancel-in-progress: true + steps: + - uses: actions/checkout@v6 + + - name: Cache CocoaPods and user gems + uses: actions/cache@v5 + with: + path: | + ~/.gem + ~/Library/Caches/CocoaPods + ~/.cocoapods/repos + key: ${{ runner.os }}-pods-v1-${{ hashFiles('scripts/setup-workspace.sh') }} + restore-keys: | + ${{ runner.os }}-pods-v1- + + - name: Ensure CocoaPods tooling + run: | + mkdir -p ~/.codenameone + cp maven/UpdateCodenameOne.jar ~/.codenameone/ + set -euo pipefail + GEM_USER_DIR="$(ruby -e 'print Gem.user_dir')" + export PATH="$GEM_USER_DIR/bin:$PATH" + if ! command -v pod >/dev/null 2>&1; then + gem install cocoapods xcodeproj --no-document --user-install + fi + pod --version + + - name: Compute setup-workspace hash + id: setup_hash + run: echo "hash=$(shasum -a 256 scripts/setup-workspace.sh | awk '{print $1}')" >> "$GITHUB_OUTPUT" + + - name: Set TMPDIR + run: echo "TMPDIR=${{ runner.temp }}" >> $GITHUB_ENV + + - name: Cache codenameone-tools + uses: actions/cache@v5 + with: + path: ${{ runner.temp }}/codenameone-tools + key: ${{ runner.os }}-cn1-tools-${{ steps.setup_hash.outputs.hash }} + restore-keys: | + ${{ runner.os }}-cn1-tools- + + - name: Cache Maven repository + uses: actions/cache@v5 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-m2-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-m2- + + - name: Restore cn1-binaries cache + uses: actions/cache@v5 + with: + path: ../cn1-binaries + key: cn1-binaries-${{ runner.os }}-${{ steps.setup_hash.outputs.hash }} + restore-keys: | + cn1-binaries-${{ runner.os }}- + + - name: Restore built CN1 + iOS port artifacts + uses: actions/cache/restore@v4 + with: + path: | + ~/.m2/repository/com/codenameone + Themes + Ports/iOSPort/nativeSources + key: ${{ needs.build-port.outputs.cn1_built_cache_key }} + fail-on-cache-miss: true + + - name: Build dedicated IAP app (StoreKit compiled in) + id: build_ios_app + env: + CN1_APP_DIR: scripts/purchase-test-app/app + run: ./scripts/build-ios-app.sh -q -DskipTests + timeout-minutes: 30 + + - name: Run iOS StoreKitTest purchase test (XCTest) + env: + ARTIFACTS_DIR: ${{ github.workspace }}/artifacts/native-ios-purchase-tests + run: | + set -euo pipefail + mkdir -p "${ARTIFACTS_DIR}" + ./scripts/run-ios-purchase-tests.sh \ + "${{ steps.build_ios_app.outputs.workspace }}" \ + "${{ steps.build_ios_app.outputs.scheme }}" + timeout-minutes: 25 + + - name: Upload native iOS purchase artifacts + if: always() + uses: actions/upload-artifact@v7 + with: + name: ios-purchase-tests + path: artifacts + if-no-files-found: warn + retention-days: 14 + + native-android: + name: Android billing-bridge purchase (emulator) + runs-on: ubuntu-latest + timeout-minutes: 60 + env: + GITHUB_TOKEN: ${{ secrets.CN1SS_GH_TOKEN }} + GH_TOKEN: ${{ secrets.CN1SS_GH_TOKEN }} + steps: + - uses: actions/checkout@v6 + - name: Set TMPDIR + run: echo "TMPDIR=${{ runner.temp }}" >> $GITHUB_ENV + - name: Cache codenameone-tools + uses: actions/cache@v5 + with: + path: ${{ runner.temp }}/codenameone-tools + key: ${{ runner.os }}-cn1-tools-${{ hashFiles('scripts/setup-workspace.sh') }} + restore-keys: | + ${{ runner.os }}-cn1-tools- + - name: Cache Maven repository + uses: actions/cache@v5 + with: + path: ~/.m2/repository + key: ${{ runner.os }}-m2-android-purchase-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-m2-android-purchase- + ${{ runner.os }}-m2- + - name: Cache Gradle + uses: actions/cache@v5 + with: + path: | + ~/.gradle/caches + ~/.gradle/wrapper + key: ${{ runner.os }}-gradle-purchase-${{ hashFiles('scripts/purchase-test-app/**/build.gradle*', 'Ports/Android/build.gradle*') }} + restore-keys: | + ${{ runner.os }}-gradle-purchase- + ${{ runner.os }}-gradle- + - name: Setup workspace + run: ./scripts/setup-workspace.sh -q -DskipTests + - name: Build Android port + run: ./scripts/build-android-port.sh -q -DskipTests + - name: Build dedicated IAP app (Android) + id: build-android-app + env: + CN1_APP_DIR: scripts/purchase-test-app/app + CN1_ANDROID_TEST_SOURCE_DIR: scripts/purchase-test-app/android-test-src + run: | + mkdir -p ~/.codenameone + cp maven/UpdateCodenameOne.jar ~/.codenameone/ + ./scripts/build-android-app.sh -q -DskipTests + - name: Enable KVM for Android emulator + run: | + echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules + sudo udevadm control --reload-rules + sudo udevadm trigger --name-match=kvm + - name: Run Android purchase instrumentation test (targeted) + uses: reactivecircus/android-emulator-runner@v2 + with: + api-level: 36 + arch: x86_64 + target: google_apis + disk-size: 2048M + # android-emulator-runner runs each script line in its own shell, so + # cd + gradlew must be a single `&&` line. Runs ONLY the purchase test + # (it self-asserts by scraping logcat for CN1SS:IAP:SUBMITTED). + script: cd "${{ steps.build-android-app.outputs.gradle_project_dir }}" && ./gradlew --no-daemon --stacktrace connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.codenameone.examples.purchasetest.PurchaseBillingInstrumentationTest + - name: Upload Android purchase test report + if: always() + uses: actions/upload-artifact@v7 + with: + name: android-purchase-tests + path: ${{ steps.build-android-app.outputs.gradle_project_dir }}/app/build/reports/androidTests + if-no-files-found: warn + retention-days: 14 diff --git a/Ports/Android/src/com/codename1/impl/android/CodenameOneActivity.java b/Ports/Android/src/com/codename1/impl/android/CodenameOneActivity.java index ab5365a5be..fda5662552 100644 --- a/Ports/Android/src/com/codename1/impl/android/CodenameOneActivity.java +++ b/Ports/Android/src/com/codename1/impl/android/CodenameOneActivity.java @@ -95,9 +95,26 @@ protected IBillingSupport createBillingSupport() { return null; } + /** + * Test-only injection point for the billing implementation. The generated + * application stub overrides {@link #createBillingSupport()} to return the + * real Google Play {@code BillingSupport} whenever the app uses the Purchase + * API, which shadows any subclass override. Instrumentation tests that need + * a fake (there is no local Play Billing sandbox) set this before the + * activity resumes so {@link #getBillingSupport()} returns the fake instead. + * Not used in production. + */ + private static IBillingSupport billingSupportTestOverride; + + public static void setBillingSupportTestOverride(IBillingSupport support) { + billingSupportTestOverride = support; + } + private IBillingSupport getBillingSupport() { if (billingSupport == null) { - billingSupport = createBillingSupport(); + billingSupport = billingSupportTestOverride != null + ? billingSupportTestOverride + : createBillingSupport(); } return billingSupport; } diff --git a/maven/core-unittests/src/test/java/com/codename1/payment/PurchaseTest.java b/maven/core-unittests/src/test/java/com/codename1/payment/PurchaseTest.java index 19a1b1d387..6b929521c4 100644 --- a/maven/core-unittests/src/test/java/com/codename1/payment/PurchaseTest.java +++ b/maven/core-unittests/src/test/java/com/codename1/payment/PurchaseTest.java @@ -5,6 +5,7 @@ import com.codename1.junit.FormTest; import com.codename1.junit.TestLogger; import com.codename1.junit.UITestBase; +import com.codename1.testing.TestCodenameOneImplementation; import com.codename1.ui.Display; import com.codename1.util.SuccessCallback; import org.junit.jupiter.api.AfterEach; @@ -290,6 +291,54 @@ public void onSucess(Boolean value) { assertEquals(3, store.getSubmittedReceipts().size()); } + @FormTest + void testReceiptStoreSharedAcrossFreshPurchaseInstances() { + // Regression test for #5186: Display.getInAppPurchase() returns a + // FRESH Purchase instance on every call on every real port (iOS + // ZoozPurchase, Android ZoozPurchase, the JavaSE anonymous subclass). + // The native receipt path enters through the static + // Purchase.postReceipt(...) which calls getInAppPurchase().postReceipt(r) + // on yet another fresh instance. If receiptStore were a per-instance + // field, the store installed by the app would be invisible to that + // instance and submitReceipt would never fire. This test pins the + // ports' behaviour with a factory so it fails if receiptStore stops + // being shared across instances. + implementation.setInAppPurchase(null); + implementation.setInAppPurchaseFactory(new TestCodenameOneImplementation.InAppPurchaseFactory() { + public Purchase create() { + return new TestPurchase(); + } + }); + try { + TestReceiptStore store = new TestReceiptStore(); + + // Sanity-check the harness reproduces the ports' behaviour: each + // getInAppPurchase() call yields a distinct instance. + assertNotSame(Display.getInstance().getInAppPurchase(), + Display.getInstance().getInAppPurchase(), + "Factory must hand out a fresh Purchase per call, like the real ports"); + + // Configure the store on ONE freshly-returned instance... + ((Purchase) Display.getInstance().getInAppPurchase()).setReceiptStore(store); + + // ...then drive the native entry point, which internally uses a + // DIFFERENT freshly-returned instance. + Purchase.postReceipt(Receipt.STORE_CODE_ITUNES, "pro", "tx-shared", + System.currentTimeMillis(), "order-shared"); + flushSerialCalls(); + + assertEquals(1, store.getSubmittedReceipts().size(), + "ReceiptStore set on one Purchase instance must be visible to the native " + + "postReceipt path that arrives on a different instance"); + assertEquals("tx-shared", store.getSubmittedReceipts().get(0).getTransactionId()); + assertTrue(((Purchase) Display.getInstance().getInAppPurchase()).getPendingPurchases().isEmpty(), + "Successfully submitted receipt should be drained from the pending queue"); + } finally { + ((Purchase) Display.getInstance().getInAppPurchase()).setReceiptStore(null); + implementation.setInAppPurchaseFactory(null); + } + } + @FormTest void testPostReceiptSkipsReceiptThatWasAlreadySuccessfullySubmitted() { // Simulate iOS StoreKit redelivering a transaction across app diff --git a/maven/core-unittests/src/test/java/com/codename1/testing/TestCodenameOneImplementation.java b/maven/core-unittests/src/test/java/com/codename1/testing/TestCodenameOneImplementation.java index 42e3b5bbc5..5466b1eff3 100644 --- a/maven/core-unittests/src/test/java/com/codename1/testing/TestCodenameOneImplementation.java +++ b/maven/core-unittests/src/test/java/com/codename1/testing/TestCodenameOneImplementation.java @@ -149,6 +149,7 @@ public class TestCodenameOneImplementation extends CodenameOneImplementation { private AsyncResource mediaAsync; private final Map> mediaAsyncByUri = new ConcurrentHashMap>(); private Purchase inAppPurchase; + private InAppPurchaseFactory inAppPurchaseFactory; private int startRemoteControlInvocations; private int stopRemoteControlInvocations; private boolean mutableImagesFast = true; @@ -1095,6 +1096,7 @@ public void reset() { localizationManager = null; imageIO = null; inAppPurchase = null; + inAppPurchaseFactory = null; contactIdCounter.set(1); accessPointIds = new String[0]; accessPointTypes.clear(); @@ -3041,8 +3043,25 @@ public void setInAppPurchase(Purchase purchase) { this.inAppPurchase = purchase; } + /// Factory that produces a fresh {@link Purchase} on every + /// {@link #getInAppPurchase()} call. The real platform ports + /// (iOS {@code ZoozPurchase}, Android {@code ZoozPurchase}, the JavaSE + /// anonymous subclass) all construct a new instance per call, so a test + /// that needs to reproduce that behaviour (e.g. verifying state shared + /// across instances) installs a factory rather than a cached instance. + public interface InAppPurchaseFactory { + Purchase create(); + } + + public void setInAppPurchaseFactory(InAppPurchaseFactory factory) { + this.inAppPurchaseFactory = factory; + } + @Override public Purchase getInAppPurchase() { + if (inAppPurchaseFactory != null) { + return inAppPurchaseFactory.create(); + } if (inAppPurchase != null) { return inAppPurchase; } diff --git a/scripts/build-android-app.sh b/scripts/build-android-app.sh index c26ef4fa39..2b2bd499e0 100755 --- a/scripts/build-android-app.sh +++ b/scripts/build-android-app.sh @@ -73,16 +73,19 @@ fi export ANDROID_SDK_ROOT ANDROID_HOME="$ANDROID_SDK_ROOT" ba_log "Using Android SDK at $ANDROID_SDK_ROOT" -APP_DIR="scripts/hellocodenameone" +# CN1_APP_DIR lets this script build any CN1 app (e.g. the dedicated IAP +# purchase-test app), not just hellocodenameone. Default preserves prior +# behaviour exactly. +APP_DIR="${CN1_APP_DIR:-scripts/hellocodenameone}" [ -d "$APP_DIR" ] || { ba_log "Failed to create Codename One application project" >&2; exit 1; } [ -f "$APP_DIR/build.sh" ] && chmod +x "$APP_DIR/build.sh" # --- Build Android gradle project --- -ba_log "Building Android gradle project using Codename One port" -cd $APP_DIR +ba_log "Building Android gradle project ($APP_DIR) using Codename One port" ( - # hellocodenameone targets Java 17, so both the maven-compiler-plugin + cd "$REPO_ROOT/$APP_DIR" + # The sample targets Java 17, so both the maven-compiler-plugin # and any forked tooling need a 17 JDK. Mirrors what build-ios-app.sh # does for the iOS pipeline. export JAVA_HOME="$JAVA17_HOME" @@ -96,7 +99,7 @@ cd $APP_DIR -Dopen=false \ -U -e ) -cd ../.. +cd "$REPO_ROOT" GRADLE_PROJECT_DIR=$(find "$APP_DIR/android/target" -maxdepth 2 -type d -name "*-android-source" | head -n 1 || true) if [ -z "$GRADLE_PROJECT_DIR" ]; then @@ -109,9 +112,14 @@ fi ba_log "Normalizing Android Gradle project in $GRADLE_PROJECT_DIR" # --- Install Android instrumentation harness for coverage --- -ANDROID_TEST_SOURCE_DIR="$SCRIPT_DIR/device-runner-app/androidTest" +# CN1_ANDROID_TEST_SOURCE_DIR overrides the instrumentation sources (the +# purchase-test app installs its own); the destination package mirrors the +# app's codename1.packageName so it works for any app, not just hellocodenameone. +ANDROID_TEST_SOURCE_DIR="${CN1_ANDROID_TEST_SOURCE_DIR:-$SCRIPT_DIR/device-runner-app/androidTest}" ANDROID_TEST_ROOT="$GRADLE_PROJECT_DIR/app/src/androidTest" -ANDROID_TEST_JAVA_DIR="$ANDROID_TEST_ROOT/java/com/codenameone/examples/hellocodenameone" +APP_PACKAGE="$(sed -n 's/^codename1.packageName=//p' "$REPO_ROOT/$APP_DIR/common/codenameone_settings.properties" | head -n1)" +APP_PACKAGE="${APP_PACKAGE:-com.codenameone.examples.hellocodenameone}" +ANDROID_TEST_JAVA_DIR="$ANDROID_TEST_ROOT/java/$(printf '%s' "$APP_PACKAGE" | tr . /)" if [ -d "$ANDROID_TEST_ROOT" ]; then ba_log "Removing template Android instrumentation tests from $ANDROID_TEST_ROOT" rm -rf "$ANDROID_TEST_ROOT" diff --git a/scripts/ios/purchase-tests/Products.storekit b/scripts/ios/purchase-tests/Products.storekit new file mode 100644 index 0000000000..d4c5cdd6bc --- /dev/null +++ b/scripts/ios/purchase-tests/Products.storekit @@ -0,0 +1,38 @@ +{ + "identifier" : "CN1E2E0001-0000-0000-0000-000000000001", + "nonRenewingSubscriptions" : [ + + ], + "products" : [ + { + "displayPrice" : "0.99", + "familyShareable" : false, + "internalID" : "CN1E2E0001-0000-0000-0000-0000000000A1", + "localizations" : [ + { + "description" : "Codename One e2e test consumable", + "displayName" : "CN1 Test Pro", + "locale" : "en_US" + } + ], + "productID" : "com.codenameone.hello.pro", + "referenceName" : "CN1 Test Pro", + "type" : "Consumable" + } + ], + "settings" : { + "_failTransactionsEnabled" : false, + "_locale" : "en_US", + "_storefront" : "USA", + "_storeKitErrors" : [ + + ] + }, + "subscriptionGroups" : [ + + ], + "version" : { + "major" : 3, + "minor" : 0 + } +} diff --git a/scripts/ios/purchase-tests/README.md b/scripts/ios/purchase-tests/README.md new file mode 100644 index 0000000000..81688123ad --- /dev/null +++ b/scripts/ios/purchase-tests/README.md @@ -0,0 +1,49 @@ +# iOS Native Purchase Tests (StoreKitTest) + +Native XCTest assets that validate the In-App-Purchase / ReceiptStore stack end +to end on the iOS simulator using Apple's **StoreKitTest** framework +(`SKTestSession`) -- a *simulated* App Store, no sandbox account and no network. + +## How it works + +1. The sample app (`HelloCodenameOne`) references `com.codename1.payment.*`, so + the build's bytecode scanner flips `IPhoneBuilder.usesPurchaseAPI`, which + defines `CN1_USE_STOREKIT` and links `StoreKit.framework`. The CN1 StoreKit + observer (`paymentQueue:updatedTransactions:`) is therefore compiled in and + registered at runtime. +2. At startup the app installs `RecordingReceiptStore`, which forwards every + submitted receipt's `transactionId` through the `PurchaseTestSink` native + interface; the iOS implementation persists it in `NSUserDefaults`. +3. The hosted XCTest (`PurchaseStoreKitTests`) creates an `SKTestSession` from + `Products.storekit`, buys a product, and the purchase flows through the real + `SKPaymentQueue` into the CN1 observer -> generated `Purchase.postReceipt` + -> receipt-sync engine -> the installed `RecordingReceiptStore`. +4. The test reads back the `NSUserDefaults` sink (same process, hosted test) and + asserts the receipt was submitted. + +This is the iOS-level guard for issue #5186: the observer submits through a +freshly-constructed `Purchase` instance, so a recorded submission proves the +store installed on a *different* instance at startup was visible to it (the +shared/static `receiptStore`). + +## Files + +- `native-tests/PurchaseStoreKitTests.m` -- the hosted StoreKitTest XCTest. +- `Products.storekit` -- StoreKit configuration (one consumable, + `com.codenameone.hello.pro`). +- `install-native-purchase-tests.sh` -- copies the test sources + + `Products.storekit` into the generated Xcode project, configures the test + target as hosted, and links `StoreKit` + `StoreKitTest`. + +## Related runner + +- `scripts/run-ios-purchase-tests.sh` -- installs the assets and runs + `xcodebuild test` on a simulator. + +## Sample-app wiring (committed) + +- `scripts/hellocodenameone/common/.../PurchaseTestSink.java` -- native iface. +- `scripts/hellocodenameone/common/.../RecordingReceiptStore.java` -- the store. +- `scripts/hellocodenameone/ios/src/main/objectivec/...PurchaseTestSinkImpl.m` + -- iOS sink (NSUserDefaults); javase/android impls record in memory. +- `HelloCodenameOne.kt` `init()` references `Purchase` and installs the store. diff --git a/scripts/ios/purchase-tests/install-native-purchase-tests.sh b/scripts/ios/purchase-tests/install-native-purchase-tests.sh new file mode 100755 index 0000000000..f2aa99879f --- /dev/null +++ b/scripts/ios/purchase-tests/install-native-purchase-tests.sh @@ -0,0 +1,135 @@ +#!/usr/bin/env bash +# Inject the native StoreKitTest XCTest sources into the generated iOS Xcode +# project. Keeps tests in-repo under scripts/ios/purchase-tests/native-tests +# while attaching them to the generated HelloCodenameOneTests target, links the +# StoreKit + StoreKitTest frameworks, and bundles Products.storekit as a test +# resource so SKTestSession can load it. + +set -euo pipefail + +PROJECT_DIR="${1:-}" +TEST_SOURCES_DIR="${2:-scripts/ios/purchase-tests/native-tests}" +STOREKIT_CONFIG="${3:-scripts/ios/purchase-tests/Products.storekit}" + +log() { echo "[install-native-purchase-tests] $1"; } + +if [ -z "$PROJECT_DIR" ] || [ ! -d "$PROJECT_DIR" ]; then + log "project directory missing: $PROJECT_DIR" >&2 + exit 2 +fi +if [ ! -d "$TEST_SOURCES_DIR" ]; then + log "test sources directory missing: $TEST_SOURCES_DIR" >&2 + exit 2 +fi +if [ ! -f "$STOREKIT_CONFIG" ]; then + log "StoreKit configuration missing: $STOREKIT_CONFIG" >&2 + exit 2 +fi + +PROJECT_DIR="$(cd "$PROJECT_DIR" && pwd)" +TEST_SOURCES_DIR="$(cd "$TEST_SOURCES_DIR" && pwd)" +STOREKIT_CONFIG="$(cd "$(dirname "$STOREKIT_CONFIG")" && pwd)/$(basename "$STOREKIT_CONFIG")" +DEST_DIR="$PROJECT_DIR/NativePurchaseTests" +mkdir -p "$DEST_DIR" + +# Copy test sources + the StoreKit config so they live alongside the project. +find "$TEST_SOURCES_DIR" -type f \( -name '*.m' -o -name '*.mm' -o -name '*.swift' -o -name '*.h' \) -print0 | + while IFS= read -r -d '' src; do + cp "$src" "$DEST_DIR/$(basename "$src")" + done +cp "$STOREKIT_CONFIG" "$DEST_DIR/$(basename "$STOREKIT_CONFIG")" + +ruby - "$PROJECT_DIR" "$DEST_DIR" "$(basename "$STOREKIT_CONFIG")" <<'RUBY' +require 'xcodeproj' +require 'fileutils' + +project_dir = ARGV[0] +dest_dir = ARGV[1] +storekit_name = ARGV[2] +project_path = Dir[File.join(project_dir, '*.xcodeproj')].first +abort("No .xcodeproj found under #{project_dir}") unless project_path + +project = Xcodeproj::Project.open(project_path) +test_target = project.targets.find { |t| t.product_type == 'com.apple.product-type.bundle.unit-test' } || + project.targets.find { |t| t.name.end_with?('Tests') } +abort("No unit-test target found in #{project_path}") unless test_target +app_target = project.targets.find { |t| t.product_type == 'com.apple.product-type.application' } || + project.targets.find { |t| t.name == test_target.name.sub(/Tests$/, '') } +abort("No app target found in #{project_path}") unless app_target + +# Ensure the unit-test target has a concrete Info.plist in generated projects. +plist_name = "#{test_target.name}-Info.plist" +plist_rel = File.join(test_target.name, plist_name) +plist_abs = File.join(project_dir, plist_rel) +FileUtils.mkdir_p(File.dirname(plist_abs)) +unless File.exist?(plist_abs) + File.write(plist_abs, <<~PLIST) + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + BNDL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + + + PLIST +end + +# Hosted test bundle: StoreKitTest + the CN1 VM both need the app process. +test_target.build_configurations.each do |config| + app_product = app_target.product_name || app_target.name + host_path = "$(BUILT_PRODUCTS_DIR)/#{app_product}.app/#{app_product}" + config.build_settings['TEST_TARGET_NAME'] = app_target.name + config.build_settings['TEST_HOST'] = host_path + config.build_settings['BUNDLE_LOADER'] = host_path + config.build_settings['INFOPLIST_FILE'] = plist_rel +end + +group = project.main_group.find_subpath('NativePurchaseTests', true) + +# Attach .m/.mm/.swift sources to the test target's compile phase. +source_files = Dir[File.join(dest_dir, '*.{m,mm,swift}')].sort +abort("No test source files found in #{dest_dir}") if source_files.empty? +source_files.each do |source| + rel_path = File.join('NativePurchaseTests', File.basename(source)) + file_ref = group.files.find { |f| f.path == rel_path } || group.new_file(rel_path) + unless test_target.source_build_phase.files_references.include?(file_ref) + test_target.source_build_phase.add_file_reference(file_ref, true) + end +end + +# Bundle the StoreKit configuration as a test resource so +# SKTestSession initWithConfigurationFileNamed: can find it. +sk_rel = File.join('NativePurchaseTests', storekit_name) +sk_ref = group.files.find { |f| f.path == sk_rel } || group.new_file(sk_rel) +unless test_target.resources_build_phase.files_references.include?(sk_ref) + test_target.resources_build_phase.add_file_reference(sk_ref, true) +end + +# Link StoreKit + StoreKitTest into the test target. +framework_group = project.frameworks_group || project.main_group['Frameworks'] || project.main_group.new_group('Frameworks') +['System/Library/Frameworks/StoreKit.framework', + 'System/Library/Frameworks/StoreKitTest.framework'].each do |fw| + ref = framework_group.files.find { |f| f.path == fw } || framework_group.new_file(fw) + unless test_target.frameworks_build_phase.files_references.include?(ref) + test_target.frameworks_build_phase.add_file_reference(ref, true) + end +end + +project.save +puts "[install-native-purchase-tests] Installed #{source_files.length} test source file(s) + #{storekit_name} into #{test_target.name}" +RUBY diff --git a/scripts/ios/purchase-tests/native-tests/PurchaseStoreKitTests.m b/scripts/ios/purchase-tests/native-tests/PurchaseStoreKitTests.m new file mode 100644 index 0000000000..6edb499986 --- /dev/null +++ b/scripts/ios/purchase-tests/native-tests/PurchaseStoreKitTests.m @@ -0,0 +1,116 @@ +#import +#import + +// StoreKitTest (Xcode 12+/iOS 14+) lets us drive a *simulated* App Store +// purchase locally on the simulator -- no sandbox account, no network. The +// purchase flows through the real SKPaymentQueue, so Codename One's actual +// StoreKit observer (paymentQueue:updatedTransactions: in +// CodenameOne_GLViewController.m) fires, calls the generated +// Purchase.postReceipt(...), and the receipt-sync engine submits it to the +// ReceiptStore the sample app installed at startup (RecordingReceiptStore). +// That store forwards the transactionId to the PurchaseTestSink native +// interface, whose iOS implementation persists it in NSUserDefaults -- which +// this hosted XCTest reads back in-process to assert the end-to-end path. +// +// This is the iOS-level guard for issue #5186: the observer submits through a +// freshly-constructed Purchase instance, so a recorded submission proves the +// store installed on a different instance at startup was visible to it. +#if __has_include() +#import +#define CN1_HAS_STOREKIT_TEST 1 + +// SKTestSession's synchronous buy selector is buyProductWithIdentifier:error: +// (verified against the simulator runtime). StoreKitTest ships no umbrella +// header in the SDK, so declare it to dispatch correctly without a warning. +@interface SKTestSession (CN1PurchaseTest) +- (BOOL)buyProductWithIdentifier:(NSString *)productIdentifier error:(NSError **)error; +@end +#endif + +static NSString * const kProductId = @"com.codenameone.hello.pro"; +static NSString * const kSinkKey = @"CN1IAPTestSubmittedReceipts"; + +@interface PurchaseStoreKitTests : XCTestCase +@end + +@implementation PurchaseStoreKitTests { +#ifdef CN1_HAS_STOREKIT_TEST + SKTestSession *_session; +#endif +} + +- (void)setUp { + [super setUp]; + self.continueAfterFailure = NO; + [[NSUserDefaults standardUserDefaults] removeObjectForKey:kSinkKey]; + [[NSUserDefaults standardUserDefaults] synchronize]; +} + +- (void)tearDown { +#ifdef CN1_HAS_STOREKIT_TEST + if (@available(iOS 14.0, *)) { + [_session clearTransactions]; + } + _session = nil; +#endif + [super tearDown]; +} + +- (NSString *)recordedSubmissions { + NSArray *recorded = [[NSUserDefaults standardUserDefaults] arrayForKey:kSinkKey]; + return recorded ? [recorded componentsJoinedByString:@","] : @""; +} + +// Spin the run loop until `predicate` is true or the timeout elapses. The CN1 +// VM boots and registers the StoreKit observer asynchronously, so we poll +// rather than assume immediate delivery. +- (BOOL)waitUntil:(BOOL (^)(void))predicate timeout:(NSTimeInterval)timeout { + NSDate *deadline = [NSDate dateWithTimeIntervalSinceNow:timeout]; + while ([deadline timeIntervalSinceNow] > 0) { + if (predicate()) { + return YES; + } + [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode + beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.25]]; + } + return predicate(); +} + +- (void)testStoreKitPurchaseReachesReceiptStore { +#ifndef CN1_HAS_STOREKIT_TEST + XCTSkip("StoreKitTest framework unavailable in this SDK"); +#else + if (@available(iOS 14.0, *)) { + NSError *error = nil; + _session = [[SKTestSession alloc] initWithConfigurationFileNamed:@"Products" error:&error]; + XCTAssertNotNil(_session, @"Failed to load Products.storekit configuration: %@", error); + _session.disableDialogs = YES; + _session.askToBuyEnabled = NO; + [_session clearTransactions]; + + // Give the CN1 VM a moment to boot and register the SKPaymentQueue + // observer. Even if the buy lands first, StoreKit re-delivers the + // queued transaction once the observer attaches, so this is just to + // reduce flake. + [self waitUntil:^BOOL{ return NO; } timeout:5.0]; + + NSError *buyError = nil; + BOOL bought = [_session buyProductWithIdentifier:kProductId error:&buyError]; + XCTAssertTrue(bought, @"buyProductWithIdentifier failed: %@", buyError); + + BOOL submitted = [self waitUntil:^BOOL{ + return [[NSUserDefaults standardUserDefaults] arrayForKey:kSinkKey].count > 0; + } timeout:60.0]; + + XCTAssertTrue(submitted, + @"No receipt was submitted to the ReceiptStore within the timeout. " + @"Recorded submissions: '%@'. This means the StoreKit purchase did not " + @"flow through the CN1 observer into the receipt-sync engine and the " + @"installed ReceiptStore.", [self recordedSubmissions]); + } else { + XCTSkip("StoreKitTest requires iOS 14+"); + } +#endif +} + +@end diff --git a/scripts/purchase-test-app/.gitignore b/scripts/purchase-test-app/.gitignore new file mode 100644 index 0000000000..4cbc1019d7 --- /dev/null +++ b/scripts/purchase-test-app/.gitignore @@ -0,0 +1,4 @@ +app/*/target/ +app/**/target/ +app/common/androidCerts/ +*.ks diff --git a/scripts/purchase-test-app/android-test-src/CN1TestBillingSupport.java b/scripts/purchase-test-app/android-test-src/CN1TestBillingSupport.java new file mode 100644 index 0000000000..523410d174 --- /dev/null +++ b/scripts/purchase-test-app/android-test-src/CN1TestBillingSupport.java @@ -0,0 +1,68 @@ +package com.codenameone.examples.purchasetest; + +import com.codename1.impl.android.IBillingSupport; +import com.codename1.payment.Product; +import com.codename1.payment.Purchase; +import com.codename1.payment.Receipt; + +/** + * Fake {@link IBillingSupport} used by {@link PurchaseBillingInstrumentationTest}. + * + * There is no local Google Play Billing sandbox, so instead of talking to a real + * {@code BillingClient} this fake synthesizes a completed purchase exactly where + * the real {@code BillingSupport.onPurchasesUpdated(...)} would: by calling the + * static {@link Purchase#postReceipt}. That drives the cross-platform + * receipt-sync engine and the app's installed {@code RecordingReceiptStore}, + * which logs {@code CN1SS:IAP:SUBMITTED}. + * + * {@link #purchase(String)} is invoked directly by the instrumentation test + * once the CN1 VM has booted and installed the store (deterministic), rather + * than auto-firing from {@link #initBilling()} where it would race app startup. + * Android-side guard for #5186: postReceipt submits through a freshly + * constructed Purchase instance, so a recorded submission proves the store + * installed on a different instance is visible to it. + */ +public class CN1TestBillingSupport implements IBillingSupport { + static final String TEST_SKU = "com.codenameone.hello.pro"; + static final String TEST_TX_ID = "android-test-tx-1"; + + @Override + public void purchase(String item) { + System.out.println("CN1SS:IAP_FAKE fired postReceipt for " + TEST_TX_ID); + Purchase.postReceipt(Receipt.STORE_CODE_PLAY, TEST_SKU, TEST_TX_ID, + System.currentTimeMillis(), "{\"orderId\":\"GPA.TEST-0001\"}"); + } + + @Override + public void initBilling() { + // No-op: the test drives the purchase explicitly after the store is + // installed, so we don't race app startup here. + } + + @Override + public boolean wasPurchased(String item) { + return false; + } + + @Override + public void subscribe(String item) { + } + + @Override + public void consumeAndAcknowlegePurchases() { + } + + @Override + public void onDestroy() { + } + + @Override + public Product[] getProducts(String[] skus, boolean fromCacheOnly) { + return new Product[0]; + } + + @Override + public boolean isConsumable(String item) { + return true; + } +} diff --git a/scripts/purchase-test-app/android-test-src/PurchaseBillingInstrumentationTest.java b/scripts/purchase-test-app/android-test-src/PurchaseBillingInstrumentationTest.java new file mode 100644 index 0000000000..d35e0f8f0f --- /dev/null +++ b/scripts/purchase-test-app/android-test-src/PurchaseBillingInstrumentationTest.java @@ -0,0 +1,99 @@ +package com.codenameone.examples.purchasetest; + +import android.app.UiAutomation; +import android.content.Context; +import android.content.Intent; +import android.os.ParcelFileDescriptor; +import android.util.Log; + +import androidx.test.core.app.ApplicationProvider; +import androidx.test.ext.junit.runners.AndroidJUnit4; +import androidx.test.platform.app.InstrumentationRegistry; + +import com.codename1.impl.android.CodenameOneActivity; + +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; + +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.InputStreamReader; + +import static org.junit.Assert.assertTrue; + +/** + * Android-side e2e guard for the IAP / ReceiptStore bridge (issue #5186). + * + * Installs {@link CN1TestBillingSupport} via the framework test seam + * ({@link CodenameOneActivity#setBillingSupportTestOverride}) and launches the + * dedicated IAP app. Once the CN1 VM has booted and installed the + * RecordingReceiptStore (CN1SS:IAP_DIAG), it drives a synthetic purchase through + * the fake -> Purchase.postReceipt -> receipt-sync -> the installed store, then + * scrapes logcat for CN1SS:IAP:SUBMITTED. Driving the purchase explicitly after + * the store is ready keeps the test deterministic (no startup race). + */ +@RunWith(AndroidJUnit4.class) +public class PurchaseBillingInstrumentationTest { + private static final String TAG = "PurchaseBillingTest"; + private static final String INSTALLED_MARKER = "CN1SS:IAP_DIAG installed=true"; + private static final String SUBMITTED_MARKER = "CN1SS:IAP:SUBMITTED " + CN1TestBillingSupport.TEST_TX_ID; + + @After + public void clearOverride() { + CodenameOneActivity.setBillingSupportTestOverride(null); + } + + @Test + public void purchaseReachesReceiptStore() throws Exception { + CN1TestBillingSupport fake = new CN1TestBillingSupport(); + // Demonstrates the injection seam (the app would route billing here); + // we also drive purchase() directly below so timing is deterministic. + CodenameOneActivity.setBillingSupportTestOverride(fake); + + Context context = ApplicationProvider.getApplicationContext(); + Intent intent = context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()); + assertTrue("Launch intent not found for package " + context.getPackageName(), intent != null); + intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); + context.startActivity(intent); + + // Wait until the CN1 VM has booted and installed the RecordingReceiptStore. + boolean installed = waitForMarker(INSTALLED_MARKER, 90_000L); + assertTrue("App did not install the RecordingReceiptStore (no '" + INSTALLED_MARKER + + "' in logcat) - the VM may not have booted.", installed); + + // Now fire the synthetic purchase through the bridge; the store exists, + // so submitReceipt runs and logs CN1SS:IAP:SUBMITTED. + fake.purchase(CN1TestBillingSupport.TEST_SKU); + + boolean submitted = waitForMarker(SUBMITTED_MARKER, 60_000L); + assertTrue("Did not observe '" + SUBMITTED_MARKER + "' in logcat. The synthetic purchase " + + "did not flow through Purchase.postReceipt into the installed ReceiptStore.", submitted); + } + + private boolean waitForMarker(String marker, long timeoutMs) throws Exception { + long deadline = System.currentTimeMillis() + timeoutMs; + UiAutomation automation = InstrumentationRegistry.getInstrumentation().getUiAutomation(); + ParcelFileDescriptor pfd = automation.executeShellCommand("logcat -v brief"); + try (FileInputStream fis = new FileInputStream(pfd.getFileDescriptor()); + BufferedReader reader = new BufferedReader(new InputStreamReader(fis))) { + String line; + while (System.currentTimeMillis() < deadline) { + if (reader.ready() && (line = reader.readLine()) != null) { + if (line.contains(marker)) { + Log.i(TAG, "Observed marker: " + marker); + return true; + } + } else { + Thread.sleep(200); + } + } + } finally { + try { + pfd.close(); + } catch (Exception ignored) { + } + } + return false; + } +} diff --git a/scripts/purchase-test-app/app/.mvn/jvm.config b/scripts/purchase-test-app/app/.mvn/jvm.config new file mode 100644 index 0000000000..e69de29bb2 diff --git a/scripts/purchase-test-app/app/.mvn/wrapper/maven-wrapper.properties b/scripts/purchase-test-app/app/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 0000000000..d58dfb70ba --- /dev/null +++ b/scripts/purchase-test-app/app/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +wrapperVersion=3.3.2 +distributionType=only-script +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip diff --git a/scripts/purchase-test-app/app/android/pom.xml b/scripts/purchase-test-app/app/android/pom.xml new file mode 100644 index 0000000000..4d2ff5cda6 --- /dev/null +++ b/scripts/purchase-test-app/app/android/pom.xml @@ -0,0 +1,134 @@ + + + 4.0.0 + + com.codenameone.examples.purchasetest + cn1purchasetest + 1.0-SNAPSHOT + + com.codenameone.examples.purchasetest + cn1purchasetest-android + 1.0-SNAPSHOT + + cn1purchasetest-android + + + UTF-8 + 17 + 17 + android + android + android-device + + + src/main/empty + + + + src/main/java + + + src/main/resources + + + + + com.codenameone + codenameone-maven-plugin + ${cn1.plugin.version} + + + build-android + package + + build + + + + + + + + + + + com.codenameone + codenameone-core + provided + + + ${project.groupId} + ${cn1app.name}-common + ${project.version} + + + ${project.groupId} + ${cn1app.name}-common + ${project.version} + tests + test + + + + + + + run-android + + + + org.codehaus.mojo + properties-maven-plugin + 1.0.0 + + + initialize + + read-project-properties + + + + ${basedir}/../common/codenameone_settings.properties + + + + + + + + maven-antrun-plugin + + + adb-install + verify + + run + + + + Running adb install + + + + + + + Trying to start app on device using adb + + + + + + + + + + + + + + + + + + diff --git a/scripts/purchase-test-app/app/android/src/main/java/com/codenameone/examples/purchasetest/PurchaseTestSinkImpl.java b/scripts/purchase-test-app/app/android/src/main/java/com/codenameone/examples/purchasetest/PurchaseTestSinkImpl.java new file mode 100644 index 0000000000..96762687d3 --- /dev/null +++ b/scripts/purchase-test-app/app/android/src/main/java/com/codenameone/examples/purchasetest/PurchaseTestSinkImpl.java @@ -0,0 +1,34 @@ +package com.codenameone.examples.purchasetest; + +import java.util.ArrayList; +import java.util.List; + +/** Desktop/simulator impl of {@link PurchaseTestSink}; records in memory. */ +public class PurchaseTestSinkImpl { + private static final List SUBMITTED = new ArrayList(); + + public void recordSubmittedReceipt(String transactionId) { + synchronized (SUBMITTED) { + SUBMITTED.add(transactionId == null ? "" : transactionId); + } + } + + public String recordedSubmissions() { + synchronized (SUBMITTED) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < SUBMITTED.size(); i++) { + if (i > 0) sb.append(','); + sb.append(SUBMITTED.get(i)); + } + return sb.toString(); + } + } + + public void reset() { + synchronized (SUBMITTED) { SUBMITTED.clear(); } + } + + public boolean isSupported() { + return true; + } +} diff --git a/scripts/purchase-test-app/app/common/codenameone_settings.properties b/scripts/purchase-test-app/app/common/codenameone_settings.properties new file mode 100644 index 0000000000..7f40d6a6f7 --- /dev/null +++ b/scripts/purchase-test-app/app/common/codenameone_settings.properties @@ -0,0 +1,36 @@ +#Updated keystore +#Sat Jun 06 20:07:54 IDT 2026 +codename1.android.keystore=/Users/shai/dev/cn2/CodenameOne/scripts/purchase-test-app/app/android/../common/androidCerts/KeyChain.ks +codename1.android.keystoreAlias=androidKey +codename1.android.keystorePassword=password +codename1.arg.android.licenseKey=CN1TESTPLACEHOLDERKEYNOTFORPRODUCTIONxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxIDAQAB +codename1.arg.android.useAndroidX=true +codename1.arg.ios.applicationQueriesSchemes=cydia +codename1.arg.ios.newStorageLocation=true +codename1.arg.ios.NSCameraUsageDescription=Used by the CI smoke test to verify the com.codename1.camera native bridge compiles. The app never opens a camera session. +codename1.arg.ios.uiscene=true +codename1.arg.java.version=17 +codename1.cssTheme=true +codename1.displayName=CN1PurchaseTest +codename1.icon=icon.png +codename1.ios.appid=Q5GHSKAL2F.com.codenameone.examples.purchasetest +codename1.ios.certificate= +codename1.ios.certificatePassword= +codename1.ios.debug.certificate= +codename1.ios.debug.certificatePassword= +codename1.ios.debug.provision= +codename1.ios.provision= +codename1.ios.release.certificate= +codename1.ios.release.certificatePassword= +codename1.ios.release.provision= +codename1.j2me.nativeTheme=nbproject/nativej2me.res +codename1.kotlin=false +codename1.languageLevel=5 +codename1.mainName=PurchaseTestApp +codename1.packageName=com.codenameone.examples.purchasetest +codename1.rim.certificatePassword= +codename1.rim.signtoolCsk= +codename1.rim.signtoolDb= +codename1.secondaryTitle=IAP e2e test +codename1.vendor=CodenameOne +codename1.version=1.0 diff --git a/scripts/purchase-test-app/app/common/icon.png b/scripts/purchase-test-app/app/common/icon.png new file mode 100644 index 0000000000..1f4fa5dd25 Binary files /dev/null and b/scripts/purchase-test-app/app/common/icon.png differ diff --git a/scripts/purchase-test-app/app/common/pom.xml b/scripts/purchase-test-app/app/common/pom.xml new file mode 100644 index 0000000000..8952e05f05 --- /dev/null +++ b/scripts/purchase-test-app/app/common/pom.xml @@ -0,0 +1,397 @@ + + + 4.0.0 + + com.codenameone.examples.purchasetest + cn1purchasetest + 1.0-SNAPSHOT + + com.codenameone.examples.purchasetest + cn1purchasetest-common + 1.0-SNAPSHOT + jar + + + + + com.codenameone + codenameone-core + provided + + + + + com.codenameone + cn1-ads-mock + ${cn1.version} + + + + + + + + + + + install-codenameone + ${user.home}/.codenameone/guibuilder.jar + + + + org.apache.maven.plugins + maven-antrun-plugin + + + + validate + + run + + + + + + + + + + + + + + + + + + + + + + + + + + + kotlin + + + + ${basedir}/src/main/kotlin + + + + 1.6.0 + true + + + + org.jetbrains.kotlin + kotlin-stdlib + ${kotlin.version} + + + + + + org.jetbrains + annotations + 13.0 + + + com.codenameone + java-runtime + provided + + + + + + org.codehaus.mojo + properties-maven-plugin + 1.0.0 + + + initialize + + read-project-properties + + + + ${basedir}/codenameone_settings.properties + + + + + + + org.jetbrains.kotlin + kotlin-maven-plugin + ${kotlin.version} + + + compile + + compile + + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/main/java + + + -no-reflect + -no-jdk + + + + + test-compile + + test-compile + + + + ${project.basedir}/src/test/kotlin + ${project.basedir}/src/test/java + + + -no-reflect + -no-jdk + + + + + + + + + + + + + javase + + + codename1.platform + javase + + + + javase + + + + + org.codehaus.mojo + exec-maven-plugin + + java + true + + -Xmx1024M + + -classpath + + ${exec.mainClass} + ${cn1.mainClass} + + + + + + + + + + simulator + + javase + + + + + + ios-debug + + + iphone + + + ios + + + + + ios-release + + + iphone + true + + + ios + true + + + + + javascript + + javascript + javascript + + + + + android + + android + android + + + + + uwp + + windows + win + + + + + windows + + desktop_windows + javase + + + + + mac + + desktop_macosx + javase + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + ${maven.compiler.source} + ${maven.compiler.target} + + + + org.codehaus.mojo + properties-maven-plugin + 1.0.0 + + + initialize + + read-project-properties + + + + ${basedir}/codenameone_settings.properties + + + + + + + + com.codenameone + codenameone-maven-plugin + + + + transcode-svg + generate-sources + + transcode-svg + + + + generate-gui-sources + process-sources + + generate-gui-sources + + + + cn1-process-classes + process-classes + + bytecode-compliance + css + process-annotations + + + + + attach-test-artifact + test + + attach-test-artifact + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + + + + + + + diff --git a/scripts/purchase-test-app/app/common/src/main/css/theme.css b/scripts/purchase-test-app/app/common/src/main/css/theme.css new file mode 100644 index 0000000000..62709812ae --- /dev/null +++ b/scripts/purchase-test-app/app/common/src/main/css/theme.css @@ -0,0 +1,4 @@ +/* Minimal theme for the IAP e2e test app. */ +#Constants { + includeNativeBool: true; +} diff --git a/scripts/purchase-test-app/app/common/src/main/java/com/codenameone/examples/purchasetest/PurchaseTestApp.java b/scripts/purchase-test-app/app/common/src/main/java/com/codenameone/examples/purchasetest/PurchaseTestApp.java new file mode 100644 index 0000000000..09847217a5 --- /dev/null +++ b/scripts/purchase-test-app/app/common/src/main/java/com/codenameone/examples/purchasetest/PurchaseTestApp.java @@ -0,0 +1,41 @@ +package com.codenameone.examples.purchasetest; + +import com.codename1.payment.Purchase; +import com.codename1.system.Lifecycle; +import com.codename1.ui.Form; +import com.codename1.ui.Label; +import com.codename1.ui.layouts.BoxLayout; + +/** + * Minimal Codename One app dedicated to the In-App-Purchase e2e tests. + * + * It references com.codename1.payment.* so the platform builders compile the + * IAP native bridge (iOS: defines CN1_USE_STOREKIT + links StoreKit; + * Android: pulls in Play Billing), and installs a {@link RecordingReceiptStore} + * so the iOS StoreKitTest and Android billing-bridge tests can assert that a + * purchase reached the store. Kept separate from the hellocodenameone sample so + * IAP wiring never ripples into the screenshot/notification CI workflows. + */ +public class PurchaseTestApp extends Lifecycle { + @Override + public void init(Object context) { + super.init(context); + try { + Purchase.getInAppPurchase().setReceiptStore(new RecordingReceiptStore()); + // Drain anything enqueued before the store was installed (the + // Android fake fires from the activity's onCreate, which can race + // ahead of this init). + Purchase.getInAppPurchase().synchronizeReceipts(); + System.out.println("CN1SS:IAP_DIAG installed=true"); + } catch (Throwable t) { + System.out.println("CN1SS:IAP_DIAG:EXCEPTION " + t.getClass().getName() + ": " + t.getMessage()); + } + } + + @Override + public void runApp() { + Form hi = new Form("Purchase Test", BoxLayout.y()); + hi.add(new Label("IAP e2e test app")); + hi.show(); + } +} diff --git a/scripts/purchase-test-app/app/common/src/main/java/com/codenameone/examples/purchasetest/PurchaseTestSink.java b/scripts/purchase-test-app/app/common/src/main/java/com/codenameone/examples/purchasetest/PurchaseTestSink.java new file mode 100644 index 0000000000..8951777372 --- /dev/null +++ b/scripts/purchase-test-app/app/common/src/main/java/com/codenameone/examples/purchasetest/PurchaseTestSink.java @@ -0,0 +1,17 @@ +package com.codenameone.examples.purchasetest; + +import com.codename1.system.NativeInterface; + +/** + * Test-only sink: {@link RecordingReceiptStore} forwards each submitted + * receipt's transactionId here, and the iOS implementation persists it to + * NSUserDefaults where the hosted XCTest can read it back. Implemented per + * platform so the app builds everywhere; only iOS is exercised by the test. + */ +public interface PurchaseTestSink extends NativeInterface { + void recordSubmittedReceipt(String transactionId); + + String recordedSubmissions(); + + void reset(); +} diff --git a/scripts/purchase-test-app/app/common/src/main/java/com/codenameone/examples/purchasetest/RecordingReceiptStore.java b/scripts/purchase-test-app/app/common/src/main/java/com/codenameone/examples/purchasetest/RecordingReceiptStore.java new file mode 100644 index 0000000000..48bbbad790 --- /dev/null +++ b/scripts/purchase-test-app/app/common/src/main/java/com/codenameone/examples/purchasetest/RecordingReceiptStore.java @@ -0,0 +1,38 @@ +package com.codenameone.examples.purchasetest; + +import com.codename1.payment.Receipt; +import com.codename1.payment.ReceiptStore; +import com.codename1.system.NativeLookup; +import com.codename1.util.SuccessCallback; + +/** + * Test ReceiptStore installed at startup. Does no networking: it reports + * success immediately and forwards the submitted transactionId to the native + * {@link PurchaseTestSink} (iOS) plus logs CN1SS:IAP:SUBMITTED so the Android + * instrumentation test can scrape logcat. + * + * iOS-/Android-level guard for #5186: the platform receipt path submits through + * a freshly constructed Purchase instance, so a recorded submission proves the + * store installed on a different instance is visible to it. + */ +public class RecordingReceiptStore implements ReceiptStore { + private final PurchaseTestSink sink; + + public RecordingReceiptStore() { + PurchaseTestSink s = NativeLookup.create(PurchaseTestSink.class); + sink = (s != null && s.isSupported()) ? s : null; + } + + public void submitReceipt(Receipt receipt, SuccessCallback callback) { + if (receipt != null && sink != null) { + sink.recordSubmittedReceipt(receipt.getTransactionId()); + } + System.out.println("CN1SS:IAP:SUBMITTED " + + (receipt == null ? "null" : receipt.getTransactionId())); + callback.onSucess(Boolean.TRUE); + } + + public void fetchReceipts(SuccessCallback callback) { + callback.onSucess(new Receipt[0]); + } +} diff --git a/scripts/purchase-test-app/app/ios/pom.xml b/scripts/purchase-test-app/app/ios/pom.xml new file mode 100644 index 0000000000..aee3f2cdee --- /dev/null +++ b/scripts/purchase-test-app/app/ios/pom.xml @@ -0,0 +1,71 @@ + + + 4.0.0 + + com.codenameone.examples.purchasetest + cn1purchasetest + 1.0-SNAPSHOT + + com.codenameone.examples.purchasetest + cn1purchasetest-ios + 1.0-SNAPSHOT + + cn1purchasetest-ios + + + UTF-8 + 17 + 17 + ios + ios + ios-device + + + + + src/main/objectivec + + + src/main/resources + + + + + com.codenameone + codenameone-maven-plugin + ${cn1.plugin.version} + + + build-ios + package + + build + + + + + + + + + + + ${project.groupId} + ${cn1app.name}-common + ${project.version} + + + ${project.groupId} + ${cn1app.name}-common + ${project.version} + tests + test + + + + + + + + + diff --git a/scripts/purchase-test-app/app/ios/src/main/objectivec/com_codenameone_examples_purchasetest_PurchaseTestSinkImpl.m b/scripts/purchase-test-app/app/ios/src/main/objectivec/com_codenameone_examples_purchasetest_PurchaseTestSinkImpl.m new file mode 100644 index 0000000000..1fd02f7945 --- /dev/null +++ b/scripts/purchase-test-app/app/ios/src/main/objectivec/com_codenameone_examples_purchasetest_PurchaseTestSinkImpl.m @@ -0,0 +1,33 @@ +#import "com_codenameone_examples_purchasetest_PurchaseTestSinkImpl.h" + +// Persist submitted receipt transactionIds in NSUserDefaults so the hosted +// XCTest (PurchaseStoreKitTests) can read them back in-process after driving a +// purchase through SKTestSession. Key is shared with the test. +static NSString * const CN1IAPTestSubmittedKey = @"CN1IAPTestSubmittedReceipts"; + +@implementation com_codenameone_examples_purchasetest_PurchaseTestSinkImpl + +-(void)recordSubmittedReceipt:(NSString*)transactionId { + NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; + NSArray *existing = [defaults arrayForKey:CN1IAPTestSubmittedKey]; + NSMutableArray *updated = existing ? [existing mutableCopy] : [NSMutableArray array]; + [updated addObject:(transactionId != nil ? transactionId : @"")]; + [defaults setObject:updated forKey:CN1IAPTestSubmittedKey]; + [defaults synchronize]; +} + +-(NSString*)recordedSubmissions { + NSArray *existing = [[NSUserDefaults standardUserDefaults] arrayForKey:CN1IAPTestSubmittedKey]; + return existing ? [existing componentsJoinedByString:@","] : @""; +} + +-(void)reset { + [[NSUserDefaults standardUserDefaults] removeObjectForKey:CN1IAPTestSubmittedKey]; + [[NSUserDefaults standardUserDefaults] synchronize]; +} + +-(BOOL)isSupported { + return YES; +} + +@end diff --git a/scripts/purchase-test-app/app/mvnw b/scripts/purchase-test-app/app/mvnw new file mode 100755 index 0000000000..19529ddf8c --- /dev/null +++ b/scripts/purchase-test-app/app/mvnw @@ -0,0 +1,259 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.2 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${0##*/mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/scripts/purchase-test-app/app/mvnw.cmd b/scripts/purchase-test-app/app/mvnw.cmd new file mode 100644 index 0000000000..b150b91ed5 --- /dev/null +++ b/scripts/purchase-test-app/app/mvnw.cmd @@ -0,0 +1,149 @@ +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.2 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" (%__MVNW_CMD__% %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace '^.*'+$MVNW_REPO_PATTERN,'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' +$MAVEN_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/scripts/purchase-test-app/app/pom.xml b/scripts/purchase-test-app/app/pom.xml new file mode 100644 index 0000000000..b9ed9fda05 --- /dev/null +++ b/scripts/purchase-test-app/app/pom.xml @@ -0,0 +1,141 @@ + + 4.0.0 + com.codenameone.examples.purchasetest + cn1purchasetest + 1.0-SNAPSHOT + pom + cn1purchasetest + cn1purchasetest + https://www.codenameone.com + + + GPL v2 With Classpath Exception + https://openjdk.java.net/legal/gplv2+ce.html + repo + A business-friendly OSS license + + + +common + + + 8.0-SNAPSHOT + 8.0-SNAPSHOT + UTF-8 + 17 + 17 + 1.7.11 + 3.8.0 + 17 + 17 + 17 + 17 + 17 + cn1purchasetest + + + + + com.codenameone + java-runtime + ${cn1.version} + + + com.codenameone + codenameone-core + ${cn1.version} + + + com.codenameone + codenameone-javase + ${cn1.version} + + + com.codenameone + codenameone-buildclient + ${cn1.version} + system + ${user.home}/.codenameone/CodeNameOneBuildClient.jar + + + + + + + + com.codenameone + codenameone-maven-plugin + ${cn1.plugin.version} + + + org.apache.maven.plugins + maven-compiler-plugin + ${maven-compiler-plugin.version} + + + org.codehaus.mojo + exec-maven-plugin + 3.0.0 + + + maven-antrun-plugin + org.apache.maven.plugins + 3.1.0 + + + + + + com.codenameone + codenameone-maven-plugin + ${cn1.plugin.version} + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M5 + + + com.codenameone + codenameone-maven-plugin + ${cn1.plugin.version} + + + + + + + + + + + ios + + + codename1.platform + ios + + + + ios + + + + android + + + codename1.platform + android + + + + android + + + + diff --git a/scripts/run-ios-purchase-tests.sh b/scripts/run-ios-purchase-tests.sh new file mode 100755 index 0000000000..2db085e842 --- /dev/null +++ b/scripts/run-ios-purchase-tests.sh @@ -0,0 +1,124 @@ +#!/usr/bin/env bash +# Run the native StoreKitTest purchase XCTest for the generated Codename One +# iOS project. This script: +# 1) installs the in-repo StoreKitTest sources + Products.storekit into the +# generated Xcode project (and links StoreKit/StoreKitTest), +# 2) auto-selects an available simulator destination, +# 3) executes `xcodebuild test` using the standard Xcode test runner. + +set -euo pipefail + +ri_log() { echo "[run-ios-purchase-tests] $1"; } + +if [ $# -lt 1 ]; then + ri_log "Usage: $0 [app_scheme] [test_scheme]" >&2 + exit 2 +fi + +WORKSPACE_PATH="$1" +APP_SCHEME="${2:-}" +TEST_SCHEME="${3:-}" + +if [ ! -d "$WORKSPACE_PATH" ]; then + ri_log "Xcode workspace/project not found at $WORKSPACE_PATH" >&2 + exit 3 +fi + +XCODE_CONTAINER_FLAG="-workspace" +if [[ "$WORKSPACE_PATH" == *.xcodeproj ]]; then + XCODE_CONTAINER_FLAG="-project" +fi + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" +cd "$REPO_ROOT" + +if [ -z "$APP_SCHEME" ]; then + if [[ "$WORKSPACE_PATH" == *.xcworkspace ]]; then + APP_SCHEME="$(basename "$WORKSPACE_PATH" .xcworkspace)" + else + APP_SCHEME="$(basename "$WORKSPACE_PATH" .xcodeproj)" + fi +fi +if [ -z "$TEST_SCHEME" ]; then + TEST_SCHEME="${APP_SCHEME}Tests" +fi + +PROJECT_DIR="$(cd "$(dirname "$WORKSPACE_PATH")" && pwd)" + +ri_log "Injecting native StoreKitTest purchase tests into project at $PROJECT_DIR" +"$REPO_ROOT/scripts/ios/purchase-tests/install-native-purchase-tests.sh" "$PROJECT_DIR" +"$REPO_ROOT/scripts/ios/create-shared-scheme.py" "$PROJECT_DIR" "$APP_SCHEME" +"$REPO_ROOT/scripts/ios/create-shared-scheme.py" "$PROJECT_DIR" "$TEST_SCHEME" + +ri_log "Discovering simulator destination for test scheme $TEST_SCHEME" +DESTINATION="$(xcodebuild "$XCODE_CONTAINER_FLAG" "$WORKSPACE_PATH" -scheme "$TEST_SCHEME" -showdestinations 2>/dev/null \ + | sed -n 's/.*{ platform:iOS Simulator,.*id:\([^,}]*\).*/\1/p' \ + | grep -v "placeholder" \ + | head -n 1 \ + | sed 's#^#platform=iOS Simulator,id=#' || true)" + +if [ -z "$DESTINATION" ]; then + ri_log "No concrete iOS Simulator destination from -showdestinations; querying simctl" + EXISTING_ID="$(xcrun simctl list -j devices available 2>/dev/null \ + | python3 -c 'import json,sys +data=json.load(sys.stdin) +for runtime, devs in data.get("devices", {}).items(): + if "iOS" not in runtime: + continue + for d in devs: + if d.get("isAvailable") and "iPhone" in d.get("name",""): + print(d["udid"]); sys.exit(0)' 2>/dev/null || true)" + if [ -n "$EXISTING_ID" ]; then + ri_log "Reusing existing iPhone simulator $EXISTING_ID" + DESTINATION="platform=iOS Simulator,id=$EXISTING_ID" + else + LATEST_RUNTIME="$(xcrun simctl list -j runtimes available 2>/dev/null \ + | python3 -c 'import json,sys +runtimes=[r for r in json.load(sys.stdin).get("runtimes",[]) if r.get("isAvailable") and r.get("identifier","").startswith("com.apple.CoreSimulator.SimRuntime.iOS-")] +runtimes.sort(key=lambda r: r.get("version",""), reverse=True) +print(runtimes[0]["identifier"] if runtimes else "")' 2>/dev/null || true)" + LATEST_DEVICE_TYPE="$(xcrun simctl list -j devicetypes 2>/dev/null \ + | python3 -c 'import json,sys +types=[t["identifier"] for t in json.load(sys.stdin).get("devicetypes",[]) if "iPhone" in t.get("name","")] +types.sort(reverse=True) +print(types[0] if types else "")' 2>/dev/null || true)" + if [ -n "$LATEST_RUNTIME" ] && [ -n "$LATEST_DEVICE_TYPE" ]; then + ri_log "Creating throwaway simulator (device=$LATEST_DEVICE_TYPE runtime=$LATEST_RUNTIME)" + NEW_ID="$(xcrun simctl create "cn1-purchase-tests" "$LATEST_DEVICE_TYPE" "$LATEST_RUNTIME" 2>/dev/null || true)" + if [ -n "$NEW_ID" ]; then + DESTINATION="platform=iOS Simulator,id=$NEW_ID" + fi + fi + fi +fi + +if [ -z "$DESTINATION" ]; then + ri_log "Falling back to name-based destination (will fail if no iPhone 16 is installed)" + DESTINATION="platform=iOS Simulator,name=iPhone 16" +fi + +SIMULATOR_ID="$(printf "%s" "$DESTINATION" | sed -n 's/.*id=\([^,]*\).*/\1/p')" +if [ -n "$SIMULATOR_ID" ]; then + ri_log "Booting simulator $SIMULATOR_ID" + xcrun simctl boot "$SIMULATOR_ID" >/dev/null 2>&1 || true + xcrun simctl bootstatus "$SIMULATOR_ID" -b >/dev/null 2>&1 || true +fi + +ARTIFACTS_DIR="${ARTIFACTS_DIR:-$REPO_ROOT/artifacts}" +mkdir -p "$ARTIFACTS_DIR" +TEST_LOG="$ARTIFACTS_DIR/xcode-purchase-tests.log" + +ri_log "Running xcodebuild test (scheme=$TEST_SCHEME, destination=$DESTINATION)" +set +e +xcodebuild \ + "$XCODE_CONTAINER_FLAG" "$WORKSPACE_PATH" \ + -scheme "$TEST_SCHEME" \ + -destination "$DESTINATION" \ + -only-testing:"${TEST_SCHEME}/PurchaseStoreKitTests" \ + test | tee "$TEST_LOG" +RC=${PIPESTATUS[0]} +set -e + +ri_log "xcodebuild test exit code: $RC" +exit "$RC"