diff --git a/.github/workflows/dev-tag.yml b/.github/workflows/dev-tag.yml new file mode 100644 index 000000000..8d27abbdd --- /dev/null +++ b/.github/workflows/dev-tag.yml @@ -0,0 +1,72 @@ +name: Checks for release + +on: + push: + tags: + - 'dev-*' + +jobs: + dependency-versions: + name: Dependency Versions + runs-on: ubuntu-latest + outputs: + versions: ${{ steps.result.outputs.versions }} + steps: + - uses: actions/checkout@v4 + - uses: supertokens/get-core-dependencies-action@main + id: result + unit-tests: + name: Run unit tests + uses: ./.github/workflows/unit-test.yml + stress-tests: + uses: ./.github/workflows/stress-tests.yml + mark-as-passed: + needs: [dependency-versions, unit-tests, stress-tests] + name: Mark as passed + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + plugin: + - sqlite + - postgresql + - mysql + - mongodb + steps: + - name: Mark plugin as passed + if: matrix.plugin != 'sqlite' + uses: muhfaris/request-action@v1 + with: + url: https://api.supertokens.io/0/plugin + method: PATCH + headers: | + { + "Content-Type": "application/json", + "api-version": "0" + } + body: | + { + "password": "${{ secrets.SUPERTOKENS_API_KEY }}", + "version": "${{ needs.dependency-versions.outputs.versions['core'] }}", + "planType": "FREE", + "name": "${{ matrix.plugin }}", + "testPassed": true + } + - name: Mark core as passed + if: matrix.plugin == 'sqlite' + uses: muhfaris/request-action@v1 + with: + url: https://api.supertokens.io/0/core + method: PATCH + headers: | + { + "Content-Type": "application/json", + "api-version": "0" + } + body: | + { + "password": "${{ secrets.SUPERTOKENS_API_KEY }}", + "version": "${{ needs.dependency-versions.outputs.versions['core'] }}", + "planType": "FREE", + "testPassed": true + } diff --git a/.github/workflows/github-actions-changelog.yml b/.github/workflows/github-actions-changelog.yml deleted file mode 100644 index 47aaf4a24..000000000 --- a/.github/workflows/github-actions-changelog.yml +++ /dev/null @@ -1,15 +0,0 @@ -name: "Enforcing changelog in PRs Workflow" -on: - pull_request: - types: [ opened, synchronize, reopened, ready_for_review, labeled, unlabeled ] - -jobs: - # Enforces the update of a changelog file on every pull request - changelog: - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - uses: dangoslen/changelog-enforcer@v2 - with: - changeLogPath: 'CHANGELOG.md' - skipLabels: 'Skip-Changelog' \ No newline at end of file diff --git a/.github/workflows/lint-pr-title.yml b/.github/workflows/lint-pr-title.yml deleted file mode 100644 index 96281a745..000000000 --- a/.github/workflows/lint-pr-title.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: "Lint PR Title" - -on: - pull_request: - types: - - opened - - reopened - - edited - - synchronize - -jobs: - pr-title: - name: Lint PR title - runs-on: ubuntu-latest - steps: - - uses: amannn/action-semantic-pull-request@v3 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - with: - validateSingleCommit: true \ No newline at end of file diff --git a/.github/workflows/pr-checks.yml b/.github/workflows/pr-checks.yml new file mode 100644 index 000000000..6f9403d8c --- /dev/null +++ b/.github/workflows/pr-checks.yml @@ -0,0 +1,27 @@ +name: PR Checks +on: + pull_request: + types: [ opened, synchronize, reopened, ready_for_review, labeled, unlabeled ] + +jobs: + pr-title: + name: Lint PR title + runs-on: ubuntu-latest + steps: + - uses: amannn/action-semantic-pull-request@v3 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + validateSingleCommit: true + changelog: + name: Enforce Changelog + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - uses: dangoslen/changelog-enforcer@v2 + with: + changeLogPath: 'CHANGELOG.md' + skipLabels: 'Skip-Changelog' + unit-tests: + name: Run unit tests + uses: ./.github/workflows/unit-test.yml diff --git a/.github/workflows/publish-dev-docker.yml b/.github/workflows/publish-dev-docker.yml index a5ca2f1c6..6d7f87c72 100644 --- a/.github/workflows/publish-dev-docker.yml +++ b/.github/workflows/publish-dev-docker.yml @@ -4,9 +4,75 @@ on: branches: - "**" jobs: + dependency-branches: + name: Dependency Branches + runs-on: ubuntu-latest + outputs: + branches: ${{ steps.result.outputs.branches }} + + steps: + - uses: actions/checkout@v4 + - uses: supertokens/get-core-dependencies-action@main + id: result + with: + running-for: core docker: + name: Docker runs-on: ubuntu-latest + needs: dependency-branches + outputs: + tag: ${{ steps.set_tag.outputs.TAG }} + strategy: + fail-fast: false + matrix: + plugin: + - postgresql + - mysql + # - mongodb steps: + - name: Set up JDK 15.0.1 + uses: actions/setup-java@v2 + with: + java-version: 15.0.1 + distribution: zulu + - uses: actions/checkout@v2 + with: + repository: supertokens/supertokens-root + path: ./supertokens-root + ref: master + - uses: actions/checkout@v2 + with: + path: ./supertokens-root/supertokens-core + - uses: actions/checkout@v2 + with: + repository: supertokens/supertokens-plugin-interface + path: ./supertokens-root/supertokens-plugin-interface + ref: ${{ fromJson(needs.dependency-branches.outputs.branches)['plugin-interface'] }} + - uses: actions/checkout@v2 + if: matrix.plugin != 'sqlite' + with: + repository: supertokens/supertokens-${{ matrix.plugin }}-plugin + path: ./supertokens-root/supertokens-${{ matrix.plugin }}-plugin + ref: ${{ fromJson(needs.dependency-branches.outputs.branches)[matrix.plugin] }} + - name: Load Modules + run: | + cd supertokens-root + echo "core,master + plugin-interface,master + ${{ matrix.plugin }}-plugin,master + " > modules.txt + cat modules.txt + ./loadModules + - name: Setup test env + run: cd supertokens-root && ./utils/setupTestEnv --local + - name: Generate config file + run: | + cd supertokens-root + touch config_temp.yaml + cat supertokens-core/config.yaml >> config_temp.yaml + cat supertokens-${{ matrix.plugin }}-plugin/config.yaml >> config_temp.yaml + mv config_temp.yaml config.yaml + - name: set tag id: set_tag run: | @@ -17,26 +83,15 @@ jobs: with: username: ${{ vars.DOCKERHUB_USERNAME }} password: ${{ secrets.DOCKERHUB_TOKEN }} - - - name: Set up QEMU + - name: Set up QEMU uses: docker/setup-qemu-action@v3 - - - name: Set up Docker Buildx + - name: Set up Docker Buildx uses: docker/setup-buildx-action@v3 - - # - name: Build and export to Docker - # uses: docker/build-push-action@v6 - # with: - # load: true - # tags: ${{ env.TEST_TAG }} - - # - name: Test - # run: | - # docker run --rm ${{ env.TEST_TAG }} - name: Build and push uses: docker/build-push-action@v6 with: push: true - tags: supertokens/supertokens-core:dev-branch-${{ steps.set_tag.outputs.TAG }} - file: .github/helpers/Dockerfile + context: ./supertokens-root + tags: supertokens/supertokens-dev-${{ matrix.plugin }}:${{ steps.set_tag.outputs.TAG }} + file: ./supertokens-root/supertokens-${{ matrix.plugin }}-plugin/.github/helpers/docker/Dockerfile diff --git a/.github/workflows/stress-tests.yml b/.github/workflows/stress-tests.yml new file mode 100644 index 000000000..7f61c29e5 --- /dev/null +++ b/.github/workflows/stress-tests.yml @@ -0,0 +1,48 @@ +name: Stress Tests + +on: + workflow_call: + inputs: + tag: + description: 'Docker image tag to use' + required: true + type: string + + +jobs: + stress-tests: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Set up Node.js + uses: actions/setup-node@v3 + with: + node-version: '20' + - name: Install dependencies + run: | + cd stress-tests + npm install + - name: Update Docker image in compose + run: | + cd stress-tests + sed -i 's|supertokens/supertokens-postgresql|supertokens/supertokens-dev-postgresql:${{ inputs.tag }}|' docker-compose.yml + cat docker-compose.yml + - name: Bring up the services + run: | + cd stress-tests + docker compose up -d + - name: Generate user jsons + run: | + cd stress-tests + npm run generate-users + - name: Run one million users test + id: one-million-users + run: | + cd stress-tests + npm run one-million-users | tee stress-tests.log + - name: Display Test Statistics + run: | + echo "## Stress Test Results" >> $GITHUB_STEP_SUMMARY + echo "| Test | Duration |" >> $GITHUB_STEP_SUMMARY + echo "|------|----------|" >> $GITHUB_STEP_SUMMARY + jq -r '.measurements[] | "| \(.title) | \(.formatted) |"' stress-tests/stats.json >> $GITHUB_STEP_SUMMARY diff --git a/.github/workflows/tests-pass-check-pr.yml b/.github/workflows/tests-pass-check-pr.yml deleted file mode 100644 index 07467d9d4..000000000 --- a/.github/workflows/tests-pass-check-pr.yml +++ /dev/null @@ -1,24 +0,0 @@ -name: "Check if \"Run tests\" action succeeded" - -on: - pull_request: - types: - - opened - - reopened - - edited - - synchronize - -jobs: - pr-run-test-action: - name: Check if "Run tests" action succeeded - timeout-minutes: 60 - concurrency: - group: ${{ github.head_ref }} - cancel-in-progress: true - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v2 - - name: node install - run: cd ./.github/helpers && npm i - - name: Calling github API - run: cd ./.github/helpers && GITHUB_TOKEN=${{ github.token }} REPO=${{ github.repository }} RUN_ID=${{ github.run_id }} BRANCH=${{ github.head_ref }} JOB_ID=${{ github.job }} SOURCE_OWNER=${{ github.event.pull_request.head.repo.owner.login }} CURRENT_SHA=${{ github.event.pull_request.head.sha }} node node_modules/github-workflow-helpers/test-pass-check-pr.js \ No newline at end of file diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml deleted file mode 100644 index d4255461e..000000000 --- a/.github/workflows/tests.yml +++ /dev/null @@ -1,37 +0,0 @@ -name: "Run tests" -on: - workflow_dispatch: - inputs: - pluginRepoOwnerName: - description: 'supertokens-plugin-interface repo owner name' - default: supertokens - required: true - pluginInterfaceBranch: - description: 'supertokens-plugin-interface repos branch name' - default: master - required: true - -jobs: - test_job: - name: Run tests - timeout-minutes: 60 - runs-on: ubuntu-latest - container: rishabhpoddar/supertokens_core_testing - steps: - - uses: actions/checkout@v2 - - name: Cloning supertokens-root - run: cd ../ && git clone https://github.com/supertokens/supertokens-root.git - - name: Update Java 1 - run: update-alternatives --install "/usr/bin/java" "java" "/usr/java/jdk-15.0.1/bin/java" 2 - - name: Update Java 2 - run: update-alternatives --install "/usr/bin/javac" "javac" "/usr/java/jdk-15.0.1/bin/javac" 2 - - name: Modifying modules.txt in supertokens-root - run: cd ../supertokens-root && echo "core,master\nplugin-interface,${{ github.event.inputs.pluginInterfaceBranch }},${{ github.event.inputs.pluginRepoOwnerName }}" > modules.txt - - name: Contents of modules.txt - run: cat ../supertokens-root/modules.txt - - name: Running loadModules in supertokens-root - run: cd ../supertokens-root && ./loadModules - - name: Copying current supertokens-core branch into supertokens-root - run: cd ../supertokens-root && rm -rf ./supertokens-core && cp -r ../supertokens-core ./ - - name: Building and running tests - run: cd ../supertokens-root && ./startTestingEnv \ No newline at end of file diff --git a/.github/workflows/unit-test.yml b/.github/workflows/unit-test.yml new file mode 100644 index 000000000..298f93fce --- /dev/null +++ b/.github/workflows/unit-test.yml @@ -0,0 +1,83 @@ +name: Unit Tests + +on: + workflow_call: + +jobs: + dependency-branches: + name: Dependency Branches + runs-on: ubuntu-latest + outputs: + branches: ${{ steps.result.outputs.branches }} + + steps: + - uses: actions/checkout@v4 + - uses: supertokens/get-core-dependencies-action@main + id: result + + test: + name: Unit tests + needs: dependency-branches + strategy: + fail-fast: false + matrix: + plugin: + - sqlite + - postgresql + - mysql + - mongodb + + runs-on: ubuntu-latest + steps: + - name: Set up JDK 15.0.1 + uses: actions/setup-java@v2 + with: + java-version: 15.0.1 + distribution: zulu + - uses: actions/checkout@v2 + with: + repository: supertokens/supertokens-root + path: ./supertokens-root + ref: master + - uses: actions/checkout@v2 + with: + path: ./supertokens-root/supertokens-core + - uses: actions/checkout@v2 + with: + repository: supertokens/supertokens-plugin-interface + path: ./supertokens-root/supertokens-plugin-interface + ref: ${{ fromJson(needs.dependency-branches.outputs.branches)['plugin-interface'] }} + - uses: actions/checkout@v2 + if: matrix.plugin != 'sqlite' + with: + repository: supertokens/supertokens-${{ matrix.plugin }}-plugin + path: ./supertokens-root/supertokens-${{ matrix.plugin }}-plugin + ref: ${{ fromJson(needs.dependency-branches.outputs.branches)[matrix.plugin] }} + - name: Load Modules + run: | + cd supertokens-root + echo "core,master + plugin-interface,master + ${{ matrix.plugin }}-plugin,master + " > modules.txt + cat modules.txt + ./loadModules + - name: Setup test env + run: cd supertokens-root && ./utils/setupTestEnv --local + - name: Start ${{ matrix.plugin }} server + if: matrix.plugin != 'sqlite' + run: cd supertokens-root/supertokens-${{ matrix.plugin }}-plugin && ./startDb.sh + - name: Run tests + env: + ST_PLUGIN_NAME: ${{ matrix.plugin }} + run: | + cd supertokens-root + ./gradlew test + - name: Publish Test Report + uses: mikepenz/action-junit-report@v5 + if: always() + with: + report_paths: '**/build/test-results/test/TEST-*.xml' + detailed_summary: true + include_passed: false + annotate_notice: true diff --git a/CHANGELOG.md b/CHANGELOG.md index a2f7b414b..84b214c71 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] +- Migrates tests to Github Actions + ## [10.1.4] - Fixes bulk migration user roles association when there is no external userId assigned to the user diff --git a/build.gradle b/build.gradle index 5e07e4a3d..ddac8e17f 100644 --- a/build.gradle +++ b/build.gradle @@ -118,6 +118,7 @@ test { outputs.upToDateWhen { false } showStandardStreams = true } + maxParallelForks = Runtime.runtime.availableProcessors() } import org.gradle.api.tasks.testing.logging.TestExceptionFormat diff --git a/ee/src/test/java/io/supertokens/ee/test/TestMultitenancyStats.java b/ee/src/test/java/io/supertokens/ee/test/TestMultitenancyStats.java index 6acc45566..ee0d491a2 100644 --- a/ee/src/test/java/io/supertokens/ee/test/TestMultitenancyStats.java +++ b/ee/src/test/java/io/supertokens/ee/test/TestMultitenancyStats.java @@ -44,14 +44,14 @@ public void testPaidStatsIsSentForAllAppsInMultitenancy() throws Exception { String[] args = {"../../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); - CronTaskTest.getInstance(process.main).setIntervalInSeconds(EELicenseCheck.RESOURCE_KEY, 1); + CronTaskTest.getInstance(process.getProcess()).setIntervalInSeconds(EELicenseCheck.RESOURCE_KEY, 1); Assert.assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - if (StorageLayer.isInMemDb(process.main)) { + if (StorageLayer.isInMemDb(process.getProcess())) { // cause we keep all features enabled in memdb anyway return; } diff --git a/ee/src/test/java/io/supertokens/ee/test/TestingProcessManager.java b/ee/src/test/java/io/supertokens/ee/test/TestingProcessManager.java index c19a80d89..9a27a3944 100644 --- a/ee/src/test/java/io/supertokens/ee/test/TestingProcessManager.java +++ b/ee/src/test/java/io/supertokens/ee/test/TestingProcessManager.java @@ -16,7 +16,7 @@ static void deleteAllInformation() throws Exception { String[] args = {"../../"}; TestingProcess process = TestingProcessManager.start(args); process.checkOrWaitForEvent(PROCESS_STATE.STARTED); - process.main.deleteAllInformationForTesting(); + process.getProcess().deleteAllInformationForTesting(); process.kill(); System.out.println("----------DELETE ALL INFORMATION----------"); } diff --git a/ee/src/test/java/io/supertokens/ee/test/Utils.java b/ee/src/test/java/io/supertokens/ee/test/Utils.java index 2235c3349..1a8d0f7b3 100644 --- a/ee/src/test/java/io/supertokens/ee/test/Utils.java +++ b/ee/src/test/java/io/supertokens/ee/test/Utils.java @@ -24,7 +24,8 @@ public static void afterTesting() { try { // remove config.yaml file - ProcessBuilder pb = new ProcessBuilder("rm", "config.yaml"); + String workerId = System.getProperty("org.gradle.test.worker", ""); + ProcessBuilder pb = new ProcessBuilder("rm", "config" + workerId + ".yaml"); pb.directory(new File(installDir)); Process process = pb.start(); process.waitFor(); @@ -58,7 +59,8 @@ public static void reset() { // if the default config is not the same as the current config, we must reset the storage layer File ogConfig = new File("../../temp/config.yaml"); - File currentConfig = new File("../../config.yaml"); + String workerId = System.getProperty("org.gradle.test.worker", ""); + File currentConfig = new File("../../config" + workerId + ".yaml"); if (currentConfig.isFile()) { byte[] ogConfigContent = Files.readAllBytes(ogConfig.toPath()); byte[] currentConfigContent = Files.readAllBytes(currentConfig.toPath()); @@ -67,7 +69,7 @@ public static void reset() { } } - ProcessBuilder pb = new ProcessBuilder("cp", "temp/config.yaml", "./config.yaml"); + ProcessBuilder pb = new ProcessBuilder("cp", "temp/config.yaml", "./config" + workerId + ".yaml"); pb.directory(new File(installDir)); Process process = pb.start(); process.waitFor(); @@ -96,14 +98,15 @@ static void commentConfigValue(String key) throws IOException { String newStr = "\n# " + key + ":"; StringBuilder originalFileContent = new StringBuilder(); - try (BufferedReader reader = new BufferedReader(new FileReader("../../config.yaml"))) { + String workerId = System.getProperty("org.gradle.test.worker", ""); + try (BufferedReader reader = new BufferedReader(new FileReader("../../config" + workerId + ".yaml"))) { String currentReadingLine = reader.readLine(); while (currentReadingLine != null) { originalFileContent.append(currentReadingLine).append(System.lineSeparator()); currentReadingLine = reader.readLine(); } String modifiedFileContent = originalFileContent.toString().replaceAll(oldStr, newStr); - try (BufferedWriter writer = new BufferedWriter(new FileWriter("../../config.yaml"))) { + try (BufferedWriter writer = new BufferedWriter(new FileWriter("../../config" + workerId + ".yaml"))) { writer.write(modifiedFileContent); } } @@ -117,14 +120,15 @@ public static void setValueInConfig(String key, String value) throws IOException String oldStr = "\n((#\\s)?)" + key + "(:|((:\\s).+))\n"; String newStr = "\n" + key + ": " + value + "\n"; StringBuilder originalFileContent = new StringBuilder(); - try (BufferedReader reader = new BufferedReader(new FileReader("../../config.yaml"))) { + String workerId = System.getProperty("org.gradle.test.worker", ""); + try (BufferedReader reader = new BufferedReader(new FileReader("../../config" + workerId + ".yaml"))) { String currentReadingLine = reader.readLine(); while (currentReadingLine != null) { originalFileContent.append(currentReadingLine).append(System.lineSeparator()); currentReadingLine = reader.readLine(); } String modifiedFileContent = originalFileContent.toString().replaceAll(oldStr, newStr); - try (BufferedWriter writer = new BufferedWriter(new FileWriter("../../config.yaml"))) { + try (BufferedWriter writer = new BufferedWriter(new FileWriter("../../config" + workerId + ".yaml"))) { writer.write(modifiedFileContent); } } diff --git a/ee/src/test/java/io/supertokens/ee/test/api/DeleteLicenseKeyAPITest.java b/ee/src/test/java/io/supertokens/ee/test/api/DeleteLicenseKeyAPITest.java index 6f9b5123f..da61e2044 100644 --- a/ee/src/test/java/io/supertokens/ee/test/api/DeleteLicenseKeyAPITest.java +++ b/ee/src/test/java/io/supertokens/ee/test/api/DeleteLicenseKeyAPITest.java @@ -45,7 +45,7 @@ public void testDeletingLicenseKeyWhenItIsNotSet() throws Exception { // check that no LicenseKey exits try { - FeatureFlag.getInstance(process.main).getLicenseKey(); + FeatureFlag.getInstance(process.getProcess()).getLicenseKey(); fail(); } catch (NoLicenseKeyFoundException ignored) { } @@ -58,7 +58,7 @@ public void testDeletingLicenseKeyWhenItIsNotSet() throws Exception { // check that no LicenseKey exits try { - FeatureFlag.getInstance(process.main).getLicenseKey(); + FeatureFlag.getInstance(process.getProcess()).getLicenseKey(); fail(); } catch (NoLicenseKeyFoundException ignored) { } @@ -90,7 +90,7 @@ public void testDeletingLicenseKey() throws Exception { // check that no LicenseKey exits try { - FeatureFlag.getInstance(process.main).getLicenseKey(); + FeatureFlag.getInstance(process.getProcess()).getLicenseKey(); fail(); } catch (NoLicenseKeyFoundException ignored) { } diff --git a/ee/src/test/java/io/supertokens/ee/test/api/GetFeatureFlagAPITest.java b/ee/src/test/java/io/supertokens/ee/test/api/GetFeatureFlagAPITest.java index efd133a86..24e34e1b5 100644 --- a/ee/src/test/java/io/supertokens/ee/test/api/GetFeatureFlagAPITest.java +++ b/ee/src/test/java/io/supertokens/ee/test/api/GetFeatureFlagAPITest.java @@ -38,7 +38,7 @@ public void testRetrievingFeatureFlagInfoWhenNoLicenseKeyIsSet() throws Exceptio TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); Assert.assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); - if (StorageLayer.isInMemDb(process.main)) { + if (StorageLayer.isInMemDb(process.getProcess())) { // cause we keep all features enabled in memdb anyway return; } @@ -72,7 +72,7 @@ public void testRetrievingFeatureFlagInfoWhenLicenseKeyIsSet() throws Exception TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); Assert.assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); - if (StorageLayer.isInMemDb(process.main)) { + if (StorageLayer.isInMemDb(process.getProcess())) { // cause we keep all features enabled in memdb anyway return; } diff --git a/ee/src/test/java/io/supertokens/ee/test/api/GetLicenseKeyAPITest.java b/ee/src/test/java/io/supertokens/ee/test/api/GetLicenseKeyAPITest.java index e963404ef..3305bf8fc 100644 --- a/ee/src/test/java/io/supertokens/ee/test/api/GetLicenseKeyAPITest.java +++ b/ee/src/test/java/io/supertokens/ee/test/api/GetLicenseKeyAPITest.java @@ -85,7 +85,7 @@ public void testRetrievingLicenseKeyWhenEEFolderDoesNotExist() throws Exception assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); - Assert.assertNull(FeatureFlag.getInstance(process.main).getEeFeatureFlagInstance()); + Assert.assertNull(FeatureFlag.getInstance(process.getProcess()).getEeFeatureFlagInstance()); Assert.assertEquals(FeatureFlag.getInstance(process.getProcess()).getEnabledFeatures().length, 0); diff --git a/ee/src/test/java/io/supertokens/ee/test/api/SetLicenseKeyAPITest.java b/ee/src/test/java/io/supertokens/ee/test/api/SetLicenseKeyAPITest.java index 847d8a58a..a8c64086c 100644 --- a/ee/src/test/java/io/supertokens/ee/test/api/SetLicenseKeyAPITest.java +++ b/ee/src/test/java/io/supertokens/ee/test/api/SetLicenseKeyAPITest.java @@ -74,9 +74,9 @@ public void testSettingLicenseKeyWhenEEFolderDoesNotExist() throws Exception { assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); - Assert.assertNull(FeatureFlag.getInstance(process.main).getEeFeatureFlagInstance()); + Assert.assertNull(FeatureFlag.getInstance(process.getProcess()).getEeFeatureFlagInstance()); - Assert.assertEquals(FeatureFlag.getInstance(process.getProcess()).getEnabledFeatures().length, 0); + Assert.assertEquals(0, FeatureFlag.getInstance(process.getProcess()).getEnabledFeatures().length); // set license key when ee folder does not exist JsonObject requestBody = new JsonObject(); diff --git a/src/main/java/io/supertokens/ActiveUsers.java b/src/main/java/io/supertokens/ActiveUsers.java index 0bd6f51f3..25695b6c4 100644 --- a/src/main/java/io/supertokens/ActiveUsers.java +++ b/src/main/java/io/supertokens/ActiveUsers.java @@ -24,7 +24,7 @@ public static void updateLastActive(AppIdentifier appIdentifier, Main main, Stri @TestOnly public static void updateLastActive(Main main, String userId) { try { - ActiveUsers.updateLastActive(new AppIdentifier(null, null), + ActiveUsers.updateLastActive(ResourceDistributor.getAppForTesting().toAppIdentifier(), main, userId); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -55,6 +55,6 @@ public static void updateLastActiveAfterLinking(Main main, AppIdentifier appIden @TestOnly public static int countUsersActiveSince(Main main, long time) throws StorageQueryException, TenantOrAppNotFoundException { - return countUsersActiveSince(main, new AppIdentifier(null, null), time); + return countUsersActiveSince(main, ResourceDistributor.getAppForTesting().toAppIdentifier(), time); } } diff --git a/src/main/java/io/supertokens/Main.java b/src/main/java/io/supertokens/Main.java index 9dcec2a26..20f184ba8 100644 --- a/src/main/java/io/supertokens/Main.java +++ b/src/main/java/io/supertokens/Main.java @@ -36,11 +36,13 @@ import io.supertokens.exceptions.QuitProgramException; import io.supertokens.featureflag.FeatureFlag; import io.supertokens.jwt.exceptions.UnsupportedJWTSigningAlgorithmException; +import io.supertokens.multitenancy.Multitenancy; import io.supertokens.multitenancy.MultitenancyHelper; import io.supertokens.output.Logging; import io.supertokens.pluginInterface.exceptions.DbInitException; import io.supertokens.pluginInterface.exceptions.InvalidConfigException; import io.supertokens.pluginInterface.exceptions.StorageQueryException; +import io.supertokens.pluginInterface.multitenancy.TenantConfig; import io.supertokens.pluginInterface.multitenancy.TenantIdentifier; import io.supertokens.storageLayer.StorageLayer; import io.supertokens.version.Version; @@ -362,12 +364,16 @@ public void proceedToEnableFeatureFlag() { } private void createDotStartedFileForThisProcess() throws IOException { + String startedDir = ".started"; + if (isTesting) { + startedDir = ".started" + System.getProperty("org.gradle.test.worker", ""); + } CoreConfig config = Config.getBaseConfig(this); String fileLocation = CLIOptions.get(this).getTempDirLocation() == null ? CLIOptions.get(this).getInstallationPath() : CLIOptions.get(this).getTempDirLocation(); String fileName = OperatingSystem.getOS() == OperatingSystem.OS.WINDOWS - ? fileLocation + ".started\\" + config.getHost(this) + "-" + ? fileLocation + startedDir + "\\" + config.getHost(this) + "-" + config.getPort(this) - : fileLocation + ".started/" + config.getHost(this) + "-" + : fileLocation + startedDir + "/" + config.getHost(this) + "-" + config.getPort(this); File dotStarted = new File(fileName); if (!dotStarted.exists()) { @@ -410,9 +416,10 @@ public void deleteAllInformationForTesting() throws Exception { @TestOnly public void killForTestingAndWaitForShutdown() throws InterruptedException { - assertIsTesting(); - wakeUpMainThreadToShutdown(); - mainThread.join(); + // Do not kill for now + assertIsTesting(); + wakeUpMainThreadToShutdown(); + mainThread.join(); } // must not throw any error diff --git a/src/main/java/io/supertokens/ProcessState.java b/src/main/java/io/supertokens/ProcessState.java index 100b622ac..901d136e5 100644 --- a/src/main/java/io/supertokens/ProcessState.java +++ b/src/main/java/io/supertokens/ProcessState.java @@ -104,7 +104,7 @@ public enum PROCESS_STATE { public static class EventAndException { public Exception exception; public JsonObject data; - PROCESS_STATE state; + public PROCESS_STATE state; public EventAndException(PROCESS_STATE state, Exception e) { this.state = state; diff --git a/src/main/java/io/supertokens/ResourceDistributor.java b/src/main/java/io/supertokens/ResourceDistributor.java index c2cace681..be202acb9 100644 --- a/src/main/java/io/supertokens/ResourceDistributor.java +++ b/src/main/java/io/supertokens/ResourceDistributor.java @@ -35,10 +35,22 @@ public class ResourceDistributor { private final Map resources = new HashMap<>(1); private final Main main; + private static TenantIdentifier appUsedForTesting = TenantIdentifier.BASE_TENANT; + public ResourceDistributor(Main main) { this.main = main; } + @TestOnly + public static void setAppForTesting(TenantIdentifier app) { + appUsedForTesting = app; + } + + @TestOnly + public static TenantIdentifier getAppForTesting() { + return appUsedForTesting; + } + public synchronized SingletonResource getResource(AppIdentifier appIdentifier, @Nonnull String key) throws TenantOrAppNotFoundException { return getResource(appIdentifier.getAsPublicTenantIdentifier(), key); @@ -90,7 +102,7 @@ public synchronized SingletonResource getResource(TenantIdentifier tenantIdentif @TestOnly public synchronized SingletonResource getResource(@Nonnull String key) { - return resources.get(new KeyClass(new TenantIdentifier(null, null, null), key)); + return resources.get(new KeyClass(appUsedForTesting, key)); } public synchronized SingletonResource setResource(TenantIdentifier tenantIdentifier, @@ -150,7 +162,7 @@ public synchronized Map getAllResourcesWithResource @TestOnly public synchronized SingletonResource setResource(@Nonnull String key, SingletonResource resource) { - return setResource(new TenantIdentifier(null, null, null), key, resource); + return setResource(appUsedForTesting, key, resource); } public interface Func { diff --git a/src/main/java/io/supertokens/authRecipe/AuthRecipe.java b/src/main/java/io/supertokens/authRecipe/AuthRecipe.java index a51edfc58..d3b2c6367 100644 --- a/src/main/java/io/supertokens/authRecipe/AuthRecipe.java +++ b/src/main/java/io/supertokens/authRecipe/AuthRecipe.java @@ -17,6 +17,7 @@ package io.supertokens.authRecipe; import io.supertokens.Main; +import io.supertokens.ResourceDistributor; import io.supertokens.authRecipe.exception.*; import io.supertokens.bulkimport.BulkImportUserUtils; import io.supertokens.featureflag.exceptions.FeatureNotEnabledException; @@ -59,7 +60,7 @@ public class AuthRecipe { @TestOnly public static boolean unlinkAccounts(Main main, String recipeUserId) throws StorageQueryException, UnknownUserIdException, InputUserIdIsNotAPrimaryUserException { - return unlinkAccounts(main, new AppIdentifier(null, null), StorageLayer.getStorage(main), recipeUserId); + return unlinkAccounts(main, ResourceDistributor.getAppForTesting().toAppIdentifier(), StorageLayer.getStorage(main), recipeUserId); } @@ -124,7 +125,7 @@ public static boolean unlinkAccounts(Main main, AppIdentifier appIdentifier, @TestOnly public static AuthRecipeUserInfo getUserById(Main main, String userId) throws StorageQueryException { - return getUserById(new AppIdentifier(null, null), StorageLayer.getStorage(main), userId); + return getUserById(ResourceDistributor.getAppForTesting().toAppIdentifier(), StorageLayer.getStorage(main), userId); } public static AuthRecipeUserInfo getUserById(AppIdentifier appIdentifier, Storage storage, String userId) @@ -203,7 +204,7 @@ public static CanLinkAccountsResult canLinkAccounts(Main main, String recipeUser throws StorageQueryException, UnknownUserIdException, InputUserIdIsNotAPrimaryUserException, RecipeUserIdAlreadyLinkedWithAnotherPrimaryUserIdException, AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException { - return canLinkAccounts(new AppIdentifier(null, null), StorageLayer.getStorage(main), recipeUserId, + return canLinkAccounts(ResourceDistributor.getAppForTesting().toAppIdentifier(), StorageLayer.getStorage(main), recipeUserId, primaryUserId); } @@ -508,7 +509,7 @@ public static LinkAccountsResult linkAccounts(Main main, String recipeUserId, St FeatureNotEnabledException, InputUserIdIsNotAPrimaryUserException, RecipeUserIdAlreadyLinkedWithAnotherPrimaryUserIdException { try { - return linkAccounts(main, new AppIdentifier(null, null), + return linkAccounts(main, ResourceDistributor.getAppForTesting().toAppIdentifier(), StorageLayer.getStorage(main), recipeUserId, primaryUserId); } catch (TenantOrAppNotFoundException e) { throw new RuntimeException(e); @@ -648,7 +649,7 @@ public static CreatePrimaryUserResult canCreatePrimaryUser(Main main, String recipeUserId) throws StorageQueryException, AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException, RecipeUserIdAlreadyLinkedWithPrimaryUserIdException, UnknownUserIdException { - return canCreatePrimaryUser(new AppIdentifier(null, null), StorageLayer.getStorage(main), recipeUserId); + return canCreatePrimaryUser(ResourceDistributor.getAppForTesting().toAppIdentifier(), StorageLayer.getStorage(main), recipeUserId); } public static CreatePrimaryUserResult canCreatePrimaryUser(AppIdentifier appIdentifier, @@ -920,7 +921,7 @@ public static CreatePrimaryUserResult createPrimaryUser(Main main, RecipeUserIdAlreadyLinkedWithPrimaryUserIdException, UnknownUserIdException, FeatureNotEnabledException { try { - return createPrimaryUser(main, new AppIdentifier(null, null), StorageLayer.getStorage(main), recipeUserId); + return createPrimaryUser(main, ResourceDistributor.getAppForTesting().toAppIdentifier(), StorageLayer.getStorage(main), recipeUserId); } catch (TenantOrAppNotFoundException e) { throw new RuntimeException(e); } @@ -1181,7 +1182,7 @@ public static long getUsersCount(Main main, RECIPE_ID[] includeRecipeIds) throws StorageQueryException { try { Storage storage = StorageLayer.getStorage(main); - return getUsersCountForTenant(TenantIdentifier.BASE_TENANT, storage, includeRecipeIds); + return getUsersCountForTenant(ResourceDistributor.getAppForTesting(), storage, includeRecipeIds); } catch (TenantOrAppNotFoundException | BadPermissionException e) { throw new IllegalStateException(e); } @@ -1231,7 +1232,7 @@ public static UserPaginationContainer getUsers(Main main, throws StorageQueryException, UserPaginationToken.InvalidTokenException { try { Storage storage = StorageLayer.getStorage(main); - return getUsers(TenantIdentifier.BASE_TENANT, storage, + return getUsers(ResourceDistributor.getAppForTesting(), storage, limit, timeJoinedOrder, paginationToken, includeRecipeIds, dashboardSearchTags); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -1389,7 +1390,7 @@ private static void deleteUserHelper(TransactionConnection con, AppIdentifier ap public static void deleteUser(Main main, String userId, boolean removeAllLinkedAccounts) throws StorageQueryException, StorageTransactionLogicException { Storage storage = StorageLayer.getStorage(main); - AppIdentifier appIdentifier = new AppIdentifier(null, null); + AppIdentifier appIdentifier = ResourceDistributor.getAppForTesting().toAppIdentifier(); UserIdMapping mapping = io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(appIdentifier, storage, userId, UserIdType.ANY); @@ -1400,7 +1401,7 @@ public static void deleteUser(Main main, String userId, boolean removeAllLinkedA public static void deleteUser(Main main, String userId) throws StorageQueryException, StorageTransactionLogicException { Storage storage = StorageLayer.getStorage(main); - AppIdentifier appIdentifier = new AppIdentifier(null, null); + AppIdentifier appIdentifier = ResourceDistributor.getAppForTesting().toAppIdentifier(); UserIdMapping mapping = io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(appIdentifier, storage, userId, UserIdType.ANY); diff --git a/src/main/java/io/supertokens/config/Config.java b/src/main/java/io/supertokens/config/Config.java index 488267d2c..d8fca0cf0 100644 --- a/src/main/java/io/supertokens/config/Config.java +++ b/src/main/java/io/supertokens/config/Config.java @@ -95,8 +95,13 @@ public static JsonObject getBaseConfigAsJsonObject(Main main) throws IOException } private static String getConfigFilePath(Main main) { + String configFile = "config.yaml"; + if (Main.isTesting) { + String workerId = System.getProperty("org.gradle.test.worker", ""); + configFile = "config" + workerId + ".yaml"; + } return CLIOptions.get(main).getConfigFilePath() == null - ? CLIOptions.get(main).getInstallationPath() + "config.yaml" + ? CLIOptions.get(main).getInstallationPath() + configFile : CLIOptions.get(main).getConfigFilePath(); } @@ -305,7 +310,7 @@ public static CoreConfig getBaseConfig(Main main) { @TestOnly public static CoreConfig getConfig(Main main) { try { - return getConfig(new TenantIdentifier(null, null, null), main); + return getConfig(ResourceDistributor.getAppForTesting(), main); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); } diff --git a/src/main/java/io/supertokens/config/CoreConfig.java b/src/main/java/io/supertokens/config/CoreConfig.java index da3956d1d..b58933afc 100644 --- a/src/main/java/io/supertokens/config/CoreConfig.java +++ b/src/main/java/io/supertokens/config/CoreConfig.java @@ -973,6 +973,24 @@ void normalizeAndValidate(Main main, boolean includeConfigFilePath) throws Inval } } + if (Main.isTesting) { + if (oauth_provider_public_service_url == null) { + oauth_provider_public_service_url = "http://localhost:" + System.getProperty("ST_OAUTH_PROVIDER_SERVICE_PORT"); + } + if (oauth_provider_admin_service_url == null) { + oauth_provider_admin_service_url = "http://localhost:" + System.getProperty("ST_OAUTH_PROVIDER_ADMIN_PORT"); + } + if (oauth_provider_url_configured_in_oauth_provider == null) { + oauth_provider_url_configured_in_oauth_provider = "http://localhost:4444"; + } + if (oauth_client_secret_encryption_key == null) { + oauth_client_secret_encryption_key = "clientsecretencryptionkey"; + } + if (oauth_provider_consent_login_base_url == null) { + oauth_provider_consent_login_base_url = "http://localhost:3001/auth"; + } + } + isNormalizedAndValid = true; } diff --git a/src/main/java/io/supertokens/cronjobs/deleteExpiredTotpTokens/DeleteExpiredTotpTokens.java b/src/main/java/io/supertokens/cronjobs/deleteExpiredTotpTokens/DeleteExpiredTotpTokens.java index be43a4a65..e7184e23b 100644 --- a/src/main/java/io/supertokens/cronjobs/deleteExpiredTotpTokens/DeleteExpiredTotpTokens.java +++ b/src/main/java/io/supertokens/cronjobs/deleteExpiredTotpTokens/DeleteExpiredTotpTokens.java @@ -7,6 +7,7 @@ import io.supertokens.output.Logging; import io.supertokens.pluginInterface.STORAGE_TYPE; import io.supertokens.pluginInterface.multitenancy.TenantIdentifier; +import io.supertokens.pluginInterface.multitenancy.exceptions.TenantOrAppNotFoundException; import io.supertokens.pluginInterface.totp.sqlStorage.TOTPSQLStorage; import io.supertokens.storageLayer.StorageLayer; import org.jetbrains.annotations.TestOnly; @@ -30,7 +31,11 @@ public static DeleteExpiredTotpTokens init(Main main, @TestOnly public static DeleteExpiredTotpTokens getInstance(Main main) { - return (DeleteExpiredTotpTokens) main.getResourceDistributor().getResource(RESOURCE_KEY); + try { + return (DeleteExpiredTotpTokens) main.getResourceDistributor().getResource(TenantIdentifier.BASE_TENANT, RESOURCE_KEY); + } catch (TenantOrAppNotFoundException e) { + throw new IllegalStateException(e); + } } @Override diff --git a/src/main/java/io/supertokens/dashboard/Dashboard.java b/src/main/java/io/supertokens/dashboard/Dashboard.java index a987fe9eb..478de1621 100644 --- a/src/main/java/io/supertokens/dashboard/Dashboard.java +++ b/src/main/java/io/supertokens/dashboard/Dashboard.java @@ -17,6 +17,7 @@ package io.supertokens.dashboard; import io.supertokens.Main; +import io.supertokens.ResourceDistributor; import io.supertokens.dashboard.exceptions.UserSuspendedException; import io.supertokens.emailpassword.PasswordHashing; import io.supertokens.featureflag.EE_FEATURES; @@ -55,7 +56,7 @@ public static DashboardUser signUpDashboardUser(Main main, String email, throws StorageQueryException, DuplicateEmailException, FeatureNotEnabledException { try { Storage storage = StorageLayer.getStorage(main); - return signUpDashboardUser(new AppIdentifier(null, null), storage, + return signUpDashboardUser(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, main, email, password); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -103,7 +104,7 @@ public static DashboardUser signUpDashboardUser(AppIdentifier appIdentifier, Sto public static DashboardUser[] getAllDashboardUsers(Main main) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); - return getAllDashboardUsers(new AppIdentifier(null, null), storage, main); + return getAllDashboardUsers(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, main); } public static DashboardUser[] getAllDashboardUsers(AppIdentifier appIdentifier, Storage storage, Main main) @@ -127,7 +128,7 @@ public static String signInDashboardUser(Main main, String email, String passwor throws StorageQueryException, UserSuspendedException { try { Storage storage = StorageLayer.getStorage(main); - return signInDashboardUser(new AppIdentifier(null, null), storage, + return signInDashboardUser(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, main, email, password); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -159,7 +160,7 @@ public static String signInDashboardUser(AppIdentifier appIdentifier, Storage st public static boolean deleteUserWithUserId(Main main, String userId) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); - return deleteUserWithUserId(new AppIdentifier(null, null), storage, userId); + return deleteUserWithUserId(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, userId); } public static boolean deleteUserWithUserId(AppIdentifier appIdentifier, Storage storage, String userId) @@ -201,7 +202,7 @@ private static boolean isUserSuspended(AppIdentifier appIdentifier, Storage stor public static boolean deleteUserWithEmail(Main main, String email) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); - return deleteUserWithEmail(new AppIdentifier(null, null), storage, email); + return deleteUserWithEmail(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, email); } public static boolean deleteUserWithEmail(AppIdentifier appIdentifier, Storage storage, String email) @@ -223,7 +224,7 @@ public static DashboardUser updateUsersCredentialsWithUserId(Main main, String u try { Storage storage = StorageLayer.getStorage(main); return updateUsersCredentialsWithUserId( - new AppIdentifier(null, null), storage, main, userId, + ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, main, userId, newEmail, newPassword); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -291,7 +292,7 @@ public static DashboardUser updateUsersCredentialsWithUserId(AppIdentifier appId public static DashboardUser getDashboardUserByEmail(Main main, String email) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); - return getDashboardUserByEmail(new AppIdentifier(null, null), storage, email); + return getDashboardUserByEmail(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, email); } public static DashboardUser getDashboardUserByEmail(AppIdentifier appIdentifier, Storage storage, String email) @@ -305,7 +306,7 @@ public static DashboardUser getDashboardUserByEmail(AppIdentifier appIdentifier, public static boolean revokeSessionWithSessionId(Main main, String sessionId) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); - return revokeSessionWithSessionId(new AppIdentifier(null, null), storage, sessionId); + return revokeSessionWithSessionId(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, sessionId); } public static boolean revokeSessionWithSessionId(AppIdentifier appIdentifier, Storage storage, String sessionId) @@ -320,7 +321,7 @@ public static DashboardSessionInfo[] getAllDashboardSessionsForUser(Main main, throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); return getAllDashboardSessionsForUser( - new AppIdentifier(null, null), storage, userId); + ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, userId); } public static DashboardSessionInfo[] getAllDashboardSessionsForUser(AppIdentifier appIdentifier, Storage storage, @@ -390,7 +391,7 @@ public static String validatePassword(String password) { public static boolean isValidUserSession(Main main, String sessionId) throws StorageQueryException, UserSuspendedException { Storage storage = StorageLayer.getStorage(main); - return isValidUserSession(new AppIdentifier(null, null), storage, main, sessionId); + return isValidUserSession(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, main, sessionId); } public static boolean isValidUserSession(AppIdentifier appIdentifier, Storage storage, Main main, String sessionId) diff --git a/src/main/java/io/supertokens/emailpassword/EmailPassword.java b/src/main/java/io/supertokens/emailpassword/EmailPassword.java index 61384e86a..72e3470a3 100644 --- a/src/main/java/io/supertokens/emailpassword/EmailPassword.java +++ b/src/main/java/io/supertokens/emailpassword/EmailPassword.java @@ -17,6 +17,7 @@ package io.supertokens.emailpassword; import io.supertokens.Main; +import io.supertokens.ResourceDistributor; import io.supertokens.authRecipe.AuthRecipe; import io.supertokens.config.Config; import io.supertokens.config.CoreConfig; @@ -74,7 +75,7 @@ public ImportUserResponse(boolean didUserAlreadyExist, AuthRecipeUserInfo user) @TestOnly public static long getPasswordResetTokenLifetimeForTests(Main main) { try { - return getPasswordResetTokenLifetime(new TenantIdentifier(null, null, null), main); + return getPasswordResetTokenLifetime(ResourceDistributor.getAppForTesting(), main); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); } @@ -90,7 +91,7 @@ public static AuthRecipeUserInfo signUp(Main main, @Nonnull String email, @Nonnu throws DuplicateEmailException, StorageQueryException { try { Storage storage = StorageLayer.getStorage(main); - return signUp(new TenantIdentifier(null, null, null), storage, + return signUp(ResourceDistributor.getAppForTesting(), storage, main, email, password); } catch (TenantOrAppNotFoundException | BadPermissionException e) { throw new IllegalStateException(e); @@ -157,7 +158,7 @@ public static ImportUserResponse importUserWithPasswordHash(Main main, @Nonnull Storage storage = StorageLayer.getStorage(main); return importUserWithPasswordHash( - new TenantIdentifier(null, null, null), storage, main, email, + ResourceDistributor.getAppForTesting(), storage, main, email, passwordHash, hashingAlgorithm); } catch (TenantOrAppNotFoundException | BadPermissionException e) { throw new IllegalStateException(e); @@ -276,7 +277,7 @@ public static ImportUserResponse importUserWithPasswordHash(Main main, @Nonnull try { Storage storage = StorageLayer.getStorage(main); return importUserWithPasswordHash( - new TenantIdentifier(null, null, null), storage, + ResourceDistributor.getAppForTesting(), storage, main, email, passwordHash, null); } catch (TenantOrAppNotFoundException | BadPermissionException e) { throw new IllegalStateException(e); @@ -289,7 +290,7 @@ public static AuthRecipeUserInfo signIn(Main main, @Nonnull String email, throws StorageQueryException, WrongCredentialsException { try { Storage storage = StorageLayer.getStorage(main); - return signIn(new TenantIdentifier(null, null, null), storage, + return signIn(ResourceDistributor.getAppForTesting(), storage, main, email, password); } catch (TenantOrAppNotFoundException | BadPermissionException e) { throw new IllegalStateException(e); @@ -353,7 +354,7 @@ public static String generatePasswordResetTokenBeforeCdi4_0(Main main, String us try { Storage storage = StorageLayer.getStorage(main); return generatePasswordResetTokenBeforeCdi4_0( - new TenantIdentifier(null, null, null), storage, + ResourceDistributor.getAppForTesting(), storage, main, userId); } catch (TenantOrAppNotFoundException | BadPermissionException | WebserverAPI.BadRequestException e) { throw new IllegalStateException(e); @@ -366,7 +367,7 @@ public static String generatePasswordResetTokenBeforeCdi4_0WithoutAddingEmail(Ma try { Storage storage = StorageLayer.getStorage(main); return generatePasswordResetToken( - new TenantIdentifier(null, null, null), storage, + ResourceDistributor.getAppForTesting(), storage, main, userId, null); } catch (TenantOrAppNotFoundException | BadPermissionException e) { throw new IllegalStateException(e); @@ -379,7 +380,7 @@ public static String generatePasswordResetToken(Main main, String userId, String try { Storage storage = StorageLayer.getStorage(main); return generatePasswordResetToken( - new TenantIdentifier(null, null, null), storage, + ResourceDistributor.getAppForTesting(), storage, main, userId, email); } catch (TenantOrAppNotFoundException | BadPermissionException e) { throw new IllegalStateException(e); @@ -456,7 +457,7 @@ public static String resetPassword(Main main, String token, StorageTransactionLogicException { try { Storage storage = StorageLayer.getStorage(main); - return resetPassword(new TenantIdentifier(null, null, null), storage, + return resetPassword(ResourceDistributor.getAppForTesting(), storage, main, token, password); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -530,7 +531,7 @@ public static ConsumeResetPasswordTokenResult consumeResetPasswordToken(Main mai StorageTransactionLogicException { try { Storage storage = StorageLayer.getStorage(main); - return consumeResetPasswordToken(new TenantIdentifier(null, null, null), storage, + return consumeResetPasswordToken(ResourceDistributor.getAppForTesting(), storage, token); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -628,7 +629,7 @@ public static void updateUsersEmailOrPassword(Main main, UnknownUserIdException, DuplicateEmailException, EmailChangeNotAllowedException { try { Storage storage = StorageLayer.getStorage(main); - updateUsersEmailOrPassword(new AppIdentifier(null, null), storage, + updateUsersEmailOrPassword(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, main, userId, email, password); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -725,7 +726,7 @@ public static AuthRecipeUserInfo getUserUsingId(Main main, String userId) throws StorageQueryException { try { Storage storage = StorageLayer.getStorage(main); - return getUserUsingId(new AppIdentifier(null, null), storage, userId); + return getUserUsingId(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, userId); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); } diff --git a/src/main/java/io/supertokens/emailpassword/PasswordHashing.java b/src/main/java/io/supertokens/emailpassword/PasswordHashing.java index b179e2b9e..197588dc0 100644 --- a/src/main/java/io/supertokens/emailpassword/PasswordHashing.java +++ b/src/main/java/io/supertokens/emailpassword/PasswordHashing.java @@ -30,6 +30,8 @@ import org.jetbrains.annotations.TestOnly; import org.mindrot.jbcrypt.BCrypt; +import java.util.HashMap; +import java.util.Map; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; @@ -42,6 +44,9 @@ public class PasswordHashing extends ResourceDistributor.SingletonResource { final BlockingQueue firebaseSCryptBoundedQueue; final Main main; + private final Map cachedPasswordHashForTesting = new HashMap<>(); + public static boolean bypassHashCachingInTesting = false; + private PasswordHashing(Main main) { this.argon2BoundedQueue = new LinkedBlockingQueue<>( Config.getBaseConfig(main).getArgon2HashingPoolSize()); @@ -75,7 +80,7 @@ public static void init(Main main) { @TestOnly public String createHashWithSalt(String password) { try { - return createHashWithSalt(new AppIdentifier(null, null), password); + return createHashWithSalt(ResourceDistributor.getAppForTesting().toAppIdentifier(), password); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); } @@ -84,6 +89,10 @@ public String createHashWithSalt(String password) { public String createHashWithSalt(AppIdentifier appIdentifier, String password) throws TenantOrAppNotFoundException { + if (Main.isTesting && !bypassHashCachingInTesting && cachedPasswordHashForTesting.containsKey(password)) { + return cachedPasswordHashForTesting.get(password); + } + String passwordHash = ""; TenantIdentifier tenantIdentifier = appIdentifier.getAsPublicTenantIdentifier(); @@ -108,6 +117,10 @@ public String createHashWithSalt(AppIdentifier appIdentifier, String password) } catch (UnsupportedPasswordHashingFormatException e) { throw new IllegalStateException(e); } + + if (Main.isTesting) { + cachedPasswordHashForTesting.put(password, passwordHash); + } return passwordHash; } diff --git a/src/main/java/io/supertokens/emailverification/EmailVerification.java b/src/main/java/io/supertokens/emailverification/EmailVerification.java index 63719d222..b5a451d17 100644 --- a/src/main/java/io/supertokens/emailverification/EmailVerification.java +++ b/src/main/java/io/supertokens/emailverification/EmailVerification.java @@ -17,6 +17,7 @@ package io.supertokens.emailverification; import io.supertokens.Main; +import io.supertokens.ResourceDistributor; import io.supertokens.config.Config; import io.supertokens.emailverification.exception.EmailAlreadyVerifiedException; import io.supertokens.emailverification.exception.EmailVerificationInvalidTokenException; @@ -44,7 +45,7 @@ public class EmailVerification { public static long getEmailVerificationTokenLifetimeForTests(Main main) { try { return getEmailVerificationTokenLifetime( - new TenantIdentifier(null, null, null), main); + ResourceDistributor.getAppForTesting(), main); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); } @@ -62,7 +63,7 @@ public static String generateEmailVerificationToken(Main main, String userId, St try { Storage storage = StorageLayer.getStorage(main); return generateEmailVerificationToken( - new TenantIdentifier(null, null, null), storage, + ResourceDistributor.getAppForTesting(), storage, main, userId, email); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -107,7 +108,7 @@ public static User verifyEmail(Main main, String token) EmailVerificationInvalidTokenException, NoSuchAlgorithmException, StorageTransactionLogicException { try { Storage storage = StorageLayer.getStorage(main); - return verifyEmail(new TenantIdentifier(null, null, null), storage, token); + return verifyEmail(ResourceDistributor.getAppForTesting(), storage, token); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); } @@ -182,7 +183,7 @@ public static User verifyEmail(TenantIdentifier tenantIdentifier, Storage storag public static boolean isEmailVerified(Main main, String userId, String email) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); - return isEmailVerified(new AppIdentifier(null, null), storage, + return isEmailVerified(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, userId, email); } @@ -196,7 +197,7 @@ public static boolean isEmailVerified(AppIdentifier appIdentifier, Storage stora public static void revokeAllTokens(Main main, String userId, String email) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); - revokeAllTokens(new TenantIdentifier(null, null, null), storage, + revokeAllTokens(ResourceDistributor.getAppForTesting(), storage, userId, email); } @@ -211,7 +212,7 @@ public static void unverifyEmail(Main main, String userId, String email) throws StorageQueryException { try { Storage storage = StorageLayer.getStorage(main); - unverifyEmail(new AppIdentifier(null, null), storage, userId, email); + unverifyEmail(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, userId, email); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); } @@ -249,7 +250,7 @@ public static String generateEmailVerificationTokenTheOldWay(Main main, String u try { StorageUtils.getEmailVerificationStorage(StorageLayer.getStorage(main)) - .addEmailVerificationToken(new TenantIdentifier(null, null, null), + .addEmailVerificationToken(ResourceDistributor.getAppForTesting(), new EmailVerificationTokenInfo(userId, hashedToken, System.currentTimeMillis() + EmailVerification.getEmailVerificationTokenLifetimeForTests(main), email)); diff --git a/src/main/java/io/supertokens/featureflag/FeatureFlag.java b/src/main/java/io/supertokens/featureflag/FeatureFlag.java index 362051c07..f420b5a1f 100644 --- a/src/main/java/io/supertokens/featureflag/FeatureFlag.java +++ b/src/main/java/io/supertokens/featureflag/FeatureFlag.java @@ -108,7 +108,7 @@ public JsonObject getPaidFeatureStats() throws StorageQueryException, TenantOrAp public static FeatureFlag getInstance(Main main) { try { return (FeatureFlag) main.getResourceDistributor() - .getResource(new AppIdentifier(null, null), RESOURCE_KEY); + .getResource(ResourceDistributor.getAppForTesting(), RESOURCE_KEY); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); } diff --git a/src/main/java/io/supertokens/inmemorydb/Start.java b/src/main/java/io/supertokens/inmemorydb/Start.java index c15eb7514..c5f3587a7 100644 --- a/src/main/java/io/supertokens/inmemorydb/Start.java +++ b/src/main/java/io/supertokens/inmemorydb/Start.java @@ -2748,7 +2748,7 @@ public void createDevice(AppIdentifier appIdentifier, TOTPDevice device) try { startTransaction(con -> { try { - createDevice_Transaction(con, new AppIdentifier(null, null), device); + createDevice_Transaction(con, appIdentifier, device); } catch (DeviceAlreadyExistsException | TenantOrAppNotFoundException e) { throw new StorageTransactionLogicException(e); } diff --git a/src/main/java/io/supertokens/jwt/JWTSigningFunctions.java b/src/main/java/io/supertokens/jwt/JWTSigningFunctions.java index 8ba7714e9..8a1f76a23 100644 --- a/src/main/java/io/supertokens/jwt/JWTSigningFunctions.java +++ b/src/main/java/io/supertokens/jwt/JWTSigningFunctions.java @@ -23,6 +23,7 @@ import com.google.gson.GsonBuilder; import com.google.gson.JsonObject; import io.supertokens.Main; +import io.supertokens.ResourceDistributor; import io.supertokens.jwt.exceptions.UnsupportedJWTSigningAlgorithmException; import io.supertokens.pluginInterface.exceptions.StorageQueryException; import io.supertokens.pluginInterface.exceptions.StorageTransactionLogicException; @@ -54,7 +55,7 @@ public static String createJWTToken(Main main, String algorithm, throws StorageQueryException, StorageTransactionLogicException, NoSuchAlgorithmException, InvalidKeySpecException, JWTCreationException, UnsupportedJWTSigningAlgorithmException { try { - return createJWTToken(new AppIdentifier(null, null), main, algorithm, payload, jwksDomain, + return createJWTToken(ResourceDistributor.getAppForTesting().toAppIdentifier(), main, algorithm, payload, jwksDomain, jwtValidityInSeconds, useDynamicKey); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); diff --git a/src/main/java/io/supertokens/passwordless/Passwordless.java b/src/main/java/io/supertokens/passwordless/Passwordless.java index 2ff4e28ef..ba943a944 100644 --- a/src/main/java/io/supertokens/passwordless/Passwordless.java +++ b/src/main/java/io/supertokens/passwordless/Passwordless.java @@ -17,6 +17,7 @@ package io.supertokens.passwordless; import io.supertokens.Main; +import io.supertokens.ResourceDistributor; import io.supertokens.authRecipe.AuthRecipe; import io.supertokens.config.Config; import io.supertokens.emailpassword.exceptions.EmailChangeNotAllowedException; @@ -74,7 +75,7 @@ public static CreateCodeResponse createCode(Main main, String email, String phon try { Storage storage = StorageLayer.getStorage(main); return createCode( - new TenantIdentifier(null, null, null), storage, + ResourceDistributor.getAppForTesting(), storage, main, email, phoneNumber, deviceId, userInputCode); } catch (TenantOrAppNotFoundException | BadPermissionException e) { throw new IllegalStateException(e); @@ -161,7 +162,7 @@ public static DeviceWithCodes getDeviceWithCodesById(Main main, String deviceId) NoSuchAlgorithmException, Base64EncodingException { Storage storage = StorageLayer.getStorage(main); return getDeviceWithCodesById( - new TenantIdentifier(null, null, null), storage, + ResourceDistributor.getAppForTesting(), storage, deviceId); } @@ -170,7 +171,7 @@ public static DeviceWithCodes getDeviceWithCodesByIdHash(Main main, String devic throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); return getDeviceWithCodesByIdHash( - new TenantIdentifier(null, null, null), storage, + ResourceDistributor.getAppForTesting(), storage, deviceIdHash); } @@ -210,7 +211,7 @@ public static List getDevicesWithCodesByEmail(Main main, String throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); return getDevicesWithCodesByEmail( - new TenantIdentifier(null, null, null), storage, email); + ResourceDistributor.getAppForTesting(), storage, email); } public static List getDevicesWithCodesByPhoneNumber( @@ -235,7 +236,7 @@ public static List getDevicesWithCodesByPhoneNumber(Main main, throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); return getDevicesWithCodesByPhoneNumber( - new TenantIdentifier(null, null, null), storage, + ResourceDistributor.getAppForTesting(), storage, phoneNumber); } @@ -249,7 +250,7 @@ public static ConsumeCodeResponse consumeCode(Main main, try { Storage storage = StorageLayer.getStorage(main); return consumeCode( - new TenantIdentifier(null, null, null), storage, + ResourceDistributor.getAppForTesting(), storage, main, deviceId, deviceIdHashFromUser, userInputCode, linkCode, false); } catch (TenantOrAppNotFoundException | BadPermissionException e) { throw new IllegalStateException(e); @@ -266,7 +267,7 @@ public static ConsumeCodeResponse consumeCode(Main main, try { Storage storage = StorageLayer.getStorage(main); return consumeCode( - new TenantIdentifier(null, null, null), storage, + ResourceDistributor.getAppForTesting(), storage, main, deviceId, deviceIdHashFromUser, userInputCode, linkCode, setEmailVerified); } catch (TenantOrAppNotFoundException | BadPermissionException e) { throw new IllegalStateException(e); @@ -567,7 +568,7 @@ public static void createPasswordlessUsers(Storage storage, public static void removeCode(Main main, String codeId) throws StorageQueryException, StorageTransactionLogicException { Storage storage = StorageLayer.getStorage(main); - removeCode(new TenantIdentifier(null, null, null), storage, + removeCode(ResourceDistributor.getAppForTesting(), storage, codeId); } @@ -622,7 +623,7 @@ public static void removeCodesByEmail(Main main, String email) throws StorageQueryException, StorageTransactionLogicException { Storage storage = StorageLayer.getStorage(main); removeCodesByEmail( - new TenantIdentifier(null, null, null), storage, email); + ResourceDistributor.getAppForTesting(), storage, email); } public static void removeCodesByEmail(TenantIdentifier tenantIdentifier, Storage storage, String email) @@ -642,7 +643,7 @@ public static void removeCodesByPhoneNumber(Main main, throws StorageQueryException, StorageTransactionLogicException { Storage storage = StorageLayer.getStorage(main); removeCodesByPhoneNumber( - new TenantIdentifier(null, null, null), storage, + ResourceDistributor.getAppForTesting(), storage, phoneNumber); } @@ -664,7 +665,7 @@ public static AuthRecipeUserInfo getUserById(Main main, String userId) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); return getUserById( - new AppIdentifier(null, null), storage, userId); + ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, userId); } @Deprecated @@ -689,7 +690,7 @@ public static AuthRecipeUserInfo getUserByPhoneNumber(Main main, String phoneNumber) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); return getUserByPhoneNumber( - new TenantIdentifier(null, null, null), storage, + ResourceDistributor.getAppForTesting(), storage, phoneNumber); } @@ -714,7 +715,7 @@ public static AuthRecipeUserInfo getUserByEmail(Main main, String email) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); return getUserByEmail( - new TenantIdentifier(null, null, null), storage, email); + ResourceDistributor.getAppForTesting(), storage, email); } @Deprecated @@ -740,7 +741,7 @@ public static void updateUser(Main main, String userId, DuplicatePhoneNumberException, UserWithoutContactInfoException, EmailChangeNotAllowedException, PhoneNumberChangeNotAllowedException { Storage storage = StorageLayer.getStorage(main); - updateUser(new AppIdentifier(null, null), storage, + updateUser(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, userId, emailUpdate, phoneNumberUpdate); } diff --git a/src/main/java/io/supertokens/session/Session.java b/src/main/java/io/supertokens/session/Session.java index 380068a5e..865758de8 100644 --- a/src/main/java/io/supertokens/session/Session.java +++ b/src/main/java/io/supertokens/session/Session.java @@ -19,6 +19,7 @@ import com.google.gson.JsonObject; import io.supertokens.Main; import io.supertokens.ProcessState; +import io.supertokens.ResourceDistributor; import io.supertokens.config.Config; import io.supertokens.config.CoreConfig; import io.supertokens.exceptions.AccessTokenPayloadError; @@ -100,7 +101,7 @@ public static SessionInformationHolder createNewSession(Main main, Storage storage = StorageLayer.getStorage(main); try { return createNewSession( - new TenantIdentifier(null, null, null), storage, main, + ResourceDistributor.getAppForTesting(), storage, main, recipeUserId, userDataInJWT, userDataInDatabase, false, AccessToken.getLatestVersion(), false); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -120,7 +121,7 @@ public static SessionInformationHolder createNewSession(Main main, @Nonnull Stri Storage storage = StorageLayer.getStorage(main); try { return createNewSession( - new TenantIdentifier(null, null, null), storage, main, + ResourceDistributor.getAppForTesting(), storage, main, recipeUserId, userDataInJWT, userDataInDatabase, enableAntiCsrf, version, useStaticKey); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -200,7 +201,7 @@ public static SessionInformationHolder regenerateToken(Main main, InvalidKeyException, JWT.JWTException, UnsupportedJWTSigningAlgorithmException, AccessTokenPayloadError, TryRefreshTokenException { try { - return regenerateToken(new AppIdentifier(null, null), main, token, userDataInJWT); + return regenerateToken(ResourceDistributor.getAppForTesting().toAppIdentifier(), main, token, userDataInJWT); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); } @@ -326,7 +327,7 @@ public static SessionInformationHolder getSession(Main main, @Nonnull String tok StorageTransactionLogicException, TryRefreshTokenException, UnauthorisedException, UnsupportedJWTSigningAlgorithmException, AccessTokenPayloadError { try { - return getSession(new AppIdentifier(null, null), main, token, antiCsrfToken, enableAntiCsrf, + return getSession(ResourceDistributor.getAppForTesting().toAppIdentifier(), main, token, antiCsrfToken, enableAntiCsrf, doAntiCsrfCheck, checkDatabase); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -532,7 +533,7 @@ public static SessionInformationHolder refreshSession(Main main, @Nonnull String UnauthorisedException, StorageQueryException, TokenTheftDetectedException, UnsupportedJWTSigningAlgorithmException, AccessTokenPayloadError { try { - return refreshSession(new AppIdentifier(null, null), main, refreshToken, antiCsrfToken, + return refreshSession(ResourceDistributor.getAppForTesting().toAppIdentifier(), main, refreshToken, antiCsrfToken, enableAntiCsrf, accessTokenVersion, null); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -768,7 +769,7 @@ public static String[] revokeSessionUsingSessionHandles(Main main, throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); return revokeSessionUsingSessionHandles(main, - new AppIdentifier(null, null), storage, + ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, sessionHandles); } @@ -860,7 +861,7 @@ private static String[] revokeSessionUsingSessionHandles(TenantIdentifier tenant public static String[] revokeAllSessionsForUser(Main main, String userId) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); return revokeAllSessionsForUser(main, - new AppIdentifier(null, null), storage, userId, true); + ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, userId, true); } public static String[] revokeAllSessionsForUser(Main main, AppIdentifier appIdentifier, @@ -886,7 +887,7 @@ public static String[] getAllNonExpiredSessionHandlesForUser(Main main, String u throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); return getAllNonExpiredSessionHandlesForUser(main, - new AppIdentifier(null, null), storage, userId, true); + ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, userId, true); } public static String[] getAllNonExpiredSessionHandlesForUser( @@ -957,7 +958,7 @@ public static JsonObject getSessionData(Main main, String sessionHandle) throws StorageQueryException, UnauthorisedException { Storage storage = StorageLayer.getStorage(main); return getSessionData( - new TenantIdentifier(null, null, null), storage, + ResourceDistributor.getAppForTesting(), storage, sessionHandle); } @@ -978,7 +979,7 @@ public static JsonObject getJWTData(Main main, String sessionHandle) throws StorageQueryException, UnauthorisedException { Storage storage = StorageLayer.getStorage(main); return getJWTData( - new TenantIdentifier(null, null, null), storage, + ResourceDistributor.getAppForTesting(), storage, sessionHandle); } @@ -998,7 +999,7 @@ public static io.supertokens.pluginInterface.session.SessionInfo getSession(Main throws StorageQueryException, UnauthorisedException { Storage storage = StorageLayer.getStorage(main); return getSession( - new TenantIdentifier(null, null, null), storage, + ResourceDistributor.getAppForTesting(), storage, sessionHandle); } @@ -1028,7 +1029,7 @@ public static void updateSession(Main main, String sessionHandle, AccessToken.VERSION version) throws StorageQueryException, UnauthorisedException, AccessTokenPayloadError { Storage storage = StorageLayer.getStorage(main); - updateSession(new TenantIdentifier(null, null, null), storage, + updateSession(ResourceDistributor.getAppForTesting(), storage, sessionHandle, sessionData, jwtData, version); } diff --git a/src/main/java/io/supertokens/session/accessToken/AccessToken.java b/src/main/java/io/supertokens/session/accessToken/AccessToken.java index 4e316ad28..21cbdb7ee 100644 --- a/src/main/java/io/supertokens/session/accessToken/AccessToken.java +++ b/src/main/java/io/supertokens/session/accessToken/AccessToken.java @@ -21,6 +21,7 @@ import io.supertokens.Main; import io.supertokens.ProcessState; import io.supertokens.ProcessState.PROCESS_STATE; +import io.supertokens.ResourceDistributor; import io.supertokens.config.Config; import io.supertokens.exceptions.AccessTokenPayloadError; import io.supertokens.exceptions.TryRefreshTokenException; @@ -175,7 +176,7 @@ public static AccessTokenInfo getInfoFromAccessToken(@Nonnull Main main, throws StorageQueryException, StorageTransactionLogicException, TryRefreshTokenException, UnsupportedJWTSigningAlgorithmException { try { - return getInfoFromAccessToken(new AppIdentifier(null, null), main, token, doAntiCsrfCheck); + return getInfoFromAccessToken(ResourceDistributor.getAppForTesting().toAppIdentifier(), main, token, doAntiCsrfCheck); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); } @@ -186,7 +187,7 @@ public static AccessTokenInfo getInfoFromAccessToken(@Nonnull Main main, public static AccessTokenInfo getInfoFromAccessTokenWithoutVerifying(@Nonnull String token) throws JWTException, TryRefreshTokenException { return getInfoFromAccessTokenWithoutVerifying( - new AppIdentifier(null, null), token); + ResourceDistributor.getAppForTesting().toAppIdentifier(), token); } public static AccessTokenInfo getInfoFromAccessTokenWithoutVerifying(AppIdentifier appIdentifier, @@ -209,7 +210,7 @@ public static TokenInfo createNewAccessToken(@Nonnull Main main, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, UnsupportedJWTSigningAlgorithmException, AccessTokenPayloadError { try { - return createNewAccessToken(new TenantIdentifier(null, null, null), main, sessionHandle, userId, userId, + return createNewAccessToken(ResourceDistributor.getAppForTesting(), main, sessionHandle, userId, userId, refreshTokenHash1, parentRefreshTokenHash1, userData, antiCsrfToken, expiryTime, version, useStaticKey); @@ -275,7 +276,7 @@ public static TokenInfo createNewAccessTokenV1(@Nonnull Main main, NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, UnsupportedJWTSigningAlgorithmException, AccessTokenPayloadError { try { - return createNewAccessTokenV1(new TenantIdentifier(null, null, null), main, sessionHandle, userId, + return createNewAccessTokenV1(ResourceDistributor.getAppForTesting(), main, sessionHandle, userId, refreshTokenHash1, parentRefreshTokenHash1, userData, antiCsrfToken); } catch (TenantOrAppNotFoundException e) { diff --git a/src/main/java/io/supertokens/session/refreshToken/RefreshToken.java b/src/main/java/io/supertokens/session/refreshToken/RefreshToken.java index dfc04f251..88fbac529 100644 --- a/src/main/java/io/supertokens/session/refreshToken/RefreshToken.java +++ b/src/main/java/io/supertokens/session/refreshToken/RefreshToken.java @@ -18,6 +18,7 @@ import com.google.gson.Gson; import io.supertokens.Main; +import io.supertokens.ResourceDistributor; import io.supertokens.config.Config; import io.supertokens.exceptions.UnauthorisedException; import io.supertokens.pluginInterface.exceptions.StorageQueryException; @@ -46,7 +47,7 @@ public class RefreshToken { public static RefreshTokenInfo getInfoFromRefreshToken(@Nonnull Main main, @Nonnull String token) throws UnauthorisedException, StorageQueryException, StorageTransactionLogicException { try { - return getInfoFromRefreshToken(new AppIdentifier(null, null), main, token); + return getInfoFromRefreshToken(ResourceDistributor.getAppForTesting().toAppIdentifier(), main, token); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); } @@ -92,7 +93,7 @@ public static TokenInfo createNewRefreshToken(@Nonnull Main main, @Nonnull Strin IllegalBlockSizeException, BadPaddingException, StorageTransactionLogicException, InvalidAlgorithmParameterException, InvalidKeySpecException { try { - return createNewRefreshToken(new TenantIdentifier(null, null, null), main, sessionHandle, userId, + return createNewRefreshToken(ResourceDistributor.getAppForTesting(), main, sessionHandle, userId, parentRefreshTokenHash1, antiCsrfToken); } catch (TenantOrAppNotFoundException e) { diff --git a/src/main/java/io/supertokens/signingkeys/AccessTokenSigningKey.java b/src/main/java/io/supertokens/signingkeys/AccessTokenSigningKey.java index dc5fad694..1cb9fd262 100644 --- a/src/main/java/io/supertokens/signingkeys/AccessTokenSigningKey.java +++ b/src/main/java/io/supertokens/signingkeys/AccessTokenSigningKey.java @@ -85,7 +85,7 @@ public static AccessTokenSigningKey getInstance(AppIdentifier appIdentifier, Mai @TestOnly public static AccessTokenSigningKey getInstance(Main main) { try { - return getInstance(new AppIdentifier(null, null), main); + return getInstance(ResourceDistributor.getAppForTesting().toAppIdentifier(), main); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); } diff --git a/src/main/java/io/supertokens/signingkeys/SigningKeys.java b/src/main/java/io/supertokens/signingkeys/SigningKeys.java index 5f5265e51..85598e421 100644 --- a/src/main/java/io/supertokens/signingkeys/SigningKeys.java +++ b/src/main/java/io/supertokens/signingkeys/SigningKeys.java @@ -63,7 +63,7 @@ public static SigningKeys getInstance(AppIdentifier appIdentifier, Main main) @TestOnly public static SigningKeys getInstance(Main main) { try { - return getInstance(new AppIdentifier(null, null), main); + return getInstance(ResourceDistributor.getAppForTesting().toAppIdentifier(), main); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); } diff --git a/src/main/java/io/supertokens/thirdparty/ThirdParty.java b/src/main/java/io/supertokens/thirdparty/ThirdParty.java index a7f18bb54..c0ef4ee99 100644 --- a/src/main/java/io/supertokens/thirdparty/ThirdParty.java +++ b/src/main/java/io/supertokens/thirdparty/ThirdParty.java @@ -17,6 +17,7 @@ package io.supertokens.thirdparty; import io.supertokens.Main; +import io.supertokens.ResourceDistributor; import io.supertokens.emailpassword.exceptions.EmailChangeNotAllowedException; import io.supertokens.multitenancy.Multitenancy; import io.supertokens.multitenancy.exception.BadPermissionException; @@ -113,7 +114,7 @@ public static SignInUpResponse signInUp2_7(Main main, try { Storage storage = StorageLayer.getStorage(main); return signInUp2_7( - new TenantIdentifier(null, null, null), storage, + ResourceDistributor.getAppForTesting(), storage, thirdPartyId, thirdPartyUserId, email, isEmailVerified); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -126,7 +127,7 @@ public static SignInUpResponse signInUp(Main main, String thirdPartyId, String t try { Storage storage = StorageLayer.getStorage(main); return signInUp( - new TenantIdentifier(null, null, null), storage, main, + ResourceDistributor.getAppForTesting(), storage, main, thirdPartyId, thirdPartyUserId, email, false); } catch (TenantOrAppNotFoundException | BadPermissionException e) { throw new IllegalStateException(e); @@ -140,7 +141,7 @@ public static SignInUpResponse signInUp(Main main, String thirdPartyId, String t try { Storage storage = StorageLayer.getStorage(main); return signInUp( - new TenantIdentifier(null, null, null), storage, main, + ResourceDistributor.getAppForTesting(), storage, main, thirdPartyId, thirdPartyUserId, email, isEmailVerified); } catch (TenantOrAppNotFoundException | BadPermissionException e) { throw new IllegalStateException(e); @@ -389,7 +390,7 @@ public static AuthRecipeUserInfo getUser(AppIdentifier appIdentifier, Storage st @TestOnly public static AuthRecipeUserInfo getUser(Main main, String userId) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); - return getUser(new AppIdentifier(null, null), storage, userId); + return getUser(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, userId); } public static AuthRecipeUserInfo getUser(TenantIdentifier tenantIdentifier, Storage storage, @@ -405,7 +406,7 @@ public static AuthRecipeUserInfo getUser(Main main, String thirdPartyId, String throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); return getUser( - new TenantIdentifier(null, null, null), storage, + ResourceDistributor.getAppForTesting(), storage, thirdPartyId, thirdPartyUserId); } diff --git a/src/main/java/io/supertokens/totp/Totp.java b/src/main/java/io/supertokens/totp/Totp.java index c8b705668..a67f36e07 100644 --- a/src/main/java/io/supertokens/totp/Totp.java +++ b/src/main/java/io/supertokens/totp/Totp.java @@ -2,6 +2,7 @@ import com.eatthepath.otp.TimeBasedOneTimePasswordGenerator; import io.supertokens.Main; +import io.supertokens.ResourceDistributor; import io.supertokens.config.Config; import io.supertokens.featureflag.exceptions.FeatureNotEnabledException; import io.supertokens.mfa.Mfa; @@ -77,7 +78,7 @@ public static TOTPDevice registerDevice(Main main, String userId, throws StorageQueryException, DeviceAlreadyExistsException, NoSuchAlgorithmException, FeatureNotEnabledException { try { - return registerDevice(new AppIdentifier(null, null), StorageLayer.getStorage(main), + return registerDevice(ResourceDistributor.getAppForTesting().toAppIdentifier(), StorageLayer.getStorage(main), main, userId, deviceName, skew, period); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -359,7 +360,7 @@ public static boolean verifyDevice(Main main, throws UnknownDeviceException, InvalidTotpException, LimitReachedException, StorageQueryException, StorageTransactionLogicException { try { - return verifyDevice(new TenantIdentifier(null, null, null), + return verifyDevice(ResourceDistributor.getAppForTesting(), StorageLayer.getStorage(main), main, userId, deviceName, code); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -425,7 +426,7 @@ public static void verifyCode(Main main, String userId, String code) throws InvalidTotpException, UnknownTotpUserIdException, LimitReachedException, StorageQueryException, StorageTransactionLogicException, FeatureNotEnabledException { try { - verifyCode(new TenantIdentifier(null, null, null), StorageLayer.getStorage(main), main, + verifyCode(ResourceDistributor.getAppForTesting(), StorageLayer.getStorage(main), main, userId, code); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -469,7 +470,7 @@ public static void removeDevice(Main main, String userId, throws StorageQueryException, UnknownDeviceException, StorageTransactionLogicException { try { - removeDevice(new AppIdentifier(null, null), StorageLayer.getStorage(main), + removeDevice(ResourceDistributor.getAppForTesting().toAppIdentifier(), StorageLayer.getStorage(main), userId, deviceName); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -518,7 +519,7 @@ public static void updateDeviceName(Main main, String userId, String oldDeviceName, String newDeviceName) throws StorageQueryException, DeviceAlreadyExistsException, UnknownDeviceException { try { - updateDeviceName(new AppIdentifier(null, null), StorageLayer.getStorage(main), + updateDeviceName(ResourceDistributor.getAppForTesting().toAppIdentifier(), StorageLayer.getStorage(main), userId, oldDeviceName, newDeviceName); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -537,7 +538,7 @@ public static void updateDeviceName(AppIdentifier appIdentifier, Storage storage public static TOTPDevice[] getDevices(Main main, String userId) throws StorageQueryException { try { - return getDevices(new AppIdentifier(null, null), StorageLayer.getStorage(main), + return getDevices(ResourceDistributor.getAppForTesting().toAppIdentifier(), StorageLayer.getStorage(main), userId); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); diff --git a/src/main/java/io/supertokens/useridmapping/UserIdMapping.java b/src/main/java/io/supertokens/useridmapping/UserIdMapping.java index 18ad6bf44..9d6fd0ecf 100644 --- a/src/main/java/io/supertokens/useridmapping/UserIdMapping.java +++ b/src/main/java/io/supertokens/useridmapping/UserIdMapping.java @@ -17,6 +17,7 @@ package io.supertokens.useridmapping; import io.supertokens.Main; +import io.supertokens.ResourceDistributor; import io.supertokens.StorageAndUserIdMapping; import io.supertokens.StorageAndUserIdMappingForBulkImport; import io.supertokens.pluginInterface.Storage; @@ -408,7 +409,7 @@ public static void createUserIdMapping(Main main, UserIdMappingAlreadyExistsException, StorageQueryException, ServletException, UnknownUserIdException { try { Storage storage = StorageLayer.getStorage(main); - createUserIdMapping(new AppIdentifier(null, null), new Storage[]{storage}, superTokensUserId, + createUserIdMapping(ResourceDistributor.getAppForTesting().toAppIdentifier(), new Storage[]{storage}, superTokensUserId, externalUserId, externalUserIdInfo, force, makeExceptionForEmailVerification); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -500,7 +501,7 @@ public static io.supertokens.pluginInterface.useridmapping.UserIdMapping getUser UserIdType userIdType) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); - return getUserIdMapping(new AppIdentifier(null, null), storage, userId, userIdType); + return getUserIdMapping(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, userId, userIdType); } public static boolean deleteUserIdMapping(AppIdentifier appIdentifier, Storage storage, String userId, @@ -554,7 +555,7 @@ public static boolean deleteUserIdMapping(Main main, String userId, throws StorageQueryException, ServletException { Storage storage = StorageLayer.getStorage(main); return deleteUserIdMapping( - new AppIdentifier(null, null), storage, userId, userIdType, force); + ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, userId, userIdType, force); } public static boolean updateOrDeleteExternalUserIdInfo(AppIdentifier appIdentifier, Storage storage, @@ -591,7 +592,7 @@ public static boolean updateOrDeleteExternalUserIdInfo(Main main, @Nullable String externalUserIdInfo) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); - return updateOrDeleteExternalUserIdInfo(new AppIdentifier(null, null), storage, + return updateOrDeleteExternalUserIdInfo(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, userId, userIdType, externalUserIdInfo); } @@ -610,7 +611,7 @@ public static HashMap getUserIdMappingForSuperTokensUserIds(Main throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); return getUserIdMappingForSuperTokensUserIds( - new AppIdentifier(null, null), storage, userIds); + ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, userIds); } public static List findNonAuthStoragesWhereUserIdIsUsedOrAssertIfUsed( diff --git a/src/main/java/io/supertokens/usermetadata/UserMetadata.java b/src/main/java/io/supertokens/usermetadata/UserMetadata.java index 545e5eaa1..e911b1660 100644 --- a/src/main/java/io/supertokens/usermetadata/UserMetadata.java +++ b/src/main/java/io/supertokens/usermetadata/UserMetadata.java @@ -18,6 +18,7 @@ import com.google.gson.JsonObject; import io.supertokens.Main; +import io.supertokens.ResourceDistributor; import io.supertokens.pluginInterface.Storage; import io.supertokens.pluginInterface.StorageUtils; import io.supertokens.pluginInterface.exceptions.StorageQueryException; @@ -42,7 +43,7 @@ public static JsonObject updateUserMetadata(Main main, Storage storage = StorageLayer.getStorage(main); try { return updateUserMetadata( - new AppIdentifier(null, null), storage, + ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, userId, metadataUpdate); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -117,7 +118,7 @@ public static void updateMultipleUsersMetadata(AppIdentifier appIdentifier, Stor @TestOnly public static JsonObject getUserMetadata(Main main, @Nonnull String userId) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); - return getUserMetadata(new AppIdentifier(null, null), storage, userId); + return getUserMetadata(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, userId); } public static JsonObject getUserMetadata(AppIdentifier appIdentifier, Storage storage, @@ -137,7 +138,7 @@ public static JsonObject getUserMetadata(AppIdentifier appIdentifier, Storage st @TestOnly public static void deleteUserMetadata(Main main, @Nonnull String userId) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); - deleteUserMetadata(new AppIdentifier(null, null), storage, userId); + deleteUserMetadata(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, userId); } public static void deleteUserMetadata(AppIdentifier appIdentifier, Storage storage, diff --git a/src/main/java/io/supertokens/userroles/UserRoles.java b/src/main/java/io/supertokens/userroles/UserRoles.java index 8d88b637a..88c766e80 100644 --- a/src/main/java/io/supertokens/userroles/UserRoles.java +++ b/src/main/java/io/supertokens/userroles/UserRoles.java @@ -17,6 +17,7 @@ package io.supertokens.userroles; import io.supertokens.Main; +import io.supertokens.ResourceDistributor; import io.supertokens.pluginInterface.Storage; import io.supertokens.pluginInterface.StorageUtils; import io.supertokens.pluginInterface.bulkimport.exceptions.BulkImportBatchInsertException; @@ -113,7 +114,7 @@ public static boolean addRoleToUser(Main main, String userId, String role) Storage storage = StorageLayer.getStorage(main); try { return addRoleToUser( - main, new TenantIdentifier(null, null, null), + main, ResourceDistributor.getAppForTesting(), storage, userId, role); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -165,7 +166,7 @@ public static boolean createNewRoleOrModifyItsPermissions(Main main, throws StorageQueryException, StorageTransactionLogicException, TenantOrAppNotFoundException { Storage storage = StorageLayer.getStorage(main); return createNewRoleOrModifyItsPermissions( - new AppIdentifier(null, null), storage, role, + ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, role, permissions); } @@ -179,7 +180,7 @@ public static boolean doesRoleExist(AppIdentifier appIdentifier, Storage storage public static boolean doesRoleExist(Main main, String role) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); - return doesRoleExist(new AppIdentifier(null, null), storage, role); + return doesRoleExist(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, role); } // remove a role mapped to a user, if the role doesn't exist throw a UNKNOWN_ROLE_EXCEPTION error @@ -214,7 +215,7 @@ public static boolean removeUserRole(Main main, String userId, String role) throws StorageQueryException, StorageTransactionLogicException, UnknownRoleException { Storage storage = StorageLayer.getStorage(main); return removeUserRole( - new TenantIdentifier(null, null, null), storage, + ResourceDistributor.getAppForTesting(), storage, userId, role); } @@ -228,8 +229,7 @@ public static String[] getRolesForUser(TenantIdentifier tenantIdentifier, Storag public static String[] getRolesForUser(Main main, String userId) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); - return getRolesForUser( - new TenantIdentifier(null, null, null), storage, userId); + return getRolesForUser(ResourceDistributor.getAppForTesting(), storage, userId); } // retrieve all users who have the input role, if role does not exist then throw UNKNOWN_ROLE_EXCEPTION @@ -250,8 +250,7 @@ public static String[] getUsersForRole(TenantIdentifier tenantIdentifier, Storag public static String[] getUsersForRole(Main main, String role) throws StorageQueryException, UnknownRoleException { Storage storage = StorageLayer.getStorage(main); - return getUsersForRole( - new TenantIdentifier(null, null, null), storage, role); + return getUsersForRole(ResourceDistributor.getAppForTesting(), storage, role); } // retrieve all permissions associated with the role @@ -274,8 +273,7 @@ public static String[] getPermissionsForRole(AppIdentifier appIdentifier, Storag public static String[] getPermissionsForRole(Main main, String role) throws StorageQueryException, UnknownRoleException { Storage storage = StorageLayer.getStorage(main); - return getPermissionsForRole( - new AppIdentifier(null, null), storage, role); + return getPermissionsForRole(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, role); } // delete permissions from a role, if the role doesn't exist throw an UNKNOWN_ROLE_EXCEPTION @@ -314,7 +312,7 @@ public static void deletePermissionsFromRole(Main main, String role, @Nullable String[] permissions) throws StorageQueryException, StorageTransactionLogicException, UnknownRoleException { Storage storage = StorageLayer.getStorage(main); - deletePermissionsFromRole(new AppIdentifier(null, null), storage, + deletePermissionsFromRole(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, role, permissions); } @@ -331,7 +329,7 @@ public static String[] getRolesThatHavePermission(Main main, String permission) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); return getRolesThatHavePermission( - new AppIdentifier(null, null), storage, permission); + ResourceDistributor.getAppForTesting().toAppIdentifier(), storage, permission); } // delete a role @@ -357,7 +355,7 @@ public static boolean deleteRole(Main main, AppIdentifier appIdentifier, String @TestOnly public static boolean deleteRole(Main main, String role) throws StorageQueryException, TenantOrAppNotFoundException { - return deleteRole(main, new AppIdentifier(null, null), role); + return deleteRole(main, ResourceDistributor.getAppForTesting().toAppIdentifier(), role); } // retrieve all roles that have been created @@ -369,7 +367,7 @@ public static String[] getRoles(AppIdentifier appIdentifier, Storage storage) @TestOnly public static String[] getRoles(Main main) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); - return getRoles(new AppIdentifier(null, null), storage); + return getRoles(ResourceDistributor.getAppForTesting().toAppIdentifier(), storage); } // delete all roles associated with a user @@ -383,8 +381,7 @@ public static int deleteAllRolesForUser(TenantIdentifier tenantIdentifier, Stora public static int deleteAllRolesForUser(Main main, String userId) throws StorageQueryException { Storage storage = StorageLayer.getStorage(main); - return deleteAllRolesForUser( - new TenantIdentifier(null, null, null), storage, userId); + return deleteAllRolesForUser(ResourceDistributor.getAppForTesting(), storage, userId); } } diff --git a/src/test/java/io/supertokens/test/APIKeysTest.java b/src/test/java/io/supertokens/test/APIKeysTest.java index 828ad9e7e..c7ce821e8 100644 --- a/src/test/java/io/supertokens/test/APIKeysTest.java +++ b/src/test/java/io/supertokens/test/APIKeysTest.java @@ -16,7 +16,6 @@ package io.supertokens.test; -import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; @@ -50,6 +49,9 @@ public class APIKeysTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -67,7 +69,7 @@ public void testGetApiKeysDoesNotReturnNullWhenAPIKeyIsSet() throws Exception { Utils.setValueInConfig("api_keys", "abctijenbogweg=-2438243u98"); // set api_keys - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String[] apiKeys = Config.getConfig(process.getProcess()).getAPIKeys(); @@ -84,7 +86,7 @@ public void testGetApiKeysDoesNotReturnNullWhenAPIKeyIsSet() throws Exception { public void testGetApiKeysReturnsNullWhenAPIKeyIsNotSet() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); assertNull(Config.getConfig(process.getProcess()).getAPIKeys()); @@ -101,7 +103,7 @@ public void testErrorIsThrownWhenInvalidApiKeyIsSet() throws Exception { // api key length less that minimum length 20 Utils.setValueInConfig("api_keys", "abc"); // set api_keys - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException event = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(event); assertEquals(event.exception.getCause().getMessage(), @@ -114,7 +116,7 @@ public void testErrorIsThrownWhenInvalidApiKeyIsSet() throws Exception { // setting api key with non-supported symbols Utils.setValueInConfig("api_keys", "abC&^0t4t3t40t4@#%greognr"); // set api_keys - process = TestingProcessManager.start(args); + process = TestingProcessManager.startIsolatedProcess(args); event = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(event); @@ -135,7 +137,7 @@ public void testSettingValidAndInvalidApiKeysAndErrorIsThrown() throws Exception Utils.setValueInConfig("api_keys", validKey + "," + invalidKey); // set api_keys - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException event = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(event); assertEquals(event.exception.getCause().getMessage(), @@ -155,7 +157,7 @@ public void testCreatingSessionWithAndWithoutAPIKey() throws Exception { String apiKey = "hg40239oirjgBHD9450=Beew123-"; Utils.setValueInConfig("api_keys", apiKey); // set api_keys - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; @@ -206,9 +208,11 @@ public void testSettingAPIKeyAndCallingConfigAndHelloWithoutIt() throws Exceptio String apiKey = "hg40239oirjgBHD9450=Beew123-"; Utils.setValueInConfig("api_keys", apiKey); // set api_keys - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); + HttpRequestForTesting.disableAddingAppId = true; + String response = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", "http://localhost:3567/hello", null, 1000, 1000, null, Utils.getCdiVersionStringLatestForTests(), ""); assertEquals(response, "Hello"); @@ -241,7 +245,7 @@ public void testSettingMultipleAPIKeys() throws Exception { Utils.setValueInConfig("api_keys", apiKey1 + "," + apiKey2 + "," + apiKey3); // set api_keys - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; @@ -313,7 +317,7 @@ public void testSettingMultipleAPIKeysWithSpacing() throws Exception { Utils.setValueInConfig("api_keys", " " + apiKey1 + ", " + apiKey2 + ", " + apiKey3 + "," + apiKey4); // set // api_keys - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; @@ -389,7 +393,7 @@ public void testDifferentWaysToPassAPIKey() throws Exception { Utils.setValueInConfig("api_keys", apiKey1); // set api_keys - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; @@ -497,6 +501,9 @@ private static T sendJsonRequest(Main main, String url, JsonElement requestB int connectionTimeoutMS, int readTimeoutMS, String method, Map headers) throws IOException, io.supertokens.test.httpRequest.HttpResponseException { + if (HttpRequestForTesting.corePort != null) { + url = url.replace(":3567", ":" + HttpRequestForTesting.corePort); + } URL obj = getURL(main, "", url); InputStream inputStream = null; HttpURLConnection con = null; diff --git a/src/test/java/io/supertokens/test/APITestsWithTrailingSlash.java b/src/test/java/io/supertokens/test/APITestsWithTrailingSlash.java index 548924d32..970f0dbae 100644 --- a/src/test/java/io/supertokens/test/APITestsWithTrailingSlash.java +++ b/src/test/java/io/supertokens/test/APITestsWithTrailingSlash.java @@ -35,6 +35,9 @@ public class APITestsWithTrailingSlash { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/ActiveUsersTest.java b/src/test/java/io/supertokens/test/ActiveUsersTest.java index 108bc38ee..8600ad78d 100644 --- a/src/test/java/io/supertokens/test/ActiveUsersTest.java +++ b/src/test/java/io/supertokens/test/ActiveUsersTest.java @@ -29,6 +29,9 @@ public class ActiveUsersTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/ApiVersionAPITest.java b/src/test/java/io/supertokens/test/ApiVersionAPITest.java index 2bb28f136..beaa9e24a 100644 --- a/src/test/java/io/supertokens/test/ApiVersionAPITest.java +++ b/src/test/java/io/supertokens/test/ApiVersionAPITest.java @@ -47,6 +47,9 @@ public class ApiVersionAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -63,7 +66,7 @@ public void beforeEach() { public void testThatCoreDriverInterfaceSupportedVersionsAreBeingReturnedByTheAPI() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); StringBuilder fileContent = new StringBuilder(); @@ -96,7 +99,7 @@ public void testThatCoreDriverInterfaceSupportedVersionsAreBeingReturnedByTheAPI public void testThatNoVersionIsNeededForThisAPI() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); // without setting cdi-version header @@ -122,7 +125,7 @@ public void testThatNoVersionIsNeededForThisAPI() throws Exception { public void testThatApiVersionsAreBasedOnWebserverAPIsSupportedVersions() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); JsonObject apiVersionResponse = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", @@ -145,7 +148,7 @@ public void testThatApiVersionsAreBasedOnWebserverAPIsSupportedVersions() throws public void testThatAllReturnedVersionsHaveXYFormat() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); JsonObject apiVersionResponse = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", @@ -163,7 +166,7 @@ public void testThatAllReturnedVersionsHaveXYFormat() throws Exception { public void testThatWebsiteAndAPIDomainAreSaved() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); { @@ -175,8 +178,7 @@ public void testThatWebsiteAndAPIDomainAreSaved() throws Exception { assertEquals("https://example.com", Multitenancy.getWebsiteDomain(StorageLayer.getBaseStorage(process.getProcess()), - new AppIdentifier(null, - null))); + process.getAppForTesting().toAppIdentifier())); } { Map params = new HashMap<>(); @@ -187,8 +189,7 @@ public void testThatWebsiteAndAPIDomainAreSaved() throws Exception { assertEquals("https://api.example.com", Multitenancy.getAPIDomain(StorageLayer.getBaseStorage(process.getProcess()), - new AppIdentifier(null, - null))); + process.getAppForTesting().toAppIdentifier())); } process.kill(); @@ -199,10 +200,9 @@ public void testThatWebsiteAndAPIDomainAreSaved() throws Exception { public void testAPIVersionWorksEvenIfThereIsAnException() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/AuthRecipeAPITest2_10.java b/src/test/java/io/supertokens/test/AuthRecipeAPITest2_10.java index d8806711a..4cff71771 100644 --- a/src/test/java/io/supertokens/test/AuthRecipeAPITest2_10.java +++ b/src/test/java/io/supertokens/test/AuthRecipeAPITest2_10.java @@ -38,6 +38,9 @@ public class AuthRecipeAPITest2_10 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/AuthRecipeAPITest2_8.java b/src/test/java/io/supertokens/test/AuthRecipeAPITest2_8.java index 5d17b3eb5..91f13d975 100644 --- a/src/test/java/io/supertokens/test/AuthRecipeAPITest2_8.java +++ b/src/test/java/io/supertokens/test/AuthRecipeAPITest2_8.java @@ -36,6 +36,9 @@ public class AuthRecipeAPITest2_8 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/AuthRecipeTest.java b/src/test/java/io/supertokens/test/AuthRecipeTest.java index 5af5d82ae..0ecb4c342 100644 --- a/src/test/java/io/supertokens/test/AuthRecipeTest.java +++ b/src/test/java/io/supertokens/test/AuthRecipeTest.java @@ -54,6 +54,9 @@ public class AuthRecipeTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -200,9 +203,13 @@ public void paginationTest() throws Exception { } AuthRecipeUserInfo user1 = EmailPassword.signUp(process.getProcess(), "test0@example.com", "password0"); + Thread.sleep(20); AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test1@example.com", "password1"); + Thread.sleep(20); AuthRecipeUserInfo user3 = EmailPassword.signUp(process.getProcess(), "test20@example.com", "password2"); + Thread.sleep(20); AuthRecipeUserInfo user4 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "password3"); + Thread.sleep(20); { UserPaginationContainer users = AuthRecipe.getUsers(process.getProcess(), 100, "ASC", null, diff --git a/src/test/java/io/supertokens/test/AuthRecipesParallelTest.java b/src/test/java/io/supertokens/test/AuthRecipesParallelTest.java index e78ea330c..4db9d118b 100644 --- a/src/test/java/io/supertokens/test/AuthRecipesParallelTest.java +++ b/src/test/java/io/supertokens/test/AuthRecipesParallelTest.java @@ -41,6 +41,9 @@ public class AuthRecipesParallelTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/CDIVersionTest.java b/src/test/java/io/supertokens/test/CDIVersionTest.java index 3f2295997..4840f08d7 100644 --- a/src/test/java/io/supertokens/test/CDIVersionTest.java +++ b/src/test/java/io/supertokens/test/CDIVersionTest.java @@ -51,6 +51,9 @@ public class CDIVersionTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -64,7 +67,7 @@ public void beforeEach() { @Test public void testThatAPIUsesLatestVersionByDefault() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { @@ -102,7 +105,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO @Test public void testThatAPIUsesVersionSpecifiedInTheRequest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { @@ -146,7 +149,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO public void testThatAPIUsesVersionSpecifiedInConfigAsDefault() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); Utils.setValueInConfig("supertokens_max_cdi_version", "2.21"); process.startProcess(); @@ -188,7 +191,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO public void testThatAPIUsesVersionSpecifiedInRequestWhenTheConfigIsPresent() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); Utils.setValueInConfig("supertokens_max_cdi_version", "2.21"); process.startProcess(); @@ -230,7 +233,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO public void testCDIVersionWorksPerApp() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); Utils.setValueInConfig("supertokens_max_cdi_version", "2.21"); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); @@ -307,14 +310,13 @@ public void testJWKSEndpointWorksInAllCases() throws Exception { { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); { // check regular output JsonObject response = HttpRequest.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/.well-known/jwks.json", null, + "http://localhost:" + HttpRequestForTesting.corePort + "/.well-known/jwks.json", null, 1000, 1000, null); assertEquals(response.entrySet().size(), 1); @@ -341,7 +343,7 @@ public void testJWKSEndpointWorksInAllCases() throws Exception { { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); Utils.setValueInConfig("supertokens_max_cdi_version", "2.9"); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -349,7 +351,7 @@ public void testJWKSEndpointWorksInAllCases() throws Exception { { // check regular output JsonObject response = HttpRequest.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/.well-known/jwks.json", null, + "http://localhost:" + HttpRequestForTesting.corePort + "/.well-known/jwks.json", null, 1000, 1000, null); assertEquals(response.entrySet().size(), 1); @@ -377,7 +379,7 @@ public void testJWKSEndpointWorksInAllCases() throws Exception { public void testInvalidSemanticVersion() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); Utils.setValueInConfig("supertokens_max_cdi_version", "2.x"); process.startProcess(); @@ -394,7 +396,7 @@ public void testInvalidSemanticVersion() throws Exception { public void testUnsupportedVersion() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); Utils.setValueInConfig("supertokens_max_cdi_version", "2.1"); process.startProcess(); @@ -410,7 +412,7 @@ public void testUnsupportedVersion() throws Exception { public void testThatGreatedThanMaxCDIVersionIsNotAllowed() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); Utils.setValueInConfig("supertokens_max_cdi_version", "\"2.20\""); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -449,7 +451,7 @@ public void testThatGreatedThanMaxCDIVersionIsNotAllowed() throws Exception { public void testAPIVersionsWhenMaxCDIVersionIsSet() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); Utils.setValueInConfig("supertokens_max_cdi_version", "\"2.20\""); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/CLIOptionsTest.java b/src/test/java/io/supertokens/test/CLIOptionsTest.java index e3bae94f0..2b7ccbd42 100644 --- a/src/test/java/io/supertokens/test/CLIOptionsTest.java +++ b/src/test/java/io/supertokens/test/CLIOptionsTest.java @@ -23,6 +23,7 @@ import io.supertokens.output.Logging; import io.supertokens.pluginInterface.multitenancy.TenantIdentifier; import io.supertokens.test.TestingProcessManager.TestingProcess; +import io.supertokens.test.httpRequest.HttpRequestForTesting; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; @@ -41,6 +42,9 @@ public class CLIOptionsTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -55,7 +59,7 @@ public void beforeEach() { @Test public void cli0ArgsTest() throws TestingProcessManagerException, InterruptedException { String[] args = {}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); EventAndException e = process.checkOrWaitForEvent(PROCESS_STATE.INIT_FAILURE); assertTrue(e != null && e.exception.getMessage().equals("Please provide installation path location for SuperTokens")); @@ -66,7 +70,7 @@ public void cli0ArgsTest() throws TestingProcessManagerException, InterruptedExc @Test public void cli1ArgsTest() throws TestingProcessManagerException, InterruptedException { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); EventAndException e = process.checkOrWaitForEvent(PROCESS_STATE.STARTED); assertNotNull(e); process.kill(); @@ -77,7 +81,7 @@ public void cli2ArgsTest() throws Exception { // testing that when badInput is given to second cli argument, default values for host and port are used String[] args = {"../", "random"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); assertEquals(Config.getConfig(process.getProcess()).getHost(process.getProcess()), "localhost"); @@ -89,7 +93,7 @@ public void cli2ArgsTest() throws Exception { // custom host and port args = new String[]{"../", "host=127.0.0.1", "port=8081"}; - process = TestingProcessManager.start(args); + process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); assertEquals(Config.getConfig(process.getProcess()).getHost(process.getProcess()), "127.0.0.1"); @@ -102,33 +106,33 @@ public void cli2ArgsTest() throws Exception { @Test public void testMultipleInstancesAtTheSameTime() throws Exception { - String[] args = {"../"}; + String[] args = {"../", "port=3567"}; try { // Create 2 custom config files - ProcessBuilder pb = new ProcessBuilder("cp", "config.yaml", "temp/new1Config.yaml"); + ProcessBuilder pb = new ProcessBuilder("cp", "temp/config.yaml", "temp/new1Config.yaml"); pb.directory(new File(args[0])); Process p1 = pb.start(); p1.waitFor(); - pb = new ProcessBuilder("cp", "config.yaml", "temp/new2Config.yaml"); + pb = new ProcessBuilder("cp", "temp/config.yaml", "temp/new2Config.yaml"); pb.directory(new File(args[0])); p1 = pb.start(); p1.waitFor(); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args, true); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); args = new String[]{"../", "port=8081", "configFile=" + new File("../temp/new1Config.yaml").getAbsolutePath()}; - TestingProcess process1 = TestingProcessManager.start(args); + TestingProcess process1 = TestingProcessManager.startIsolatedProcess(args, true); assertNotNull(process1.checkOrWaitForEvent(PROCESS_STATE.STARTED)); args = new String[]{"../", "port=8082", "configFile=" + new File("../temp/new2Config.yaml").getAbsolutePath()}; - TestingProcess process2 = TestingProcessManager.start(args); + TestingProcess process2 = TestingProcessManager.startIsolatedProcess(args, true); assertNotNull(process2.checkOrWaitForEvent(PROCESS_STATE.STARTED)); assertEquals(Config.getConfig(process.getProcess()).getPort(process.getProcess()), 3567); @@ -292,27 +296,28 @@ public void cli2TempLocationTest() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); + int port = HttpRequestForTesting.corePort; + assertEquals(Config.getConfig(process.getProcess()).getHost(process.getProcess()), "localhost"); - assertEquals(Config.getConfig(process.getProcess()).getPort(process.getProcess()), 3567); + assertEquals(Config.getConfig(process.getProcess()).getPort(process.getProcess()), port); process.kill(); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STOPPED)); //process starts with tempDirLocation param too. - args = new String[]{"../", "tempDirLocation=" + new File("../tempDir/").getAbsolutePath()}; + args = new String[]{"../", "tempDirLocation=" + new File("../tempDir/").getAbsolutePath(), "port="+port}; - process = TestingProcessManager.start(args); + process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); assertEquals(Config.getConfig(process.getProcess()).getHost(process.getProcess()), "localhost"); - assertEquals(Config.getConfig(process.getProcess()).getPort(process.getProcess()), 3567); + assertEquals(Config.getConfig(process.getProcess()).getPort(process.getProcess()), port); process.kill(); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STOPPED)); - } } diff --git a/src/test/java/io/supertokens/test/ConfigAPITest2_7.java b/src/test/java/io/supertokens/test/ConfigAPITest2_7.java index 4eb06ff43..dc378fb83 100644 --- a/src/test/java/io/supertokens/test/ConfigAPITest2_7.java +++ b/src/test/java/io/supertokens/test/ConfigAPITest2_7.java @@ -40,6 +40,9 @@ public class ConfigAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -54,12 +57,12 @@ public void beforeEach() { public void inputErrorConfigAPITest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); // null for parameters try { - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/config", null, 1000, 1000, + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/config", null, 1000, 1000, null); fail(); } catch (HttpResponseException e) { @@ -72,7 +75,7 @@ public void inputErrorConfigAPITest() throws Exception { try { HashMap map = new HashMap<>(); map.put("pd", ProcessHandle.current().pid() + ""); - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/config", map, 1000, 1000, null); + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/config", map, 1000, 1000, null); fail(); } catch (HttpResponseException e) { assertTrue(e.getMessage() @@ -89,7 +92,7 @@ public void inputErrorConfigAPITest() throws Exception { public void testVersion2InputErrorConfigAPITest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); // null for parameters @@ -126,7 +129,7 @@ public void testCustomConfigPath() throws Exception { String path = new File("../temp/config.yaml").getAbsolutePath(); String[] args = {"../", "configFile=" + path}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); // map to store pid as parameter @@ -148,11 +151,14 @@ public void testCustomConfigPath() throws Exception { @Test public void testVersion2TestCustomConfigPath() throws Exception { String path = new File("../temp/config.yaml").getAbsolutePath(); - String[] args = {"../", "configFile=" + path}; + int port = TestingProcessManager.getFreePort(); + String[] args = {"../", "configFile=" + path, "port="+port}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); + HttpRequestForTesting.corePort = port; + // map to store pid as parameter Map map = new HashMap<>(); map.put("pid", ProcessHandle.current().pid() + ""); @@ -173,7 +179,7 @@ public void testVersion2TestCustomConfigPath() throws Exception { public void outputPossibilitiesConfigAPITest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); Main main = process.getProcess(); @@ -188,7 +194,7 @@ public void outputPossibilitiesConfigAPITest() throws Exception { map.put("pid", ProcessHandle.current().pid() + ""); // check regular output - JsonObject response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/config", map, + JsonObject response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/config", map, 1000, 1000, null); assertEquals(response.get("status").getAsString(), "OK"); @@ -199,7 +205,7 @@ public void outputPossibilitiesConfigAPITest() throws Exception { map = new HashMap<>(); map.put("pid", "-1"); - response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/config", map, 1000, 1000, + response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/config", map, 1000, 1000, null); assertEquals(response.get("status").getAsString(), "NOT_ALLOWED"); @@ -213,7 +219,7 @@ public void outputPossibilitiesConfigAPITest() throws Exception { public void testVersion2OutputPossibilitiesConfigAPITest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); Main main = process.getProcess(); diff --git a/src/test/java/io/supertokens/test/ConfigTest2_21.java b/src/test/java/io/supertokens/test/ConfigTest2_21.java index ea583ed84..370e82ef8 100644 --- a/src/test/java/io/supertokens/test/ConfigTest2_21.java +++ b/src/test/java/io/supertokens/test/ConfigTest2_21.java @@ -32,6 +32,9 @@ public class ConfigTest2_21 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -48,7 +51,7 @@ public void testThatDeprecatedConfigStillWorks() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); EventAndException startEvent = process.checkOrWaitForEvent(PROCESS_STATE.STARTED); assertNotNull(startEvent); @@ -70,7 +73,7 @@ public void testThatNewConfigWorks() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); EventAndException startEvent = process.checkOrWaitForEvent(PROCESS_STATE.STARTED); assertNotNull(startEvent); @@ -92,7 +95,7 @@ public void testCoreConfigTypeValidationInConfigYaml() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); EventAndException startEvent = process.checkOrWaitForEvent(PROCESS_STATE.INIT_FAILURE); assertNotNull(startEvent); diff --git a/src/test/java/io/supertokens/test/ConfigTest2_6.java b/src/test/java/io/supertokens/test/ConfigTest2_6.java index bbd6f7aca..6f6694af0 100644 --- a/src/test/java/io/supertokens/test/ConfigTest2_6.java +++ b/src/test/java/io/supertokens/test/ConfigTest2_6.java @@ -25,6 +25,7 @@ import io.supertokens.config.CoreConfig; import io.supertokens.config.CoreConfigTestContent; import io.supertokens.test.TestingProcessManager.TestingProcess; +import io.supertokens.test.httpRequest.HttpRequestForTesting; import org.junit.*; import org.junit.rules.TestRule; @@ -40,6 +41,9 @@ public class ConfigTest2_6 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -54,7 +58,7 @@ public void beforeEach() { public void testThatDefaultConfigLoadsCorrectly() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); EventAndException startEvent = process.checkOrWaitForEvent(PROCESS_STATE.STARTED); assertNotNull(startEvent); @@ -72,7 +76,7 @@ public void testThatCustomValuesInConfigAreLoaded() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); EventAndException startEvent = process.checkOrWaitForEvent(PROCESS_STATE.STARTED); assertNotNull(startEvent); @@ -95,7 +99,7 @@ public void testThatInvalidConfigThrowRightError() throws Exception { // out of range core_config_version Utils.setValueInConfig("core_config_version", "-1"); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); @@ -109,7 +113,7 @@ public void testThatInvalidConfigThrowRightError() throws Exception { // out of range value for access_token_validity Utils.setValueInConfig("access_token_validity", "-1"); - process = TestingProcessManager.start(args); + process = TestingProcessManager.startIsolatedProcess(args); e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); @@ -123,7 +127,7 @@ public void testThatInvalidConfigThrowRightError() throws Exception { Utils.reset(); Utils.setValueInConfig("max_server_pool_size", "-1"); - process = TestingProcessManager.start(args); + process = TestingProcessManager.startIsolatedProcess(args); e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); @@ -142,7 +146,7 @@ public void testInvalidTotpConfigThrowsExpectedError() throws Exception { Utils.setValueInConfig("totp_max_attempts", "0"); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); @@ -155,7 +159,7 @@ public void testInvalidTotpConfigThrowsExpectedError() throws Exception { Utils.reset(); Utils.setValueInConfig("totp_rate_limit_cooldown_sec", "0"); - process = TestingProcessManager.start(args); + process = TestingProcessManager.startIsolatedProcess(args); e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); @@ -176,7 +180,7 @@ private String getConfigFileLocation(Main main) { public void testThatNonTestingConfigValuesThrowErrors() throws Exception { String[] args = {"../"}; Utils.setValueInConfig("refresh_token_validity", "-1"); - TestingProcess process = TestingProcessManager.start(args, false); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); CoreConfigTestContent.getInstance(process.getProcess()).setKeyValue(CoreConfigTestContent.VALIDITY_TESTING, true); process.startProcess(); @@ -194,18 +198,19 @@ public void testThatNonTestingConfigValuesThrowErrors() throws Exception { @Test public void testThatMissingConfigFileThrowsError() throws Exception { - String[] args = {"../"}; + String configFile = new File(new File(".").getAbsoluteFile().getParentFile().getParentFile().getPath(), "config.yaml").getAbsolutePath(); + String[] args = {"../", "configFile=" + configFile}; ProcessBuilder pb = new ProcessBuilder("rm", "config.yaml"); pb.directory(new File(args[0])); Process process1 = pb.start(); process1.waitFor(); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); assertEquals(e.exception.getMessage(), - "../config.yaml (No such file or directory)"); + configFile + " (No such file or directory)"); process.kill(); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STOPPED)); @@ -215,9 +220,9 @@ public void testThatMissingConfigFileThrowsError() throws Exception { @Test public void testCustomLocationForConfigLoadsCorrectly() throws Exception { // relative file path - String[] args = {"../", "configFile=../temp/config.yaml"}; + String[] args = {"../", "configFile=./temp/config.yaml"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); EventAndException e = process.checkOrWaitForEvent(PROCESS_STATE.INIT_FAILURE); assertNotNull(e); assertEquals(e.exception.getMessage(), "configPath option must be an absolute path only"); @@ -229,7 +234,7 @@ public void testCustomLocationForConfigLoadsCorrectly() throws Exception { File f = new File("../temp/config.yaml"); args = new String[]{"../", "configFile=" + f.getAbsolutePath()}; - process = TestingProcessManager.start(args); + process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); checkConfigValues(Config.getConfig(process.getProcess()), process, true); @@ -262,7 +267,6 @@ private static void checkConfigValues(CoreConfig config, TestingProcess process, config.getAccessTokenDynamicSigningKeyUpdateIntervalInMillis(), 7 * 24 * 60 * 60 * 1000); assertEquals(config.getHost(process.getProcess()), "localhost"); - assertEquals(config.getPort(process.getProcess()), 3567); assertNull(config.getAPIKeys()); assertEquals(10, config.getMaxThreadPoolSize()); assertFalse(config.getHttpsEnabled()); diff --git a/src/test/java/io/supertokens/test/CronjobTest.java b/src/test/java/io/supertokens/test/CronjobTest.java index 015337b3c..4108c5283 100644 --- a/src/test/java/io/supertokens/test/CronjobTest.java +++ b/src/test/java/io/supertokens/test/CronjobTest.java @@ -362,6 +362,9 @@ public int getCount() { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -376,7 +379,7 @@ public void beforeEach() { public void testThatCronjobThrowsQuitProgramExceptionAndQuits() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); Cronjobs.addCronjob(process.getProcess(), QuitProgramExceptionCronjob.getInstance(process.getProcess())); @@ -389,7 +392,7 @@ public void testThatCronjobThrowsQuitProgramExceptionAndQuits() throws Exception public void testThatCronjobThrowsError() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -416,7 +419,7 @@ public void testNormalCronjob() throws Exception { normalCronjobCounter = 0; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); assertEquals(normalCronjobCounter, 0); @@ -434,7 +437,7 @@ public void testNormalCronjob() throws Exception { public void testAddingCronJobTwice() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); int initialSize = Cronjobs.getInstance(process.getProcess()).getTasks().size(); @@ -453,10 +456,9 @@ public void testAddingCronJobTwice() throws Exception { public void testAddingTenantsDoesNotIncreaseCronJobs() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -547,10 +549,9 @@ public void testAddingTenantsDoesNotIncreaseCronJobs() throws Exception { public void testTargetTenantCronTask() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -605,10 +606,9 @@ public void testTargetTenantCronTask() throws Exception { public void testPerTenantCronTask() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -665,10 +665,9 @@ public void testPerTenantCronTask() throws Exception { public void testPerAppCronTask() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -725,10 +724,9 @@ public void testPerAppCronTask() throws Exception { public void testPerUserPoolCronTask() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -791,7 +789,7 @@ public void testPerUserPoolCronTask() throws Exception { public void testThatCoreAutomaticallySyncsToConfigChangesInDb() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); CronTaskTest.getInstance(process.getProcess()).setIntervalInSeconds(SyncCoreConfigWithDb.RESOURCE_KEY, @@ -871,7 +869,7 @@ public void testThatCoreAutomaticallySyncsToConfigChangesInDb() throws Exception public void testThatReAddingSameCronTaskDoesNotScheduleMoreExecutors() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); for (int i = 0; i < 10; i++) { @@ -891,7 +889,7 @@ public void testThatReAddingSameCronTaskDoesNotScheduleMoreExecutors() throws Ex public void testThatNoCronJobIntervalIsMoreThanADay() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -912,10 +910,9 @@ public void testThatNoCronJobIntervalIsMoreThanADay() throws Exception { public void testThatCronJobsHaveTenantsInfoAfterRestart() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -972,8 +969,10 @@ public void testThatCronJobsHaveTenantsInfoAfterRestart() throws Exception { for (List> tenantsInfo : tenantsInfos) { if (tenantsInfo != null) { assertEquals(2, tenantsInfo.size()); - assertEquals(1, tenantsInfo.get(0).size()); - assertEquals(4, tenantsInfo.get(1).size()); + assertTrue( + (tenantsInfo.get(0).size() == 1 && tenantsInfo.get(1).size() == 4) || + (tenantsInfo.get(1).size() == 1 && tenantsInfo.get(0).size() == 4) + ); count++; } } @@ -984,7 +983,7 @@ public void testThatCronJobsHaveTenantsInfoAfterRestart() throws Exception { assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); - process = TestingProcessManager.start(args, false); + process = TestingProcessManager.startIsolatedProcess(args, false); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); process.startProcess(); @@ -999,8 +998,10 @@ public void testThatCronJobsHaveTenantsInfoAfterRestart() throws Exception { for (List> tenantsInfo : tenantsInfos) { if (tenantsInfo != null) { assertEquals(2, tenantsInfo.size()); - assertEquals(1, tenantsInfo.get(0).size()); - assertEquals(4, tenantsInfo.get(1).size()); + assertTrue( + (tenantsInfo.get(0).size() == 1 && tenantsInfo.get(1).size() == 4) || + (tenantsInfo.get(0).size() == 4 && tenantsInfo.get(1).size() == 1) + ); count++; } } @@ -1015,7 +1016,7 @@ public void testThatCronJobsHaveTenantsInfoAfterRestart() throws Exception { public void testThatThereAreTasksOfAllCronTaskClassesAndHaveCorrectIntervals() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -1091,7 +1092,7 @@ public void testThatThereAreTasksOfAllCronTaskClassesAndHaveCorrectIntervals() t public void testThatIsCronJobLoadedReturnsTheGoodValues() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); boolean isLoaded = Cronjobs.isCronjobLoaded(process.getProcess(), CounterCronJob.getInstance(process.getProcess())); @@ -1123,6 +1124,9 @@ public void testThatIsCronJobLoadedReturnsTheGoodValues() throws Exception { isLoaded = Cronjobs.isCronjobLoaded(process.getProcess(), CounterCronJob.getInstance(process.getProcess())); assertTrue(isLoaded); + + process.kill(); + assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } @Test @@ -1131,7 +1135,7 @@ public void testThatBulkMigrationCronJobLoadedWhenNoEnvVarSet() throws Exception setEnv(Collections.emptyMap()); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -1147,6 +1151,9 @@ public void testThatBulkMigrationCronJobLoadedWhenNoEnvVarSet() throws Exception assertTrue(bulkImportCron instanceof ProcessBulkImportUsers); setEnv(Collections.emptyMap()); + + process.kill(); + assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } @Test @@ -1154,7 +1161,7 @@ public void testThatBulkMigrationCronJobLoadedWhenEnvVarSetToTrue() throws Excep String[] args = {"../"}; setEnv(Map.of("BULK_MIGRATION_CRON_ENABLED", "true")); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -1170,6 +1177,9 @@ public void testThatBulkMigrationCronJobLoadedWhenEnvVarSetToTrue() throws Excep assertTrue(bulkImportCron instanceof ProcessBulkImportUsers); setEnv(Collections.emptyMap()); + + process.kill(); + assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } @Test @@ -1177,7 +1187,7 @@ public void testThatBulkMigrationCronJobNotLoadedWhenEnvVarSetToFalse() throws E String[] args = {"../"}; setEnv(Map.of("BULK_MIGRATION_CRON_ENABLED", "false")); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -1192,6 +1202,9 @@ public void testThatBulkMigrationCronJobNotLoadedWhenEnvVarSetToFalse() throws E assertNull(bulkImportCron); setEnv(Collections.emptyMap()); + + process.kill(); + assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } protected static void setEnv(Map newenv) throws Exception { diff --git a/src/test/java/io/supertokens/test/DotStartedFileTest.java b/src/test/java/io/supertokens/test/DotStartedFileTest.java index e54b30e89..c6e1c9e28 100644 --- a/src/test/java/io/supertokens/test/DotStartedFileTest.java +++ b/src/test/java/io/supertokens/test/DotStartedFileTest.java @@ -18,6 +18,8 @@ import io.supertokens.ProcessState; import io.supertokens.config.Config; +import io.supertokens.test.httpRequest.HttpRequestForTesting; + import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; @@ -34,6 +36,9 @@ public class DotStartedFileTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -46,32 +51,22 @@ public void beforeEach() { @Test public void fiveProcessInParallelDotStartedFileTest() throws Exception { - String[] args = {"../"}; - - TestingProcessManager.TestingProcess process1 = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process1 = TestingProcessManager.startIsolatedProcess(new String[]{"../", "port=7080"}, true); assertNotNull(process1.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); - Utils.setValueInConfig("port", "8081"); - - TestingProcessManager.TestingProcess process2 = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process2 = TestingProcessManager.startIsolatedProcess(new String[]{"../", "port=7081"}, true); assertNotNull(process2.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); - Utils.setValueInConfig("port", "8082"); - - TestingProcessManager.TestingProcess process3 = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process3 = TestingProcessManager.startIsolatedProcess(new String[]{"../", "port=7082"}, true); assertNotNull(process3.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); - Utils.setValueInConfig("port", "8083"); - - TestingProcessManager.TestingProcess process4 = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process4 = TestingProcessManager.startIsolatedProcess(new String[]{"../", "port=7083"}, true); assertNotNull(process4.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); - Utils.setValueInConfig("port", "8084"); - - TestingProcessManager.TestingProcess process5 = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process5 = TestingProcessManager.startIsolatedProcess(new String[]{"../", "port=7084"}, true); assertNotNull(process5.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); - File[] flist = new File("../.started").listFiles(); + File[] flist = new File("../.started" + System.getProperty("org.gradle.test.worker", "")).listFiles(); assert flist != null; int processCounter = flist.length; assertEquals(processCounter, 5); @@ -80,7 +75,7 @@ public void fiveProcessInParallelDotStartedFileTest() throws Exception { assertNotNull(process1.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); processCounter--; - flist = new File("../.started").listFiles(); + flist = new File("../.started" + System.getProperty("org.gradle.test.worker", "")).listFiles(); assert flist != null; assertEquals(processCounter, flist.length); @@ -88,7 +83,7 @@ public void fiveProcessInParallelDotStartedFileTest() throws Exception { assertNotNull(process2.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); processCounter--; - flist = new File("../.started").listFiles(); + flist = new File("../.started" + System.getProperty("org.gradle.test.worker", "")).listFiles(); assert flist != null; assertEquals(processCounter, flist.length); @@ -96,7 +91,7 @@ public void fiveProcessInParallelDotStartedFileTest() throws Exception { assertNotNull(process3.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); processCounter--; - flist = new File("../.started").listFiles(); + flist = new File("../.started" + System.getProperty("org.gradle.test.worker", "")).listFiles(); assert flist != null; assertEquals(processCounter, flist.length); @@ -104,7 +99,7 @@ public void fiveProcessInParallelDotStartedFileTest() throws Exception { assertNotNull(process4.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); processCounter--; - flist = new File("../.started").listFiles(); + flist = new File("../.started" + System.getProperty("org.gradle.test.worker", "")).listFiles(); assert flist != null; assertEquals(processCounter, flist.length); @@ -112,7 +107,7 @@ public void fiveProcessInParallelDotStartedFileTest() throws Exception { assertNotNull(process5.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); processCounter--; - flist = new File("../.started").listFiles(); + flist = new File("../.started" + System.getProperty("org.gradle.test.worker", "")).listFiles(); assert flist != null; assertEquals(processCounter, flist.length); } @@ -120,17 +115,16 @@ public void fiveProcessInParallelDotStartedFileTest() throws Exception { @Test public void dotStartedFileNameAndContentTest() throws Exception { String[] args = {"../"}; - String host = "localhost"; - String port = "8081"; - String hostPortNameCheck = host + "-" + port; - String basePathCheck = "/test"; - - Utils.setValueInConfig("port", port); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); - File loc = new File("../.started"); + String host = "localhost"; + String basePathCheck = "/test"; + String port = "" + HttpRequestForTesting.corePort; + String hostPortNameCheck = host + "-" + port; + + File loc = new File("../.started" + System.getProperty("org.gradle.test.worker", "")); File[] dotStartedNameAndContent = loc.listFiles(); assert dotStartedNameAndContent != null; @@ -141,7 +135,7 @@ public void dotStartedFileNameAndContentTest() throws Exception { String line = dotStartedContent[0]; assertEquals(line, Long.toString(ProcessHandle.current().pid())); line = dotStartedContent.length > 1 ? dotStartedContent[1] : ""; - assertEquals(line, Config.getConfig(process.main).getBasePath()); + assertEquals(line, Config.getConfig(process.getProcess()).getBasePath()); assertEquals(line, ""); process.kill(); @@ -150,9 +144,12 @@ public void dotStartedFileNameAndContentTest() throws Exception { // Ensure that base_path is set in .started file Utils.setValueInConfig("base_path", basePathCheck); - process = TestingProcessManager.start(args); + process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); + port = "" + HttpRequestForTesting.corePort; + hostPortNameCheck = host + "-" + port; + dotStartedNameAndContent = loc.listFiles(); assert dotStartedNameAndContent != null; assertEquals(1, dotStartedNameAndContent.length); @@ -162,7 +159,7 @@ public void dotStartedFileNameAndContentTest() throws Exception { line = dotStartedContent[0]; assertEquals(line, Long.toString(ProcessHandle.current().pid())); line = dotStartedContent.length > 1 ? dotStartedContent[1] : ""; - assertEquals(line, Config.getConfig(process.main).getBasePath()); + assertEquals(line, Config.getConfig(process.getProcess()).getBasePath()); assertEquals(line, basePathCheck); process.kill(); @@ -176,7 +173,7 @@ public void processFailToStartDotStartedFileTest() throws Exception { Utils.setValueInConfig("access_token_validity", "-1"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE)); File dotStartedFile = new File("../.started/localhost-3567"); @@ -197,10 +194,10 @@ public void dotStartedFileAtTempDirLocation() throws Exception { Utils.setValueInConfig("port", port); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); - File loc = new File(tempDirLocation + "/.started"); + File loc = new File(tempDirLocation + "/.started" + System.getProperty("org.gradle.test.worker", "")); File[] dotStartedNameAndContent = loc.listFiles(); assert dotStartedNameAndContent != null; @@ -211,7 +208,7 @@ public void dotStartedFileAtTempDirLocation() throws Exception { String line = dotStartedContent[0]; assertEquals(line, Long.toString(ProcessHandle.current().pid())); line = dotStartedContent.length > 1 ? dotStartedContent[1] : ""; - assertEquals(line, Config.getConfig(process.main).getBasePath()); + assertEquals(line, Config.getConfig(process.getProcess()).getBasePath()); assertEquals(line, ""); process.kill(); diff --git a/src/test/java/io/supertokens/test/FeatureFlagTest.java b/src/test/java/io/supertokens/test/FeatureFlagTest.java index a80013308..af39ac49b 100644 --- a/src/test/java/io/supertokens/test/FeatureFlagTest.java +++ b/src/test/java/io/supertokens/test/FeatureFlagTest.java @@ -54,6 +54,9 @@ public class FeatureFlagTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -62,6 +65,7 @@ public static void afterTesting() { @Before public void beforeEach() { Utils.reset(); + TestingProcessManager.killAllIsolatedProcesses(); } @Test @@ -69,16 +73,16 @@ public void noLicenseKeyShouldHaveEmptyFeatureFlag() throws InterruptedException, StorageQueryException, TenantOrAppNotFoundException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - Assert.assertNotNull(FeatureFlag.getInstance(process.main).getEeFeatureFlagInstance()); + Assert.assertNotNull(FeatureFlag.getInstance(process.getProcess()).getEeFeatureFlagInstance()); - if (StorageLayer.isInMemDb(process.main)) { + if (StorageLayer.isInMemDb(process.getProcess())) { Assert.assertEquals(FeatureFlag.getInstance(process.getProcess()).getEnabledFeatures().length, EE_FEATURES.values().length); } else { @@ -107,13 +111,13 @@ public void missingEEFolderShouldBeSameAsNoLicenseKey() FeatureFlag.clearURLClassLoader(); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.EE_FOLDER_LOCATION, "random"); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); - Assert.assertNull(FeatureFlag.getInstance(process.main).getEeFeatureFlagInstance()); + Assert.assertNull(FeatureFlag.getInstance(process.getProcess()).getEeFeatureFlagInstance()); Assert.assertEquals(FeatureFlag.getInstance(process.getProcess()).getEnabledFeatures().length, 0); @@ -133,7 +137,7 @@ public void missingEEFolderShouldBeSameAsNoLicenseKey() public void testThatCallingGetFeatureFlagAPIReturnsEmptyArray() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); Assert.assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -145,7 +149,7 @@ public void testThatCallingGetFeatureFlagAPIReturnsEmptyArray() throws Exception null, 1000, 1000, null, WebserverAPI.getLatestCDIVersion().get(), ""); Assert.assertEquals("OK", response.get("status").getAsString()); Assert.assertNotNull(response.get("features")); - if (StorageLayer.isInMemDb(process.main)) { + if (StorageLayer.isInMemDb(process.getProcess())) { Assert.assertEquals(EE_FEATURES.values().length, response.get("features").getAsJsonArray().size()); } else { Assert.assertEquals(0, response.get("features").getAsJsonArray().size()); @@ -162,14 +166,14 @@ public void testThatCallingGetFeatureFlagAPIReturnsEmptyArray() throws Exception public void testThatCallingGetFeatureFlagAPIReturnsMfaStats() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); Assert.assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlag.getInstance(process.main).setLicenseKeyAndSyncFeatures(OPAQUE_KEY_WITH_MFA_MULTITENANCY_FEATURE); + FeatureFlag.getInstance(process.getProcess()).setLicenseKeyAndSyncFeatures(OPAQUE_KEY_WITH_MFA_MULTITENANCY_FEATURE); // Get the stats without any users/activity { @@ -182,7 +186,7 @@ public void testThatCallingGetFeatureFlagAPIReturnsMfaStats() throws Exception { JsonObject usageStats = response.get("usageStats").getAsJsonObject(); JsonArray maus = usageStats.get("maus").getAsJsonArray(); - if (StorageLayer.isInMemDb(process.main)) { + if (StorageLayer.isInMemDb(process.getProcess())) { assert features.size() == EE_FEATURES.values().length; } else { assert features.size() == 2; // MFA + MULTITENANCY @@ -242,7 +246,7 @@ public void testThatCallingGetFeatureFlagAPIReturnsMfaStats() throws Exception { JsonObject usageStats = response.get("usageStats").getAsJsonObject(); JsonArray maus = usageStats.get("maus").getAsJsonArray(); - if (StorageLayer.isInMemDb(process.main)) { + if (StorageLayer.isInMemDb(process.getProcess())) { assert features.size() == EE_FEATURES.values().length; } else { assert features.size() == 2; // MFA + MULTITENANCY @@ -286,7 +290,7 @@ public void testThatCallingGetFeatureFlagAPIReturnsMfaStats() throws Exception { JsonObject usageStats = response.get("usageStats").getAsJsonObject(); JsonArray maus = usageStats.get("maus").getAsJsonArray(); - if (StorageLayer.isInMemDb(process.main)) { + if (StorageLayer.isInMemDb(process.getProcess())) { assert features.size() == EE_FEATURES.values().length; } else { assert features.size() == 2; // MFA + MULTITENANCY @@ -405,7 +409,7 @@ public void testThatCallingGetFeatureFlagAPIReturnsMfaStats() throws Exception { public void testFeatureFlagWithMultitenancyFor500Tenants() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -413,7 +417,7 @@ public void testFeatureFlagWithMultitenancyFor500Tenants() throws Exception { return; } - FeatureFlag.getInstance(process.main).setLicenseKeyAndSyncFeatures(OPAQUE_KEY_WITH_MULTITENANCY_FEATURE); + FeatureFlag.getInstance(process.getProcess()).setLicenseKeyAndSyncFeatures(OPAQUE_KEY_WITH_MULTITENANCY_FEATURE); for (int i = 0; i < 500; i++) { TenantIdentifier tenantIdentifier = new TenantIdentifier(null, null, "t" + i); @@ -463,7 +467,7 @@ public void testFeatureFlagWithMultitenancyFor500Tenants() throws Exception { public void testThatMultitenantStatsAreAccurate() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -471,7 +475,7 @@ public void testThatMultitenantStatsAreAccurate() throws Exception { return; } - FeatureFlag.getInstance(process.main).setLicenseKeyAndSyncFeatures(OPAQUE_KEY_WITH_MULTITENANCY_FEATURE); + FeatureFlag.getInstance(process.getProcess()).setLicenseKeyAndSyncFeatures(OPAQUE_KEY_WITH_MULTITENANCY_FEATURE); for (int i = 0; i < 5; i++) { JsonObject coreConfig = new JsonObject(); @@ -572,7 +576,7 @@ public void testThatMultitenantStatsAreAccurate() throws Exception { public void testThatMultitenantStatsAreAccurateForAnApp() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -580,7 +584,7 @@ public void testThatMultitenantStatsAreAccurateForAnApp() throws Exception { return; } - FeatureFlag.getInstance(process.main).setLicenseKeyAndSyncFeatures(OPAQUE_KEY_WITH_MULTITENANCY_FEATURE); + FeatureFlag.getInstance(process.getProcess()).setLicenseKeyAndSyncFeatures(OPAQUE_KEY_WITH_MULTITENANCY_FEATURE); Multitenancy.addNewOrUpdateAppOrTenant( process.getProcess(), @@ -695,7 +699,7 @@ public void testThatMultitenantStatsAreAccurateForAnApp() throws Exception { public void testThatMultitenantStatsAreAccurateForACud() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -707,7 +711,7 @@ public void testThatMultitenantStatsAreAccurateForACud() throws Exception { return; } - FeatureFlag.getInstance(process.main).setLicenseKeyAndSyncFeatures(OPAQUE_KEY_WITH_MULTITENANCY_FEATURE); + FeatureFlag.getInstance(process.getProcess()).setLicenseKeyAndSyncFeatures(OPAQUE_KEY_WITH_MULTITENANCY_FEATURE); { JsonObject coreConfig = new JsonObject(); @@ -826,7 +830,7 @@ public void testThatMultitenantStatsAreAccurateForACud() throws Exception { public void testPaidFeaturesAreEnabledIfUsingInMemoryDatabase() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -861,7 +865,7 @@ public void testPaidFeaturesAreEnabledIfUsingInMemoryDatabase() throws Exception public void testNetworkCallIsMadeInCoreInit() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -882,7 +886,7 @@ public void testNetworkCallIsMadeInCoreInit() throws Exception { // Restart core and check if the call was made during init - process = TestingProcessManager.start(args); + process = TestingProcessManager.startIsolatedProcess(args); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.LICENSE_KEY_CHECK_NETWORK_CALL)); @@ -932,7 +936,7 @@ public void testPaidStatsContainsAllEnabledFeatures() throws Exception { for (String license : licenses) { Utils.reset(); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -952,7 +956,7 @@ public void testPaidStatsContainsAllEnabledFeatures() throws Exception { process.kill(false); // Restart core and check if the call was made during init - process = TestingProcessManager.start(args); + process = TestingProcessManager.startIsolatedProcess(args); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); ProcessState.EventAndException event = process.checkOrWaitForEvent( diff --git a/src/test/java/io/supertokens/test/HelloAPITest.java b/src/test/java/io/supertokens/test/HelloAPITest.java index fdd6ad3e3..b279146ce 100644 --- a/src/test/java/io/supertokens/test/HelloAPITest.java +++ b/src/test/java/io/supertokens/test/HelloAPITest.java @@ -38,6 +38,9 @@ public class HelloAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -52,13 +55,15 @@ public void beforeEach() { public void testHelloAPIWithBasePath1() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); Utils.setValueInConfig("base_path", "/base"); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); + HttpRequestForTesting.disableAddingAppId = true; + String res = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", "http://localhost:3567/base", null, 1000, 1000, null, Utils.getCdiVersionStringLatestForTests(), ""); @@ -77,13 +82,15 @@ public void testHelloAPIWithBasePath1() throws Exception { public void testHelloAPIWithBasePath2() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); Utils.setValueInConfig("base_path", "/hello"); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); + HttpRequestForTesting.disableAddingAppId = true; + String res = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", "http://localhost:3567/hello", null, 1000, 1000, null, Utils.getCdiVersionStringLatestForTests(), ""); @@ -102,7 +109,7 @@ public void testHelloAPIWithBasePath2() throws Exception { public void testHelloAPIWithBasePath3() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); Utils.setValueInConfig("base_path", "/hello"); @@ -155,6 +162,8 @@ public void testHelloAPIWithBasePath3() throws Exception { "http://localhost:3567/hello/appid-hello/test/", // baseUrl + app + tenant + / }; + HttpRequestForTesting.disableAddingAppId = true; + for (String helloUrl : HELLO_ROUTES) { System.out.println(helloUrl); String res = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", @@ -188,7 +197,7 @@ public void testHelloAPIWithBasePath3() throws Exception { public void testWithBasePathThatHelloAPIDoesNotRequireAPIKeys() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); Utils.setValueInConfig("api_keys", "asdfasdfasdf123412341234"); @@ -244,6 +253,8 @@ public void testWithBasePathThatHelloAPIDoesNotRequireAPIKeys() throws Exception "http://localhost:3567/hello/appid-hello/test/", // baseUrl + app + tenant + / }; + HttpRequestForTesting.disableAddingAppId = true; + for (String helloUrl : HELLO_ROUTES) { System.out.println(helloUrl); String res = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", @@ -278,7 +289,7 @@ public void testWithBasePathThatHelloAPIDoesNotRequireAPIKeys() throws Exception public void testThatHelloAPIDoesNotRequireAPIKeys() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); Utils.setValueInConfig("api_keys", "asdfasdfasdf123412341234"); diff --git a/src/test/java/io/supertokens/test/HttpRequestTest.java b/src/test/java/io/supertokens/test/HttpRequestTest.java index 973d37818..de005f387 100644 --- a/src/test/java/io/supertokens/test/HttpRequestTest.java +++ b/src/test/java/io/supertokens/test/HttpRequestTest.java @@ -21,6 +21,7 @@ import io.supertokens.ProcessState; import io.supertokens.httpRequest.HttpRequest; import io.supertokens.httpRequest.HttpResponseException; +import io.supertokens.test.httpRequest.HttpRequestForTesting; import io.supertokens.webserver.Webserver; import io.supertokens.webserver.WebserverAPI; import org.junit.AfterClass; @@ -43,6 +44,9 @@ public class HttpRequestTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -60,6 +64,8 @@ public void jsonResponseTest() throws Exception { TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); + int port = HttpRequestForTesting.corePort; + // Json Response API Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { private static final long serialVersionUID = -7347714438908490973L; @@ -104,23 +110,23 @@ protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws // jsonResponse with post request JsonObject response = HttpRequest.sendJsonPOSTRequest(process.getProcess(), "", - "http://localhost:3567/jsonResponse", null, 1000, 1000, null); + "http://localhost:" + port + "/jsonResponse", null, 1000, 1000, null); assertEquals(response.get("key").getAsString(), "value"); // jsonResponse with get request - response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/jsonResponse", null, + response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + port + "/jsonResponse", null, 1000, 1000, null); assertEquals(response.get("key1").getAsString(), "value1"); // jsonResponse with put request - response = HttpRequest.sendJsonPUTRequest(process.getProcess(), "", "http://localhost:3567/jsonResponse", null, + response = HttpRequest.sendJsonPUTRequest(process.getProcess(), "", "http://localhost:" + port + "/jsonResponse", null, 1000, 1000, null); assertEquals(response.get("key2").getAsString(), "value2"); // jsonResponse with delete request - response = HttpRequest.sendJsonDELETERequest(process.getProcess(), "", "http://localhost:3567/jsonResponse", + response = HttpRequest.sendJsonDELETERequest(process.getProcess(), "", "http://localhost:" + port + "/jsonResponse", null, 1000, 1000, null); assertEquals(response.get("key3").getAsString(), "value3"); @@ -135,6 +141,8 @@ public void nonJsonResponseTest() throws Exception { TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); + int port = HttpRequestForTesting.corePort; + Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { private static final long serialVersionUID = -5953383281218376801L; @@ -175,21 +183,21 @@ protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws // nonJson Post request String response = HttpRequest.sendJsonPOSTRequest(process.getProcess(), "", - "http://localhost:3567/nonJsonResponse", null, 1000, 1000, null); + "http://localhost:" + port + "/nonJsonResponse", null, 1000, 1000, null); assertEquals("Non JSON Response", response); // nonJson Get request - response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/nonJsonResponse", null, + response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + port + "/nonJsonResponse", null, 1000, 1000, null); assertEquals("Non JSON Response", response); // nonJson Put request - response = HttpRequest.sendJsonPUTRequest(process.getProcess(), "", "http://localhost:3567/nonJsonResponse", + response = HttpRequest.sendJsonPUTRequest(process.getProcess(), "", "http://localhost:" + port + "/nonJsonResponse", null, 1000, 1000, null); assertEquals("Non JSON Response", response); // nonJson Delete request - response = HttpRequest.sendJsonDELETERequest(process.getProcess(), "", "http://localhost:3567/nonJsonResponse", + response = HttpRequest.sendJsonDELETERequest(process.getProcess(), "", "http://localhost:" + port + "/nonJsonResponse", null, 1000, 1000, null); assertEquals("Non JSON Response", response); @@ -204,6 +212,8 @@ public void errorRequestTest() throws Exception { TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); + int port = HttpRequestForTesting.corePort; + // error request api Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { private static final long serialVersionUID = -9210034480396407612L; @@ -243,7 +253,7 @@ public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IO // Post error request try { - HttpRequest.sendJsonPOSTRequest(process.getProcess(), "", "http://localhost:3567/errorRequest", null, 1000, + HttpRequest.sendJsonPOSTRequest(process.getProcess(), "", "http://localhost:" + port + "/errorRequest", null, 1000, 1000, null); fail(); } catch (HttpResponseException e) { @@ -252,7 +262,7 @@ public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IO // Get error Request try { - HttpRequest.sendJsonPOSTRequest(process.getProcess(), "", "http://localhost:3567/errorRequest", null, 1000, + HttpRequest.sendJsonPOSTRequest(process.getProcess(), "", "http://localhost:" + port + "/errorRequest", null, 1000, 1000, null); fail(); } catch (HttpResponseException e) { @@ -261,7 +271,7 @@ public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IO // Put error Request try { - HttpRequest.sendJsonPUTRequest(process.getProcess(), "", "http://localhost:3567/errorRequest", null, 1000, + HttpRequest.sendJsonPUTRequest(process.getProcess(), "", "http://localhost:" + port + "/errorRequest", null, 1000, 1000, null); fail(); } catch (HttpResponseException e) { @@ -270,7 +280,7 @@ public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IO // Delete error Request try { - HttpRequest.sendJsonDELETERequest(process.getProcess(), "", "http://localhost:3567/errorRequest", null, + HttpRequest.sendJsonDELETERequest(process.getProcess(), "", "http://localhost:" + port + "/errorRequest", null, 1000, 1000, null); fail(); } catch (HttpResponseException e) { @@ -289,6 +299,8 @@ public void withAndWithoutBodyTest() throws Exception { TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); + int port = HttpRequestForTesting.corePort; + // api to check with Body Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { private static final long serialVersionUID = 6527072853102511509L; @@ -361,14 +373,14 @@ protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws // Post Request with Body { JsonObject response = HttpRequest.sendJsonPOSTRequest(process.getProcess(), "", - "http://localhost:3567/withBody", jsonBody, 1000, 1000, null); + "http://localhost:" + port + "/withBody", jsonBody, 1000, 1000, null); assertEquals(response.get("message").getAsString(), "Body Found"); } // Put Request with Body { JsonObject response = HttpRequest.sendJsonPUTRequest(process.getProcess(), "", - "http://localhost:3567/withBody", jsonBody, 1000, 1000, null); + "http://localhost:" + port + "/withBody", jsonBody, 1000, 1000, null); assertEquals(response.get("message").getAsString(), "Body Found"); @@ -377,7 +389,7 @@ protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws // Delete Request with Body { JsonObject response = HttpRequest.sendJsonDELETERequest(process.getProcess(), "", - "http://localhost:3567/withBody", jsonBody, 1000, 1000, null); + "http://localhost:" + port + "/withBody", jsonBody, 1000, 1000, null); assertEquals(response.get("message").getAsString(), "Body Found"); @@ -452,7 +464,7 @@ protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws // post request without body { JsonObject response = HttpRequest.sendJsonPOSTRequest(process.getProcess(), "", - "http://localhost:3567/withoutBody", null, 1000, 1000, null); + "http://localhost:" + port + "/withoutBody", null, 1000, 1000, null); assertEquals(response.get("message").getAsString(), "No Body Found"); @@ -461,7 +473,7 @@ protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws // put request without body { JsonObject response = HttpRequest.sendJsonPUTRequest(process.getProcess(), "", - "http://localhost:3567/withoutBody", null, 1000, 1000, null); + "http://localhost:" + port + "/withoutBody", null, 1000, 1000, null); assertEquals(response.get("message").getAsString(), "No Body Found"); @@ -470,7 +482,7 @@ protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws // Delete request without body { JsonObject response = HttpRequest.sendJsonDELETERequest(process.getProcess(), "", - "http://localhost:3567/withoutBody", null, 1000, 1000, null); + "http://localhost:" + port + "/withoutBody", null, 1000, 1000, null); assertEquals(response.get("message").getAsString(), "No Body Found"); @@ -488,6 +500,8 @@ public void withAndWithoutVersionTest() throws Exception { TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); + int port = HttpRequestForTesting.corePort; + // api to check withVersion Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { @@ -543,7 +557,7 @@ public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IO // Get Request { - String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/withVersion", + String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + port + "/withVersion", null, 1000, 1000, 0); assertEquals(response, "0"); @@ -552,7 +566,7 @@ public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IO // Post Request { String response = HttpRequest.sendJsonPOSTRequest(process.getProcess(), "", - "http://localhost:3567/withVersion", null, 1000, 1000, 0); + "http://localhost:" + port + "/withVersion", null, 1000, 1000, 0); assertEquals(response, "0"); } @@ -560,7 +574,7 @@ public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IO // Put Request { String response = HttpRequest.sendJsonPUTRequest(process.getProcess(), "", - "http://localhost:3567/withVersion", null, 1000, 1000, 0); + "http://localhost:" + port + "/withVersion", null, 1000, 1000, 0); assertEquals(response, "0"); } @@ -568,7 +582,7 @@ public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IO // Delete Request { String response = HttpRequest.sendJsonDELETERequest(process.getProcess(), "", - "http://localhost:3567/withVersion", null, 1000, 1000, 0); + "http://localhost:" + port + "/withVersion", null, 1000, 1000, 0); assertEquals(response, "0"); } @@ -625,7 +639,7 @@ public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IO { String response = HttpRequest.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/withoutVersion", null, 1000, 1000, null); + "http://localhost:" + port + "/withoutVersion", null, 1000, 1000, null); assertEquals(response, "No Version was sent"); } @@ -633,7 +647,7 @@ public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IO // Post Request { String response = HttpRequest.sendJsonPOSTRequest(process.getProcess(), "", - "http://localhost:3567/withoutVersion", null, 1000, 1000, null); + "http://localhost:" + port + "/withoutVersion", null, 1000, 1000, null); assertEquals(response, "No Version was sent"); } @@ -641,7 +655,7 @@ public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IO // Put Request { String response = HttpRequest.sendJsonPUTRequest(process.getProcess(), "", - "http://localhost:3567/withoutVersion", null, 1000, 1000, null); + "http://localhost:" + port + "/withoutVersion", null, 1000, 1000, null); assertEquals(response, "No Version was sent"); } @@ -649,7 +663,7 @@ public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IO // Delete Request { String response = HttpRequest.sendJsonDELETERequest(process.getProcess(), "", - "http://localhost:3567/withoutVersion", null, 1000, 1000, null); + "http://localhost:" + port + "/withoutVersion", null, 1000, 1000, null); assertEquals(response, "No Version was sent"); } @@ -665,6 +679,8 @@ public void getRequestTest() throws Exception { TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); + int port = HttpRequestForTesting.corePort; + // api to check getRequestWithParams Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { @@ -701,7 +717,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO { String response = HttpRequest.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/getTestWithParams", map, 1000, 1000, null); + "http://localhost:" + port + "/getTestWithParams", map, 1000, 1000, null); assertEquals(response, "200"); } @@ -729,7 +745,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO { String response = HttpRequest.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/getTestWithoutParams", null, 1000, 1000, null); + "http://localhost:" + port + "/getTestWithoutParams", null, 1000, 1000, null); assertEquals(response, "200"); } process.kill(); diff --git a/src/test/java/io/supertokens/test/InMemoryDBStorageTest.java b/src/test/java/io/supertokens/test/InMemoryDBStorageTest.java index 081e7ec7c..edc52de5e 100644 --- a/src/test/java/io/supertokens/test/InMemoryDBStorageTest.java +++ b/src/test/java/io/supertokens/test/InMemoryDBStorageTest.java @@ -48,6 +48,9 @@ public class InMemoryDBStorageTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -65,7 +68,7 @@ public void beforeEach() { public void transactionIsolationTesting() throws InterruptedException, StorageQueryException, StorageTransactionLogicException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -186,7 +189,7 @@ public void transactionIsolationTesting() @Test public void transactionTest() throws InterruptedException, StorageQueryException, StorageTransactionLogicException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -214,7 +217,7 @@ public void transactionTest() throws InterruptedException, StorageQueryException public void transactionDoNotCommitButStillCommitsTest() throws InterruptedException, StorageQueryException, StorageTransactionLogicException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -242,7 +245,7 @@ public void transactionDoNotCommitButStillCommitsTest() public void transactionThrowCompileTimeErrorAndExpectRollbackTest() throws InterruptedException, StorageQueryException, StorageTransactionLogicException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -275,7 +278,7 @@ public void transactionThrowCompileTimeErrorAndExpectRollbackTest() public void transactionThrowRunTimeErrorAndExpectRollbackTest() throws InterruptedException, StorageQueryException, StorageTransactionLogicException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -309,7 +312,7 @@ public void transactionThrowRunTimeErrorAndExpectRollbackTest() public void multipleParallelTransactionTest() throws InterruptedException, IOException { String[] args = {"../"}; Utils.setValueInConfig("access_token_dynamic_signing_key_update_interval", "0.00005"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/InMemoryDBTest.java b/src/test/java/io/supertokens/test/InMemoryDBTest.java index 485fbbbc5..2232318db 100644 --- a/src/test/java/io/supertokens/test/InMemoryDBTest.java +++ b/src/test/java/io/supertokens/test/InMemoryDBTest.java @@ -53,6 +53,9 @@ public class InMemoryDBTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -67,7 +70,7 @@ public void beforeEach() { public void testCodeCreationRapidly() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -110,7 +113,7 @@ public void testCodeCreationRapidly() throws Exception { public void testConcurrentMetadataUpdates() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -149,7 +152,7 @@ public void testConcurrentMetadataUpdates() throws Exception { public void createAndForgetSession() throws Exception { { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -174,7 +177,7 @@ public void createAndForgetSession() throws Exception { } { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -191,7 +194,7 @@ public void createAndForgetSession() throws Exception { public void createAndGetSession() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -229,7 +232,7 @@ public void createAndGetSession() throws Exception { public void createAndGetSessionNoAntiCSRF() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -268,7 +271,7 @@ public void createSessionWhichExpiresInOneSecondCheck() throws Exception { Utils.setValueInConfig("access_token_validity", "1"); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -301,7 +304,7 @@ public void createSessionWhichExpiresInOneSecondCheck() throws Exception { public void createNewSessionAndAlterJWTPayload() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -344,7 +347,7 @@ public void createNewSessionAndAlterJWTPayload() throws Exception { public void createAndGetSessionWithEmptyJWTPayload() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -379,7 +382,7 @@ public void createAndGetSessionWithEmptyJWTPayload() throws Exception { public void createAndGetSessionWithComplexJWTPayload() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -427,7 +430,7 @@ public void createAndGetSessionV2WithSigningKeyChange() throws Exception { Utils.setValueInConfig("access_token_validity", "1"); // 1 second String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -486,7 +489,7 @@ public void createAndGetSessionWithSigningKeyChange() throws Exception { Utils.setValueInConfig("access_token_validity", "1"); // 1 second String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -542,7 +545,7 @@ public void refreshSessionTestWithAntiCsrf() throws Exception { Utils.setValueInConfig("access_token_validity", "1"); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -631,7 +634,7 @@ public void refreshSessionTestWithNoAntiCsrf() throws Exception { Utils.setValueInConfig("access_token_validity", "1"); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -716,7 +719,7 @@ public void refreshSessionTestWithNoAntiCsrf() throws Exception { public void createAndGetSessionBadAntiCsrfFailure() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -749,7 +752,7 @@ public void refreshTokenExpiresAfterShortTime() throws Exception { Utils.setValueInConfig("refresh_token_validity", "" + 1.5 / 60.0); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -842,7 +845,7 @@ public void refreshTokenExpiresAfterShortTime() throws Exception { @Test public void forceInMemDBIsTrueIfSetToTrue() throws InterruptedException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertTrue(process.getProcess().isForceInMemoryDB()); @@ -856,8 +859,7 @@ public void forceInMemDBIsTrueIfSetToTrue() throws InterruptedException { @Test public void forceInMemDBIsFalseByDefault() throws InterruptedException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertFalse(process.getProcess().isForceInMemoryDB()); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); } diff --git a/src/test/java/io/supertokens/test/InputParserTest.java b/src/test/java/io/supertokens/test/InputParserTest.java index 2f4c0325f..49f8859f7 100644 --- a/src/test/java/io/supertokens/test/InputParserTest.java +++ b/src/test/java/io/supertokens/test/InputParserTest.java @@ -35,6 +35,9 @@ public class InputParserTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/IpAllowDenyRegexTest.java b/src/test/java/io/supertokens/test/IpAllowDenyRegexTest.java index b281663be..3d395da77 100644 --- a/src/test/java/io/supertokens/test/IpAllowDenyRegexTest.java +++ b/src/test/java/io/supertokens/test/IpAllowDenyRegexTest.java @@ -29,6 +29,8 @@ import io.supertokens.pluginInterface.multitenancy.*; import io.supertokens.storageLayer.StorageLayer; import io.supertokens.test.TestingProcessManager.TestingProcess; +import io.supertokens.test.httpRequest.HttpRequestForTesting; + import org.junit.*; import org.junit.rules.TestRule; import org.mockito.Mockito; @@ -43,6 +45,9 @@ public class IpAllowDenyRegexTest extends Mockito { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -56,7 +61,7 @@ public void beforeEach() { @Test public void defaultIpDenyAllowIsNull() throws InterruptedException { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); assert (Config.getConfig(process.getProcess()).getIpAllowRegex() == null); @@ -74,7 +79,7 @@ public void EmptyStringIpDenyOrAllowIsNull() throws InterruptedException, IOExce String[] args = {"../"}; Utils.setValueInConfig("ip_allow_regex", "\" \""); Utils.setValueInConfig("ip_deny_regex", "\"\""); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); assert (Config.getConfig(process.getProcess()).getIpAllowRegex() == null); @@ -93,7 +98,7 @@ public void EmptyConfigIpDenyOrAllowIsNull() throws InterruptedException, IOExce String[] args = {"../"}; Utils.setValueInConfig("ip_allow_regex", ""); Utils.setValueInConfig("ip_deny_regex", ""); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); assert (Config.getConfig(process.getProcess()).getIpAllowRegex() == null); @@ -111,7 +116,7 @@ public void InvalidRegexErrorForIpAllow() throws InterruptedException, IOExcepti { String[] args = {"../"}; Utils.setValueInConfig("ip_allow_regex", "\"*\""); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); assertTrue(e.exception.getMessage() @@ -127,7 +132,7 @@ public void InvalidRegexErrorForIpDeny() throws InterruptedException, IOExceptio { String[] args = {"../"}; Utils.setValueInConfig("ip_deny_regex", "\"*\""); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); assertTrue(e.exception.getMessage() @@ -143,11 +148,11 @@ public void CheckAllowRegexWorks() throws Exception { { String[] args = {"../"}; Utils.setValueInConfig("ip_allow_regex", "192.123.3.4"); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); try { - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/hello", null, 1000, 1000, + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/hello", null, 1000, 1000, null); throw new Exception("test failed"); } catch (HttpResponseException e) { @@ -164,10 +169,10 @@ public void CheckAllowLocalhostWorks() throws InterruptedException, IOException, { String[] args = {"../"}; Utils.setValueInConfig("ip_allow_regex", "127\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+|::1|0:0:0:0:0:0:0:1"); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); - String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/hello", null, + String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/hello", null, 1000, 1000, null); Assert.assertEquals("Hello", response); @@ -180,10 +185,10 @@ public void CheckAllowLocalhostWorks() throws InterruptedException, IOException, { String[] args = {"../"}; Utils.setValueInConfig("ip_allow_regex", "127\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+"); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); - String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/hello", null, + String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/hello", null, 1000, 1000, null); Assert.assertEquals("Hello", response); @@ -196,10 +201,10 @@ public void CheckAllowLocalhostWorks() throws InterruptedException, IOException, { String[] args = {"../"}; Utils.setValueInConfig("ip_allow_regex", "'127\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+'"); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); - String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/hello", null, + String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/hello", null, 1000, 1000, null); Assert.assertEquals("Hello", response); @@ -213,10 +218,10 @@ public void CheckAllowLocalhostWorks() throws InterruptedException, IOException, String[] args = {"../"}; Utils.setValueInConfig("ip_allow_regex", "\"127\\\\\\\\.\\\\\\\\d+\\\\\\\\.\\\\\\\\d+\\\\\\\\.\\\\\\\\d+\""); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); - String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/hello", null, + String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/hello", null, 1000, 1000, null); Assert.assertEquals("Hello", response); @@ -230,11 +235,11 @@ public void CheckDenyLocalhostWorks() throws Exception { { String[] args = {"../"}; Utils.setValueInConfig("ip_deny_regex", "127\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+|::1|0:0:0:0:0:0:0:1"); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); try { - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/hello", null, 1000, 1000, + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/hello", null, 1000, 1000, null); throw new Exception("test failed"); } catch (HttpResponseException e) { @@ -250,11 +255,11 @@ public void CheckDenyLocalhostWorks() throws Exception { { String[] args = {"../"}; Utils.setValueInConfig("ip_deny_regex", "127\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+"); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); try { - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/hello", null, 1000, 1000, + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/hello", null, 1000, 1000, null); throw new Exception("test failed"); } catch (HttpResponseException e) { @@ -270,11 +275,11 @@ public void CheckDenyLocalhostWorks() throws Exception { { String[] args = {"../"}; Utils.setValueInConfig("ip_deny_regex", "'127\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+'"); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); try { - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/hello", null, 1000, 1000, + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/hello", null, 1000, 1000, null); throw new Exception("test failed"); } catch (HttpResponseException e) { @@ -290,11 +295,11 @@ public void CheckDenyLocalhostWorks() throws Exception { { String[] args = {"../"}; Utils.setValueInConfig("ip_deny_regex", "\"127\\\\\\\\.\\\\\\\\d+\\\\\\\\.\\\\\\\\d+\\\\\\\\.\\\\\\\\d+\""); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); try { - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/hello", null, 1000, 1000, + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/hello", null, 1000, 1000, null); throw new Exception("test failed"); } catch (HttpResponseException e) { @@ -312,11 +317,13 @@ public void CheckAllowAndDenyLocalhostWorks() throws Exception { String[] args = {"../"}; Utils.setValueInConfig("ip_deny_regex", "127\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+|::1|0:0:0:0:0:0:0:1"); Utils.setValueInConfig("ip_allow_regex", "127\\\\.\\\\d+\\\\.\\\\d+\\\\.\\\\d+|::1|0:0:0:0:0:0:0:1"); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); + int port = HttpRequestForTesting.corePort; + try { - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/hello", null, 1000, 1000, + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + port + "/hello", null, 1000, 1000, null); throw new Exception("test failed"); } catch (HttpResponseException e) { @@ -339,14 +346,16 @@ public void CheckNoLoggingForNotAllowedAPIRoutes() throws Exception { Utils.setValueInConfig("info_log_path", "\"null\""); Utils.setValueInConfig("error_log_path", "\"null\""); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); System.setOut(new PrintStream(stdOutput)); System.setErr(new PrintStream(errorOutput)); + int port = HttpRequestForTesting.corePort; + try { - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/hello", null, 1000, 1000, + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + port + "/hello", null, 1000, 1000, null); throw new Exception("test failed"); } catch (HttpResponseException e) { @@ -370,7 +379,7 @@ public void CheckThatIPFiltersAreTenantSpecific() throws Exception { { // test allow works Utils.reset(); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); process.startProcess(); @@ -396,14 +405,16 @@ public void CheckThatIPFiltersAreTenantSpecific() throws Exception { new JsonObject() ), false); + int port = HttpRequestForTesting.corePort; + // this should pass - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/hello", null, 1000, 1000, + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + port + "/hello", null, 1000, 1000, null); - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/t2/hello", null, 1000, 1000, + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + port + "/t2/hello", null, 1000, 1000, null); try { - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/t1/hello", null, 1000, 1000, + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + port + "/t1/hello", null, 1000, 1000, null); fail(); } catch (HttpResponseException e) { @@ -416,7 +427,7 @@ public void CheckThatIPFiltersAreTenantSpecific() throws Exception { { // test deny works Utils.reset(); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); process.startProcess(); @@ -438,14 +449,16 @@ public void CheckThatIPFiltersAreTenantSpecific() throws Exception { new JsonObject() ), false); + int port = HttpRequestForTesting.corePort; + // this should pass - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/hello", null, 1000, 1000, + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + port + "/hello", null, 1000, 1000, null); - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/t2/hello", null, 1000, 1000, + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + port + "/t2/hello", null, 1000, 1000, null); try { - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/t1/hello", null, 1000, 1000, + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + port + "/t1/hello", null, 1000, 1000, null); fail(); } catch (HttpResponseException e) { diff --git a/src/test/java/io/supertokens/test/JWKSPublicAPITest.java b/src/test/java/io/supertokens/test/JWKSPublicAPITest.java index fd9cc53d4..37a47485b 100644 --- a/src/test/java/io/supertokens/test/JWKSPublicAPITest.java +++ b/src/test/java/io/supertokens/test/JWKSPublicAPITest.java @@ -20,6 +20,7 @@ import com.google.gson.JsonObject; import io.supertokens.ProcessState; import io.supertokens.httpRequest.HttpRequest; +import io.supertokens.test.httpRequest.HttpRequestForTesting; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; @@ -37,6 +38,9 @@ public class JWKSPublicAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -56,7 +60,7 @@ public void testSuccessOutput() throws Exception { // check regular output JsonObject response = HttpRequest.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/.well-known/jwks.json", null, + "http://localhost:" + HttpRequestForTesting.corePort + "/.well-known/jwks.json", null, 1000, 1000, null); assertEquals(response.entrySet().size(), 1); @@ -73,7 +77,7 @@ public void testSuccessOutput() throws Exception { public void testCacheControlValue() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); Utils.setValueInConfig("access_token_dynamic_signing_key_update_interval", "1"); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -81,7 +85,7 @@ public void testCacheControlValue() throws Exception { // check regular output Map responseHeaders = new HashMap<>(); JsonObject response = HttpRequest.sendGETRequestWithResponseHeaders(process.getProcess(), "", - "http://localhost:3567/.well-known/jwks.json", null, + "http://localhost:" + HttpRequestForTesting.corePort + "/.well-known/jwks.json", null, 1000, 1000, null, responseHeaders); assertEquals(response.entrySet().size(), 1); @@ -96,7 +100,7 @@ public void testCacheControlValue() throws Exception { Thread.sleep(2000); response = HttpRequest.sendGETRequestWithResponseHeaders(process.getProcess(), "", - "http://localhost:3567/.well-known/jwks.json", null, + "http://localhost:" + HttpRequestForTesting.corePort + "/.well-known/jwks.json", null, 1000, 1000, null, responseHeaders); assertEquals(response.entrySet().size(), 1); diff --git a/src/test/java/io/supertokens/test/LogLevelTest.java b/src/test/java/io/supertokens/test/LogLevelTest.java index 1b82f2951..e0f3175d9 100644 --- a/src/test/java/io/supertokens/test/LogLevelTest.java +++ b/src/test/java/io/supertokens/test/LogLevelTest.java @@ -41,6 +41,9 @@ public class LogLevelTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -55,7 +58,7 @@ public void beforeEach() { public void testLogLevels() throws Exception { { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -75,7 +78,7 @@ public void testLogLevels() throws Exception { { Utils.setValueInConfig("log_level", "NONE"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -90,7 +93,7 @@ public void testLogLevels() throws Exception { { Utils.setValueInConfig("log_level", "ERROR"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -106,7 +109,7 @@ public void testLogLevels() throws Exception { { Utils.setValueInConfig("log_level", "WARN"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -123,7 +126,7 @@ public void testLogLevels() throws Exception { { Utils.setValueInConfig("log_level", "INFO"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -141,7 +144,7 @@ public void testLogLevels() throws Exception { { Utils.setValueInConfig("log_level", "DEBUG"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -163,7 +166,7 @@ public void testLogLevelNoneOutput() throws Exception { { Utils.setValueInConfig("log_level", "NONE"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -207,7 +210,7 @@ public void testLogLevelErrorOutput() throws Exception { { Utils.setValueInConfig("log_level", "ERROR"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -261,7 +264,7 @@ public void testLogLevelWarnOutput() throws Exception { { Utils.setValueInConfig("log_level", "WARN"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -315,7 +318,7 @@ public void testLogLevelInfoOutput() throws Exception { { Utils.setValueInConfig("log_level", "INFO"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -369,7 +372,7 @@ public void testLogLevelDebugOutput() throws Exception { { Utils.setValueInConfig("log_level", "DEBUG"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -429,7 +432,7 @@ public void testLogLevelNoneOutputWithConfigErrorShouldLog() throws Exception { Utils.setValueInConfig("log_level", "NONE"); Utils.setValueInConfig("access_token_validity", "-1"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.INIT_FAILURE)); @@ -449,7 +452,7 @@ public void testLogLevelsUpperLowerCase() throws Exception { { Utils.setValueInConfig("log_level", "NonE"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -464,7 +467,7 @@ public void testLogLevelsUpperLowerCase() throws Exception { { Utils.setValueInConfig("log_level", "error"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -480,7 +483,7 @@ public void testLogLevelsUpperLowerCase() throws Exception { { Utils.setValueInConfig("log_level", "wArN"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -497,7 +500,7 @@ public void testLogLevelsUpperLowerCase() throws Exception { { Utils.setValueInConfig("log_level", "info"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -515,7 +518,7 @@ public void testLogLevelsUpperLowerCase() throws Exception { { Utils.setValueInConfig("log_level", "debug"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -536,7 +539,7 @@ public void testLogLevelsUpperLowerCase() throws Exception { public void testIncorrectLogLevel() throws Exception { Utils.setValueInConfig("log_level", "random"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); diff --git a/src/test/java/io/supertokens/test/LoggingTest.java b/src/test/java/io/supertokens/test/LoggingTest.java index 91ae6a52a..6cdc96757 100644 --- a/src/test/java/io/supertokens/test/LoggingTest.java +++ b/src/test/java/io/supertokens/test/LoggingTest.java @@ -49,6 +49,9 @@ public class LoggingTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -62,7 +65,7 @@ public void beforeEach() { @Test public void noErrorLogsOnCoreStart() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); boolean errorFlag = false; @@ -90,7 +93,7 @@ public void noErrorLogsOnCoreStart() throws Exception { @Test public void defaultLogging() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); Logging.error(process.getProcess(), TenantIdentifier.BASE_TENANT, "From test", false); @@ -137,7 +140,7 @@ public void customLogging() throws Exception { Utils.setValueInConfig("info_log_path", "\"tempLogging/info.log\""); Utils.setValueInConfig("error_log_path", "\"tempLogging/error.log\""); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); Logging.error(process.getProcess(), TenantIdentifier.BASE_TENANT, "From Test", false); @@ -185,7 +188,7 @@ public void customLogging() throws Exception { public void confirmLoggerClosed() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -217,12 +220,10 @@ public void testStandardOutLoggingWithNullStr() throws Exception { System.setOut(new PrintStream(stdOutput)); System.setErr(new PrintStream(errorOutput)); - TestingProcess process = TestingProcessManager.start(args, false); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); + assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); try { - process.startProcess(); - assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); - Logging.debug(process.getProcess(), TenantIdentifier.BASE_TENANT, "outTest-dfkn3knsakn"); Logging.error(process.getProcess(), TenantIdentifier.BASE_TENANT, "errTest-sdvjovnoasid", true); @@ -251,14 +252,13 @@ public void testTenantNotFoundExceptionUsesTheRightCUD() throws Exception { System.setOut(new PrintStream(stdOutput)); System.setErr(new PrintStream(errorOutput)); - TestingProcess process = TestingProcessManager.start(args, false); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); + FeatureFlagTestContent.getInstance(process.getProcess()) + .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ + EE_FEATURES.MULTI_TENANCY}); + assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); try { - FeatureFlagTestContent.getInstance(process.getProcess()) - .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ - EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); - assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; @@ -328,11 +328,10 @@ public void testStandardOutLoggingWithNull() throws Exception { System.setOut(new PrintStream(stdOutput)); System.setErr(new PrintStream(errorOutput)); - TestingProcess process = TestingProcessManager.start(args, false); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); + assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); try { - process.startProcess(); - assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); Logging.debug(process.getProcess(), TenantIdentifier.BASE_TENANT, "outTest-dfkn3knsakn"); Logging.error(process.getProcess(), TenantIdentifier.BASE_TENANT, "errTest-sdvjovnoasid", true); @@ -353,7 +352,7 @@ public void testStandardOutLoggingWithNull() throws Exception { public void testThatSubFoldersAreCreated() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args, false); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); try { Utils.setValueInConfig("info_log_path", "../temp/a/b/info.log"); process.startProcess(); @@ -381,7 +380,7 @@ public void testThatSubFoldersAreCreated() throws Exception { @Test public void testDefaultLoggingFilePath() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/PathRouterTest.java b/src/test/java/io/supertokens/test/PathRouterTest.java index cbce604ff..4eb0a8bbd 100644 --- a/src/test/java/io/supertokens/test/PathRouterTest.java +++ b/src/test/java/io/supertokens/test/PathRouterTest.java @@ -59,6 +59,9 @@ public class PathRouterTest extends Mockito { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -72,7 +75,7 @@ public void beforeEach() { @Test public void test500ErrorMessage() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { @@ -140,6 +143,9 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) assertEquals("Http error. Status Code: 500. Message: java.lang.RuntimeException: Runtime Exception", e.getMessage()); } } + + process.kill(); + assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STOPPED)); } @Test @@ -148,7 +154,7 @@ public void basicTenantIdFetchingTest() StorageQueryException, FeatureNotEnabledException, TenantOrAppNotFoundException, InvalidConfigException, CannotModifyBaseConfigException, BadPermissionException { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -324,7 +330,7 @@ public void basicTenantIdFetchingWihQueryParamTest() StorageQueryException, FeatureNotEnabledException, TenantOrAppNotFoundException, InvalidConfigException, CannotModifyBaseConfigException, BadPermissionException { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -500,7 +506,7 @@ public void basicTenantIdFetchingWithBasePathTest() CannotModifyBaseConfigException, BadPermissionException { String[] args = {"../"}; Utils.setValueInConfig("base_path", "base_path"); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -571,6 +577,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) }); } + HttpRequestForTesting.disableAddingAppId = true; + { String response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", "http://localhost:3567/base_path/test", new HashMap<>(), 1000, 1000, null, @@ -686,7 +694,7 @@ public void basicTenantIdFetchingWithBasePathTest2() CannotModifyBaseConfigException, BadPermissionException { String[] args = {"../"}; Utils.setValueInConfig("base_path", "/base/path"); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -758,6 +766,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) }); } + HttpRequestForTesting.disableAddingAppId = true; + { String response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", "http://localhost:3567/base/path/test", new HashMap<>(), 1000, 1000, null, @@ -873,7 +883,7 @@ public void basicTenantIdFetchingWithBasePathTest3() CannotModifyBaseConfigException, BadPermissionException { String[] args = {"../"}; Utils.setValueInConfig("base_path", "/t1"); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -945,6 +955,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) }); } + HttpRequestForTesting.disableAddingAppId = true; + { String response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", "http://localhost:3567/t1/test", new HashMap<>(), 1000, 1000, null, @@ -1057,7 +1069,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) @Test public void withRecipeRouterTest() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1086,7 +1098,7 @@ null, null, new JsonObject() false); Webserver.getInstance(process.getProcess()) - .addAPI(new RecipeRouter(process.main, new WebserverAPI(process.getProcess(), "") { + .addAPI(new RecipeRouter(process.getProcess(), new WebserverAPI(process.getProcess(), "") { private static final long serialVersionUID = 1L; @@ -1169,6 +1181,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO } }); + HttpRequestForTesting.disableAddingAppId = true; + { String response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", "http://localhost:3567/test", new HashMap<>(), 1000, 1000, null, @@ -1212,11 +1226,11 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO @Test public void errorFromAddAPICauseOfSameRoute() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); Webserver.getInstance(process.getProcess()) - .addAPI(new RecipeRouter(process.main, new WebserverAPI(process.getProcess(), "") { + .addAPI(new RecipeRouter(process.getProcess(), new WebserverAPI(process.getProcess(), "") { private static final long serialVersionUID = 1L; @@ -1284,12 +1298,12 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) @Test public void errorFromRecipeRouterCauseOfSameRouteAndRid() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); try { Webserver.getInstance(process.getProcess()) - .addAPI(new RecipeRouter(process.main, new WebserverAPI(process.getProcess(), "r1") { + .addAPI(new RecipeRouter(process.getProcess(), new WebserverAPI(process.getProcess(), "r1") { private static final long serialVersionUID = 1L; @@ -1349,7 +1363,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) try { Webserver.getInstance(process.getProcess()) - .addAPI(new RecipeRouter(process.main, new WebserverAPI(process.getProcess(), "") { + .addAPI(new RecipeRouter(process.getProcess(), new WebserverAPI(process.getProcess(), "") { private static final long serialVersionUID = 1L; @@ -1421,10 +1435,9 @@ public void tenantNotFoundTest() String[] args = {"../"}; Utils.setValueInConfig("host", "\"0.0.0.0\""); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1550,10 +1563,9 @@ public void tenantNotFoundTest2() String[] args = {"../"}; Utils.setValueInConfig("host", "\"0.0.0.0\""); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1674,10 +1686,9 @@ public void tenantNotFoundTest3() String[] args = {"../"}; Utils.setValueInConfig("host", "\"0.0.0.0\""); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1761,7 +1772,7 @@ public void basicAppIdTesting() StorageQueryException, FeatureNotEnabledException, TenantOrAppNotFoundException, InvalidConfigException, CannotModifyBaseConfigException, BadPermissionException { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -2066,7 +2077,7 @@ public void basicAppIdWithBasePathTesting() CannotModifyBaseConfigException, BadPermissionException { String[] args = {"../"}; Utils.setValueInConfig("base_path", "base_path"); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -2184,6 +2195,8 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) }); } + HttpRequestForTesting.disableAddingAppId = true; + { String response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", "http://localhost:3567/base_path/appid-abc/test", new HashMap<>(), 1000, 1000, null, @@ -2355,7 +2368,7 @@ public void basicAppIdWithBase2PathTesting() CannotModifyBaseConfigException, BadPermissionException { String[] args = {"../"}; Utils.setValueInConfig("base_path", "appid-path"); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -2647,10 +2660,9 @@ public void tenantNotFoundWithAppIdTest() String[] args = {"../"}; Utils.setValueInConfig("host", "\"0.0.0.0\""); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -2795,10 +2807,9 @@ public void tenantNotFoundWithAppIdTest2() String[] args = {"../"}; Utils.setValueInConfig("host", "\"0.0.0.0\""); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -2876,6 +2887,8 @@ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws I } }); + HttpRequestForTesting.disableAddingAppId = true; + { String response = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", "http://localhost:3567/test", new JsonObject(), 1000, 1000, null, @@ -2966,10 +2979,9 @@ public void tenantNotFoundWithAppIdTest3() String[] args = {"../"}; Utils.setValueInConfig("host", "\"0.0.0.0\""); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/PluginTest.java b/src/test/java/io/supertokens/test/PluginTest.java index fd3b74f08..eedc7f2a5 100644 --- a/src/test/java/io/supertokens/test/PluginTest.java +++ b/src/test/java/io/supertokens/test/PluginTest.java @@ -72,7 +72,7 @@ public void missingPluginFolderTest() throws Exception { // delete plugin directory delete(new File(args[0] + "plugin")); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED); assertNotNull(e); @@ -102,7 +102,7 @@ public void emptyPluginFolderTest() throws Exception { // create empty plugin directory new File(args[0] + "plugin").mkdir(); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED); assertNotNull(e); @@ -138,7 +138,7 @@ public void doesNotContainPluginTest() throws Exception { delete(new File(args[0] + "plugin/" + pluginName)); } - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED); assertNotNull(e); @@ -215,7 +215,7 @@ private void delete(File toDelete) { // Process process1 = pb.start(); // process1.waitFor(); // -// TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); +// TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); // assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE)); // // process.kill(); diff --git a/src/test/java/io/supertokens/test/RequestStatsTest.java b/src/test/java/io/supertokens/test/RequestStatsTest.java index 7140a119e..2e282994a 100644 --- a/src/test/java/io/supertokens/test/RequestStatsTest.java +++ b/src/test/java/io/supertokens/test/RequestStatsTest.java @@ -47,6 +47,9 @@ public class RequestStatsTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -61,17 +64,14 @@ public void beforeEach() { public void testLastMinuteStats() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - // Wait for a minute to pass - Thread.sleep(60000 - (System.currentTimeMillis() % 60000) + 100); - - ExecutorService ex = Executors.newFixedThreadPool(100); + ExecutorService ex = Executors.newFixedThreadPool( StorageLayer.isInMemDb(process.getProcess()) ? 1 : 100); int numRequests = 1000; for (int i = 0; i < numRequests; i++) { int finalI = i; @@ -88,9 +88,6 @@ public void testLastMinuteStats() throws Exception { ex.shutdown(); ex.awaitTermination(45, TimeUnit.SECONDS); // should finish in 45 seconds - // Wait for a minute to pass - Thread.sleep(60000 - (System.currentTimeMillis() % 60000) + 100); - JsonObject stats = HttpRequestForTesting .sendGETRequest(process.getProcess(), "", "http://localhost:3567/requests/stats", null, 5000, 5000, null, Utils.getCdiVersionStringLatestForTests(), null); @@ -109,7 +106,7 @@ public void testLastMinuteStats() throws Exception { avg = e.getAsDouble(); } } - assertEquals(1439, count); + assertTrue(count >= 1438 && count <= 1440); count = 0; for (JsonElement e : peakRps) { @@ -119,7 +116,6 @@ public void testLastMinuteStats() throws Exception { assertTrue(e.getAsInt() > avg); } } - assertEquals(1439, count); assertEquals(System.currentTimeMillis() / 60000, stats.get("atMinute").getAsLong()); @@ -131,11 +127,10 @@ public void testLastMinuteStats() throws Exception { public void testLastMinuteStatsPerApp() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -151,10 +146,7 @@ public void testLastMinuteStatsPerApp() throws Exception { new JsonObject() ), false); - // Wait for a minute to pass - Thread.sleep(60000 - (System.currentTimeMillis() % 60000) + 100); - - ExecutorService ex = Executors.newFixedThreadPool(100); + ExecutorService ex = Executors.newFixedThreadPool(StorageLayer.isInMemDb(process.getProcess()) ? 1 : 100); int numRequests = 500; for (int i = 0; i < numRequests; i++) { int finalI = i; @@ -179,9 +171,6 @@ public void testLastMinuteStatsPerApp() throws Exception { ex.shutdown(); ex.awaitTermination(45, TimeUnit.SECONDS); // should finish in 45 seconds - // Wait for a minute to pass - Thread.sleep(60000 - (System.currentTimeMillis() % 60000) + 100); - { JsonObject stats = HttpRequestForTesting .sendGETRequest(process.getProcess(), "", "http://localhost:3567/requests/stats", null, 5000, @@ -201,7 +190,7 @@ public void testLastMinuteStatsPerApp() throws Exception { avg = e.getAsDouble(); } } - assertEquals(1439, count); + assertTrue(1438 <= count && count <= 1440); count = 0; for (JsonElement e : peakRps) { @@ -211,7 +200,7 @@ public void testLastMinuteStatsPerApp() throws Exception { assertTrue(e.getAsInt() > avg); } } - assertEquals(1439, count); + assertTrue(1438 <= count && count <= 1440); assertEquals(System.currentTimeMillis() / 60000, stats.get("atMinute").getAsLong()); } @@ -236,7 +225,7 @@ public void testLastMinuteStatsPerApp() throws Exception { avg = e.getAsDouble(); } } - assertEquals(1439, count); + assertTrue(1438 <= count && count <= 1440); count = 0; for (JsonElement e : peakRps) { @@ -246,7 +235,7 @@ public void testLastMinuteStatsPerApp() throws Exception { assertTrue(e.getAsInt() > avg); } } - assertEquals(1439, count); + assertTrue(1438 <= count && count <= 1440); assertEquals(System.currentTimeMillis() / 60000, stats.get("atMinute").getAsLong()); } @@ -259,11 +248,10 @@ public void testLastMinuteStatsPerApp() throws Exception { public void testWithNonExistantApp() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/ResourceDistributorTest.java b/src/test/java/io/supertokens/test/ResourceDistributorTest.java index 091f75683..314309371 100644 --- a/src/test/java/io/supertokens/test/ResourceDistributorTest.java +++ b/src/test/java/io/supertokens/test/ResourceDistributorTest.java @@ -50,6 +50,9 @@ public ResourceB() { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -64,10 +67,9 @@ public void beforeEach() { public void testClearAllResourcesWithKeyWorksCorrectly() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); AppIdentifier a1 = new AppIdentifier(null, "a1"); diff --git a/src/test/java/io/supertokens/test/SemVerTest.java b/src/test/java/io/supertokens/test/SemVerTest.java index 7a1f1168d..0a9ed2f20 100644 --- a/src/test/java/io/supertokens/test/SemVerTest.java +++ b/src/test/java/io/supertokens/test/SemVerTest.java @@ -27,6 +27,9 @@ public class SemVerTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/ShutdownTest.java b/src/test/java/io/supertokens/test/ShutdownTest.java index d2c5bc072..1d2bfdacb 100644 --- a/src/test/java/io/supertokens/test/ShutdownTest.java +++ b/src/test/java/io/supertokens/test/ShutdownTest.java @@ -32,6 +32,9 @@ public class ShutdownTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -46,7 +49,7 @@ public void beforeEach() { public void shutdownSignalTest() throws TestingProcessManagerException, InterruptedException { // TODO: make sure all processes like cron jobs and tomcat etc are shutdown - to do later... String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); EventAndException e = process.checkOrWaitForEvent(PROCESS_STATE.STARTED); assertNotNull(e); process.kill(); diff --git a/src/test/java/io/supertokens/test/StorageLayerTest.java b/src/test/java/io/supertokens/test/StorageLayerTest.java index d649cc7fb..03af2d1d5 100644 --- a/src/test/java/io/supertokens/test/StorageLayerTest.java +++ b/src/test/java/io/supertokens/test/StorageLayerTest.java @@ -30,6 +30,9 @@ public class StorageLayerTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -70,7 +73,7 @@ public static void insertUsedCodeUtil(TOTPSQLStorage storage, TOTPUsedCode usedC public void totpCodeLengthTest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess() .setForceInMemoryDB(); // this test is for SQLite. We have different versions for PSQL and MySQL process.startProcess(); diff --git a/src/test/java/io/supertokens/test/StorageTest.java b/src/test/java/io/supertokens/test/StorageTest.java index 6483de013..10ff114aa 100644 --- a/src/test/java/io/supertokens/test/StorageTest.java +++ b/src/test/java/io/supertokens/test/StorageTest.java @@ -56,6 +56,9 @@ public class StorageTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -72,7 +75,7 @@ public void beforeEach() { @Test public void transactionIsolationWithoutAnInitialRowTesting() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); for (int i = 0; i < 10; i++) { @@ -195,7 +198,7 @@ public void transactionIsolationWithoutAnInitialRowTesting() throws Exception { public void transactionIsolationWithAnInitialRowTesting() throws InterruptedException, StorageQueryException, StorageTransactionLogicException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); for (int i = 0; i < 100; i++) { @@ -304,7 +307,7 @@ public void transactionIsolationWithAnInitialRowTesting() public void transactionIsolationTesting() throws InterruptedException, StorageQueryException, StorageTransactionLogicException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); Storage storage = StorageLayer.getStorage(process.getProcess()); @@ -529,7 +532,7 @@ public void transactionIsolationTesting() @Test public void transactionTest() throws InterruptedException, StorageQueryException, StorageTransactionLogicException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); Storage storage = StorageLayer.getStorage(process.getProcess()); @@ -581,7 +584,7 @@ public void transactionTest() throws InterruptedException, StorageQueryException public void transactionDoNotCommitButStillCommitsTest() throws InterruptedException, StorageQueryException, StorageTransactionLogicException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); Storage storage = StorageLayer.getStorage(process.getProcess()); @@ -611,7 +614,7 @@ public void transactionDoNotCommitButStillCommitsTest() @Test public void transactionDoNotInsertIfAlreadyExistsForNoSQL() throws InterruptedException, StorageQueryException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); Storage storage = StorageLayer.getStorage(process.getProcess()); @@ -641,7 +644,7 @@ public void transactionDoNotInsertIfAlreadyExistsForNoSQL() throws InterruptedEx public void transactionThrowCompileTimeErrorAndExpectRollbackTest() throws InterruptedException, StorageQueryException, StorageTransactionLogicException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); Storage storage = StorageLayer.getStorage(process.getProcess()); @@ -678,7 +681,7 @@ public void transactionThrowCompileTimeErrorAndExpectRollbackTest() public void transactionThrowRunTimeErrorAndExpectRollbackTest() throws InterruptedException, StorageQueryException, StorageTransactionLogicException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); Storage storage = StorageLayer.getStorage(process.getProcess()); @@ -728,7 +731,7 @@ public void storageDeadAndAlive() throws InterruptedException, IOException, Http request.addProperty("enableAntiCsrf", false); request.addProperty("useStaticKey", false); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); Storage storage = StorageLayer.getStorage(process.getProcess()); @@ -782,7 +785,7 @@ public void storageDeadAndAlive() throws InterruptedException, IOException, Http public void multipleParallelTransactionTest() throws InterruptedException, IOException { String[] args = {"../"}; Utils.setValueInConfig("access_token_dynamic_signing_key_update_interval", "0.00005"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); int numberOfThreads = 1000; diff --git a/src/test/java/io/supertokens/test/SuperTokensSaaSSecretTest.java b/src/test/java/io/supertokens/test/SuperTokensSaaSSecretTest.java index f6ca82cc7..7b91f203d 100644 --- a/src/test/java/io/supertokens/test/SuperTokensSaaSSecretTest.java +++ b/src/test/java/io/supertokens/test/SuperTokensSaaSSecretTest.java @@ -56,6 +56,9 @@ public class SuperTokensSaaSSecretTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -75,7 +78,7 @@ public void testGetApiKeysDoesNotReturnNullWhenAPIKeyIsSet() throws Exception { "abctijenbogweg=-2438243u98-abctijenbocdsfcegweg=-2438243u98ef23c"); // set api_keys Utils.setValueInConfig("api_keys", "adslfkj398erchpsodihfp3w9q8ehcpioh"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String apiKey = Config.getConfig(process.getProcess()).getSuperTokensSaaSSecret(); @@ -91,7 +94,7 @@ public void testGetApiKeysDoesNotReturnNullWhenAPIKeyIsSet() throws Exception { public void testGetApiKeysReturnsNullWhenAPIKeyIsNotSet() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); assertNull(Config.getConfig(process.getProcess()).getSuperTokensSaaSSecret()); @@ -108,7 +111,7 @@ public void testErrorIsThrownWhenInvalidApiKeyIsSet() throws Exception { // api key length less that minimum length 20 Utils.setValueInConfig("supertokens_saas_secret", "abc"); // set api_keys - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException event = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(event); assertEquals(event.exception.getCause().getMessage(), @@ -123,7 +126,7 @@ public void testErrorIsThrownWhenInvalidApiKeyIsSet() throws Exception { Utils.setValueInConfig("supertokens_saas_secret", "abc"); // set api_keys Utils.setValueInConfig("api_keys", "adslfkj398erchpsodihfp3w9q8ehcpioh"); - process = TestingProcessManager.start(args); + process = TestingProcessManager.startIsolatedProcess(args); event = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(event); assertEquals(event.exception.getCause().getMessage(), @@ -138,7 +141,7 @@ public void testErrorIsThrownWhenInvalidApiKeyIsSet() throws Exception { Utils.setValueInConfig("supertokens_saas_secret", "abC&^0t4t3t40t4@#%greognradsfadsfiu3b8cuhbosjiadbfiiubio8"); // set api_keys Utils.setValueInConfig("api_keys", "adslfkj398erchpsodihfp3w9q8ehcpioh"); - process = TestingProcessManager.start(args); + process = TestingProcessManager.startIsolatedProcess(args); event = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(event); @@ -162,7 +165,7 @@ public void testSettingValidAndInvalidApiKeysAndErrorIsThrown() throws Exception Utils.setValueInConfig("supertokens_saas_secret", validKey + "," + invalidKey); Utils.setValueInConfig("api_keys", "adslfkj398erchpsodihfp3w9q8ehcpioh"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException event = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(event); assertEquals(event.exception.getCause().getMessage(), @@ -183,7 +186,7 @@ public void testCreatingSessionWithAndWithoutAPIKey() throws Exception { Utils.setValueInConfig("supertokens_saas_secret", apiKey); // set api_keys Utils.setValueInConfig("api_keys", "adslfkj398erchpsodihfp3w9q8ehcpioh"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -240,7 +243,7 @@ public void testSettingAPIKeyAndCallingConfigAndHelloWithoutIt() throws Exceptio Utils.setValueInConfig("supertokens_saas_secret", apiKey); // set supertokens_saas_secret Utils.setValueInConfig("api_keys", "adslfkj398erchpsodihfp3w9q8ehcpioh"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String response = HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", @@ -273,7 +276,7 @@ public void testCreatingSessionWithAndWithoutAPIKeyWhenSuperTokensSaaSSecretIsAl String apiKey = "hg40239oirjgBHD9450=Beew123--hg40239oir"; Utils.setValueInConfig("api_keys", apiKey); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -337,6 +340,8 @@ public void gettingTenantShouldNotExposeSuperTokensSaaSSecret() throws InterruptedException, IOException, InvalidConfigException, TenantOrAppNotFoundException, InvalidProviderConfigException, StorageQueryException, FeatureNotEnabledException, CannotModifyBaseConfigException, BadPermissionException { + HttpRequestForTesting.disableAddingAppId = true; + String[] args = {"../"}; String saasSecret = "hg40239oirjgBHD9450=Beew123--hg40239oirjgBHD9450=Beew123--hg40239oirjgBHD9450=Beew123-"; @@ -344,23 +349,22 @@ public void gettingTenantShouldNotExposeSuperTokensSaaSSecret() Utils.setValueInConfig("refresh_token_validity", "144001"); Utils.setValueInConfig("access_token_signing_key_dynamic", "false"); Utils.setValueInConfig("api_keys", "adslfkj398erchpsodihfp3w9q8ehcpioh"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - Multitenancy.addNewOrUpdateAppOrTenant(process.main, new TenantIdentifier(null, null, null), + Multitenancy.addNewOrUpdateAppOrTenant(process.getProcess(), new TenantIdentifier(null, null, null), new TenantConfig(new TenantIdentifier(null, null, "t1"), new EmailPasswordConfig(false), new ThirdPartyConfig(false, new ThirdPartyConfig.Provider[0]), new PasswordlessConfig(false), null, null, new JsonObject())); - TenantConfig[] tenantConfigs = Multitenancy.getAllTenants(process.main); + TenantConfig[] tenantConfigs = Multitenancy.getAllTenants(process.getProcess()); assertEquals(tenantConfigs.length, 2); assertEquals(tenantConfigs[0].tenantIdentifier, new TenantIdentifier(null, null, null)); @@ -378,15 +382,16 @@ public void testThatTenantCannotSetSuperTokensSaasSecret() throws InterruptedException, IOException, InvalidConfigException, TenantOrAppNotFoundException, InvalidProviderConfigException, StorageQueryException, FeatureNotEnabledException, CannotModifyBaseConfigException, BadPermissionException { + HttpRequestForTesting.disableAddingAppId = true; + String[] args = {"../"}; String saasSecret = "hg40239oirjgBHD9450=Beew123--hg40239oirjgBHD9450=Beew123--hg40239oirjgBHD9450=Beew123-"; Utils.setValueInConfig("supertokens_saas_secret", saasSecret); Utils.setValueInConfig("api_keys", "adslfkj398erchpsodihfp3w9q8ehcpioh"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -396,7 +401,7 @@ public void testThatTenantCannotSetSuperTokensSaasSecret() try { JsonObject j = new JsonObject(); j.addProperty("supertokens_saas_secret", saasSecret); - Multitenancy.addNewOrUpdateAppOrTenant(process.main, new TenantIdentifier(null, null, null), + Multitenancy.addNewOrUpdateAppOrTenant(process.getProcess(), new TenantIdentifier(null, null, null), new TenantConfig(new TenantIdentifier(null, null, "t1"), new EmailPasswordConfig(false), new ThirdPartyConfig(false, new ThirdPartyConfig.Provider[0]), new PasswordlessConfig(false), @@ -456,10 +461,9 @@ public void testThatTenantCannotSetProtectedConfigIfSuperTokensSaaSSecretIsSet() Utils.setValueInConfig("supertokens_saas_secret", saasSecret); String apiKey = "hg40239oirjgBHD9450=Beew123--hg40239oiBeew123-"; Utils.setValueInConfig("api_keys", apiKey); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.isInMemDb(process.getProcess())) { @@ -474,7 +478,7 @@ public void testThatTenantCannotSetProtectedConfigIfSuperTokensSaaSSecretIsSet() try { JsonObject j = new JsonObject(); j.addProperty(PROTECTED_CORE_CONFIG[i], ""); - Multitenancy.addNewOrUpdateAppOrTenant(process.main, + Multitenancy.addNewOrUpdateAppOrTenant(process.getProcess(), new TenantConfig(new TenantIdentifier(null, null, "t1"), new EmailPasswordConfig(false), new ThirdPartyConfig(false, new ThirdPartyConfig.Provider[0]), new PasswordlessConfig(false), @@ -533,16 +537,17 @@ public void testThatTenantCannotGetProtectedConfigIfSuperTokensSaaSSecretIsSet() throws InterruptedException, IOException, InvalidConfigException, TenantOrAppNotFoundException, InvalidProviderConfigException, StorageQueryException, FeatureNotEnabledException, CannotModifyBaseConfigException, BadPermissionException, HttpResponseException { + HttpRequestForTesting.disableAddingAppId = true; + String[] args = {"../"}; String saasSecret = "hg40239oirjgBHD9450=Beew123--hg40239oirjgBHD9450=Beew123--hg40239oirjgBHD9450=Beew123-"; Utils.setValueInConfig("supertokens_saas_secret", saasSecret); String apiKey = "hg40239oirjgBHD9450=Beew123--hg40239oiBeew123-"; Utils.setValueInConfig("api_keys", apiKey); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.isInMemDb(process.getProcess())) { @@ -562,7 +567,7 @@ public void testThatTenantCannotGetProtectedConfigIfSuperTokensSaaSSecretIsSet() } else if (PROTECTED_CORE_CONFIG_VALUES[i] instanceof Integer) { j.addProperty(PROTECTED_CORE_CONFIG[i], (Integer) PROTECTED_CORE_CONFIG_VALUES[i]); } - Multitenancy.addNewOrUpdateAppOrTenant(process.main, new TenantIdentifier(null, null, null), + Multitenancy.addNewOrUpdateAppOrTenant(process.getProcess(), new TenantIdentifier(null, null, null), new TenantConfig(new TenantIdentifier(null, "a" + i, null), new EmailPasswordConfig(false), new ThirdPartyConfig(false, new ThirdPartyConfig.Provider[0]), new PasswordlessConfig(false), @@ -626,16 +631,17 @@ public void testThatTenantCannotGetProtectedConfigIfSuperTokensSaaSSecretIsSet() @Test public void testLogContainsCorrectCud() throws Exception { + HttpRequestForTesting.disableAddingAppId = true; + String[] args = {"../"}; String saasSecret = "hg40239oirjgBHD9450=Beew123--hg40239oirjgBHD9450=Beew123--hg40239oirjgBHD9450=Beew123-"; Utils.setValueInConfig("supertokens_saas_secret", saasSecret); String apiKey = "hg40239oirjgBHD9450=Beew123--hg40239oiBeew123-"; Utils.setValueInConfig("api_keys", apiKey); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.isInMemDb(process.getProcess())) { diff --git a/src/test/java/io/supertokens/test/TelemetryAPITest2_7.java b/src/test/java/io/supertokens/test/TelemetryAPITest2_7.java index 863cc3a92..2098fa012 100644 --- a/src/test/java/io/supertokens/test/TelemetryAPITest2_7.java +++ b/src/test/java/io/supertokens/test/TelemetryAPITest2_7.java @@ -39,6 +39,9 @@ public class TelemetryAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -53,7 +56,7 @@ public void beforeEach() { public void testTelemetryDisabledInMemDb() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (!Version.getVersion(process.getProcess()).getPluginName().equals("sqlite")) { @@ -73,7 +76,7 @@ public void testTelemetryDisabledInMemDb() throws Exception { public void testDefaultTelemetry() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (Version.getVersion(process.getProcess()).getPluginName().equals("sqlite")) { @@ -95,7 +98,7 @@ public void testDisableTelemetry() throws Exception { Utils.setValueInConfig("disable_telemetry", "true"); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (Version.getVersion(process.getProcess()).getPluginName().equals("sqlite")) { @@ -116,7 +119,7 @@ public void testEnableTelemetry() throws Exception { Utils.setValueInConfig("disable_telemetry", "false"); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (Version.getVersion(process.getProcess()).getPluginName().equals("sqlite")) { diff --git a/src/test/java/io/supertokens/test/TelemetryTest.java b/src/test/java/io/supertokens/test/TelemetryTest.java index 73af36fac..1d73ff1e0 100644 --- a/src/test/java/io/supertokens/test/TelemetryTest.java +++ b/src/test/java/io/supertokens/test/TelemetryTest.java @@ -49,6 +49,9 @@ public class TelemetryTest extends Mockito { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -65,7 +68,7 @@ public void testThatDisablingTelemetryDoesNotSendOne() throws Exception { Utils.setValueInConfig("disable_telemetry", "true"); - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); assertNull(process.checkOrWaitForEvent(PROCESS_STATE.SENDING_TELEMETRY, 2000)); @@ -78,7 +81,7 @@ public void testThatDisablingTelemetryDoesNotSendOne() throws Exception { public void testThatTelemetryDoesNotSendOneIfInMemDb() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); if (!Version.getVersion(process.getProcess()).getPluginName().equals("sqlite")) { @@ -95,7 +98,7 @@ public void testThatTelemetryDoesNotSendOneIfInMemDb() throws Exception { public void testThatTelemetryDoesNotSendOneIfInMemDbButActualDBThere() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args, false); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); @@ -115,8 +118,7 @@ public void testThatTelemetryDoesNotSendOneIfInMemDbButActualDBThere() throws Ex public void testThatTelemetryWorks() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args, false); - process.startProcess(); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getBaseStorage(process.getProcess()).getType() == STORAGE_TYPE.SQL) { @@ -125,7 +127,7 @@ public void testThatTelemetryWorks() throws Exception { // Restarting the process to send telemetry again process.kill(false); - process = TestingProcessManager.start(args, false); + process = TestingProcessManager.startIsolatedProcess(args, false); ByteArrayOutputStream output = new ByteArrayOutputStream(); final HttpURLConnection mockCon = mock(HttpURLConnection.class); @@ -194,8 +196,7 @@ protected URLConnection openConnection(URL u) { public void testThatTelemetryWorksWithApiDomainAndWebsiteDomainSet() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args, false); - process.startProcess(); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getBaseStorage(process.getProcess()).getType() == STORAGE_TYPE.SQL) { @@ -207,7 +208,7 @@ public void testThatTelemetryWorksWithApiDomainAndWebsiteDomainSet() throws Exce // Restarting the process to send telemetry again process.kill(false); - process = TestingProcessManager.start(args, false); + process = TestingProcessManager.startIsolatedProcess(args, false); ByteArrayOutputStream output = new ByteArrayOutputStream(); final HttpURLConnection mockCon = mock(HttpURLConnection.class); @@ -280,7 +281,7 @@ public void testThatTelemetryIdDoesNotChange() throws Exception { { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args, false); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); ByteArrayOutputStream output = new ByteArrayOutputStream(); final HttpURLConnection mockCon = mock(HttpURLConnection.class); @@ -329,7 +330,7 @@ protected URLConnection openConnection(URL u) { { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args, false); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); ByteArrayOutputStream output = new ByteArrayOutputStream(); final HttpURLConnection mockCon = mock(HttpURLConnection.class); @@ -384,7 +385,7 @@ protected URLConnection openConnection(URL u) { public void testThatTelemetryWillNotGoIfTestingAndNoMockRequest() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (Version.getVersion(process.getProcess()).getPluginName().equals("sqlite")) { diff --git a/src/test/java/io/supertokens/test/TestHelloAPIRateLimiting.java b/src/test/java/io/supertokens/test/TestHelloAPIRateLimiting.java index 9c91a76d8..708022553 100644 --- a/src/test/java/io/supertokens/test/TestHelloAPIRateLimiting.java +++ b/src/test/java/io/supertokens/test/TestHelloAPIRateLimiting.java @@ -48,6 +48,9 @@ public class TestHelloAPIRateLimiting { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -150,7 +153,7 @@ private boolean callHello2(TenantIdentifier tenantIdentifier, Main main) public void testThatTheHelloAPIisRateLimited() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); process.startProcess(); @@ -182,7 +185,7 @@ public void testThatTheHelloAPIisRateLimited() throws Exception { public void testThatTheHelloAPIisRateLimitedPerApp() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); process.startProcess(); @@ -226,7 +229,7 @@ public void testThatTheHelloAPIisRateLimitedPerApp() throws Exception { public void testThatTheHelloAPIisRateLimited2() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); process.startProcess(); diff --git a/src/test/java/io/supertokens/test/TestServiceUtils.java b/src/test/java/io/supertokens/test/TestServiceUtils.java new file mode 100644 index 000000000..2be414893 --- /dev/null +++ b/src/test/java/io/supertokens/test/TestServiceUtils.java @@ -0,0 +1,255 @@ +/* + * Copyright (c) 2025, VRAI Labs and/or its affiliates. All rights reserved. + * + * This software is licensed under the Apache License, Version 2.0 (the + * "License") as published by the Apache Software Foundation. + * + * 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. + */ + +package io.supertokens.test; + +import java.io.IOException; +import java.util.Random; + +public class TestServiceUtils { + static { + Runtime.getRuntime().addShutdownHook(new Thread(() -> { + try { + killServices(); + } catch (Exception e) { + System.out.println(e.getMessage()); + } + })); + } + + public static void startServices() { + try { + OAuthProviderService.startService(); + PostgresqlService.startService(); + MysqlService.startService(); + MongodbService.startService(); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public static void killServices() throws InterruptedException, IOException { + OAuthProviderService.killService(); + PostgresqlService.killService(); + MysqlService.killService(); + MongodbService.killService(); + } + + private static class CmdHelper { + public static int runCommand(String[] command) throws InterruptedException, IOException { + ProcessBuilder processBuilder = new ProcessBuilder(); + processBuilder.command(command); + Process process = processBuilder.start(); + process.waitFor(); + return process.exitValue(); + } + } + + private static class PostgresqlService { + private static final String PG_SERVICE_NAME = "postgres_" + System.getProperty("org.gradle.test.worker", "base"); + + private static final int PG_DB_PORT = new Random().nextInt(5000) + 15000; + + static { + System.setProperty("ST_POSTGRESQL_PLUGIN_SERVER_PORT", "" + PG_DB_PORT); + } + + private static int runQuery(String query) throws InterruptedException, IOException { + System.out.println("Running query: " + query); + return CmdHelper.runCommand(new String[] { + "docker", "exec", PG_SERVICE_NAME, "psql", "-U", "root", "postgres", "-c", query + }); + } + + public static void startService() throws IOException, InterruptedException { + if (!System.getenv().containsKey("ST_PLUGIN_NAME") || System.getenv("ST_PLUGIN_NAME").equals("postgresql")) { + int exitCode = CmdHelper.runCommand(new String[] { + "docker", "run", "--rm", "--name", PG_SERVICE_NAME, + "-e", "POSTGRES_USER=root", + "-e", "POSTGRES_PASSWORD=root", + "-d", "-p", PG_DB_PORT + ":5432", + "postgres", + "-c", "max_connections=1000" + }); + + if (exitCode != 0) { + throw new RuntimeException("Failed to start PostgreSQL service"); + } + + for (int i = 0; i < 1000; i++) { + exitCode = CmdHelper.runCommand(new String[] { + "docker", "exec", PG_SERVICE_NAME, "pg_isready", "-U", "root" + }); + if (exitCode == 0) { + break; + } + Thread.sleep(200); + } + + while (runQuery("CREATE DATABASE supertokens;") != 0) { + Thread.sleep(200); + } + + for (int i = 0; i <= 10; i++) { + while (runQuery("CREATE DATABASE st" + i + ";") != 0) { + Thread.sleep(200); + } + } + } + } + + public static void killService() throws IOException, InterruptedException { + CmdHelper.runCommand(new String[] { + "docker", "stop", PG_SERVICE_NAME + }); + } + } + + private static class MysqlService { + private static final String MYSQL_SERVICE_NAME = "mysql_" + System.getProperty("org.gradle.test.worker", "base"); + private static final int MYSQL_DB_PORT = new Random().nextInt(5000) + 20000; + + static { + System.setProperty("ST_MYSQL_PLUGIN_SERVER_PORT", "" + MYSQL_DB_PORT); + } + + private static int runQuery(String query) throws InterruptedException, IOException { + System.out.println("Running query: " + query); + return CmdHelper.runCommand(new String[] { + "docker", "exec", MYSQL_SERVICE_NAME, "mysql", "-uroot", "-proot", "-e", query + }); + } + + public static void startService() throws IOException, InterruptedException { + if (!System.getenv().containsKey("ST_PLUGIN_NAME") || System.getenv("ST_PLUGIN_NAME").equals("mysql")) { + int exitCode = CmdHelper.runCommand(new String[] { + "docker", "run", "--rm", "--name", MYSQL_SERVICE_NAME, + "-e", "MYSQL_ROOT_PASSWORD=root", + "-d", "-p", MYSQL_DB_PORT + ":3306", + "mysql" + }); + + if (exitCode != 0) { + throw new RuntimeException("Failed to start MySQL service"); + } + + for (int i = 0; i < 1000; i++) { + exitCode = CmdHelper.runCommand(new String[] { + "docker", "exec", MYSQL_SERVICE_NAME, "mysqladmin", "ping", "-uroot", "-proot", "-h", "localhost" + }); + if (exitCode == 0) { + break; + } + Thread.sleep(200); + } + + while (runQuery("CREATE DATABASE supertokens;") != 0) { + Thread.sleep(200); + } + + for (int i = 0; i <= 10; i++) { + while (runQuery("CREATE DATABASE st" + i + ";") != 0) { + Thread.sleep(200); + } + } + } + } + + public static void killService() throws IOException, InterruptedException { + CmdHelper.runCommand(new String[] { + "docker", "stop", MYSQL_SERVICE_NAME + }); + } + } + + private static class MongodbService { + private static final String MONGODB_SERVICE_NAME = "mongodb_" + System.getProperty("org.gradle.test.worker", "base"); + private static final int MONGODB_PORT = new Random().nextInt(5000) + 30000; + + static { + System.setProperty("ST_MONGODB_PLUGIN_SERVER_PORT", "" + MONGODB_PORT); + } + + private static int runCommand(String command) throws InterruptedException, IOException { + System.out.println("Running command: " + command); + return CmdHelper.runCommand(new String[] { + "docker", "exec", MONGODB_SERVICE_NAME, "mongosh", "--eval", command + }); + } + + public static void startService() throws IOException, InterruptedException { + if (!System.getenv().containsKey("ST_PLUGIN_NAME") || System.getenv("ST_PLUGIN_NAME").equals("mongodb")) { + int exitCode = CmdHelper.runCommand(new String[] { + "docker", "run", "--rm", "--name", MONGODB_SERVICE_NAME, + "-d", "-p", MONGODB_PORT + ":27017", + "-e", "MONGO_INITDB_ROOT_USERNAME=root", + "-e", "MONGO_INITDB_ROOT_PASSWORD=root", + "mongo:latest" + }); + + if (exitCode != 0) { + throw new RuntimeException("Failed to start MongoDB service"); + } + + // Wait for MongoDB to be ready + for (int i = 0; i < 1000; i++) { + exitCode = CmdHelper.runCommand(new String[] { + "docker", "exec", MONGODB_SERVICE_NAME, "mongosh", "--eval", "db.version()" + }); + if (exitCode == 0) { + break; + } + Thread.sleep(200); + } + + // Create databases + while (runCommand("use supertokens") != 0) { + Thread.sleep(200); + } + } + } + + public static void killService() throws IOException, InterruptedException { + CmdHelper.runCommand(new String[] { + "docker", "stop", MONGODB_SERVICE_NAME + }); + } + } + + private static class OAuthProviderService { + private static final int SVC_PORT1 = new Random().nextInt(2500) * 2 + 25000; + private static final int SVC_PORT2 = SVC_PORT1 + 1; + private static final String SVC_NAME = "oauth-cicd-" + System.getProperty("org.gradle.test.worker", "base"); + + static { + System.setProperty("ST_OAUTH_PROVIDER_SERVICE_PORT", "" + SVC_PORT1); + System.setProperty("ST_OAUTH_PROVIDER_ADMIN_PORT", "" + SVC_PORT2); + } + + public static void startService() throws IOException, InterruptedException { + // docker run -p 4444:4444 -p 4445:4445 -d --rm --name hydra-cicd rishabhpoddar/oauth-server-cicd + CmdHelper.runCommand(new String[] { + "docker", "run", "-p", SVC_PORT1 + ":4444", "-p", SVC_PORT2 + ":4445", "-d", "--rm", "--name", SVC_NAME, "rishabhpoddar/oauth-server-cicd" + }); + } + + public static void killService() throws InterruptedException, IOException { + CmdHelper.runCommand(new String[] { + "docker", "stop", SVC_NAME + }); + } + } +} diff --git a/src/test/java/io/supertokens/test/TestingProcessManager.java b/src/test/java/io/supertokens/test/TestingProcessManager.java index e7943f438..1c204a32b 100644 --- a/src/test/java/io/supertokens/test/TestingProcessManager.java +++ b/src/test/java/io/supertokens/test/TestingProcessManager.java @@ -16,85 +16,318 @@ package io.supertokens.test; +import com.google.gson.JsonObject; import io.supertokens.Main; import io.supertokens.ProcessState; import io.supertokens.ProcessState.EventAndException; import io.supertokens.ProcessState.PROCESS_STATE; +import io.supertokens.ResourceDistributor; +import io.supertokens.multitenancy.Multitenancy; +import io.supertokens.pluginInterface.STORAGE_TYPE; +import io.supertokens.pluginInterface.exceptions.StorageQueryException; +import io.supertokens.pluginInterface.multitenancy.*; import io.supertokens.storageLayer.StorageLayer; +import io.supertokens.test.httpRequest.HttpRequestForTesting; -import java.util.ArrayList; +import java.util.*; import static org.junit.Assert.assertNotNull; public class TestingProcessManager { - private static final ArrayList alive = new ArrayList<>(); + static { + TestServiceUtils.startServices(); + } - static void deleteAllInformation() throws Exception { - System.out.println("----------DELETE ALL INFORMATION----------"); - String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); - process.checkOrWaitForEvent(PROCESS_STATE.STARTED); - process.main.deleteAllInformationForTesting(); - process.kill(); - System.out.println("----------DELETE ALL INFORMATION----------"); + private static final ArrayList isolatedProcesses = new ArrayList<>(); + + public static void killAll() throws InterruptedException { + killAllIsolatedProcesses(); + SharedProcess.end(); } - static void killAll() { - synchronized (alive) { - for (TestingProcess testingProcess : alive) { + static void killAllIsolatedProcesses() { + synchronized (isolatedProcesses) { + for (TestingProcess testingProcess : isolatedProcesses) { try { - testingProcess.kill(); + testingProcess.kill(true); + testingProcess.endProcess(); } catch (InterruptedException ignored) { } } - alive.clear(); + isolatedProcesses.clear(); } } - public static TestingProcess start(String[] args, boolean startProcess) throws InterruptedException { - final Object waitForInit = new Object(); - synchronized (alive) { - TestingProcess mainProcess = new TestingProcess(args) { + public static TestingProcess start(String[] args) throws InterruptedException { + killAllIsolatedProcesses(); + return SharedProcess.start(args); + } - @Override - public void run() { - try { + public static TestingProcess startIsolatedProcess(String[] args) throws InterruptedException { + return startIsolatedProcess(args, true); + } - this.main = new Main(); - synchronized (waitForInit) { - waitForInit.notifyAll(); - } + public static TestingProcess startIsolatedProcess(String[] args, boolean startProcess) throws InterruptedException { + SharedProcess.end(); - if (startProcess) { - this.getProcess().start(getArgs()); - } else { - synchronized (waitToStart) { - if (!waitToStartNotified) { - waitToStart.wait(); - } + return IsolatedProcess.start(args, startProcess); + } + + + public static interface TestingProcess { + public void startProcess(); + public void endProcess() throws InterruptedException; + public Main getProcess(); + + public void kill() throws InterruptedException; + public void kill(boolean removeData) throws InterruptedException; + + public TenantIdentifier getAppForTesting(); + + public EventAndException checkOrWaitForEvent(PROCESS_STATE state) throws InterruptedException; + public EventAndException checkOrWaitForEvent(PROCESS_STATE state, long timeToWaitMS) throws InterruptedException; + } + + public static int getFreePort() { + while (true) { + int randomPort = 10000 + (int)(Math.random() * (20000 - 10000)); + try { + java.net.Socket socket = new java.net.Socket("localhost", randomPort); + socket.close(); + Thread.sleep(100); + } catch (java.net.ConnectException e1) { + // confirm again + try { + Thread.sleep(new Random().nextInt(100)); + java.net.Socket socket = new java.net.Socket("localhost", randomPort); + socket.close(); + } catch (java.net.ConnectException e2) { + // Port is available + return randomPort; + } catch (Exception e3) { + throw new RuntimeException(e3); + } + + } catch (Exception e4) { + throw new RuntimeException(e4); + } + } + } + + public static abstract class SharedProcess extends Thread implements TestingProcess { + final Object waitToStart = new Object(); + private final String[] args; + public Main main; + boolean waitToStartNotified = false; + + private static SharedProcess instance = null; + TenantIdentifier appForTesting = TenantIdentifier.BASE_TENANT; + + public static TestingProcess start(String[] args) throws InterruptedException { + if (instance != null) { + ProcessState.getInstance(instance.getProcess()).clear(); + instance.createAppForTesting(); + ProcessState.getInstance(instance.getProcess()).addState(PROCESS_STATE.STARTED, null); + return instance; + } + + int port = getFreePort(); + + assert args.length == 1; + args = new String[]{args[0], "port="+port}; + HttpRequestForTesting.corePort = port; + + final Object waitForInit = new Object(); + synchronized (isolatedProcesses) { + instance = new SharedProcess(args) { + + @Override + public void run() { + try { + this.main = new Main(); + synchronized (waitForInit) { + waitForInit.notifyAll(); } + this.getProcess().start(getArgs()); + + } catch (Exception ignored) { } + } + }; + + synchronized (waitForInit) { + instance.start(); + waitForInit.wait(); + } + + EventAndException e = instance.checkOrWaitForEvents( + new PROCESS_STATE[]{ + PROCESS_STATE.STARTED, + PROCESS_STATE.INIT_FAILURE} + ); + + if (e != null && e.state == PROCESS_STATE.STARTED) { + instance.createAppForTesting(); + } + + return instance; + } + } + + public static void end() throws InterruptedException { + if (instance != null) { + instance.endProcess(); + } + instance = null; + } + + SharedProcess(String[] args) { + this.args = args; + } + + public void startProcess() { + synchronized (waitToStart) { + waitToStartNotified = true; + waitToStart.notify(); + } + } + + public Main getProcess() { + return main; + } + + String[] getArgs() { + return args; + } - } catch (Exception ignored) { + private void createAppForTesting() { + { + if (StorageLayer.getStorage(this.getProcess()).getType() != STORAGE_TYPE.SQL) { + try { + StorageLayer.getStorage(this.getProcess()).deleteAllInformation(); + } catch (StorageQueryException e) { + throw new RuntimeException(e); + } + return; + } + TenantConfig[] allTenants = Multitenancy.getAllTenants(getProcess()); + try { + for (TenantConfig tenantConfig : allTenants) { + if (!tenantConfig.tenantIdentifier.getTenantId().equals(TenantIdentifier.DEFAULT_TENANT_ID)) { + Multitenancy.deleteTenant(tenantConfig.tenantIdentifier, getProcess()); + } + } + for (TenantConfig tenantConfig : allTenants) { + if (!tenantConfig.tenantIdentifier.getAppId().equals(TenantIdentifier.DEFAULT_APP_ID)) { + Multitenancy.deleteApp(tenantConfig.tenantIdentifier.toAppIdentifier(), getProcess()); + } } + for (TenantConfig tenantConfig : allTenants) { + if (!tenantConfig.tenantIdentifier.getConnectionUriDomain().equals(TenantIdentifier.DEFAULT_CONNECTION_URI)) { + Multitenancy.deleteConnectionUriDomain(tenantConfig.tenantIdentifier.getConnectionUriDomain(), getProcess()); + } + } + } catch (Exception e) { + throw new RuntimeException(e); } - }; - synchronized (waitForInit) { - mainProcess.start(); - waitForInit.wait(); } - alive.add(mainProcess); - return mainProcess; + + // Create a new app and use that for testing + String appId = UUID.randomUUID().toString(); + + try { + Multitenancy.addNewOrUpdateAppOrTenant(this.getProcess(), new TenantConfig( + new TenantIdentifier(null, appId, null), + new EmailPasswordConfig(true), + new ThirdPartyConfig(true, null), + new PasswordlessConfig(true), + null, null, new JsonObject() + ), false); + } catch (Exception e) { + throw new RuntimeException(e); + } + + this.setAppForTesting(new TenantIdentifier(null, appId, null)); + ResourceDistributor.setAppForTesting(new TenantIdentifier(null, appId, null)); } - } - public static TestingProcess start(String[] args) throws InterruptedException { - return start(args, true); + public void setAppForTesting(TenantIdentifier tenantIdentifier) { + appForTesting = tenantIdentifier; + } + + public TenantIdentifier getAppForTesting() { + return appForTesting; + } + + public void kill() throws InterruptedException { + kill(true); + } + + public void kill(boolean removeAllInfo) throws InterruptedException { + assert removeAllInfo; + ProcessState.getInstance(main).addState(PROCESS_STATE.STOPPED, null); + } + + public void endProcess() throws InterruptedException { + try { + main.deleteAllInformationForTesting(); + } catch (Exception e) { + if (!e.getMessage().contains("Please call initPool before getConnection")) { + // we ignore this type of message because it's due to tests in which the init failed + // and here we try and delete assuming that init had succeeded. + throw new RuntimeException(e); + } + } + main.killForTestingAndWaitForShutdown(); + instance = null; + } + + public EventAndException checkOrWaitForEvent(PROCESS_STATE state) throws InterruptedException { + return checkOrWaitForEvent(state, 15000); + } + + public EventAndException checkOrWaitForEvent(PROCESS_STATE state, long timeToWaitMS) + throws InterruptedException { + EventAndException e = ProcessState.getInstance(main).getLastEventByName(state); + if (e == null) { + // we shall now wait until some time as passed. + final long startTime = System.currentTimeMillis(); + while (e == null && (System.currentTimeMillis() - startTime) < timeToWaitMS) { + Thread.sleep(100); + e = ProcessState.getInstance(main).getLastEventByName(state); + } + } + return e; + } + + public EventAndException checkOrWaitForEvents(PROCESS_STATE[] states) + throws InterruptedException { + return checkOrWaitForEvents(states, 15000); + } + + public EventAndException checkOrWaitForEvents(PROCESS_STATE[] states, long timeToWaitMS) + throws InterruptedException { + + // we shall now wait until some time as passed. + final long startTime = System.currentTimeMillis(); + while ((System.currentTimeMillis() - startTime) < timeToWaitMS) { + for (PROCESS_STATE state : states) { + EventAndException e = ProcessState.getInstance(main).getLastEventByName(state); + + if (e != null) { + return e; + } + } + + Thread.sleep(100); + } + return null; + } } - public static abstract class TestingProcess extends Thread { + public static abstract class IsolatedProcess extends Thread implements TestingProcess { final Object waitToStart = new Object(); private final String[] args; @@ -102,7 +335,57 @@ public static abstract class TestingProcess extends Thread { boolean waitToStartNotified = false; private boolean killed = false; - TestingProcess(String[] args) { + public static TestingProcess start(String[] args) throws InterruptedException { + return start(args, true); + } + + public static TestingProcess start(String[] args, boolean startProcess) throws InterruptedException { + if (args.length == 1) { + int port = getFreePort(); + + args = new String[]{args[0], "port="+port}; + HttpRequestForTesting.corePort = port; + } + + final Object waitForInit = new Object(); + synchronized (isolatedProcesses) { + IsolatedProcess mainProcess = new IsolatedProcess(args) { + @Override + public void run() { + try { + + this.main = new Main(); + synchronized (waitForInit) { + waitForInit.notifyAll(); + } + + if (startProcess) { + this.getProcess().start(getArgs()); + } else { + synchronized (waitToStart) { + if (!waitToStartNotified) { + waitToStart.wait(); + } + } + this.getProcess().start(getArgs()); + } + + } catch (Exception ignored) { + } + } + }; + + synchronized (waitForInit) { + mainProcess.start(); + waitForInit.wait(); + } + isolatedProcesses.add(mainProcess); + + return mainProcess; + } + } + + IsolatedProcess(String[] args) { this.args = args; } @@ -117,6 +400,10 @@ public Main getProcess() { return main; } + public void endProcess() { + // no-op + } + String[] getArgs() { return args; } @@ -129,29 +416,18 @@ public void kill(boolean removeAllInfo) throws InterruptedException { if (killed) { return; } + if (removeAllInfo) { try { main.deleteAllInformationForTesting(); } catch (Exception e) { - if (!e.getMessage().contains("Please call initPool before getConnection")) { - // we ignore this type of message because it's due to tests in which the init failed - // and here we try and delete assuming that init had succeeded. - throw new RuntimeException(e); - } + // ignore } } main.killForTestingAndWaitForShutdown(); killed = true; } - public void killWithoutDeletingData() throws InterruptedException { - if (killed) { - return; - } - main.killForTestingAndWaitForShutdown(); - killed = true; - } - public EventAndException checkOrWaitForEvent(PROCESS_STATE state) throws InterruptedException { return checkOrWaitForEvent(state, 15000); } @@ -169,12 +445,40 @@ public EventAndException checkOrWaitForEvent(PROCESS_STATE state, long timeToWai } return e; } + + public EventAndException checkOrWaitForEvents(PROCESS_STATE[] states) + throws InterruptedException { + return checkOrWaitForEvents(states, 15000); + } + + public EventAndException checkOrWaitForEvents(PROCESS_STATE[] states, long timeToWaitMS) + throws InterruptedException { + + // we shall now wait until some time as passed. + final long startTime = System.currentTimeMillis(); + while ((System.currentTimeMillis() - startTime) < timeToWaitMS) { + for (PROCESS_STATE state : states) { + EventAndException e = ProcessState.getInstance(main).getLastEventByName(state); + + if (e != null) { + return e; + } + } + + Thread.sleep(100); + } + return null; + } + + public TenantIdentifier getAppForTesting() { + return TenantIdentifier.BASE_TENANT; + } } /** * Utility function to wrap tests with, as they require TestingProcess */ - public static void withProcess(ProcessConsumer consumer) throws Exception { + public static void withSharedProcess(ProcessConsumer consumer) throws Exception { String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); diff --git a/src/test/java/io/supertokens/test/Utils.java b/src/test/java/io/supertokens/test/Utils.java index fd8a83fc8..0d953dfad 100644 --- a/src/test/java/io/supertokens/test/Utils.java +++ b/src/test/java/io/supertokens/test/Utils.java @@ -19,8 +19,11 @@ import com.google.gson.JsonArray; import com.google.gson.JsonObject; import io.supertokens.Main; +import io.supertokens.ResourceDistributor; import io.supertokens.config.CoreConfig; +import io.supertokens.emailpassword.PasswordHashing; import io.supertokens.pluginInterface.PluginInterfaceTesting; +import io.supertokens.pluginInterface.multitenancy.TenantIdentifier; import io.supertokens.pluginInterface.useridmapping.UserIdMapping; import io.supertokens.storageLayer.StorageLayer; import io.supertokens.test.httpRequest.HttpRequestForTesting; @@ -32,6 +35,7 @@ import org.junit.rules.TestRule; import org.junit.rules.TestWatcher; import org.junit.runner.Description; +import org.junit.runners.model.Statement; import org.mockito.Mockito; import java.io.*; @@ -41,6 +45,7 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; +import java.util.Random; import static org.junit.Assert.*; @@ -49,11 +54,16 @@ public abstract class Utils extends Mockito { private static ByteArrayOutputStream byteArrayOutputStream; public static void afterTesting() { + TestingProcessManager.killAllIsolatedProcesses(); + + String startedDir = ".started" + System.getProperty("org.gradle.test.worker", ""); + String installDir = "../"; try { // remove config.yaml file - ProcessBuilder pb = new ProcessBuilder("rm", "config.yaml"); + String workerId = System.getProperty("org.gradle.test.worker", ""); + ProcessBuilder pb = new ProcessBuilder("rm", "config" + workerId + ".yaml"); pb.directory(new File(installDir)); Process process = pb.start(); process.waitFor(); @@ -66,7 +76,7 @@ public static void afterTesting() { } // remove .started folders created by processes - final File dotStartedFolder = new File(installDir + ".started"); + final File dotStartedFolder = new File(installDir + startedDir); try { FileUtils.deleteDirectory(dotStartedFolder); } catch (Exception ignored) { @@ -82,17 +92,24 @@ public static String getCdiVersionStringLatestForTests() { } public static void reset() { + TestingProcessManager.killAllIsolatedProcesses(); + Main.isTesting = true; Main.isTesting_skipBulkImportUserValidationInCronJob = false; PluginInterfaceTesting.isTesting = true; Main.makeConsolePrintSilent = true; + HttpRequestForTesting.disableAddingAppId = false; String installDir = "../"; CoreConfig.setDisableOAuthValidationForTest(false); + ResourceDistributor.setAppForTesting(TenantIdentifier.BASE_TENANT); + PasswordHashing.bypassHashCachingInTesting = false; + try { // if the default config is not the same as the current config, we must reset the storage layer File ogConfig = new File("../temp/config.yaml"); - File currentConfig = new File("../config.yaml"); + String workerId = System.getProperty("org.gradle.test.worker", ""); + File currentConfig = new File("../config" + workerId + ".yaml"); if (currentConfig.isFile()) { byte[] ogConfigContent = Files.readAllBytes(ogConfig.toPath()); byte[] currentConfigContent = Files.readAllBytes(currentConfig.toPath()); @@ -101,7 +118,7 @@ public static void reset() { } } - ProcessBuilder pb = new ProcessBuilder("cp", "temp/config.yaml", "./config.yaml"); + ProcessBuilder pb = new ProcessBuilder("cp", "temp/config.yaml", "./config" + workerId + ".yaml"); pb.directory(new File(installDir)); Process process = pb.start(); process.waitFor(); @@ -110,10 +127,6 @@ public static void reset() { // mimics production. Refer to https://github.com/supertokens/supertokens-core/issues/118 commentConfigValue("disable_telemetry"); - TestingProcessManager.killAll(); - TestingProcessManager.deleteAllInformation(); - TestingProcessManager.killAll(); - byteArrayOutputStream = new ByteArrayOutputStream(); System.setErr(new PrintStream(byteArrayOutputStream)); } catch (Exception e) { @@ -130,14 +143,16 @@ static void commentConfigValue(String key) throws IOException { String newStr = "\n# " + key + ":"; StringBuilder originalFileContent = new StringBuilder(); - try (BufferedReader reader = new BufferedReader(new FileReader("../config.yaml"))) { + String workerId = System.getProperty("org.gradle.test.worker", ""); + + try (BufferedReader reader = new BufferedReader(new FileReader("../config" + workerId + ".yaml"))) { String currentReadingLine = reader.readLine(); while (currentReadingLine != null) { originalFileContent.append(currentReadingLine).append(System.lineSeparator()); currentReadingLine = reader.readLine(); } String modifiedFileContent = originalFileContent.toString().replaceAll(oldStr, newStr); - try (BufferedWriter writer = new BufferedWriter(new FileWriter("../config.yaml"))) { + try (BufferedWriter writer = new BufferedWriter(new FileWriter("../config" + workerId + ".yaml"))) { writer.write(modifiedFileContent); } } @@ -151,14 +166,15 @@ public static void setValueInConfig(String key, String value) throws IOException String oldStr = "\n((#\\s)?)" + key + "(:|((:\\s).+))\n"; String newStr = "\n" + key + ": " + value + "\n"; StringBuilder originalFileContent = new StringBuilder(); - try (BufferedReader reader = new BufferedReader(new FileReader("../config.yaml"))) { + String workerId = System.getProperty("org.gradle.test.worker", ""); + try (BufferedReader reader = new BufferedReader(new FileReader("../config" + workerId + ".yaml"))) { String currentReadingLine = reader.readLine(); while (currentReadingLine != null) { originalFileContent.append(currentReadingLine).append(System.lineSeparator()); currentReadingLine = reader.readLine(); } String modifiedFileContent = originalFileContent.toString().replaceAll(oldStr, newStr); - try (BufferedWriter writer = new BufferedWriter(new FileWriter("../config.yaml"))) { + try (BufferedWriter writer = new BufferedWriter(new FileWriter("../config" + workerId + ".yaml"))) { writer.write(modifiedFileContent); } } @@ -173,6 +189,42 @@ protected void failed(Throwable e, Description description) { }; } + public static TestRule retryFlakyTest() { + return new TestRule() { + private final int retryCount = 10; + + public Statement apply(Statement base, Description description) { + return statement(base, description); + } + + private Statement statement(final Statement base, final Description description) { + return new Statement() { + @Override + public void evaluate() throws Throwable { + Throwable caughtThrowable = null; + + // implement retry logic here + for (int i = 0; i < retryCount; i++) { + try { + base.evaluate(); + return; + } catch (Throwable t) { + caughtThrowable = t; + System.err.println(description.getDisplayName() + ": run " + (i+1) + " failed"); + TestingProcessManager.killAll(); + TestServiceUtils.killServices(); + TestServiceUtils.startServices(); + Thread.sleep(1000 + new Random().nextInt(3000)); + } + } + System.err.println(description.getDisplayName() + ": giving up after " + retryCount + " failures"); + throw caughtThrowable; + } + }; + } + }; + } + public static JsonObject signUpRequest_2_4(TestingProcessManager.TestingProcess process, String email, String password) throws IOException, HttpResponseException { @@ -286,4 +338,20 @@ public static java.util.Map splitQueryString(String query) throw } return queryParams; } + + public static void testFlaky(TestFunction test) throws Exception { + for (int i = 0; i < 5; i++) { + try { + test.run(); + return; + } catch (Exception e) { + // retry + } + } + } + + @FunctionalInterface + public interface TestFunction { + void run() throws Exception; + } } diff --git a/src/test/java/io/supertokens/test/UtilsTest.java b/src/test/java/io/supertokens/test/UtilsTest.java index 707c4e792..08cd2ed3f 100644 --- a/src/test/java/io/supertokens/test/UtilsTest.java +++ b/src/test/java/io/supertokens/test/UtilsTest.java @@ -30,6 +30,9 @@ public class UtilsTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/VersionTest.java b/src/test/java/io/supertokens/test/VersionTest.java index 95b6b303f..f87f8ef05 100644 --- a/src/test/java/io/supertokens/test/VersionTest.java +++ b/src/test/java/io/supertokens/test/VersionTest.java @@ -37,6 +37,9 @@ public class VersionTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -50,7 +53,7 @@ public void beforeEach() { @Test public void simpleLoadingOfVersionTest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); @@ -86,13 +89,18 @@ public void versionFileMissingTest() throws Exception { process1.waitFor(); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); assertEquals(e.exception.getMessage(), "java.io.FileNotFoundException: ../version.yaml (No such file or directory)"); + pb = new ProcessBuilder("cp", "temp/version.yaml", "./version.yaml"); + pb.directory(new File(installDir)); + process1 = pb.start(); + process1.waitFor(); + process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); diff --git a/src/test/java/io/supertokens/test/WebserverTest.java b/src/test/java/io/supertokens/test/WebserverTest.java index d87ee1e2a..9e1ea4eeb 100644 --- a/src/test/java/io/supertokens/test/WebserverTest.java +++ b/src/test/java/io/supertokens/test/WebserverTest.java @@ -35,7 +35,6 @@ import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import org.apache.catalina.startup.Tomcat; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; @@ -49,7 +48,6 @@ import java.net.InetAddress; import java.net.SocketTimeoutException; import java.util.HashMap; -import java.util.stream.Collectors; import static org.junit.Assert.*; @@ -69,6 +67,9 @@ public class WebserverTest extends Mockito { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -85,7 +86,7 @@ public void beforeEach() { public void testInitializeTwoRoutesAndCheckRouting() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); String recipe_1 = "Recipe1"; String recipe_2 = "Recipe2"; @@ -180,7 +181,7 @@ public void testInitializeTwoRoutesAndCheckRouting() throws Exception { public void testRecipeRouterWhereSubRoutesHaveDifferentPaths() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); String recipe_1 = "Recipe1"; String recipe_2 = "Recipe2"; @@ -217,7 +218,7 @@ public String getPath() { public void testVersionSupport() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { @@ -265,7 +266,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) public void testNoVersionGiven() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { @@ -292,7 +293,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) public void testInvalidJSONBadInput() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { @@ -313,7 +314,7 @@ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOEx }); try { - HttpRequest.sendJsonPOSTRequest(process.getProcess(), "", "http://localhost:3567/testJsonInput", null, 1000, + HttpRequest.sendJsonPOSTRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/testJsonInput", null, 1000, 1000, null); fail(); } catch (HttpResponseException e) { @@ -329,7 +330,7 @@ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOEx public void testValidJsonInput() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { @@ -350,7 +351,7 @@ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOEx }); String response = HttpRequest.sendJsonPOSTRequest(process.getProcess(), "", - "http://localhost:3567/validJsonInput", new JsonObject(), 1000, 1000, null); + "http://localhost:" + HttpRequestForTesting.corePort + "/validJsonInput", new JsonObject(), 1000, 1000, null); assertEquals(response, "validJsonBody"); process.kill(); @@ -362,7 +363,7 @@ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOEx public void testInvalidGetInput() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { @@ -384,7 +385,7 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOExc // null in parameter field try { - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/invalidGetInput", null, 1000, + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/invalidGetInput", null, 1000, 1000, null); fail(); } catch (HttpResponseException e) { @@ -398,7 +399,7 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOExc map.put("keyy", "value"); try { - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/invalidGetInput", map, 1000, + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/invalidGetInput", map, 1000, 1000, null); fail(); } catch (HttpResponseException e) { @@ -415,7 +416,7 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOExc public void testValidGetInput() throws Exception { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { @@ -435,7 +436,7 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOExc }); HashMap map = new HashMap<>(); map.put("key", "value"); - String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/validInput", map, + String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/validInput", map, 1000, 1000, null); assertEquals(response, "validGetInput"); @@ -445,17 +446,18 @@ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOExc @Test public void serverHello() throws InterruptedException, IOException, HttpResponseException { - hello("localhost", "3567"); + hello("localhost", "" + TestingProcessManager.getFreePort()); } @Test public void serverHelloWithoutDB() throws Exception { - String hostName = "localhost"; - String port = "3567"; String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); + String hostName = "localhost"; + String port = "" + HttpRequestForTesting.corePort; + StorageLayer.getStorage(process.getProcess()).setStorageLayerEnabled(false); try { @@ -496,9 +498,11 @@ public void serverHelloWithoutDB() throws Exception { private void hello(String hostName, String port) throws InterruptedException, IOException, HttpResponseException { { - String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + String[] args = {"../", "port="+port}; + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); + HttpRequestForTesting.corePort = Integer.parseInt(port); + try { String response = HttpRequest.sendGETRequest(process.getProcess(), "", @@ -528,8 +532,8 @@ private void hello(String hostName, String port) throws InterruptedException, IO } { - String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + String[] args = {"../", "port="+port}; + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); try { @@ -560,7 +564,7 @@ private void hello(String hostName, String port) throws InterruptedException, IO @Test public void serverQuitProgramException() throws InterruptedException, IOException { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { @@ -578,7 +582,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) { } }); try { - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/testforexception", null, 1000, + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/testforexception", null, 1000, 1000, null); } catch (HttpResponseException e) { assertTrue(e.statusCode == 500 @@ -591,11 +595,11 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) { @Test public void samePortTwoServersError() throws InterruptedException { - String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + String[] args = {"../", "port="+"12432"}; + TestingProcess process = TestingProcessManager.startIsolatedProcess(args, true); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); - TestingProcess process2 = TestingProcessManager.start(args); + TestingProcess process2 = TestingProcessManager.startIsolatedProcess(args, true); EventAndException e = process2.checkOrWaitForEvent(PROCESS_STATE.INIT_FAILURE); assertTrue(e != null && e.exception instanceof QuitProgramException && e.exception.getMessage().equals( "Error while starting webserver. Possible reasons:\n- Another instance of SuperTokens is already " @@ -619,14 +623,14 @@ public void differentHostNameTest() throws InterruptedException, IOException, Ht InetAddress inetAddress = InetAddress.getLocalHost(); if (!inetAddress.getHostAddress().equals("127.0.0.1")) { Utils.setValueInConfig("host", "\"" + inetAddress.getHostAddress() + "\""); - hello(inetAddress.getHostAddress(), "3567"); + hello(inetAddress.getHostAddress(), "" + TestingProcessManager.getFreePort()); try { - hello("localhost", "3567"); + hello("localhost", "" + TestingProcessManager.getFreePort()); fail(); } catch (ConnectException ignored) { } try { - hello("127.0.0.1", "3567"); + hello("127.0.0.1", "" + TestingProcessManager.getFreePort()); fail(); } catch (ConnectException ignored) { } @@ -635,10 +639,10 @@ public void differentHostNameTest() throws InterruptedException, IOException, Ht } Utils.setValueInConfig("host", "\"localhost\""); - hello("localhost", "3567"); - hello("127.0.0.1", "3567"); + hello("localhost", "" + TestingProcessManager.getFreePort()); + hello("127.0.0.1", "" + TestingProcessManager.getFreePort()); try { - hello(inetAddress.getHostAddress(), "3567"); + hello(inetAddress.getHostAddress(), "" + TestingProcessManager.getFreePort()); if (!inetAddress.getHostAddress().equals("127.0.0.1")) { fail(); } @@ -648,10 +652,10 @@ public void differentHostNameTest() throws InterruptedException, IOException, Ht Utils.reset(); Utils.setValueInConfig("host", "\"127.0.0.1\""); - hello("localhost", "3567"); - hello("127.0.0.1", "3567"); + hello("localhost", "" + TestingProcessManager.getFreePort()); + hello("127.0.0.1", "" + TestingProcessManager.getFreePort()); try { - hello(inetAddress.getHostAddress(), "3567"); + hello(inetAddress.getHostAddress(), "" + TestingProcessManager.getFreePort()); if (!inetAddress.getHostAddress().equals("127.0.0.1")) { fail(); } @@ -661,15 +665,15 @@ public void differentHostNameTest() throws InterruptedException, IOException, Ht Utils.reset(); Utils.setValueInConfig("host", "\"0.0.0.0\""); - hello("localhost", "3567"); - hello("127.0.0.1", "3567"); - hello(inetAddress.getHostAddress(), "3567"); + hello("localhost", "" + TestingProcessManager.getFreePort()); + hello("127.0.0.1", "" + TestingProcessManager.getFreePort()); + hello(inetAddress.getHostAddress(), "" + TestingProcessManager.getFreePort()); Utils.reset(); Utils.setValueInConfig("host", "\"182.168.29.69\""); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); EventAndException e = process.checkOrWaitForEvent(PROCESS_STATE.INIT_FAILURE); assertTrue(e != null && e.exception instanceof QuitProgramException && e.exception.getMessage().equals( "Error while starting webserver. Possible reasons:\n- Another instance of SuperTokens is already " @@ -682,23 +686,12 @@ public void differentHostNameTest() throws InterruptedException, IOException, Ht assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STOPPED)); } - @Test - public void differentPorts() throws InterruptedException, IOException, HttpResponseException { - Utils.setValueInConfig("port", "8081"); - hello("localhost", "8081"); - try { - hello("localhost", "3567"); - fail(); - } catch (ConnectException ignored) { - } - } - @Test public void serverThreadPoolSizeOne() throws InterruptedException, IOException { Utils.setValueInConfig("max_server_pool_size", "1"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { @@ -745,7 +738,7 @@ public void serverThreadPoolSizeTwo() throws InterruptedException, IOException { Utils.setValueInConfig("max_server_pool_size", "2"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { @@ -789,7 +782,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO @Test public void notFoundTest() throws InterruptedException, IOException { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { @@ -807,7 +800,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO } }); try { - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/randomPath", null, 1000, 1000, + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/randomPath", null, 1000, 1000, null); } catch (HttpResponseException e) { assertTrue( @@ -815,7 +808,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO } try { - HttpRequest.sendJsonPOSTRequest(process.getProcess(), "", "http://localhost:3567/notfoundmethodtest", null, + HttpRequest.sendJsonPOSTRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/notfoundmethodtest", null, 1000, 1000, null); } catch (HttpResponseException e) { assertTrue(e.statusCode == 405 @@ -849,15 +842,15 @@ public void invalidBasePathTest() throws InterruptedException, IOException { for (String base_path : tests.keySet()) { String result = tests.get(base_path); Utils.setValueInConfig("base_path", base_path); - process = TestingProcessManager.start(args); + process = TestingProcessManager.startIsolatedProcess(args); e = process.checkOrWaitForEvent(PROCESS_STATE.STARTED); - assertEquals(result, Config.getConfig(process.main).getBasePath()); + assertEquals(result, Config.getConfig(process.getProcess()).getBasePath()); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } Utils.setValueInConfig("base_path", "/some path"); - process = TestingProcessManager.start(args); + process = TestingProcessManager.startIsolatedProcess(args); e = process.checkOrWaitForEvent(PROCESS_STATE.INIT_FAILURE); assertTrue(e != null && e.exception instanceof QuitProgramException && e.exception.getCause().getMessage().equals("Invalid characters in base_path config")); @@ -869,10 +862,10 @@ public void validBasePath() throws InterruptedException, IOException, HttpRespon { Utils.setValueInConfig("base_path", "/"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); - String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/hello", null, + String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/hello", null, 1000, 1000, null); assertEquals("Hello", response); @@ -884,10 +877,10 @@ public void validBasePath() throws InterruptedException, IOException, HttpRespon { Utils.setValueInConfig("base_path", "\"\""); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); - String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/hello", null, + String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/hello", null, 1000, 1000, null); assertEquals("Hello", response); @@ -899,10 +892,10 @@ public void validBasePath() throws InterruptedException, IOException, HttpRespon { Utils.setValueInConfig("base_path", "\"/test\""); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); - String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/test/hello", + String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/test/hello", null, 1000, 1000, null); assertEquals("Hello", response); @@ -914,11 +907,11 @@ public void validBasePath() throws InterruptedException, IOException, HttpRespon { Utils.setValueInConfig("base_path", "\"/test/path\""); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); String response = HttpRequest.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/test/path/hello", null, 1000, 1000, null); + "http://localhost:" + HttpRequestForTesting.corePort + "/test/path/hello", null, 1000, 1000, null); assertEquals("Hello", response); process.kill(); @@ -928,17 +921,17 @@ public void validBasePath() throws InterruptedException, IOException, HttpRespon { Utils.setValueInConfig("base_path", "\"/te3st/Pa23th\""); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); { String response = HttpRequest.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/te3st/Pa23th/hello", null, 1000, 1000, null); + "http://localhost:" + HttpRequestForTesting.corePort + "/te3st/Pa23th/hello", null, 1000, 1000, null); assertEquals("Hello", response); } try { - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/hello", null, 1000, 1000, + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/hello", null, 1000, 1000, null); fail(); } catch (Exception e) { @@ -952,10 +945,10 @@ public void validBasePath() throws InterruptedException, IOException, HttpRespon { Utils.setValueInConfig("base_path", ""); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); - String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/hello", null, + String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/hello", null, 1000, 1000, null); assertEquals("Hello", response); @@ -969,7 +962,7 @@ public void validBasePath() throws InterruptedException, IOException, HttpRespon public void tempDirLocationWebserverStarts() throws InterruptedException, HttpResponseException, IOException { String tempDirLocation = new File("../tempDir/").getCanonicalPath(); String[] args = {"../", "tempDirLocation=" + tempDirLocation}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); Webserver.TomcatReference reference = Webserver.getInstance(process.getProcess()).getTomcatReference(); @@ -989,10 +982,10 @@ public void validBasePathWithEmptyHelloPath() throws InterruptedException, IOExc { Utils.setValueInConfig("base_path", "/"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); - String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/", null, + String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/", null, 1000, 1000, null); assertEquals("Hello", response); @@ -1004,10 +997,10 @@ public void validBasePathWithEmptyHelloPath() throws InterruptedException, IOExc { Utils.setValueInConfig("base_path", "\"\""); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); - String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/", null, + String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/", null, 1000, 1000, null); assertEquals("Hello", response); @@ -1019,10 +1012,10 @@ public void validBasePathWithEmptyHelloPath() throws InterruptedException, IOExc { Utils.setValueInConfig("base_path", "\"/test\""); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); - String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/test", + String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/test", null, 1000, 1000, null); assertEquals("Hello", response); @@ -1034,11 +1027,11 @@ public void validBasePathWithEmptyHelloPath() throws InterruptedException, IOExc { Utils.setValueInConfig("base_path", "\"/test/path\""); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); String response = HttpRequest.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/test/path/", null, 1000, 1000, null); + "http://localhost:" + HttpRequestForTesting.corePort + "/test/path/", null, 1000, 1000, null); assertEquals("Hello", response); process.kill(); @@ -1048,17 +1041,17 @@ public void validBasePathWithEmptyHelloPath() throws InterruptedException, IOExc { Utils.setValueInConfig("base_path", "\"/te3st/Pa23th\""); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); { String response = HttpRequest.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/te3st/Pa23th/", null, 1000, 1000, null); + "http://localhost:" + HttpRequestForTesting.corePort + "/te3st/Pa23th/", null, 1000, 1000, null); assertEquals("Hello", response); } try { - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/hello", null, 1000, 1000, + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort + "/hello", null, 1000, 1000, null); fail(); } catch (Exception e) { @@ -1072,10 +1065,10 @@ public void validBasePathWithEmptyHelloPath() throws InterruptedException, IOExc { Utils.setValueInConfig("base_path", ""); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); - String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567", null, + String response = HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + HttpRequestForTesting.corePort, null, 1000, 1000, null); assertEquals("Hello", response); @@ -1167,7 +1160,8 @@ private static class ThreadPoolTester implements Runnable { @Override public void run() { try { - HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:3567/testforthreadpool", null, + int port = HttpRequestForTesting.corePort; + HttpRequest.sendGETRequest(process.getProcess(), "", "http://localhost:" + port + "/testforthreadpool", null, 1000, 1500, null); } catch (Exception e) { if (e instanceof SocketTimeoutException) { diff --git a/src/test/java/io/supertokens/test/accountlinking/CreatePrimaryUserTest.java b/src/test/java/io/supertokens/test/accountlinking/CreatePrimaryUserTest.java index 22b3598d9..322d92035 100644 --- a/src/test/java/io/supertokens/test/accountlinking/CreatePrimaryUserTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/CreatePrimaryUserTest.java @@ -50,6 +50,9 @@ public class CreatePrimaryUserTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -128,7 +131,7 @@ public void testThatOnSignUpUserIsNotAPrimaryUser() throws Exception { @Test public void testThatCreationOfPrimaryUserRequiresAccountLinkingFeatureToBeEnabled() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.isInMemDb(process.getProcess())) { @@ -137,8 +140,8 @@ public void testThatCreationOfPrimaryUserRequiresAccountLinkingFeatureToBeEnable } try { - AuthRecipe.createPrimaryUser(process.main, - new AppIdentifier(null, null), StorageLayer.getStorage(process.main), ""); + AuthRecipe.createPrimaryUser(process.getProcess(), + process.getAppForTesting().toAppIdentifier(), StorageLayer.getStorage(process.getProcess()), ""); assert (false); } catch (FeatureNotEnabledException e) { assert (e.getMessage() @@ -153,11 +156,10 @@ public void testThatCreationOfPrimaryUserRequiresAccountLinkingFeatureToBeEnable @Test public void makeEmailPasswordPrimaryUserSuccess() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -167,7 +169,7 @@ public void makeEmailPasswordPrimaryUserSuccess() throws Exception { AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); assert (result.user.isPrimaryUser); @@ -179,7 +181,7 @@ public void makeEmailPasswordPrimaryUserSuccess() throws Exception { assert (result.user.getSupertokensUserId().equals(result.user.loginMethods[0].getSupertokensUserId())); assert (result.user.loginMethods[0].phoneNumber == null); - AuthRecipeUserInfo refetchedUser = AuthRecipe.getUserById(process.main, result.user.getSupertokensUserId()); + AuthRecipeUserInfo refetchedUser = AuthRecipe.getUserById(process.getProcess(), result.user.getSupertokensUserId()); assert (refetchedUser.equals(result.user)); @@ -190,11 +192,10 @@ public void makeEmailPasswordPrimaryUserSuccess() throws Exception { @Test public void makeThirdPartyPrimaryUserSuccess() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -205,7 +206,7 @@ public void makeThirdPartyPrimaryUserSuccess() throws Exception { "user-google", "test@example.com"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.getProcess(), signInUp.user.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); assert (result.user.isPrimaryUser); @@ -218,7 +219,7 @@ public void makeThirdPartyPrimaryUserSuccess() throws Exception { assert (result.user.loginMethods[0].passwordHash == null); assert (result.user.getSupertokensUserId().equals(result.user.loginMethods[0].getSupertokensUserId())); - AuthRecipeUserInfo refetchedUser = AuthRecipe.getUserById(process.main, result.user.getSupertokensUserId()); + AuthRecipeUserInfo refetchedUser = AuthRecipe.getUserById(process.getProcess(), result.user.getSupertokensUserId()); assert (refetchedUser.equals(result.user)); @@ -229,11 +230,10 @@ public void makeThirdPartyPrimaryUserSuccess() throws Exception { @Test public void makePasswordlessEmailPrimaryUserSuccess() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -245,7 +245,7 @@ public void makePasswordlessEmailPrimaryUserSuccess() throws Exception { Passwordless.ConsumeCodeResponse pResp = Passwordless.consumeCode(process.getProcess(), code.deviceId, code.deviceIdHash, code.userInputCode, null); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.getProcess(), pResp.user.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); assert (result.user.isPrimaryUser); @@ -257,7 +257,7 @@ public void makePasswordlessEmailPrimaryUserSuccess() throws Exception { assert (result.user.loginMethods[0].phoneNumber == null); assert (result.user.getSupertokensUserId().equals(result.user.loginMethods[0].getSupertokensUserId())); - AuthRecipeUserInfo refetchedUser = AuthRecipe.getUserById(process.main, result.user.getSupertokensUserId()); + AuthRecipeUserInfo refetchedUser = AuthRecipe.getUserById(process.getProcess(), result.user.getSupertokensUserId()); assert (refetchedUser.equals(result.user)); @@ -268,11 +268,10 @@ public void makePasswordlessEmailPrimaryUserSuccess() throws Exception { @Test public void makePasswordlessPhonePrimaryUserSuccess() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -284,7 +283,7 @@ public void makePasswordlessPhonePrimaryUserSuccess() throws Exception { Passwordless.ConsumeCodeResponse pResp = Passwordless.consumeCode(process.getProcess(), code.deviceId, code.deviceIdHash, code.userInputCode, null); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.getProcess(), pResp.user.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); assert (result.user.isPrimaryUser); @@ -296,7 +295,7 @@ public void makePasswordlessPhonePrimaryUserSuccess() throws Exception { assert (result.user.loginMethods[0].phoneNumber.equals("1234")); assert (result.user.getSupertokensUserId().equals(result.user.loginMethods[0].getSupertokensUserId())); - AuthRecipeUserInfo refetchedUser = AuthRecipe.getUserById(process.main, result.user.getSupertokensUserId()); + AuthRecipeUserInfo refetchedUser = AuthRecipe.getUserById(process.getProcess(), result.user.getSupertokensUserId()); assert (refetchedUser.equals(result.user)); @@ -307,11 +306,10 @@ public void makePasswordlessPhonePrimaryUserSuccess() throws Exception { @Test public void alreadyPrimaryUsertest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -321,11 +319,11 @@ public void alreadyPrimaryUsertest() throws Exception { AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); - result = AuthRecipe.createPrimaryUser(process.main, emailPasswordUser.getSupertokensUserId()); + result = AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser.getSupertokensUserId()); assert (result.wasAlreadyAPrimaryUser); assert (result.user.getSupertokensUserId().equals(emailPasswordUser.getSupertokensUserId())); assert (result.user.isPrimaryUser); @@ -337,7 +335,7 @@ public void alreadyPrimaryUsertest() throws Exception { assert (result.user.getSupertokensUserId().equals(result.user.loginMethods[0].getSupertokensUserId())); assert (result.user.loginMethods[0].phoneNumber == null); - AuthRecipeUserInfo refetchedUser = AuthRecipe.getUserById(process.main, result.user.getSupertokensUserId()); + AuthRecipeUserInfo refetchedUser = AuthRecipe.getUserById(process.getProcess(), result.user.getSupertokensUserId()); assert (refetchedUser.equals(result.user)); @@ -348,11 +346,10 @@ public void alreadyPrimaryUsertest() throws Exception { @Test public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -362,15 +359,15 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); - ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", + ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), "google", "user-google", "test@example.com"); try { - AuthRecipe.createPrimaryUser(process.main, signInUpResponse.user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), signInUpResponse.user.getSupertokensUserId()); assert (false); } catch (AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException e) { assert (e.primaryUserId.equals(emailPasswordUser.getSupertokensUserId())); @@ -384,11 +381,10 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU @Test public void makePrimarySucceedsEvenIfAnotherAccountWithSameEmailButIsNotAPrimaryUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -398,10 +394,10 @@ public void makePrimarySucceedsEvenIfAnotherAccountWithSameEmailButIsNotAPrimary AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", + ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), "google", "user-google", "test@example.com"); - AuthRecipe.CreatePrimaryUserResult r = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult r = AuthRecipe.createPrimaryUser(process.getProcess(), signInUpResponse.user.getSupertokensUserId()); assert (!r.wasAlreadyAPrimaryUser); @@ -413,41 +409,40 @@ public void makePrimarySucceedsEvenIfAnotherAccountWithSameEmailButIsNotAPrimary public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUserInAnotherTenant() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - Multitenancy.addNewOrUpdateAppOrTenant(process.main, new TenantIdentifier(null, null, null), - new TenantConfig(new TenantIdentifier(null, null, "t1"), new EmailPasswordConfig(true), + Multitenancy.addNewOrUpdateAppOrTenant(process.getProcess(), new TenantIdentifier(null, process.getAppForTesting().getAppId(), null), + new TenantConfig(new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"), new EmailPasswordConfig(true), new ThirdPartyConfig(true, new ThirdPartyConfig.Provider[0]), new PasswordlessConfig(true), null, null, new JsonObject())); - Storage storage = (StorageLayer.getStorage(process.main)); - AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(new TenantIdentifier(null, null, "t1"), + Storage storage = (StorageLayer.getStorage(process.getProcess())); + AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"), storage, process.getProcess(), "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); - ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", + ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), "google", "user-google", "test@example.com"); - Multitenancy.addUserIdToTenant(process.main, new TenantIdentifier(null, null, "t1"), + Multitenancy.addUserIdToTenant(process.getProcess(), new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"), storage, signInUpResponse.user.getSupertokensUserId()); try { - AuthRecipe.createPrimaryUser(process.main, signInUpResponse.user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), signInUpResponse.user.getSupertokensUserId()); assert (false); } catch (AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException e) { assert (e.primaryUserId.equals(emailPasswordUser.getSupertokensUserId())); @@ -462,36 +457,35 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU public void makePrimarySucceedsEvenIfAnotherAccountWithSameEmailButInADifferentTenant() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - Multitenancy.addNewOrUpdateAppOrTenant(process.main, new TenantIdentifier(null, null, null), - new TenantConfig(new TenantIdentifier(null, null, "t1"), new EmailPasswordConfig(true), + Multitenancy.addNewOrUpdateAppOrTenant(process.getProcess(), new TenantIdentifier(null, process.getAppForTesting().getAppId(), null), + new TenantConfig(new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"), new EmailPasswordConfig(true), new ThirdPartyConfig(true, new ThirdPartyConfig.Provider[0]), new PasswordlessConfig(true), null, null, new JsonObject())); - Storage storage = (StorageLayer.getStorage(process.main)); - AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(new TenantIdentifier(null, null, "t1"), + Storage storage = (StorageLayer.getStorage(process.getProcess())); + AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"), storage, process.getProcess(), "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); - ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", + ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), "google", "user-google", "test@example.com"); - AuthRecipe.CreatePrimaryUserResult r = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult r = AuthRecipe.createPrimaryUser(process.getProcess(), signInUpResponse.user.getSupertokensUserId()); assert !r.wasAlreadyAPrimaryUser; @@ -502,11 +496,10 @@ public void makePrimarySucceedsEvenIfAnotherAccountWithSameEmailButInADifferentT @Test public void makePrimaryUserFailsCauseOfUnknownUserId() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -514,7 +507,7 @@ public void makePrimaryUserFailsCauseOfUnknownUserId() throws Exception { } try { - AuthRecipe.createPrimaryUser(process.main, "random"); + AuthRecipe.createPrimaryUser(process.getProcess(), "random"); assert (false); } catch (UnknownUserIdException ignored) { } @@ -526,11 +519,10 @@ public void makePrimaryUserFailsCauseOfUnknownUserId() throws Exception { @Test public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccount() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -542,12 +534,12 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccount() throws Ex AuthRecipeUserInfo emailPasswordUser2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass1234"); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); try { - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser2.getSupertokensUserId()); assert (false); } catch (RecipeUserIdAlreadyLinkedWithPrimaryUserIdException e) { assert (e.primaryUserId.equals(emailPasswordUser1.getSupertokensUserId())); diff --git a/src/test/java/io/supertokens/test/accountlinking/DeleteUserTest.java b/src/test/java/io/supertokens/test/accountlinking/DeleteUserTest.java index cb1c6bb79..17904b598 100644 --- a/src/test/java/io/supertokens/test/accountlinking/DeleteUserTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/DeleteUserTest.java @@ -43,6 +43,9 @@ public class DeleteUserTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -56,31 +59,30 @@ public void beforeEach() { @Test public void deleteLinkedUserWithoutRemovingAllUsers() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - AuthRecipeUserInfo r1 = EmailPassword.signUp(process.main, "test@example.com", "pass123"); + AuthRecipeUserInfo r1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass123"); - AuthRecipeUserInfo r2 = EmailPassword.signUp(process.main, "test2@example.com", "pass123"); + AuthRecipeUserInfo r2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass123"); - AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + assert (!AuthRecipe.linkAccounts(process.getProcess(), r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); - AuthRecipe.deleteUser(process.main, r1.getSupertokensUserId(), false); + AuthRecipe.deleteUser(process.getProcess(), r1.getSupertokensUserId(), false); - assertNull(AuthRecipe.getUserById(process.main, r1.getSupertokensUserId())); + assertNull(AuthRecipe.getUserById(process.getProcess(), r1.getSupertokensUserId())); - AuthRecipeUserInfo user = AuthRecipe.getUserById(process.main, r2.getSupertokensUserId()); + AuthRecipeUserInfo user = AuthRecipe.getUserById(process.getProcess(), r2.getSupertokensUserId()); assert (user.loginMethods.length == 1); assert (user.isPrimaryUser); @@ -94,31 +96,30 @@ public void deleteLinkedUserWithoutRemovingAllUsers() throws Exception { @Test public void deleteLinkedPrimaryUserWithoutRemovingAllUsers() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - AuthRecipeUserInfo r1 = EmailPassword.signUp(process.main, "test@example.com", "pass123"); + AuthRecipeUserInfo r1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass123"); - AuthRecipeUserInfo r2 = EmailPassword.signUp(process.main, "test2@example.com", "pass123"); + AuthRecipeUserInfo r2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass123"); - AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + assert (!AuthRecipe.linkAccounts(process.getProcess(), r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); - AuthRecipe.deleteUser(process.main, r2.getSupertokensUserId(), false); + AuthRecipe.deleteUser(process.getProcess(), r2.getSupertokensUserId(), false); - AuthRecipeUserInfo userP = AuthRecipe.getUserById(process.main, r2.getSupertokensUserId()); + AuthRecipeUserInfo userP = AuthRecipe.getUserById(process.getProcess(), r2.getSupertokensUserId()); - AuthRecipeUserInfo user = AuthRecipe.getUserById(process.main, r1.getSupertokensUserId()); + AuthRecipeUserInfo user = AuthRecipe.getUserById(process.getProcess(), r1.getSupertokensUserId()); assert (user.loginMethods.length == 1); assert (user.isPrimaryUser); @@ -133,31 +134,30 @@ public void deleteLinkedPrimaryUserWithoutRemovingAllUsers() throws Exception { @Test public void deleteLinkedPrimaryUserRemovingAllUsers() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - AuthRecipeUserInfo r1 = EmailPassword.signUp(process.main, "test@example.com", "pass123"); + AuthRecipeUserInfo r1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass123"); - AuthRecipeUserInfo r2 = EmailPassword.signUp(process.main, "test2@example.com", "pass123"); + AuthRecipeUserInfo r2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass123"); - AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + assert (!AuthRecipe.linkAccounts(process.getProcess(), r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); - AuthRecipe.deleteUser(process.main, r2.getSupertokensUserId()); + AuthRecipe.deleteUser(process.getProcess(), r2.getSupertokensUserId()); - AuthRecipeUserInfo userP = AuthRecipe.getUserById(process.main, r2.getSupertokensUserId()); + AuthRecipeUserInfo userP = AuthRecipe.getUserById(process.getProcess(), r2.getSupertokensUserId()); - AuthRecipeUserInfo user = AuthRecipe.getUserById(process.main, r1.getSupertokensUserId()); + AuthRecipeUserInfo user = AuthRecipe.getUserById(process.getProcess(), r1.getSupertokensUserId()); assert (user == null && userP == null); @@ -169,31 +169,30 @@ public void deleteLinkedPrimaryUserRemovingAllUsers() throws Exception { public void deleteLinkedPrimaryUserRemovingAllUsers2() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - AuthRecipeUserInfo r1 = EmailPassword.signUp(process.main, "test@example.com", "pass123"); + AuthRecipeUserInfo r1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass123"); - AuthRecipeUserInfo r2 = EmailPassword.signUp(process.main, "test2@example.com", "pass123"); + AuthRecipeUserInfo r2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass123"); - AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + assert (!AuthRecipe.linkAccounts(process.getProcess(), r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); - AuthRecipe.deleteUser(process.main, r1.getSupertokensUserId()); + AuthRecipe.deleteUser(process.getProcess(), r1.getSupertokensUserId()); - AuthRecipeUserInfo userP = AuthRecipe.getUserById(process.main, r2.getSupertokensUserId()); + AuthRecipeUserInfo userP = AuthRecipe.getUserById(process.getProcess(), r2.getSupertokensUserId()); - AuthRecipeUserInfo user = AuthRecipe.getUserById(process.main, r1.getSupertokensUserId()); + AuthRecipeUserInfo user = AuthRecipe.getUserById(process.getProcess(), r1.getSupertokensUserId()); assert (user == null && userP == null); @@ -209,47 +208,46 @@ public void deleteUserTestWithUserIdMapping1() throws Exception { * e1 entry, and e1 metadata, but should not clear e2 stuff at all. * */ String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - AuthRecipeUserInfo r1 = EmailPassword.signUp(process.main, "test@example.com", "pass123"); - UserIdMapping.createUserIdMapping(process.main, r1.getSupertokensUserId(), "e1", null, false); + AuthRecipeUserInfo r1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass123"); + UserIdMapping.createUserIdMapping(process.getProcess(), r1.getSupertokensUserId(), "e1", null, false); JsonObject metadata = new JsonObject(); metadata.addProperty("k1", "v1"); - UserMetadata.updateUserMetadata(process.main, "e1", metadata); + UserMetadata.updateUserMetadata(process.getProcess(), "e1", metadata); - AuthRecipeUserInfo r2 = EmailPassword.signUp(process.main, "test2@example.com", "pass123"); - UserIdMapping.createUserIdMapping(process.main, r2.getSupertokensUserId(), "e2", null, false); - UserMetadata.updateUserMetadata(process.main, "e2", metadata); + AuthRecipeUserInfo r2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass123"); + UserIdMapping.createUserIdMapping(process.getProcess(), r2.getSupertokensUserId(), "e2", null, false); + UserMetadata.updateUserMetadata(process.getProcess(), "e2", metadata); - AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + assert (!AuthRecipe.linkAccounts(process.getProcess(), r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); - AuthRecipe.deleteUser(process.main, r1.getSupertokensUserId(), false); + AuthRecipe.deleteUser(process.getProcess(), r1.getSupertokensUserId(), false); - assertNull(AuthRecipe.getUserById(process.main, r1.getSupertokensUserId())); + assertNull(AuthRecipe.getUserById(process.getProcess(), r1.getSupertokensUserId())); - assertNull(AuthRecipe.getUserById(process.main, "e2")); + assertNull(AuthRecipe.getUserById(process.getProcess(), "e2")); - assertNotNull(AuthRecipe.getUserById(process.main, r2.getSupertokensUserId())); + assertNotNull(AuthRecipe.getUserById(process.getProcess(), r2.getSupertokensUserId())); - assertEquals(UserMetadata.getUserMetadata(process.main, "e1"), new JsonObject()); - assertEquals(UserMetadata.getUserMetadata(process.main, r1.getSupertokensUserId()), new JsonObject()); - assertEquals(UserMetadata.getUserMetadata(process.main, "e2"), metadata); - assertEquals(UserMetadata.getUserMetadata(process.main, r2.getSupertokensUserId()), new JsonObject()); - assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e1"), new JsonObject()); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), r1.getSupertokensUserId()), new JsonObject()); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e2"), metadata); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), r2.getSupertokensUserId()), new JsonObject()); + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != null); - assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); @@ -264,47 +262,46 @@ public void deleteUserTestWithUserIdMapping2() throws Exception { * Now we want to delete r1 with linked all recipes as true. This should clear r1, r2 entry clear e2 metadata. * */ String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - AuthRecipeUserInfo r1 = EmailPassword.signUp(process.main, "test@example.com", "pass123"); - UserIdMapping.createUserIdMapping(process.main, r1.getSupertokensUserId(), "e1", null, false); + AuthRecipeUserInfo r1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass123"); + UserIdMapping.createUserIdMapping(process.getProcess(), r1.getSupertokensUserId(), "e1", null, false); JsonObject metadata = new JsonObject(); metadata.addProperty("k1", "v1"); - UserMetadata.updateUserMetadata(process.main, "e1", metadata); + UserMetadata.updateUserMetadata(process.getProcess(), "e1", metadata); - AuthRecipeUserInfo r2 = EmailPassword.signUp(process.main, "test2@example.com", "pass123"); - UserIdMapping.createUserIdMapping(process.main, r2.getSupertokensUserId(), "e2", null, false); - UserMetadata.updateUserMetadata(process.main, "e2", metadata); + AuthRecipeUserInfo r2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass123"); + UserIdMapping.createUserIdMapping(process.getProcess(), r2.getSupertokensUserId(), "e2", null, false); + UserMetadata.updateUserMetadata(process.getProcess(), "e2", metadata); - AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + assert (!AuthRecipe.linkAccounts(process.getProcess(), r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); - AuthRecipe.deleteUser(process.main, r1.getSupertokensUserId()); + AuthRecipe.deleteUser(process.getProcess(), r1.getSupertokensUserId()); - assertNull(AuthRecipe.getUserById(process.main, r1.getSupertokensUserId())); + assertNull(AuthRecipe.getUserById(process.getProcess(), r1.getSupertokensUserId())); - assertNull(AuthRecipe.getUserById(process.main, "e2")); + assertNull(AuthRecipe.getUserById(process.getProcess(), "e2")); - assertNull(AuthRecipe.getUserById(process.main, r2.getSupertokensUserId())); + assertNull(AuthRecipe.getUserById(process.getProcess(), r2.getSupertokensUserId())); - assertEquals(UserMetadata.getUserMetadata(process.main, "e1"), new JsonObject()); - assertEquals(UserMetadata.getUserMetadata(process.main, r1.getSupertokensUserId()), new JsonObject()); - assertEquals(UserMetadata.getUserMetadata(process.main, "e2"), new JsonObject()); - assertEquals(UserMetadata.getUserMetadata(process.main, r2.getSupertokensUserId()), new JsonObject()); - assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e1"), new JsonObject()); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), r1.getSupertokensUserId()), new JsonObject()); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e2"), new JsonObject()); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), r2.getSupertokensUserId()), new JsonObject()); + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); - assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); @@ -321,90 +318,89 @@ public void deleteUserTestWithUserIdMapping3() throws Exception { * and r1 * */ String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - AuthRecipeUserInfo r1 = EmailPassword.signUp(process.main, "test@example.com", "pass123"); - UserIdMapping.createUserIdMapping(process.main, r1.getSupertokensUserId(), "e1", null, false); + AuthRecipeUserInfo r1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass123"); + UserIdMapping.createUserIdMapping(process.getProcess(), r1.getSupertokensUserId(), "e1", null, false); JsonObject metadata = new JsonObject(); metadata.addProperty("k1", "v1"); - UserMetadata.updateUserMetadata(process.main, "e1", metadata); + UserMetadata.updateUserMetadata(process.getProcess(), "e1", metadata); - AuthRecipeUserInfo r2 = EmailPassword.signUp(process.main, "test2@example.com", "pass123"); - UserIdMapping.createUserIdMapping(process.main, r2.getSupertokensUserId(), "e2", null, false); - UserMetadata.updateUserMetadata(process.main, "e2", metadata); + AuthRecipeUserInfo r2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass123"); + UserIdMapping.createUserIdMapping(process.getProcess(), r2.getSupertokensUserId(), "e2", null, false); + UserMetadata.updateUserMetadata(process.getProcess(), "e2", metadata); - AuthRecipeUserInfo r3 = EmailPassword.signUp(process.main, "test3@example.com", "pass123"); - UserIdMapping.createUserIdMapping(process.main, r3.getSupertokensUserId(), "e3", null, false); - UserMetadata.updateUserMetadata(process.main, "e3", metadata); + AuthRecipeUserInfo r3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "pass123"); + UserIdMapping.createUserIdMapping(process.getProcess(), r3.getSupertokensUserId(), "e3", null, false); + UserMetadata.updateUserMetadata(process.getProcess(), "e3", metadata); - AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + assert (!AuthRecipe.linkAccounts(process.getProcess(), r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); - assert (!AuthRecipe.linkAccounts(process.main, r3.getSupertokensUserId(), + assert (!AuthRecipe.linkAccounts(process.getProcess(), r3.getSupertokensUserId(), r1.getSupertokensUserId()).wasAlreadyLinked); - AuthRecipe.deleteUser(process.main, r1.getSupertokensUserId(), false); + AuthRecipe.deleteUser(process.getProcess(), r1.getSupertokensUserId(), false); - assertNull(AuthRecipe.getUserById(process.main, r1.getSupertokensUserId())); + assertNull(AuthRecipe.getUserById(process.getProcess(), r1.getSupertokensUserId())); - assertEquals(UserMetadata.getUserMetadata(process.main, "e1"), new JsonObject()); - assertEquals(UserMetadata.getUserMetadata(process.main, r1.getSupertokensUserId()), new JsonObject()); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e1"), new JsonObject()); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), r1.getSupertokensUserId()), new JsonObject()); { - AuthRecipeUserInfo userR2 = AuthRecipe.getUserById(process.main, r2.getSupertokensUserId()); - AuthRecipeUserInfo userR3 = AuthRecipe.getUserById(process.main, r3.getSupertokensUserId()); + AuthRecipeUserInfo userR2 = AuthRecipe.getUserById(process.getProcess(), r2.getSupertokensUserId()); + AuthRecipeUserInfo userR3 = AuthRecipe.getUserById(process.getProcess(), r3.getSupertokensUserId()); assert (userR2.equals(userR3)); assert (userR2.loginMethods.length == 2); - assertEquals(UserMetadata.getUserMetadata(process.main, "e2"), metadata); - assertEquals(UserMetadata.getUserMetadata(process.main, "e3"), metadata); - assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e2"), metadata); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e3"), metadata); + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != null); - assert (UserIdMapping.getUserIdMapping(process.main, r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) != + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) != null); - assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); } - AuthRecipe.deleteUser(process.main, r2.getSupertokensUserId(), false); + AuthRecipe.deleteUser(process.getProcess(), r2.getSupertokensUserId(), false); { - AuthRecipeUserInfo userR2 = AuthRecipe.getUserById(process.main, r2.getSupertokensUserId()); - AuthRecipeUserInfo userR3 = AuthRecipe.getUserById(process.main, r3.getSupertokensUserId()); + AuthRecipeUserInfo userR2 = AuthRecipe.getUserById(process.getProcess(), r2.getSupertokensUserId()); + AuthRecipeUserInfo userR3 = AuthRecipe.getUserById(process.getProcess(), r3.getSupertokensUserId()); assert (userR2.equals(userR3)); assert (userR2.loginMethods.length == 1); - assertEquals(UserMetadata.getUserMetadata(process.main, "e2"), metadata); - assertEquals(UserMetadata.getUserMetadata(process.main, "e3"), metadata); - assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e2"), metadata); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e3"), metadata); + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != null); - assert (UserIdMapping.getUserIdMapping(process.main, r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) != + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) != null); - assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); } - AuthRecipe.deleteUser(process.main, r3.getSupertokensUserId(), false); + AuthRecipe.deleteUser(process.getProcess(), r3.getSupertokensUserId(), false); { - AuthRecipeUserInfo userR2 = AuthRecipe.getUserById(process.main, r2.getSupertokensUserId()); - AuthRecipeUserInfo userR3 = AuthRecipe.getUserById(process.main, r3.getSupertokensUserId()); + AuthRecipeUserInfo userR2 = AuthRecipe.getUserById(process.getProcess(), r2.getSupertokensUserId()); + AuthRecipeUserInfo userR3 = AuthRecipe.getUserById(process.getProcess(), r3.getSupertokensUserId()); assert (userR2 == null && userR3 == null); - assertEquals(UserMetadata.getUserMetadata(process.main, "e2"), new JsonObject()); - assertEquals(UserMetadata.getUserMetadata(process.main, "e3"), new JsonObject()); - assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e2"), new JsonObject()); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e3"), new JsonObject()); + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); - assert (UserIdMapping.getUserIdMapping(process.main, r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); - assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); } diff --git a/src/test/java/io/supertokens/test/accountlinking/EmailPasswordTests.java b/src/test/java/io/supertokens/test/accountlinking/EmailPasswordTests.java index fea54dee7..953ec6f22 100644 --- a/src/test/java/io/supertokens/test/accountlinking/EmailPasswordTests.java +++ b/src/test/java/io/supertokens/test/accountlinking/EmailPasswordTests.java @@ -42,6 +42,9 @@ public class EmailPasswordTests { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -56,11 +59,10 @@ public void beforeEach() { @Test public void testUpdatePasswordWithDifferentValidUserId() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -89,11 +91,10 @@ public void testUpdatePasswordWithDifferentValidUserId() throws Exception { @Test public void testPasswordlessUserWithSameEmail() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -121,11 +122,10 @@ public void testPasswordlessUserWithSameEmail() throws Exception { @Test public void testPasswordlessUsersLinked() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/accountlinking/GetUserByAccountInfoTest.java b/src/test/java/io/supertokens/test/accountlinking/GetUserByAccountInfoTest.java index 536b68a1e..159906f7b 100644 --- a/src/test/java/io/supertokens/test/accountlinking/GetUserByAccountInfoTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/GetUserByAccountInfoTest.java @@ -60,6 +60,9 @@ public class GetUserByAccountInfoTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -124,11 +127,10 @@ AuthRecipeUserInfo createWebauthnUser(Main main, String email) throws HttpRespon @Test public void testListUsersByAccountInfoForUnlinkedAccounts() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -143,7 +145,7 @@ public void testListUsersByAccountInfoForUnlinkedAccounts() throws Exception { Storage storage = (StorageLayer.getBaseStorage(process.getProcess())); - AuthRecipeUserInfo userToTest = AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + AuthRecipeUserInfo userToTest = AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test1@example.com", null, null, null, null)[0]; assertNotNull(userToTest.getSupertokensUserId()); @@ -160,31 +162,31 @@ public void testListUsersByAccountInfoForUnlinkedAccounts() throws Exception { String webauthnCredentialId = user5.loginMethods[0].webauthN.credentialIds.get(0); // test for result - assertEquals(user1, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, storage + assertEquals(user1, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage , false, "test1@example.com", null, null, null, null)[0]); - assertEquals(user2, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, storage + assertEquals(user2, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage , false, null, null, "google", "userid1", null)[0]); - assertEquals(user2, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, storage + assertEquals(user2, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage , false, "test2@example.com", null, "google", "userid1", null)[0]); - assertEquals(user3, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, storage + assertEquals(user3, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage , false, "test3@example.com", null, null, null, null)[0]); - assertEquals(user4, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, storage + assertEquals(user4, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage , false, null, "+919876543210", null, null, null)[0]); - assertEquals(user5, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, storage + assertEquals(user5, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage , false, null, null, null, null, webauthnCredentialId)[0]); // test for no result - assertEquals(0, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, storage, + assertEquals(0, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test1@example.com", "+919876543210", null, null, null).length); - assertEquals(0, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, storage, + assertEquals(0, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test2@example.com", "+919876543210", null, null, null).length); - assertEquals(0, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, storage, + assertEquals(0, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test3@example.com", "+919876543210", null, null, null).length); - assertEquals(0, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, storage, + assertEquals(0, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, null, "+919876543210", "google", "userid1", null).length); - assertEquals(0, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, storage, + assertEquals(0, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test1@gmail.com", null, "google", "userid1", null).length); - assertEquals(0, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, storage, + assertEquals(0, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test3@gmail.com", null, null, null, webauthnCredentialId).length); process.kill(); @@ -194,11 +196,10 @@ public void testListUsersByAccountInfoForUnlinkedAccounts() throws Exception { @Test public void testListUsersByAccountInfoForUnlinkedAccountsWithUnionOption() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -212,28 +213,28 @@ public void testListUsersByAccountInfoForUnlinkedAccountsWithUnionOption() throw Storage storage = (StorageLayer.getBaseStorage(process.getProcess())); { - AuthRecipeUserInfo[] users = AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + AuthRecipeUserInfo[] users = AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, true, "test1@example.com", "+919876543210", null, null, null); assertEquals(2, users.length); assertTrue(Arrays.asList(users).contains(user1)); assertTrue(Arrays.asList(users).contains(user4)); } { - AuthRecipeUserInfo[] users = AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + AuthRecipeUserInfo[] users = AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, true, "test1@example.com", null, "google", "userid1", null); assertEquals(2, users.length); assertTrue(Arrays.asList(users).contains(user1)); assertTrue(Arrays.asList(users).contains(user2)); } { - AuthRecipeUserInfo[] users = AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + AuthRecipeUserInfo[] users = AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, true, null, "+919876543210", "google", "userid1", null); assertEquals(2, users.length); assertTrue(Arrays.asList(users).contains(user4)); assertTrue(Arrays.asList(users).contains(user2)); } { - AuthRecipeUserInfo[] users = AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + AuthRecipeUserInfo[] users = AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, true, "test1@example.com", "+919876543210", "google", "userid1", null); assertEquals(3, users.length); assertTrue(Arrays.asList(users).contains(user1)); @@ -248,11 +249,10 @@ public void testListUsersByAccountInfoForUnlinkedAccountsWithUnionOption() throw @Test public void testUnknownAccountInfo() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -260,13 +260,13 @@ public void testUnknownAccountInfo() throws Exception { } Storage storage = (StorageLayer.getBaseStorage(process.getProcess())); - assertEquals(0, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, storage, + assertEquals(0, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test1@example.com", null, null, null, null).length); - assertEquals(0, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, storage, + assertEquals(0, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, null, null, "google", "userid1", null).length); - assertEquals(0, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, storage, + assertEquals(0, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test3@example.com", null, null, null, null).length); - assertEquals(0, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, storage, + assertEquals(0, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, null, "+919876543210", null, null, null).length); process.kill(); @@ -276,11 +276,10 @@ public void testUnknownAccountInfo() throws Exception { @Test public void testListUserByAccountInfoWhenAccountsAreLinked1() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -301,19 +300,19 @@ public void testListUserByAccountInfoWhenAccountsAreLinked1() throws Exception { primaryUser = AuthRecipe.getUserById(process.getProcess(), user1.getSupertokensUserId()); - assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test1@example.com", null, null, null, null)[0]); - assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test2@example.com", null, null, null, null)[0]); - assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, null, null, "google", "userid1", null)[0]); - assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test1@example.com", null, "google", "userid1", null)[0]); - assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test2@example.com", null, "google", "userid1", null)[0]); @@ -324,11 +323,10 @@ public void testListUserByAccountInfoWhenAccountsAreLinked1() throws Exception { @Test public void testListUserByAccountInfoWhenAccountsAreLinked2() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -348,10 +346,10 @@ public void testListUserByAccountInfoWhenAccountsAreLinked2() throws Exception { primaryUser = AuthRecipe.getUserById(process.getProcess(), user1.getSupertokensUserId()); - assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test1@example.com", null, null, null, null)[0]); - assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test2@example.com", null, null, null, null)[0]); @@ -362,11 +360,10 @@ public void testListUserByAccountInfoWhenAccountsAreLinked2() throws Exception { @Test public void testListUserByAccountInfoWhenAccountsAreLinked3() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -386,10 +383,10 @@ public void testListUserByAccountInfoWhenAccountsAreLinked3() throws Exception { primaryUser = AuthRecipe.getUserById(process.getProcess(), user1.getSupertokensUserId()); - assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test1@example.com", null, null, null, null)[0]); - assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test2@example.com", null, null, null, null)[0]); @@ -400,11 +397,10 @@ public void testListUserByAccountInfoWhenAccountsAreLinked3() throws Exception { @Test public void testListUserByAccountInfoWhenAccountsAreLinked4() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -424,13 +420,13 @@ public void testListUserByAccountInfoWhenAccountsAreLinked4() throws Exception { primaryUser = AuthRecipe.getUserById(process.getProcess(), user1.getSupertokensUserId()); - assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test1@example.com", null, null, null, null)[0]); - assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, null, "+919876543210", null, null, null)[0]); - assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test1@example.com", "+919876543210", null, null, null)[0]); @@ -441,11 +437,10 @@ public void testListUserByAccountInfoWhenAccountsAreLinked4() throws Exception { @Test public void testListUserByAccountInfoWhenAccountsAreLinked5() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -465,19 +460,19 @@ public void testListUserByAccountInfoWhenAccountsAreLinked5() throws Exception { primaryUser = AuthRecipe.getUserById(process.getProcess(), user1.getSupertokensUserId()); - assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test1@example.com", null, null, null, null)[0]); - assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test2@example.com", null, null, null, null)[0]); - assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, null, null, "google", "userid1", null)[0]); - assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test1@example.com", null, "google", "userid1", null)[0]); - assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + assertEquals(primaryUser, AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test2@example.com", null, "google", "userid1", null)[0]); @@ -488,11 +483,10 @@ public void testListUserByAccountInfoWhenAccountsAreLinked5() throws Exception { @Test public void testForEmptyResults() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -517,19 +511,19 @@ public void testForEmptyResults() throws Exception { Storage storage = ( StorageLayer.getBaseStorage(process.getProcess())); { - AuthRecipeUserInfo[] users = AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + AuthRecipeUserInfo[] users = AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test5@example.com", null, null, null, null); assertEquals(0, users.length); } { - AuthRecipeUserInfo[] users = AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + AuthRecipeUserInfo[] users = AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, null, null, "google", "userid5", null); assertEquals(0, users.length); } { - AuthRecipeUserInfo[] users = AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + AuthRecipeUserInfo[] users = AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, null, "+9876", null, null, null); assertEquals(0, users.length); @@ -542,11 +536,10 @@ public void testForEmptyResults() throws Exception { @Test public void testGetUserByAccountInfoOrdersUserBasedOnTimeJoined() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -577,7 +570,7 @@ public void testGetUserByAccountInfoOrdersUserBasedOnTimeJoined() throws Excepti StorageLayer.getBaseStorage(process.getProcess())); { - AuthRecipeUserInfo[] users = AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + AuthRecipeUserInfo[] users = AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, true, "test1@example.com", null, null, null, null); @@ -587,7 +580,7 @@ public void testGetUserByAccountInfoOrdersUserBasedOnTimeJoined() throws Excepti } { - AuthRecipeUserInfo[] users = AuthRecipe.getUsersByAccountInfo(TenantIdentifier.BASE_TENANT, + AuthRecipeUserInfo[] users = AuthRecipe.getUsersByAccountInfo(process.getAppForTesting(), storage, false, "test1@example.com", null, null, null, null); diff --git a/src/test/java/io/supertokens/test/accountlinking/GetUserByIdTest.java b/src/test/java/io/supertokens/test/accountlinking/GetUserByIdTest.java index 3df98a762..62795a66a 100644 --- a/src/test/java/io/supertokens/test/accountlinking/GetUserByIdTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/GetUserByIdTest.java @@ -54,6 +54,9 @@ public class GetUserByIdTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -97,11 +100,10 @@ AuthRecipeUserInfo createPasswordlessUserWithPhone(Main main, String phone) @Test public void testAllLoginMethods() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -163,11 +165,10 @@ public void testAllLoginMethods() throws Exception { @Test public void testUnknownUserIdReturnsNull() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -184,11 +185,10 @@ public void testUnknownUserIdReturnsNull() throws Exception { public void testLoginMethodsAreSortedByTime() throws Exception { for (int i = 0; i < 10; i++) { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/accountlinking/LinkAccountsTest.java b/src/test/java/io/supertokens/test/accountlinking/LinkAccountsTest.java index b30daec46..c5fdcc611 100644 --- a/src/test/java/io/supertokens/test/accountlinking/LinkAccountsTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/LinkAccountsTest.java @@ -55,6 +55,9 @@ public class LinkAccountsTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -68,11 +71,10 @@ public void beforeEach() { @Test public void linkAccountSuccess() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -87,18 +89,18 @@ public void linkAccountSuccess() throws Exception { AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "password"); assert (!user2.isPrimaryUser); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); - Session.createNewSession(process.main, user2.getSupertokensUserId(), new JsonObject(), new JsonObject()); - String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.main, user2.getSupertokensUserId()); + Session.createNewSession(process.getProcess(), user2.getSupertokensUserId(), new JsonObject(), new JsonObject()); + String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.getProcess(), user2.getSupertokensUserId()); assert (sessions.length == 1); - boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user.getSupertokensUserId()).wasAlreadyLinked; assert (!wasAlreadyLinked); - AuthRecipeUserInfo refetchUser2 = AuthRecipe.getUserById(process.main, user2.getSupertokensUserId()); - AuthRecipeUserInfo refetchUser = AuthRecipe.getUserById(process.main, user.getSupertokensUserId()); + AuthRecipeUserInfo refetchUser2 = AuthRecipe.getUserById(process.getProcess(), user2.getSupertokensUserId()); + AuthRecipeUserInfo refetchUser = AuthRecipe.getUserById(process.getProcess(), user.getSupertokensUserId()); assert (refetchUser2.equals(refetchUser)); assert (refetchUser2.loginMethods.length == 2); assert (refetchUser.loginMethods[0].equals(user.loginMethods[0])); @@ -108,7 +110,7 @@ public void linkAccountSuccess() throws Exception { assert (refetchUser.getSupertokensUserId().equals(user.getSupertokensUserId())); // cause linkAccounts revokes sessions for the recipe user ID - sessions = Session.getAllNonExpiredSessionHandlesForUser(process.main, user2.getSupertokensUserId()); + sessions = Session.getAllNonExpiredSessionHandlesForUser(process.getProcess(), user2.getSupertokensUserId()); assert (sessions.length == 0); process.kill(); @@ -118,11 +120,10 @@ public void linkAccountSuccess() throws Exception { @Test public void linkAccountSuccessWithSameEmail() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -140,18 +141,18 @@ public void linkAccountSuccessWithSameEmail() throws Exception { AuthRecipeUserInfo user2 = signInUpResponse.user; assert (!user2.isPrimaryUser); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); - Session.createNewSession(process.main, user2.getSupertokensUserId(), new JsonObject(), new JsonObject()); - String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.main, user2.getSupertokensUserId()); + Session.createNewSession(process.getProcess(), user2.getSupertokensUserId(), new JsonObject(), new JsonObject()); + String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.getProcess(), user2.getSupertokensUserId()); assert (sessions.length == 1); - boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user.getSupertokensUserId()).wasAlreadyLinked; assert (!wasAlreadyLinked); - AuthRecipeUserInfo refetchUser2 = AuthRecipe.getUserById(process.main, user2.getSupertokensUserId()); - AuthRecipeUserInfo refetchUser = AuthRecipe.getUserById(process.main, user.getSupertokensUserId()); + AuthRecipeUserInfo refetchUser2 = AuthRecipe.getUserById(process.getProcess(), user2.getSupertokensUserId()); + AuthRecipeUserInfo refetchUser = AuthRecipe.getUserById(process.getProcess(), user.getSupertokensUserId()); assert (refetchUser2.equals(refetchUser)); assert (refetchUser2.loginMethods.length == 2); assert (refetchUser.loginMethods[0].equals(user.loginMethods[0])); @@ -161,7 +162,7 @@ public void linkAccountSuccessWithSameEmail() throws Exception { assert (refetchUser.getSupertokensUserId().equals(user.getSupertokensUserId())); // cause linkAccounts revokes sessions for the recipe user ID - sessions = Session.getAllNonExpiredSessionHandlesForUser(process.main, user2.getSupertokensUserId()); + sessions = Session.getAllNonExpiredSessionHandlesForUser(process.getProcess(), user2.getSupertokensUserId()); assert (sessions.length == 0); process.kill(); @@ -171,7 +172,7 @@ public void linkAccountSuccessWithSameEmail() throws Exception { @Test public void testThatLinkingAccountsRequiresAccountLinkingFeatureToBeEnabled() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.isInMemDb(process.getProcess())) { @@ -179,7 +180,7 @@ public void testThatLinkingAccountsRequiresAccountLinkingFeatureToBeEnabled() th } try { - AuthRecipe.linkAccounts(process.main, "", ""); + AuthRecipe.linkAccounts(process.getProcess(), "", ""); assert (false); } catch (FeatureNotEnabledException e) { assert (e.getMessage() @@ -194,11 +195,10 @@ public void testThatLinkingAccountsRequiresAccountLinkingFeatureToBeEnabled() th @Test public void linkAccountSuccessEvenIfUsingRecipeUserIdThatIsLinkedToPrimaryUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -213,20 +213,20 @@ public void linkAccountSuccessEvenIfUsingRecipeUserIdThatIsLinkedToPrimaryUser() AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "password"); assert (!user2.isPrimaryUser); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); - boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user.getSupertokensUserId()).wasAlreadyLinked; assert (!wasAlreadyLinked); AuthRecipeUserInfo user3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "password"); assert (!user3.isPrimaryUser); - wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user3.getSupertokensUserId(), + wasAlreadyLinked = AuthRecipe.linkAccounts(process.getProcess(), user3.getSupertokensUserId(), user2.getSupertokensUserId()).wasAlreadyLinked; assert (!wasAlreadyLinked); - AuthRecipeUserInfo refetchUser = AuthRecipe.getUserById(process.main, user.getSupertokensUserId()); + AuthRecipeUserInfo refetchUser = AuthRecipe.getUserById(process.getProcess(), user.getSupertokensUserId()); assert (refetchUser.loginMethods.length == 3); assert (refetchUser.loginMethods[0].equals(user.loginMethods[0])); assert (refetchUser.loginMethods[1].equals(user2.loginMethods[0])); @@ -235,7 +235,7 @@ public void linkAccountSuccessEvenIfUsingRecipeUserIdThatIsLinkedToPrimaryUser() assert (refetchUser.isPrimaryUser); assert (refetchUser.getSupertokensUserId().equals(user.getSupertokensUserId())); - AuthRecipeUserInfo refetchUser3 = AuthRecipe.getUserById(process.main, user3.getSupertokensUserId()); + AuthRecipeUserInfo refetchUser3 = AuthRecipe.getUserById(process.getProcess(), user3.getSupertokensUserId()); assert (refetchUser3.equals(refetchUser)); process.kill(); @@ -245,11 +245,10 @@ public void linkAccountSuccessEvenIfUsingRecipeUserIdThatIsLinkedToPrimaryUser() @Test public void alreadyLinkAccountLinkAgain() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -267,22 +266,22 @@ public void alreadyLinkAccountLinkAgain() throws Exception { AuthRecipeUserInfo user2 = signInUpResponse.user; assert (!user2.isPrimaryUser); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); - boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user.getSupertokensUserId()).wasAlreadyLinked; assert (!wasAlreadyLinked); - Session.createNewSession(process.main, user2.getSupertokensUserId(), new JsonObject(), new JsonObject()); - String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.main, user2.getSupertokensUserId()); + Session.createNewSession(process.getProcess(), user2.getSupertokensUserId(), new JsonObject(), new JsonObject()); + String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.getProcess(), user2.getSupertokensUserId()); assert (sessions.length == 1); - wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + wasAlreadyLinked = AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user.getSupertokensUserId()).wasAlreadyLinked; assert (wasAlreadyLinked); // cause linkAccounts revokes sessions for the recipe user ID - sessions = Session.getAllNonExpiredSessionHandlesForUser(process.main, user2.getSupertokensUserId()); + sessions = Session.getAllNonExpiredSessionHandlesForUser(process.getProcess(), user2.getSupertokensUserId()); assert (sessions.length == 1); process.kill(); @@ -292,11 +291,10 @@ public void alreadyLinkAccountLinkAgain() throws Exception { @Test public void linkAccountFailureCauseRecipeUserIdLinkedWithAnotherPrimaryUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -314,18 +312,18 @@ public void linkAccountFailureCauseRecipeUserIdLinkedWithAnotherPrimaryUser() th AuthRecipeUserInfo user2 = signInUpResponse.user; assert (!user2.isPrimaryUser); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); - boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user.getSupertokensUserId()).wasAlreadyLinked; assert (!wasAlreadyLinked); AuthRecipeUserInfo user3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "password"); assert (!user.isPrimaryUser); - AuthRecipe.createPrimaryUser(process.main, user3.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user3.getSupertokensUserId()); try { - AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), user3.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user3.getSupertokensUserId()); assert (false); } catch (RecipeUserIdAlreadyLinkedWithAnotherPrimaryUserIdException e) { assert (e.recipeUser.getSupertokensUserId().equals(user.getSupertokensUserId())); @@ -339,11 +337,10 @@ public void linkAccountFailureCauseRecipeUserIdLinkedWithAnotherPrimaryUser() th @Test public void linkAccountFailureInputUserIsNotAPrimaryUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -360,7 +357,7 @@ public void linkAccountFailureInputUserIsNotAPrimaryUser() throws Exception { assert (!user2.isPrimaryUser); try { - AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), user.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user.getSupertokensUserId()); assert (false); } catch (InputUserIdIsNotAPrimaryUserException e) { assert (e.userId.equals(user.getSupertokensUserId())); @@ -373,11 +370,10 @@ public void linkAccountFailureInputUserIsNotAPrimaryUser() throws Exception { @Test public void linkAccountFailureUserDoesNotExist() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -387,7 +383,7 @@ public void linkAccountFailureUserDoesNotExist() throws Exception { AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "password"); assert (!user.isPrimaryUser); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), "google", "user-google", @@ -396,19 +392,19 @@ public void linkAccountFailureUserDoesNotExist() throws Exception { assert (!user2.isPrimaryUser); try { - AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), "random"); + AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), "random"); assert (false); } catch (UnknownUserIdException e) { } try { - AuthRecipe.linkAccounts(process.main, "random2", user.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), "random2", user.getSupertokensUserId()); assert (false); } catch (UnknownUserIdException e) { } try { - AuthRecipe.linkAccounts(process.main, "random2", "random"); + AuthRecipe.linkAccounts(process.getProcess(), "random2", "random"); assert (false); } catch (UnknownUserIdException e) { } @@ -420,11 +416,10 @@ public void linkAccountFailureUserDoesNotExist() throws Exception { @Test public void linkAccountFailureCauseAccountInfoAssociatedWithAPrimaryUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -433,7 +428,7 @@ public void linkAccountFailureCauseAccountInfoAssociatedWithAPrimaryUser() throw AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "password"); assert (!user.isPrimaryUser); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); Thread.sleep(50); @@ -446,10 +441,10 @@ public void linkAccountFailureCauseAccountInfoAssociatedWithAPrimaryUser() throw AuthRecipeUserInfo otherPrimaryUser = EmailPassword.signUp(process.getProcess(), "test3@example.com", "password"); - AuthRecipe.createPrimaryUser(process.main, otherPrimaryUser.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), otherPrimaryUser.getSupertokensUserId()); try { - AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), otherPrimaryUser.getSupertokensUserId()); assert (false); } catch (AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException e) { @@ -464,35 +459,34 @@ public void linkAccountFailureCauseAccountInfoAssociatedWithAPrimaryUser() throw @Test public void linkAccountFailureCauseAccountInfoAssociatedWithAPrimaryUserEvenIfInDifferentTenant() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - Multitenancy.addNewOrUpdateAppOrTenant(process.main, new TenantIdentifier(null, null, null), - new TenantConfig(new TenantIdentifier(null, null, "t1"), new EmailPasswordConfig(true), + Multitenancy.addNewOrUpdateAppOrTenant(process.getProcess(), new TenantIdentifier(null, process.getAppForTesting().getAppId(), null), + new TenantConfig(new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"), new EmailPasswordConfig(true), new ThirdPartyConfig(true, null), new PasswordlessConfig(true), null, null, new JsonObject())); - Storage storage = (StorageLayer.getStorage(process.main)); + Storage storage = (StorageLayer.getStorage(process.getProcess())); AuthRecipeUserInfo user = - EmailPassword.signUp(new TenantIdentifier(null, null, "t1"), storage, + EmailPassword.signUp(new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"), storage, process.getProcess(), "test@example.com", "password"); assert (!user.isPrimaryUser); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); Thread.sleep(50); ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp( - new TenantIdentifier(null, null, "t1"), storage, + new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"), storage, process.getProcess(), "google", "user-google", "test@example.com"); @@ -502,10 +496,10 @@ public void linkAccountFailureCauseAccountInfoAssociatedWithAPrimaryUserEvenIfIn AuthRecipeUserInfo otherPrimaryUser = EmailPassword.signUp(process.getProcess(), "test3@example.com", "password"); - AuthRecipe.createPrimaryUser(process.main, otherPrimaryUser.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), otherPrimaryUser.getSupertokensUserId()); try { - AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), otherPrimaryUser.getSupertokensUserId()); assert (false); } catch (AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException e) { @@ -520,55 +514,54 @@ public void linkAccountFailureCauseAccountInfoAssociatedWithAPrimaryUserEvenIfIn @Test public void linkAccountFailureCauseAccountInfoAssociatedWithAPrimaryUserEvenIfInDifferentTenant2() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - Multitenancy.addNewOrUpdateAppOrTenant(process.main, new TenantIdentifier(null, null, null), - new TenantConfig(new TenantIdentifier(null, null, "t1"), new EmailPasswordConfig(true), + Multitenancy.addNewOrUpdateAppOrTenant(process.getProcess(), new TenantIdentifier(null, process.getAppForTesting().getAppId(), null), + new TenantConfig(new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"), new EmailPasswordConfig(true), new ThirdPartyConfig(true, null), new PasswordlessConfig(true), null, null, new JsonObject())); - Multitenancy.addNewOrUpdateAppOrTenant(process.main, new TenantIdentifier(null, null, null), - new TenantConfig(new TenantIdentifier(null, null, "t2"), new EmailPasswordConfig(true), + Multitenancy.addNewOrUpdateAppOrTenant(process.getProcess(), new TenantIdentifier(null, process.getAppForTesting().getAppId(), null), + new TenantConfig(new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t2"), new EmailPasswordConfig(true), new ThirdPartyConfig(true, null), new PasswordlessConfig(true), null, null, new JsonObject())); - Storage storage = (StorageLayer.getStorage(process.main)); + Storage storage = (StorageLayer.getStorage(process.getProcess())); AuthRecipeUserInfo conflictingUser = - EmailPassword.signUp(new TenantIdentifier(null, null, "t2"), storage, + EmailPassword.signUp(new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t2"), storage, process.getProcess(), "test@example.com", "password"); assert (!conflictingUser.isPrimaryUser); - AuthRecipe.createPrimaryUser(process.main, conflictingUser.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), conflictingUser.getSupertokensUserId()); Thread.sleep(50); AuthRecipeUserInfo user1 = - EmailPassword.signUp(new TenantIdentifier(null, null, "t1"), storage, + EmailPassword.signUp(new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"), storage, process.getProcess(), "test@example.com", "password"); assert (!user1.isPrimaryUser); AuthRecipeUserInfo user2 = - EmailPassword.signUp(new TenantIdentifier(null, null, "t2"), storage, + EmailPassword.signUp(new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t2"), storage, process.getProcess(), "test2@example.com", "password"); assert (!user1.isPrimaryUser); - AuthRecipe.createPrimaryUser(process.main, user1.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user1.getSupertokensUserId()); try { - AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user1.getSupertokensUserId()); assert (false); } catch (AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException e) { @@ -583,29 +576,28 @@ public void linkAccountFailureCauseAccountInfoAssociatedWithAPrimaryUserEvenIfIn @Test public void linkAccountSuccessAcrossTenants() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - Multitenancy.addNewOrUpdateAppOrTenant(process.main, new TenantIdentifier(null, null, null), - new TenantConfig(new TenantIdentifier(null, null, "t1"), new EmailPasswordConfig(true), + Multitenancy.addNewOrUpdateAppOrTenant(process.getProcess(), new TenantIdentifier(null, process.getAppForTesting().getAppId(), null), + new TenantConfig(new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"), new EmailPasswordConfig(true), new ThirdPartyConfig(true, new ThirdPartyConfig.Provider[0]), new PasswordlessConfig(true), null, null, new JsonObject())); - Storage storage = (StorageLayer.getStorage(process.main)); + Storage storage = (StorageLayer.getStorage(process.getProcess())); - AuthRecipeUserInfo user = EmailPassword.signUp(new TenantIdentifier(null, null, "t1"), + AuthRecipeUserInfo user = EmailPassword.signUp(new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"), storage, process.getProcess(), "test@example.com", "password"); assert (!user.isPrimaryUser); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); Thread.sleep(50); @@ -616,12 +608,12 @@ public void linkAccountSuccessAcrossTenants() throws Exception { AuthRecipeUserInfo user2 = signInUpResponse.user; assert (!user2.isPrimaryUser); - boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user.getSupertokensUserId()).wasAlreadyLinked; assert (!wasAlreadyLinked); - AuthRecipeUserInfo refetchedUser1 = AuthRecipe.getUserById(process.main, user.getSupertokensUserId()); - AuthRecipeUserInfo refetchedUser2 = AuthRecipe.getUserById(process.main, user2.getSupertokensUserId()); + AuthRecipeUserInfo refetchedUser1 = AuthRecipe.getUserById(process.getProcess(), user.getSupertokensUserId()); + AuthRecipeUserInfo refetchedUser2 = AuthRecipe.getUserById(process.getProcess(), user2.getSupertokensUserId()); assert (refetchedUser1.getSupertokensUserId().equals(refetchedUser2.getSupertokensUserId())); assert refetchedUser1.loginMethods.length == 2; assert refetchedUser1.tenantIds.size() == 2; @@ -642,11 +634,10 @@ public void linkAccountSuccessAcrossTenants() throws Exception { @Test public void linkAccountSuccessWithPasswordlessEmailAndPhoneNumber() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -665,17 +656,17 @@ public void linkAccountSuccessWithPasswordlessEmailAndPhoneNumber() throws Excep AuthRecipeUserInfo user2 = pResp.user; assert (!user2.isPrimaryUser); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); - Passwordless.updateUser(process.main, user2.getSupertokensUserId(), null, new Passwordless.FieldUpdate("1234")); - user2 = AuthRecipe.getUserById(process.main, user2.getSupertokensUserId()); + Passwordless.updateUser(process.getProcess(), user2.getSupertokensUserId(), null, new Passwordless.FieldUpdate("1234")); + user2 = AuthRecipe.getUserById(process.getProcess(), user2.getSupertokensUserId()); - boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), + boolean wasAlreadyLinked = AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user.getSupertokensUserId()).wasAlreadyLinked; assert (!wasAlreadyLinked); - AuthRecipeUserInfo refetchUser2 = AuthRecipe.getUserById(process.main, user2.getSupertokensUserId()); - AuthRecipeUserInfo refetchUser = AuthRecipe.getUserById(process.main, user.getSupertokensUserId()); + AuthRecipeUserInfo refetchUser2 = AuthRecipe.getUserById(process.getProcess(), user2.getSupertokensUserId()); + AuthRecipeUserInfo refetchUser = AuthRecipe.getUserById(process.getProcess(), user.getSupertokensUserId()); assert (refetchUser2.equals(refetchUser)); assert (refetchUser2.loginMethods.length == 2); assert (refetchUser.loginMethods[0].equals(user.loginMethods[0])); @@ -691,11 +682,10 @@ public void linkAccountSuccessWithPasswordlessEmailAndPhoneNumber() throws Excep @Test public void linkAccountMergesLastActiveTimes() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -704,20 +694,20 @@ public void linkAccountMergesLastActiveTimes() throws Exception { AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "password"); assert (!user.isPrimaryUser); - ActiveUsers.updateLastActive(process.main, user.getSupertokensUserId()); + ActiveUsers.updateLastActive(process.getProcess(), user.getSupertokensUserId()); Thread.sleep(50); AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "password"); assert (!user2.isPrimaryUser); long secondUserTime = System.currentTimeMillis(); - ActiveUsers.updateLastActive(process.main, user2.getSupertokensUserId()); + ActiveUsers.updateLastActive(process.getProcess(), user2.getSupertokensUserId()); - assertEquals(ActiveUsers.countUsersActiveSince(process.main, 0), 2); + assertEquals(ActiveUsers.countUsersActiveSince(process.getProcess(), 0), 2); long createPrimaryTime = System.currentTimeMillis(); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); Thread.sleep(50); - assertEquals(ActiveUsers.countUsersActiveSince(process.main, 0), 2); + assertEquals(ActiveUsers.countUsersActiveSince(process.getProcess(), 0), 2); { JsonObject params = new JsonObject(); @@ -731,9 +721,9 @@ public void linkAccountMergesLastActiveTimes() throws Exception { assertEquals("OK", response.get("status").getAsString()); } - assertEquals(ActiveUsers.countUsersActiveSince(process.main, 0), 1); - assertEquals(ActiveUsers.countUsersActiveSince(process.main, secondUserTime), 1); - assertEquals(ActiveUsers.countUsersActiveSince(process.main, createPrimaryTime), + assertEquals(ActiveUsers.countUsersActiveSince(process.getProcess(), 0), 1); + assertEquals(ActiveUsers.countUsersActiveSince(process.getProcess(), secondUserTime), 1); + assertEquals(ActiveUsers.countUsersActiveSince(process.getProcess(), createPrimaryTime), 1); // 1 since we update user last active while linking process.kill(); @@ -743,11 +733,10 @@ public void linkAccountMergesLastActiveTimes() throws Exception { @Test public void linkAccountMergesLastActiveTimes_PrimaryFirst() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -756,20 +745,20 @@ public void linkAccountMergesLastActiveTimes_PrimaryFirst() throws Exception { AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "password"); assert (!user.isPrimaryUser); - ActiveUsers.updateLastActive(process.main, user.getSupertokensUserId()); + ActiveUsers.updateLastActive(process.getProcess(), user.getSupertokensUserId()); Thread.sleep(50); AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "password"); assert (!user2.isPrimaryUser); long secondUserTime = System.currentTimeMillis(); - ActiveUsers.updateLastActive(process.main, user2.getSupertokensUserId()); + ActiveUsers.updateLastActive(process.getProcess(), user2.getSupertokensUserId()); - assertEquals(ActiveUsers.countUsersActiveSince(process.main, 0), 2); + assertEquals(ActiveUsers.countUsersActiveSince(process.getProcess(), 0), 2); long createPrimaryTime = System.currentTimeMillis(); - AuthRecipe.createPrimaryUser(process.main, user2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user2.getSupertokensUserId()); Thread.sleep(50); - assertEquals(ActiveUsers.countUsersActiveSince(process.main, 0), 2); + assertEquals(ActiveUsers.countUsersActiveSince(process.getProcess(), 0), 2); { JsonObject params = new JsonObject(); @@ -783,9 +772,9 @@ public void linkAccountMergesLastActiveTimes_PrimaryFirst() throws Exception { assertEquals("OK", response.get("status").getAsString()); } - assertEquals(ActiveUsers.countUsersActiveSince(process.main, 0), 1); - assertEquals(ActiveUsers.countUsersActiveSince(process.main, secondUserTime), 1); - assertEquals(ActiveUsers.countUsersActiveSince(process.main, createPrimaryTime), + assertEquals(ActiveUsers.countUsersActiveSince(process.getProcess(), 0), 1); + assertEquals(ActiveUsers.countUsersActiveSince(process.getProcess(), secondUserTime), 1); + assertEquals(ActiveUsers.countUsersActiveSince(process.getProcess(), createPrimaryTime), 1); // 1 since we update user last active while linking process.kill(); diff --git a/src/test/java/io/supertokens/test/accountlinking/MultitenantTest.java b/src/test/java/io/supertokens/test/accountlinking/MultitenantTest.java index 3c42ed9ca..a16d34abf 100644 --- a/src/test/java/io/supertokens/test/accountlinking/MultitenantTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/MultitenantTest.java @@ -66,6 +66,9 @@ public class MultitenantTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -169,11 +172,10 @@ private void createTenants(Main main) @Test public void testUserAreNotAutomaticallySharedBetweenTenantsOfLinkedAccountsForPless() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -217,11 +219,10 @@ public void testUserAreNotAutomaticallySharedBetweenTenantsOfLinkedAccountsForPl @Test public void testUserAreNotAutomaticallySharedBetweenTenantsOfLinkedAccountsForTP() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -261,11 +262,10 @@ public void testUserAreNotAutomaticallySharedBetweenTenantsOfLinkedAccountsForTP @Test public void testTenantDeletionWithAccountLinking() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -311,11 +311,10 @@ public void testTenantDeletionWithAccountLinking() throws Exception { @Test public void testTenantDeletionWithAccountLinkingWithUserRoles() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -871,11 +870,10 @@ public void execute(Main main) throws Exception { int i = 0; for (TestCase testCase : testCases) { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -914,6 +912,7 @@ public void doTest(Main main) throws Exception { for (TestCaseStep step : steps) { step.doStep(main); + Thread.sleep(20); } } } diff --git a/src/test/java/io/supertokens/test/accountlinking/SessionTests.java b/src/test/java/io/supertokens/test/accountlinking/SessionTests.java index ac12a8c9a..ac99ef5ad 100644 --- a/src/test/java/io/supertokens/test/accountlinking/SessionTests.java +++ b/src/test/java/io/supertokens/test/accountlinking/SessionTests.java @@ -56,6 +56,9 @@ public class SessionTests { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -164,11 +167,10 @@ private void createTenants(Main main) @Test public void testCreateSessionWithRecipeUserIdReturnsSessionWithPrimaryUserId() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -193,11 +195,10 @@ public void testCreateSessionWithRecipeUserIdReturnsSessionWithPrimaryUserId() t @Test public void testSessionIsRemovedWhileLinking() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -232,11 +233,10 @@ public void testSessionIsRemovedWhileLinking() throws Exception { @Test public void testSessionIsRemovedWhileUnlinking() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -271,11 +271,10 @@ public void testSessionIsRemovedWhileUnlinking() throws Exception { @Test public void testSessionBehaviourWhenUserBelongsTo2TenantsAndThenLinkedToSomeOtherUser1() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -317,11 +316,10 @@ public void testSessionBehaviourWhenUserBelongsTo2TenantsAndThenLinkedToSomeOthe @Test public void testSessionBehaviourWhenUserBelongsTo2TenantsAndThenLinkedToSomeOtherUser2() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -363,11 +361,10 @@ public void testSessionBehaviourWhenUserBelongsTo2TenantsAndThenLinkedToSomeOthe @Test public void testSessionBehaviourWhenUserBelongsTo2TenantsAndThenLinkedToSomeOtherUser3() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -404,11 +401,10 @@ public void testSessionBehaviourWhenUserBelongsTo2TenantsAndThenLinkedToSomeOthe @Test public void testCreateSessionUsesPrimaryUserIdEvenWhenTheUserIsNotInThatTenant() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -444,11 +440,10 @@ public void testCreateSessionUsesPrimaryUserIdEvenWhenTheUserIsNotInThatTenant() @Test public void testGetSessionForUserWithAndWithoutIncludingAllLinkedAccounts() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -469,14 +464,14 @@ public void testGetSessionForUserWithAndWithoutIncludingAllLinkedAccounts() thro Storage baseTenant = (StorageLayer.getBaseStorage(process.getProcess())); { - String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(TenantIdentifier.BASE_TENANT, baseTenant, + String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.getAppForTesting(), baseTenant, user1.getSupertokensUserId(), false); assertEquals(1, sessions.length); assertEquals(session1.session.handle, sessions[0]); } { - String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(TenantIdentifier.BASE_TENANT, baseTenant, + String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.getAppForTesting(), baseTenant, user2.getSupertokensUserId(), false); assertEquals(1, sessions.length); @@ -484,13 +479,13 @@ public void testGetSessionForUserWithAndWithoutIncludingAllLinkedAccounts() thro } { - String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(TenantIdentifier.BASE_TENANT, baseTenant, + String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.getAppForTesting(), baseTenant, user1.getSupertokensUserId(), true); assertEquals(2, sessions.length); } { - String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(TenantIdentifier.BASE_TENANT, baseTenant, + String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.getAppForTesting(), baseTenant, user2.getSupertokensUserId(), true); assertEquals(2, sessions.length); @@ -503,11 +498,10 @@ public void testGetSessionForUserWithAndWithoutIncludingAllLinkedAccounts() thro @Test public void testRevokeSessionsForUserWithAndWithoutIncludingAllLinkedAccounts() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -531,7 +525,7 @@ public void testRevokeSessionsForUserWithAndWithoutIncludingAllLinkedAccounts() Storage baseTenant = ( StorageLayer.getBaseStorage(process.getProcess())); - Session.revokeAllSessionsForUser(process.getProcess(), TenantIdentifier.BASE_TENANT, baseTenant, + Session.revokeAllSessionsForUser(process.getProcess(), process.getAppForTesting(), baseTenant, user1.getSupertokensUserId(), true); try { @@ -558,7 +552,7 @@ public void testRevokeSessionsForUserWithAndWithoutIncludingAllLinkedAccounts() Storage baseTenant = ( StorageLayer.getBaseStorage(process.getProcess())); - Session.revokeAllSessionsForUser(process.getProcess(), TenantIdentifier.BASE_TENANT, baseTenant, + Session.revokeAllSessionsForUser(process.getProcess(), process.getAppForTesting(), baseTenant, user2.getSupertokensUserId(), true); try { @@ -585,7 +579,7 @@ public void testRevokeSessionsForUserWithAndWithoutIncludingAllLinkedAccounts() Storage baseTenant = ( StorageLayer.getBaseStorage(process.getProcess())); - Session.revokeAllSessionsForUser(process.getProcess(), TenantIdentifier.BASE_TENANT, baseTenant, + Session.revokeAllSessionsForUser(process.getProcess(), process.getAppForTesting(), baseTenant, user1.getSupertokensUserId(), false); try { @@ -608,7 +602,7 @@ public void testRevokeSessionsForUserWithAndWithoutIncludingAllLinkedAccounts() Storage baseTenant = ( StorageLayer.getBaseStorage(process.getProcess())); - Session.revokeAllSessionsForUser(process.getProcess(), TenantIdentifier.BASE_TENANT, baseTenant, + Session.revokeAllSessionsForUser(process.getProcess(), process.getAppForTesting(), baseTenant, user2.getSupertokensUserId(), false); Session.getSession(process.getProcess(), session1.session.handle); @@ -628,11 +622,10 @@ public void testRevokeSessionsForUserWithAndWithoutIncludingAllLinkedAccounts() @Test public void testCreateSessionWithUserIdMappedForRecipeUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/accountlinking/TestGetUserSpeed.java b/src/test/java/io/supertokens/test/accountlinking/TestGetUserSpeed.java index b446715c5..6438b7a48 100644 --- a/src/test/java/io/supertokens/test/accountlinking/TestGetUserSpeed.java +++ b/src/test/java/io/supertokens/test/accountlinking/TestGetUserSpeed.java @@ -48,6 +48,9 @@ public class TestGetUserSpeed { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -170,7 +173,7 @@ public void testUserCreationLinkingAndGetByIdSpeedsCommon(TestingProcessManager. //@Test public void testUserCreationLinkingAndGetByIdSpeedsWithoutMinIdle() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); Utils.setValueInConfig("postgresql_connection_pool_size", "100"); Utils.setValueInConfig("mysql_connection_pool_size", "100"); @@ -183,14 +186,14 @@ public void testUserCreationLinkingAndGetByIdSpeedsWithoutMinIdle() throws Excep testUserCreationLinkingAndGetByIdSpeedsCommon(process, 25000, 50000, 20000); } - @Test + //@Test public void testUserCreationLinkingAndGetByIdSpeedsWithMinIdle() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); Utils.setValueInConfig("postgresql_connection_pool_size", "100"); Utils.setValueInConfig("mysql_connection_pool_size", "100"); Utils.setValueInConfig("postgresql_minimum_idle_connections", "1"); Utils.setValueInConfig("mysql_minimum_idle_connections", "1"); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ diff --git a/src/test/java/io/supertokens/test/accountlinking/TimeJoinedTest.java b/src/test/java/io/supertokens/test/accountlinking/TimeJoinedTest.java index d13fbca07..4cfe18f67 100644 --- a/src/test/java/io/supertokens/test/accountlinking/TimeJoinedTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/TimeJoinedTest.java @@ -46,6 +46,9 @@ public class TimeJoinedTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -60,11 +63,10 @@ public void beforeEach() { @Test public void testThatTimeJoinedIsCorrectWhileLinkingAndUnlinking() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -97,11 +99,10 @@ public void testThatTimeJoinedIsCorrectWhileLinkingAndUnlinking() throws Excepti @Test public void testThatTimeJoinedIsCorrectWhileAssociatingTenants() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -122,9 +123,9 @@ public void testThatTimeJoinedIsCorrectWhileAssociatingTenants() throws Exceptio Storage baseTenant = (StorageLayer.getStorage(process.getProcess())); - Multitenancy.removeUserIdFromTenant(process.getProcess(), TenantIdentifier.BASE_TENANT, baseTenant, + Multitenancy.removeUserIdFromTenant(process.getProcess(), process.getAppForTesting(), baseTenant, user1.getSupertokensUserId(), null); - Multitenancy.removeUserIdFromTenant(process.getProcess(), TenantIdentifier.BASE_TENANT, baseTenant, + Multitenancy.removeUserIdFromTenant(process.getProcess(), process.getAppForTesting(), baseTenant, user2.getSupertokensUserId(), null); { @@ -132,7 +133,7 @@ public void testThatTimeJoinedIsCorrectWhileAssociatingTenants() throws Exceptio assertEquals(user1.timeJoined, userInfo.timeJoined); } - Multitenancy.addUserIdToTenant(process.getProcess(), TenantIdentifier.BASE_TENANT, baseTenant, + Multitenancy.addUserIdToTenant(process.getProcess(), process.getAppForTesting(), baseTenant, user2.getSupertokensUserId()); { @@ -140,7 +141,7 @@ public void testThatTimeJoinedIsCorrectWhileAssociatingTenants() throws Exceptio assertEquals(user1.timeJoined, userInfo.timeJoined); } - Multitenancy.addUserIdToTenant(process.getProcess(), TenantIdentifier.BASE_TENANT, baseTenant, + Multitenancy.addUserIdToTenant(process.getProcess(), process.getAppForTesting(), baseTenant, user1.getSupertokensUserId()); { @@ -155,11 +156,10 @@ public void testThatTimeJoinedIsCorrectWhileAssociatingTenants() throws Exceptio @Test public void testUserPaginationIsFineWithUnlinkAndUnlinkAccounts() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -202,11 +202,10 @@ public void testUserPaginationIsFineWithUnlinkAndUnlinkAccounts() throws Excepti @Test public void testUserPaginationIsFineWithTenantAssociation() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -228,7 +227,7 @@ public void testUserPaginationIsFineWithTenantAssociation() throws Exception { assertEquals(1, users.users.length); } - Multitenancy.removeUserIdFromTenant(process.getProcess(), TenantIdentifier.BASE_TENANT, baseTenant, + Multitenancy.removeUserIdFromTenant(process.getProcess(), process.getAppForTesting(), baseTenant, user1.getSupertokensUserId(), null); { @@ -237,7 +236,7 @@ public void testUserPaginationIsFineWithTenantAssociation() throws Exception { assertEquals(1, users.users.length); } - Multitenancy.addUserIdToTenant(process.getProcess(), TenantIdentifier.BASE_TENANT, baseTenant, + Multitenancy.addUserIdToTenant(process.getProcess(), process.getAppForTesting(), baseTenant, user1.getSupertokensUserId()); { @@ -253,11 +252,10 @@ public void testUserPaginationIsFineWithTenantAssociation() throws Exception { @Test public void testUserSearchWorksWithUnlinkAndLinkAccounts() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -306,11 +304,10 @@ public void testUserSearchWorksWithUnlinkAndLinkAccounts() throws Exception { @Test public void testUserSearchWorksWithTenantAssociation() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -334,7 +331,7 @@ public void testUserSearchWorksWithTenantAssociation() throws Exception { assertEquals(1, users.users.length); } - Multitenancy.removeUserIdFromTenant(process.getProcess(), TenantIdentifier.BASE_TENANT, baseTenant, + Multitenancy.removeUserIdFromTenant(process.getProcess(), process.getAppForTesting(), baseTenant, user2.getSupertokensUserId(), null); { @@ -345,7 +342,7 @@ public void testUserSearchWorksWithTenantAssociation() throws Exception { assertEquals(1, users.users.length); } - Multitenancy.addUserIdToTenant(process.getProcess(), TenantIdentifier.BASE_TENANT, baseTenant, + Multitenancy.addUserIdToTenant(process.getProcess(), process.getAppForTesting(), baseTenant, user2.getSupertokensUserId()); { diff --git a/src/test/java/io/supertokens/test/accountlinking/UnlinkAccountsTest.java b/src/test/java/io/supertokens/test/accountlinking/UnlinkAccountsTest.java index 5a9d7cb74..e63333e27 100644 --- a/src/test/java/io/supertokens/test/accountlinking/UnlinkAccountsTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/UnlinkAccountsTest.java @@ -43,6 +43,9 @@ public class UnlinkAccountsTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -56,11 +59,10 @@ public void beforeEach() { @Test public void unlinkAccountSuccess() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -75,31 +77,31 @@ public void unlinkAccountSuccess() throws Exception { AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "password"); assert (!user2.isPrimaryUser); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), user.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user.getSupertokensUserId()); - Session.createNewSession(process.main, user2.getSupertokensUserId(), new JsonObject(), new JsonObject()); - String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.main, user2.getSupertokensUserId()); + Session.createNewSession(process.getProcess(), user2.getSupertokensUserId(), new JsonObject(), new JsonObject()); + String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.getProcess(), user2.getSupertokensUserId()); assert (sessions.length == 1); - boolean didDelete = AuthRecipe.unlinkAccounts(process.main, user2.getSupertokensUserId()); + boolean didDelete = AuthRecipe.unlinkAccounts(process.getProcess(), user2.getSupertokensUserId()); assert (!didDelete); - AuthRecipeUserInfo refetchUser2 = AuthRecipe.getUserById(process.main, user2.getSupertokensUserId()); + AuthRecipeUserInfo refetchUser2 = AuthRecipe.getUserById(process.getProcess(), user2.getSupertokensUserId()); assert (!refetchUser2.isPrimaryUser); assert (refetchUser2.getSupertokensUserId().equals(user2.getSupertokensUserId())); assert (refetchUser2.loginMethods.length == 1); assert (refetchUser2.loginMethods[0].getSupertokensUserId().equals(user2.getSupertokensUserId())); - AuthRecipeUserInfo refetchUser = AuthRecipe.getUserById(process.main, user.getSupertokensUserId()); + AuthRecipeUserInfo refetchUser = AuthRecipe.getUserById(process.getProcess(), user.getSupertokensUserId()); assert (!refetchUser2.equals(refetchUser)); assert (refetchUser.isPrimaryUser); assert (refetchUser.loginMethods.length == 1); assert (refetchUser.loginMethods[0].getSupertokensUserId().equals(user.getSupertokensUserId())); // cause linkAccounts revokes sessions for the recipe user ID - sessions = Session.getAllNonExpiredSessionHandlesForUser(process.main, user2.getSupertokensUserId()); + sessions = Session.getAllNonExpiredSessionHandlesForUser(process.getProcess(), user2.getSupertokensUserId()); assert (sessions.length == 0); process.kill(); @@ -109,11 +111,10 @@ public void unlinkAccountSuccess() throws Exception { @Test public void unlinkAccountWithoutPrimaryUserId() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -124,7 +125,7 @@ public void unlinkAccountWithoutPrimaryUserId() throws Exception { assert (!user.isPrimaryUser); try { - AuthRecipe.unlinkAccounts(process.main, user.getSupertokensUserId()); + AuthRecipe.unlinkAccounts(process.getProcess(), user.getSupertokensUserId()); assert (false); } catch (InputUserIdIsNotAPrimaryUserException e) { assert (e.userId.equals(user.getSupertokensUserId())); @@ -138,11 +139,10 @@ public void unlinkAccountWithoutPrimaryUserId() throws Exception { @Test public void unlinkAccountWithUnknownUserId() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -150,7 +150,7 @@ public void unlinkAccountWithUnknownUserId() throws Exception { } try { - AuthRecipe.unlinkAccounts(process.main, "random"); + AuthRecipe.unlinkAccounts(process.getProcess(), "random"); assert (false); } catch (UnknownUserIdException e) { } @@ -163,11 +163,10 @@ public void unlinkAccountWithUnknownUserId() throws Exception { @Test public void unlinkAccountWithPrimaryUserBecomesRecipeUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -177,22 +176,22 @@ public void unlinkAccountWithPrimaryUserBecomesRecipeUser() throws Exception { AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "password"); assert (!user.isPrimaryUser); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); - Session.createNewSession(process.main, user.getSupertokensUserId(), new JsonObject(), new JsonObject()); - String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.main, user.getSupertokensUserId()); + Session.createNewSession(process.getProcess(), user.getSupertokensUserId(), new JsonObject(), new JsonObject()); + String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.getProcess(), user.getSupertokensUserId()); assert (sessions.length == 1); - boolean didDelete = AuthRecipe.unlinkAccounts(process.main, user.getSupertokensUserId()); + boolean didDelete = AuthRecipe.unlinkAccounts(process.getProcess(), user.getSupertokensUserId()); assert (!didDelete); - AuthRecipeUserInfo refetchUser = AuthRecipe.getUserById(process.main, user.getSupertokensUserId()); + AuthRecipeUserInfo refetchUser = AuthRecipe.getUserById(process.getProcess(), user.getSupertokensUserId()); assert (!refetchUser.isPrimaryUser); assert (refetchUser.loginMethods.length == 1); assert (refetchUser.loginMethods[0].getSupertokensUserId().equals(user.getSupertokensUserId())); // cause linkAccounts revokes sessions for the recipe user ID - sessions = Session.getAllNonExpiredSessionHandlesForUser(process.main, user.getSupertokensUserId()); + sessions = Session.getAllNonExpiredSessionHandlesForUser(process.getProcess(), user.getSupertokensUserId()); assert (sessions.length == 0); process.kill(); @@ -202,11 +201,10 @@ public void unlinkAccountWithPrimaryUserBecomesRecipeUser() throws Exception { @Test public void unlinkAccountSuccessButDeletesUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -221,28 +219,28 @@ public void unlinkAccountSuccessButDeletesUser() throws Exception { AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "password"); assert (!user2.isPrimaryUser); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), user.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user.getSupertokensUserId()); - Session.createNewSession(process.main, user.getSupertokensUserId(), new JsonObject(), new JsonObject()); - String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.main, user.getSupertokensUserId()); + Session.createNewSession(process.getProcess(), user.getSupertokensUserId(), new JsonObject(), new JsonObject()); + String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.getProcess(), user.getSupertokensUserId()); assert (sessions.length == 1); - boolean didDelete = AuthRecipe.unlinkAccounts(process.main, user.getSupertokensUserId()); + boolean didDelete = AuthRecipe.unlinkAccounts(process.getProcess(), user.getSupertokensUserId()); assert (didDelete); - AuthRecipeUserInfo refetchUser2 = AuthRecipe.getUserById(process.main, user2.getSupertokensUserId()); + AuthRecipeUserInfo refetchUser2 = AuthRecipe.getUserById(process.getProcess(), user2.getSupertokensUserId()); assert (refetchUser2.isPrimaryUser); assert (refetchUser2.getSupertokensUserId().equals(user.getSupertokensUserId())); assert (refetchUser2.loginMethods.length == 1); assert (refetchUser2.loginMethods[0].getSupertokensUserId().equals(user2.getSupertokensUserId())); - AuthRecipeUserInfo refetchUser = AuthRecipe.getUserById(process.main, user.getSupertokensUserId()); + AuthRecipeUserInfo refetchUser = AuthRecipe.getUserById(process.getProcess(), user.getSupertokensUserId()); assert (refetchUser2.equals(refetchUser)); // cause linkAccounts revokes sessions for the recipe user ID - sessions = Session.getAllNonExpiredSessionHandlesForUser(process.main, user.getSupertokensUserId()); + sessions = Session.getAllNonExpiredSessionHandlesForUser(process.getProcess(), user.getSupertokensUserId()); assert (sessions.length == 0); process.kill(); @@ -252,11 +250,10 @@ public void unlinkAccountSuccessButDeletesUser() throws Exception { @Test public void testUnlinkUserDeletesRecipeUserAndAnotherUserLinkToIt() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/accountlinking/UpdateUserTest.java b/src/test/java/io/supertokens/test/accountlinking/UpdateUserTest.java index cc66157b6..d96babfa2 100644 --- a/src/test/java/io/supertokens/test/accountlinking/UpdateUserTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/UpdateUserTest.java @@ -40,6 +40,9 @@ public class UpdateUserTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -53,11 +56,10 @@ public void beforeEach() { @Test public void testThatUpdateEmailFailsWhenPassedWithNonEmailPasswordRecipeUserId() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/accountlinking/UserIdMappingTest.java b/src/test/java/io/supertokens/test/accountlinking/UserIdMappingTest.java index 78f4c79ac..154b527ee 100644 --- a/src/test/java/io/supertokens/test/accountlinking/UserIdMappingTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/UserIdMappingTest.java @@ -41,6 +41,9 @@ public class UserIdMappingTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -54,11 +57,10 @@ public void beforeEach() { @Test public void testUserIdMappingWithUnlinkedAccountUserid() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -89,11 +91,10 @@ public void testUserIdMappingWithUnlinkedAccountUserid() throws Exception { @Test public void testUserIdMappingWithDeletedUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/accountlinking/UserSearchTest.java b/src/test/java/io/supertokens/test/accountlinking/UserSearchTest.java index acd06e505..e9843ea9b 100644 --- a/src/test/java/io/supertokens/test/accountlinking/UserSearchTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/UserSearchTest.java @@ -45,6 +45,9 @@ public class UserSearchTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -58,11 +61,10 @@ public void beforeEach() { @Test public void testUserSearch() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/accountlinking/api/ActiveUserTest.java b/src/test/java/io/supertokens/test/accountlinking/api/ActiveUserTest.java index 122eb8b3e..906174adb 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/ActiveUserTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/ActiveUserTest.java @@ -57,6 +57,9 @@ public class ActiveUserTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -101,11 +104,10 @@ AuthRecipeUserInfo createPasswordlessUserWithPhone(Main main, String phone) @Test public void testActiveUserIsRemovedAfterLinkingAccounts() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -146,7 +148,7 @@ public void testActiveUserIsRemovedAfterLinkingAccounts() throws Exception { { // Link accounts - AuthRecipe.createPrimaryUser(process.main, user2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user2.getSupertokensUserId()); JsonObject params = new JsonObject(); params.addProperty("recipeUserId", user1.getSupertokensUserId()); diff --git a/src/test/java/io/supertokens/test/accountlinking/api/CanCreatePrimaryUserAPITest.java b/src/test/java/io/supertokens/test/accountlinking/api/CanCreatePrimaryUserAPITest.java index c682cb649..db78f13f9 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/CanCreatePrimaryUserAPITest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/CanCreatePrimaryUserAPITest.java @@ -47,6 +47,9 @@ public class CanCreatePrimaryUserAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -60,11 +63,10 @@ public void beforeEach() { @Test public void canCreateReturnsTrue() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -85,7 +87,7 @@ public void canCreateReturnsTrue() throws Exception { assertFalse(response.get("wasAlreadyAPrimaryUser").getAsBoolean()); } - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); { Map params = new HashMap<>(); @@ -106,11 +108,10 @@ public void canCreateReturnsTrue() throws Exception { @Test public void canCreateReturnsTrueWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -118,7 +119,7 @@ public void canCreateReturnsTrueWithUserIdMapping() throws Exception { } AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "abcd1234"); - UserIdMapping.createUserIdMapping(process.main, user.getSupertokensUserId(), "r1", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), user.getSupertokensUserId(), "r1", null, false); { Map params = new HashMap<>(); @@ -132,7 +133,7 @@ public void canCreateReturnsTrueWithUserIdMapping() throws Exception { assertFalse(response.get("wasAlreadyAPrimaryUser").getAsBoolean()); } - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); { Map params = new HashMap<>(); @@ -153,11 +154,10 @@ public void canCreateReturnsTrueWithUserIdMapping() throws Exception { @Test public void canCreatePrimaryUserBadInput() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -203,11 +203,10 @@ public void canCreatePrimaryUserBadInput() throws Exception { @Test public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -217,11 +216,11 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); - ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", + ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), "google", "user-google", "test@example.com"); { @@ -246,11 +245,10 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU @Test public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccount() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -262,8 +260,8 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccount() throws Ex AuthRecipeUserInfo emailPasswordUser2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass1234"); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); { @@ -289,11 +287,10 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccount() throws Ex public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUserWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -302,13 +299,13 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - UserIdMapping.createUserIdMapping(process.main, emailPasswordUser.getSupertokensUserId(), "r1", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), emailPasswordUser.getSupertokensUserId(), "r1", null, false); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); - ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", + ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), "google", "user-google", "test@example.com"); { @@ -333,11 +330,10 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU @Test public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -346,12 +342,12 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMa AuthRecipeUserInfo emailPasswordUser1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - UserIdMapping.createUserIdMapping(process.main, emailPasswordUser1.getSupertokensUserId(), "r1", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), emailPasswordUser1.getSupertokensUserId(), "r1", null, false); AuthRecipeUserInfo emailPasswordUser2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass1234"); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); { diff --git a/src/test/java/io/supertokens/test/accountlinking/api/CanLinkAccountsAPITest.java b/src/test/java/io/supertokens/test/accountlinking/api/CanLinkAccountsAPITest.java index 957dce5f6..a1976eb5b 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/CanLinkAccountsAPITest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/CanLinkAccountsAPITest.java @@ -47,6 +47,9 @@ public class CanLinkAccountsAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -60,11 +63,10 @@ public void beforeEach() { @Test public void canLinkReturnsTrue() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -75,7 +77,7 @@ public void canLinkReturnsTrue() throws Exception { AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "abcd1234"); - AuthRecipe.createPrimaryUser(process.main, user2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user2.getSupertokensUserId()); { Map params = new HashMap<>(); @@ -90,7 +92,7 @@ public void canLinkReturnsTrue() throws Exception { assertFalse(response.get("accountsAlreadyLinked").getAsBoolean()); } - AuthRecipe.linkAccounts(process.main, user.getSupertokensUserId(), user2.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), user.getSupertokensUserId(), user2.getSupertokensUserId()); { Map params = new HashMap<>(); @@ -112,11 +114,10 @@ public void canLinkReturnsTrue() throws Exception { @Test public void canLinkReturnsTrueWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -124,12 +125,12 @@ public void canLinkReturnsTrueWithUserIdMapping() throws Exception { } AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "abcd1234"); - UserIdMapping.createUserIdMapping(process.main, user.getSupertokensUserId(), "r1", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), user.getSupertokensUserId(), "r1", null, false); AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "abcd1234"); - UserIdMapping.createUserIdMapping(process.main, user2.getSupertokensUserId(), "r2", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), user2.getSupertokensUserId(), "r2", null, false); - AuthRecipe.createPrimaryUser(process.main, user2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user2.getSupertokensUserId()); { Map params = new HashMap<>(); @@ -144,7 +145,7 @@ public void canLinkReturnsTrueWithUserIdMapping() throws Exception { assertFalse(response.get("accountsAlreadyLinked").getAsBoolean()); } - AuthRecipe.linkAccounts(process.main, user.getSupertokensUserId(), user2.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), user.getSupertokensUserId(), user2.getSupertokensUserId()); { Map params = new HashMap<>(); @@ -166,11 +167,10 @@ public void canLinkReturnsTrueWithUserIdMapping() throws Exception { @Test public void canLinkUserBadInput() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -211,7 +211,7 @@ public void canLinkUserBadInput() throws Exception { } AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "abcd1234"); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "abcd1234"); @@ -256,11 +256,10 @@ public void canLinkUserBadInput() throws Exception { @Test public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -270,16 +269,16 @@ public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); - ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", + ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), "google", "user-google", "test2@example.com"); - AuthRecipe.createPrimaryUser(process.main, signInUpResponse.user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), signInUpResponse.user.getSupertokensUserId()); - ThirdParty.SignInUpResponse signInUpResponse2 = ThirdParty.signInUp(process.main, "fb", "user-fb", + ThirdParty.SignInUpResponse signInUpResponse2 = ThirdParty.signInUp(process.getProcess(), "fb", "user-fb", "test@example.com"); @@ -307,11 +306,10 @@ public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUserWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -320,22 +318,22 @@ public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - UserIdMapping.createUserIdMapping(process.main, emailPasswordUser.getSupertokensUserId(), "e1", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), emailPasswordUser.getSupertokensUserId(), "e1", null, false); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); - ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", + ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), "google", "user-google", "test2@example.com"); - UserIdMapping.createUserIdMapping(process.main, signInUpResponse.user.getSupertokensUserId(), "e2", null, + UserIdMapping.createUserIdMapping(process.getProcess(), signInUpResponse.user.getSupertokensUserId(), "e2", null, false); - AuthRecipe.createPrimaryUser(process.main, signInUpResponse.user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), signInUpResponse.user.getSupertokensUserId()); - ThirdParty.SignInUpResponse signInUpResponse2 = ThirdParty.signInUp(process.main, "fb", "user-fb", + ThirdParty.SignInUpResponse signInUpResponse2 = ThirdParty.signInUp(process.getProcess(), "fb", "user-fb", "test@example.com"); - UserIdMapping.createUserIdMapping(process.main, signInUpResponse2.user.getSupertokensUserId(), "e3", null, + UserIdMapping.createUserIdMapping(process.getProcess(), signInUpResponse2.user.getSupertokensUserId(), "e3", null, false); @@ -362,11 +360,10 @@ public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser @Test public void linkingUserFailsCauseAlreadyLinkedToAnotherAccount() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -378,14 +375,14 @@ public void linkingUserFailsCauseAlreadyLinkedToAnotherAccount() throws Exceptio AuthRecipeUserInfo emailPasswordUser2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass1234"); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); AuthRecipeUserInfo emailPasswordUser3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "pass1234"); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser3.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser3.getSupertokensUserId()); { Map params = new HashMap<>(); @@ -410,11 +407,10 @@ public void linkingUserFailsCauseAlreadyLinkedToAnotherAccount() throws Exceptio @Test public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -423,20 +419,20 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMa AuthRecipeUserInfo emailPasswordUser1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - UserIdMapping.createUserIdMapping(process.main, emailPasswordUser1.getSupertokensUserId(), "r1", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), emailPasswordUser1.getSupertokensUserId(), "r1", null, false); AuthRecipeUserInfo emailPasswordUser2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass1234"); - UserIdMapping.createUserIdMapping(process.main, emailPasswordUser2.getSupertokensUserId(), "r2", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), emailPasswordUser2.getSupertokensUserId(), "r2", null, false); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); AuthRecipeUserInfo emailPasswordUser3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "pass1234"); - UserIdMapping.createUserIdMapping(process.main, emailPasswordUser3.getSupertokensUserId(), "r3", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), emailPasswordUser3.getSupertokensUserId(), "r3", null, false); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser3.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser3.getSupertokensUserId()); { Map params = new HashMap<>(); @@ -461,11 +457,10 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMa @Test public void inputUserIsNotAPrimaryUserTest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/accountlinking/api/CreatePrimaryUserAPITest.java b/src/test/java/io/supertokens/test/accountlinking/api/CreatePrimaryUserAPITest.java index 8042faf6c..04d400cac 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/CreatePrimaryUserAPITest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/CreatePrimaryUserAPITest.java @@ -49,6 +49,9 @@ public class CreatePrimaryUserAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -62,11 +65,10 @@ public void beforeEach() { @Test public void createReturnsSucceeds() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -107,7 +109,7 @@ public void createReturnsSucceeds() throws Exception { userObj = jsonUser; } - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -129,11 +131,10 @@ public void createReturnsSucceeds() throws Exception { @Test public void createReturnsTrueWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -141,7 +142,7 @@ public void createReturnsTrueWithUserIdMapping() throws Exception { } AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "abcd1234"); - UserIdMapping.createUserIdMapping(process.main, user.getSupertokensUserId(), "r1", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), user.getSupertokensUserId(), "r1", null, false); JsonObject userObj; { @@ -174,7 +175,7 @@ public void createReturnsTrueWithUserIdMapping() throws Exception { userObj = jsonUser; } - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -209,11 +210,10 @@ public void createReturnsTrueWithUserIdMapping() throws Exception { @Test public void createPrimaryUserBadInput() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -259,11 +259,10 @@ public void createPrimaryUserBadInput() throws Exception { @Test public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -273,11 +272,11 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); - ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", + ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), "google", "user-google", "test@example.com"); { @@ -302,11 +301,10 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU @Test public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccount() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -318,8 +316,8 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccount() throws Ex AuthRecipeUserInfo emailPasswordUser2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass1234"); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); { @@ -345,11 +343,10 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccount() throws Ex public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUserWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -358,13 +355,13 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - UserIdMapping.createUserIdMapping(process.main, emailPasswordUser.getSupertokensUserId(), "r1", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), emailPasswordUser.getSupertokensUserId(), "r1", null, false); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); - ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", + ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), "google", "user-google", "test@example.com"); { @@ -389,11 +386,10 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU @Test public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -402,12 +398,12 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMa AuthRecipeUserInfo emailPasswordUser1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - UserIdMapping.createUserIdMapping(process.main, emailPasswordUser1.getSupertokensUserId(), "r1", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), emailPasswordUser1.getSupertokensUserId(), "r1", null, false); AuthRecipeUserInfo emailPasswordUser2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass1234"); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); { @@ -432,11 +428,10 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMa @Test public void createPrimaryUserInTenantWithAnotherStorage() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -444,13 +439,13 @@ public void createPrimaryUserInTenantWithAnotherStorage() throws Exception { } JsonObject coreConfig = new JsonObject(); - StorageLayer.getStorage(new TenantIdentifier(null, null, null), process.getProcess()) + StorageLayer.getStorage(new TenantIdentifier(null, process.getAppForTesting().getAppId(), null), process.getProcess()) .modifyConfigToAddANewUserPoolForTesting(coreConfig, 2); - TenantIdentifier tenantIdentifier = new TenantIdentifier(null, null, "t1"); + TenantIdentifier tenantIdentifier = new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"); Multitenancy.addNewOrUpdateAppOrTenant( process.getProcess(), - new TenantIdentifier(null, null, null), + new TenantIdentifier(null, process.getAppForTesting().getAppId(), null), new TenantConfig( tenantIdentifier, new EmailPasswordConfig(true), @@ -461,7 +456,7 @@ public void createPrimaryUserInTenantWithAnotherStorage() throws Exception { ); AuthRecipeUserInfo user = EmailPassword.signUp( - tenantIdentifier, StorageLayer.getStorage(tenantIdentifier, process.main), + tenantIdentifier, StorageLayer.getStorage(tenantIdentifier, process.getProcess()), process.getProcess(), "test@example.com", "abcd1234"); JsonObject userObj; @@ -500,9 +495,9 @@ public void createPrimaryUserInTenantWithAnotherStorage() throws Exception { userObj = jsonUser; } - AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.createPrimaryUser(process.getProcess(), tenantIdentifier.toAppIdentifier(), (StorageLayer.getStorage(tenantIdentifier, - process.main)), + process.getProcess())), user.getSupertokensUserId()); { @@ -525,8 +520,7 @@ public void createPrimaryUserInTenantWithAnotherStorage() throws Exception { @Test public void createReturnsFailsWithoutFeatureEnabled() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/accountlinking/api/DeleteUserTest.java b/src/test/java/io/supertokens/test/accountlinking/api/DeleteUserTest.java index 1431e241c..5adc65fe2 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/DeleteUserTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/DeleteUserTest.java @@ -48,6 +48,9 @@ public class DeleteUserTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -80,31 +83,30 @@ private void deleteUserAPICall(Main main, String userId, Boolean removeAllLinked @Test public void deleteLinkedUserWithoutRemovingAllUsers() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - AuthRecipeUserInfo r1 = EmailPassword.signUp(process.main, "test@example.com", "pass123"); + AuthRecipeUserInfo r1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass123"); - AuthRecipeUserInfo r2 = EmailPassword.signUp(process.main, "test2@example.com", "pass123"); + AuthRecipeUserInfo r2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass123"); - AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + assert (!AuthRecipe.linkAccounts(process.getProcess(), r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); - deleteUserAPICall(process.main, r1.getSupertokensUserId(), false); + deleteUserAPICall(process.getProcess(), r1.getSupertokensUserId(), false); - assertNull(AuthRecipe.getUserById(process.main, r1.getSupertokensUserId())); + assertNull(AuthRecipe.getUserById(process.getProcess(), r1.getSupertokensUserId())); - AuthRecipeUserInfo user = AuthRecipe.getUserById(process.main, r2.getSupertokensUserId()); + AuthRecipeUserInfo user = AuthRecipe.getUserById(process.getProcess(), r2.getSupertokensUserId()); assert (user.loginMethods.length == 1); assert (user.isPrimaryUser); @@ -118,31 +120,30 @@ public void deleteLinkedUserWithoutRemovingAllUsers() throws Exception { @Test public void deleteLinkedPrimaryUserWithoutRemovingAllUsers() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - AuthRecipeUserInfo r1 = EmailPassword.signUp(process.main, "test@example.com", "pass123"); + AuthRecipeUserInfo r1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass123"); - AuthRecipeUserInfo r2 = EmailPassword.signUp(process.main, "test2@example.com", "pass123"); + AuthRecipeUserInfo r2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass123"); - AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + assert (!AuthRecipe.linkAccounts(process.getProcess(), r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); - deleteUserAPICall(process.main, r2.getSupertokensUserId(), false); + deleteUserAPICall(process.getProcess(), r2.getSupertokensUserId(), false); - AuthRecipeUserInfo userP = AuthRecipe.getUserById(process.main, r2.getSupertokensUserId()); + AuthRecipeUserInfo userP = AuthRecipe.getUserById(process.getProcess(), r2.getSupertokensUserId()); - AuthRecipeUserInfo user = AuthRecipe.getUserById(process.main, r1.getSupertokensUserId()); + AuthRecipeUserInfo user = AuthRecipe.getUserById(process.getProcess(), r1.getSupertokensUserId()); assert (user.loginMethods.length == 1); assert (user.isPrimaryUser); @@ -157,31 +158,30 @@ public void deleteLinkedPrimaryUserWithoutRemovingAllUsers() throws Exception { @Test public void deleteLinkedPrimaryUserRemovingAllUsers() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - AuthRecipeUserInfo r1 = EmailPassword.signUp(process.main, "test@example.com", "pass123"); + AuthRecipeUserInfo r1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass123"); - AuthRecipeUserInfo r2 = EmailPassword.signUp(process.main, "test2@example.com", "pass123"); + AuthRecipeUserInfo r2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass123"); - AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + assert (!AuthRecipe.linkAccounts(process.getProcess(), r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); - deleteUserAPICall(process.main, r2.getSupertokensUserId()); + deleteUserAPICall(process.getProcess(), r2.getSupertokensUserId()); - AuthRecipeUserInfo userP = AuthRecipe.getUserById(process.main, r2.getSupertokensUserId()); + AuthRecipeUserInfo userP = AuthRecipe.getUserById(process.getProcess(), r2.getSupertokensUserId()); - AuthRecipeUserInfo user = AuthRecipe.getUserById(process.main, r1.getSupertokensUserId()); + AuthRecipeUserInfo user = AuthRecipe.getUserById(process.getProcess(), r1.getSupertokensUserId()); assert (user == null && userP == null); @@ -193,31 +193,30 @@ public void deleteLinkedPrimaryUserRemovingAllUsers() throws Exception { public void deleteLinkedPrimaryUserRemovingAllUsers2() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - AuthRecipeUserInfo r1 = EmailPassword.signUp(process.main, "test@example.com", "pass123"); + AuthRecipeUserInfo r1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass123"); - AuthRecipeUserInfo r2 = EmailPassword.signUp(process.main, "test2@example.com", "pass123"); + AuthRecipeUserInfo r2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass123"); - AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + assert (!AuthRecipe.linkAccounts(process.getProcess(), r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); - deleteUserAPICall(process.main, r1.getSupertokensUserId()); + deleteUserAPICall(process.getProcess(), r1.getSupertokensUserId()); - AuthRecipeUserInfo userP = AuthRecipe.getUserById(process.main, r2.getSupertokensUserId()); + AuthRecipeUserInfo userP = AuthRecipe.getUserById(process.getProcess(), r2.getSupertokensUserId()); - AuthRecipeUserInfo user = AuthRecipe.getUserById(process.main, r1.getSupertokensUserId()); + AuthRecipeUserInfo user = AuthRecipe.getUserById(process.getProcess(), r1.getSupertokensUserId()); assert (user == null && userP == null); @@ -233,47 +232,46 @@ public void deleteUserTestWithUserIdMapping1() throws Exception { * e1 entry, and e1 metadata, but should not clear e2 stuff at all. * */ String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - AuthRecipeUserInfo r1 = EmailPassword.signUp(process.main, "test@example.com", "pass123"); - UserIdMapping.createUserIdMapping(process.main, r1.getSupertokensUserId(), "e1", null, false); + AuthRecipeUserInfo r1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass123"); + UserIdMapping.createUserIdMapping(process.getProcess(), r1.getSupertokensUserId(), "e1", null, false); JsonObject metadata = new JsonObject(); metadata.addProperty("k1", "v1"); - UserMetadata.updateUserMetadata(process.main, "e1", metadata); + UserMetadata.updateUserMetadata(process.getProcess(), "e1", metadata); - AuthRecipeUserInfo r2 = EmailPassword.signUp(process.main, "test2@example.com", "pass123"); - UserIdMapping.createUserIdMapping(process.main, r2.getSupertokensUserId(), "e2", null, false); - UserMetadata.updateUserMetadata(process.main, "e2", metadata); + AuthRecipeUserInfo r2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass123"); + UserIdMapping.createUserIdMapping(process.getProcess(), r2.getSupertokensUserId(), "e2", null, false); + UserMetadata.updateUserMetadata(process.getProcess(), "e2", metadata); - AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + assert (!AuthRecipe.linkAccounts(process.getProcess(), r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); - deleteUserAPICall(process.main, r1.getSupertokensUserId(), false); + deleteUserAPICall(process.getProcess(), r1.getSupertokensUserId(), false); - assertNull(AuthRecipe.getUserById(process.main, r1.getSupertokensUserId())); + assertNull(AuthRecipe.getUserById(process.getProcess(), r1.getSupertokensUserId())); - assertNull(AuthRecipe.getUserById(process.main, "e2")); + assertNull(AuthRecipe.getUserById(process.getProcess(), "e2")); - assertNotNull(AuthRecipe.getUserById(process.main, r2.getSupertokensUserId())); + assertNotNull(AuthRecipe.getUserById(process.getProcess(), r2.getSupertokensUserId())); - assertEquals(UserMetadata.getUserMetadata(process.main, "e1"), new JsonObject()); - assertEquals(UserMetadata.getUserMetadata(process.main, r1.getSupertokensUserId()), new JsonObject()); - assertEquals(UserMetadata.getUserMetadata(process.main, "e2"), metadata); - assertEquals(UserMetadata.getUserMetadata(process.main, r2.getSupertokensUserId()), new JsonObject()); - assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e1"), new JsonObject()); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), r1.getSupertokensUserId()), new JsonObject()); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e2"), metadata); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), r2.getSupertokensUserId()), new JsonObject()); + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != null); - assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); @@ -288,47 +286,46 @@ public void deleteUserTestWithUserIdMapping2() throws Exception { * Now we want to delete r1 with linked all recipes as true. This should clear r1, r2 entry clear e2 metadata. * */ String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - AuthRecipeUserInfo r1 = EmailPassword.signUp(process.main, "test@example.com", "pass123"); - UserIdMapping.createUserIdMapping(process.main, r1.getSupertokensUserId(), "e1", null, false); + AuthRecipeUserInfo r1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass123"); + UserIdMapping.createUserIdMapping(process.getProcess(), r1.getSupertokensUserId(), "e1", null, false); JsonObject metadata = new JsonObject(); metadata.addProperty("k1", "v1"); - UserMetadata.updateUserMetadata(process.main, "e1", metadata); + UserMetadata.updateUserMetadata(process.getProcess(), "e1", metadata); - AuthRecipeUserInfo r2 = EmailPassword.signUp(process.main, "test2@example.com", "pass123"); - UserIdMapping.createUserIdMapping(process.main, r2.getSupertokensUserId(), "e2", null, false); - UserMetadata.updateUserMetadata(process.main, "e2", metadata); + AuthRecipeUserInfo r2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass123"); + UserIdMapping.createUserIdMapping(process.getProcess(), r2.getSupertokensUserId(), "e2", null, false); + UserMetadata.updateUserMetadata(process.getProcess(), "e2", metadata); - AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + assert (!AuthRecipe.linkAccounts(process.getProcess(), r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); - deleteUserAPICall(process.main, r1.getSupertokensUserId()); + deleteUserAPICall(process.getProcess(), r1.getSupertokensUserId()); - assertNull(AuthRecipe.getUserById(process.main, r1.getSupertokensUserId())); + assertNull(AuthRecipe.getUserById(process.getProcess(), r1.getSupertokensUserId())); - assertNull(AuthRecipe.getUserById(process.main, "e2")); + assertNull(AuthRecipe.getUserById(process.getProcess(), "e2")); - assertNull(AuthRecipe.getUserById(process.main, r2.getSupertokensUserId())); + assertNull(AuthRecipe.getUserById(process.getProcess(), r2.getSupertokensUserId())); - assertEquals(UserMetadata.getUserMetadata(process.main, "e1"), new JsonObject()); - assertEquals(UserMetadata.getUserMetadata(process.main, r1.getSupertokensUserId()), new JsonObject()); - assertEquals(UserMetadata.getUserMetadata(process.main, "e2"), new JsonObject()); - assertEquals(UserMetadata.getUserMetadata(process.main, r2.getSupertokensUserId()), new JsonObject()); - assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e1"), new JsonObject()); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), r1.getSupertokensUserId()), new JsonObject()); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e2"), new JsonObject()); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), r2.getSupertokensUserId()), new JsonObject()); + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); - assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); @@ -345,90 +342,89 @@ public void deleteUserTestWithUserIdMapping3() throws Exception { * and r1 * */ String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - AuthRecipeUserInfo r1 = EmailPassword.signUp(process.main, "test@example.com", "pass123"); - UserIdMapping.createUserIdMapping(process.main, r1.getSupertokensUserId(), "e1", null, false); + AuthRecipeUserInfo r1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass123"); + UserIdMapping.createUserIdMapping(process.getProcess(), r1.getSupertokensUserId(), "e1", null, false); JsonObject metadata = new JsonObject(); metadata.addProperty("k1", "v1"); - UserMetadata.updateUserMetadata(process.main, "e1", metadata); + UserMetadata.updateUserMetadata(process.getProcess(), "e1", metadata); - AuthRecipeUserInfo r2 = EmailPassword.signUp(process.main, "test2@example.com", "pass123"); - UserIdMapping.createUserIdMapping(process.main, r2.getSupertokensUserId(), "e2", null, false); - UserMetadata.updateUserMetadata(process.main, "e2", metadata); + AuthRecipeUserInfo r2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass123"); + UserIdMapping.createUserIdMapping(process.getProcess(), r2.getSupertokensUserId(), "e2", null, false); + UserMetadata.updateUserMetadata(process.getProcess(), "e2", metadata); - AuthRecipeUserInfo r3 = EmailPassword.signUp(process.main, "test3@example.com", "pass123"); - UserIdMapping.createUserIdMapping(process.main, r3.getSupertokensUserId(), "e3", null, false); - UserMetadata.updateUserMetadata(process.main, "e3", metadata); + AuthRecipeUserInfo r3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "pass123"); + UserIdMapping.createUserIdMapping(process.getProcess(), r3.getSupertokensUserId(), "e3", null, false); + UserMetadata.updateUserMetadata(process.getProcess(), "e3", metadata); - AuthRecipe.createPrimaryUser(process.main, r2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), r2.getSupertokensUserId()); - assert (!AuthRecipe.linkAccounts(process.main, r1.getSupertokensUserId(), + assert (!AuthRecipe.linkAccounts(process.getProcess(), r1.getSupertokensUserId(), r2.getSupertokensUserId()).wasAlreadyLinked); - assert (!AuthRecipe.linkAccounts(process.main, r3.getSupertokensUserId(), + assert (!AuthRecipe.linkAccounts(process.getProcess(), r3.getSupertokensUserId(), r1.getSupertokensUserId()).wasAlreadyLinked); - deleteUserAPICall(process.main, r1.getSupertokensUserId(), false); + deleteUserAPICall(process.getProcess(), r1.getSupertokensUserId(), false); - assertNull(AuthRecipe.getUserById(process.main, r1.getSupertokensUserId())); + assertNull(AuthRecipe.getUserById(process.getProcess(), r1.getSupertokensUserId())); - assertEquals(UserMetadata.getUserMetadata(process.main, "e1"), new JsonObject()); - assertEquals(UserMetadata.getUserMetadata(process.main, r1.getSupertokensUserId()), new JsonObject()); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e1"), new JsonObject()); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), r1.getSupertokensUserId()), new JsonObject()); { - AuthRecipeUserInfo userR2 = AuthRecipe.getUserById(process.main, r2.getSupertokensUserId()); - AuthRecipeUserInfo userR3 = AuthRecipe.getUserById(process.main, r3.getSupertokensUserId()); + AuthRecipeUserInfo userR2 = AuthRecipe.getUserById(process.getProcess(), r2.getSupertokensUserId()); + AuthRecipeUserInfo userR3 = AuthRecipe.getUserById(process.getProcess(), r3.getSupertokensUserId()); assert (userR2.equals(userR3)); assert (userR2.loginMethods.length == 2); - assertEquals(UserMetadata.getUserMetadata(process.main, "e2"), metadata); - assertEquals(UserMetadata.getUserMetadata(process.main, "e3"), metadata); - assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e2"), metadata); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e3"), metadata); + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != null); - assert (UserIdMapping.getUserIdMapping(process.main, r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) != + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) != null); - assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); } - deleteUserAPICall(process.main, r2.getSupertokensUserId(), false); + deleteUserAPICall(process.getProcess(), r2.getSupertokensUserId(), false); { - AuthRecipeUserInfo userR2 = AuthRecipe.getUserById(process.main, r2.getSupertokensUserId()); - AuthRecipeUserInfo userR3 = AuthRecipe.getUserById(process.main, r3.getSupertokensUserId()); + AuthRecipeUserInfo userR2 = AuthRecipe.getUserById(process.getProcess(), r2.getSupertokensUserId()); + AuthRecipeUserInfo userR3 = AuthRecipe.getUserById(process.getProcess(), r3.getSupertokensUserId()); assert (userR2.equals(userR3)); assert (userR2.loginMethods.length == 1); - assertEquals(UserMetadata.getUserMetadata(process.main, "e2"), metadata); - assertEquals(UserMetadata.getUserMetadata(process.main, "e3"), metadata); - assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e2"), metadata); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e3"), metadata); + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) != null); - assert (UserIdMapping.getUserIdMapping(process.main, r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) != + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) != null); - assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); } - deleteUserAPICall(process.main, r3.getSupertokensUserId(), false); + deleteUserAPICall(process.getProcess(), r3.getSupertokensUserId(), false); { - AuthRecipeUserInfo userR2 = AuthRecipe.getUserById(process.main, r2.getSupertokensUserId()); - AuthRecipeUserInfo userR3 = AuthRecipe.getUserById(process.main, r3.getSupertokensUserId()); + AuthRecipeUserInfo userR2 = AuthRecipe.getUserById(process.getProcess(), r2.getSupertokensUserId()); + AuthRecipeUserInfo userR3 = AuthRecipe.getUserById(process.getProcess(), r3.getSupertokensUserId()); assert (userR2 == null && userR3 == null); - assertEquals(UserMetadata.getUserMetadata(process.main, "e2"), new JsonObject()); - assertEquals(UserMetadata.getUserMetadata(process.main, "e3"), new JsonObject()); - assert (UserIdMapping.getUserIdMapping(process.main, r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e2"), new JsonObject()); + assertEquals(UserMetadata.getUserMetadata(process.getProcess(), "e3"), new JsonObject()); + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r2.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); - assert (UserIdMapping.getUserIdMapping(process.main, r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r3.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); - assert (UserIdMapping.getUserIdMapping(process.main, r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == + assert (UserIdMapping.getUserIdMapping(process.getProcess(), r1.getSupertokensUserId(), UserIdType.SUPERTOKENS) == null); } diff --git a/src/test/java/io/supertokens/test/accountlinking/api/EmailVerificationTest.java b/src/test/java/io/supertokens/test/accountlinking/api/EmailVerificationTest.java index f75ebce76..cf3bdfd34 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/EmailVerificationTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/EmailVerificationTest.java @@ -46,6 +46,9 @@ public class EmailVerificationTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -59,11 +62,10 @@ public void beforeEach() { @Test public void testEmailVerificationWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/accountlinking/api/GetUserByAccountInfoTest.java b/src/test/java/io/supertokens/test/accountlinking/api/GetUserByAccountInfoTest.java index 8bcceca3c..2855da8f2 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/GetUserByAccountInfoTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/GetUserByAccountInfoTest.java @@ -58,6 +58,9 @@ public class GetUserByAccountInfoTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -132,11 +135,10 @@ private JsonArray getUsersByAccountInfo(Main main, boolean doUnionOfAccountInfo, @Test public void testListUsersByAccountInfoForUnlinkedAccounts() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -187,11 +189,10 @@ public void testListUsersByAccountInfoForUnlinkedAccounts() throws Exception { @Test public void testListUserByAccountInfoByUnnormalisedPhoneNumber() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -215,11 +216,10 @@ public void testListUserByAccountInfoByUnnormalisedPhoneNumber() throws Exceptio @Test public void testListUsersByAccountInfoForUnlinkedAccountsWithUnionOption() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -273,11 +273,10 @@ public void testListUsersByAccountInfoForUnlinkedAccountsWithUnionOption() throw @Test public void testUnknownAccountInfo() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -298,11 +297,10 @@ public void testUnknownAccountInfo() throws Exception { @Test public void testListUserByAccountInfoWhenAccountsAreLinked1() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -338,11 +336,10 @@ public void testListUserByAccountInfoWhenAccountsAreLinked1() throws Exception { @Test public void testListUserByAccountInfoWhenAccountsAreLinked2() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -371,11 +368,10 @@ public void testListUserByAccountInfoWhenAccountsAreLinked2() throws Exception { @Test public void testListUserByAccountInfoWhenAccountsAreLinked3() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -404,11 +400,10 @@ public void testListUserByAccountInfoWhenAccountsAreLinked3() throws Exception { @Test public void testListUserByAccountInfoWhenAccountsAreLinked4() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -439,11 +434,10 @@ public void testListUserByAccountInfoWhenAccountsAreLinked4() throws Exception { @Test public void testListUserByAccountInfoWhenAccountsAreLinked5() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -478,11 +472,10 @@ public void testListUserByAccountInfoWhenAccountsAreLinked5() throws Exception { @Test public void testWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/accountlinking/api/GetUserByIdTest.java b/src/test/java/io/supertokens/test/accountlinking/api/GetUserByIdTest.java index f54333070..8e2ca89f7 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/GetUserByIdTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/GetUserByIdTest.java @@ -61,6 +61,9 @@ public class GetUserByIdTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -104,11 +107,10 @@ AuthRecipeUserInfo createPasswordlessUserWithPhone(Main main, String phone) @Test public void testJsonStructure() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -170,11 +172,10 @@ public void testJsonStructure() throws Exception { @Test public void testThatEmailIsAUnionOfLinkedAccounts1() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -218,11 +219,10 @@ public void testThatEmailIsAUnionOfLinkedAccounts1() throws Exception { @Test public void testThatEmailIsAUnionOfLinkedAccounts2() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -261,11 +261,10 @@ public void testThatEmailIsAUnionOfLinkedAccounts2() throws Exception { @Test public void testThatEmailIsAUnionOfLinkedAccounts3() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -304,11 +303,10 @@ public void testThatEmailIsAUnionOfLinkedAccounts3() throws Exception { @Test public void testThatEmailIsAUnionOfLinkedAccounts4() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -348,11 +346,10 @@ public void testThatEmailIsAUnionOfLinkedAccounts4() throws Exception { @Test public void testThatPhoneNumberIsUnionOfLinkedAccounts1() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -391,11 +388,10 @@ public void testThatPhoneNumberIsUnionOfLinkedAccounts1() throws Exception { @Test public void testThatPhoneNumberIsUnionOfLinkedAccounts2() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -437,11 +433,10 @@ public void testThatPhoneNumberIsUnionOfLinkedAccounts2() throws Exception { @Test public void testThatPhoneNumberIsUnionOfLinkedAccounts3() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -483,11 +478,10 @@ public void testThatPhoneNumberIsUnionOfLinkedAccounts3() throws Exception { @Test public void testWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -536,11 +530,10 @@ public void testWithUserIdMapping() throws Exception { @Test public void testUnknownUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/accountlinking/api/LinkAccountsAPITest.java b/src/test/java/io/supertokens/test/accountlinking/api/LinkAccountsAPITest.java index 4457280fe..654fe2042 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/LinkAccountsAPITest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/LinkAccountsAPITest.java @@ -48,6 +48,9 @@ public class LinkAccountsAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -61,11 +64,10 @@ public void beforeEach() { @Test public void linkReturnsTrue() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -76,7 +78,7 @@ public void linkReturnsTrue() throws Exception { AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "abcd1234"); - AuthRecipe.createPrimaryUser(process.main, user2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user2.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -92,7 +94,7 @@ public void linkReturnsTrue() throws Exception { assertTrue(response.has("user")); } - AuthRecipe.linkAccounts(process.main, user.getSupertokensUserId(), user2.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), user.getSupertokensUserId(), user2.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -115,11 +117,10 @@ public void linkReturnsTrue() throws Exception { @Test public void canLinkReturnsTrueWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -127,12 +128,12 @@ public void canLinkReturnsTrueWithUserIdMapping() throws Exception { } AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "abcd1234"); - UserIdMapping.createUserIdMapping(process.main, user.getSupertokensUserId(), "r1", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), user.getSupertokensUserId(), "r1", null, false); AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "abcd1234"); - UserIdMapping.createUserIdMapping(process.main, user2.getSupertokensUserId(), "r2", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), user2.getSupertokensUserId(), "r2", null, false); - AuthRecipe.createPrimaryUser(process.main, user2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user2.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -148,7 +149,7 @@ public void canLinkReturnsTrueWithUserIdMapping() throws Exception { assertTrue(response.has("user")); } - AuthRecipe.linkAccounts(process.main, user.getSupertokensUserId(), user2.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), user.getSupertokensUserId(), user2.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -171,11 +172,10 @@ public void canLinkReturnsTrueWithUserIdMapping() throws Exception { @Test public void canLinkUserBadInput() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -216,7 +216,7 @@ public void canLinkUserBadInput() throws Exception { } AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "abcd1234"); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "abcd1234"); @@ -261,11 +261,10 @@ public void canLinkUserBadInput() throws Exception { @Test public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -275,16 +274,16 @@ public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); - ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", + ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), "google", "user-google", "test2@example.com"); - AuthRecipe.createPrimaryUser(process.main, signInUpResponse.user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), signInUpResponse.user.getSupertokensUserId()); - ThirdParty.SignInUpResponse signInUpResponse2 = ThirdParty.signInUp(process.main, "fb", "user-fb", + ThirdParty.SignInUpResponse signInUpResponse2 = ThirdParty.signInUp(process.getProcess(), "fb", "user-fb", "test@example.com"); @@ -312,11 +311,10 @@ public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUserWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -325,22 +323,22 @@ public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - UserIdMapping.createUserIdMapping(process.main, emailPasswordUser.getSupertokensUserId(), "e1", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), emailPasswordUser.getSupertokensUserId(), "e1", null, false); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); - ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", + ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), "google", "user-google", "test2@example.com"); - UserIdMapping.createUserIdMapping(process.main, signInUpResponse.user.getSupertokensUserId(), "e2", null, + UserIdMapping.createUserIdMapping(process.getProcess(), signInUpResponse.user.getSupertokensUserId(), "e2", null, false); - AuthRecipe.createPrimaryUser(process.main, signInUpResponse.user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), signInUpResponse.user.getSupertokensUserId()); - ThirdParty.SignInUpResponse signInUpResponse2 = ThirdParty.signInUp(process.main, "fb", "user-fb", + ThirdParty.SignInUpResponse signInUpResponse2 = ThirdParty.signInUp(process.getProcess(), "fb", "user-fb", "test@example.com"); - UserIdMapping.createUserIdMapping(process.main, signInUpResponse2.user.getSupertokensUserId(), "e3", null, + UserIdMapping.createUserIdMapping(process.getProcess(), signInUpResponse2.user.getSupertokensUserId(), "e3", null, false); @@ -367,11 +365,10 @@ public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser @Test public void linkingUserFailsCauseAlreadyLinkedToAnotherAccount() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -383,14 +380,14 @@ public void linkingUserFailsCauseAlreadyLinkedToAnotherAccount() throws Exceptio AuthRecipeUserInfo emailPasswordUser2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass1234"); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); AuthRecipeUserInfo emailPasswordUser3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "pass1234"); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser3.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser3.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -417,11 +414,10 @@ public void linkingUserFailsCauseAlreadyLinkedToAnotherAccount() throws Exceptio @Test public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -430,20 +426,20 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMa AuthRecipeUserInfo emailPasswordUser1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - UserIdMapping.createUserIdMapping(process.main, emailPasswordUser1.getSupertokensUserId(), "r1", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), emailPasswordUser1.getSupertokensUserId(), "r1", null, false); AuthRecipeUserInfo emailPasswordUser2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass1234"); - UserIdMapping.createUserIdMapping(process.main, emailPasswordUser2.getSupertokensUserId(), "r2", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), emailPasswordUser2.getSupertokensUserId(), "r2", null, false); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); AuthRecipeUserInfo emailPasswordUser3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "pass1234"); - UserIdMapping.createUserIdMapping(process.main, emailPasswordUser3.getSupertokensUserId(), "r3", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), emailPasswordUser3.getSupertokensUserId(), "r3", null, false); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser3.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser3.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -469,11 +465,10 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMa @Test public void inputUserIsNotAPrimaryUserTest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -503,8 +498,7 @@ public void inputUserIsNotAPrimaryUserTest() throws Exception { @Test public void linkReturnsFailsWithoutFeatureEnabled() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -542,11 +536,10 @@ public void linkReturnsFailsWithoutFeatureEnabled() throws Exception { @Test public void testUserObjectInLinkAccountsResponse() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -557,7 +550,7 @@ public void testUserObjectInLinkAccountsResponse() throws Exception { AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "abcd1234"); - AuthRecipe.createPrimaryUser(process.main, user2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user2.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -588,11 +581,10 @@ public void testUserObjectInLinkAccountsResponse() throws Exception { @Test public void linkingUserFailsCauseAlreadyLinkedToAnotherAccountReturnsUserObject() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -604,14 +596,14 @@ public void linkingUserFailsCauseAlreadyLinkedToAnotherAccountReturnsUserObject( AuthRecipeUserInfo emailPasswordUser2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass1234"); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); AuthRecipeUserInfo emailPasswordUser3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "pass1234"); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser3.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser3.getSupertokensUserId()); { JsonObject params = new JsonObject(); diff --git a/src/test/java/io/supertokens/test/accountlinking/api/SessionTests.java b/src/test/java/io/supertokens/test/accountlinking/api/SessionTests.java index 639317ccf..67e169bff 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/SessionTests.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/SessionTests.java @@ -51,6 +51,9 @@ public class SessionTests { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -98,11 +101,10 @@ private void revokeSessionsForUser(Main main, String userId, Boolean includeAllL @Test public void testGetSessionForUserWithAndWithoutIncludingAllLinkedAccounts() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -161,11 +163,10 @@ public void testGetSessionForUserWithAndWithoutIncludingAllLinkedAccounts() thro @Test public void testRevokeSessionsForUserWithAndWithoutIncludingAllLinkedAccounts() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/accountlinking/api/TestRecipeUserIdInSignInUpAPIs.java b/src/test/java/io/supertokens/test/accountlinking/api/TestRecipeUserIdInSignInUpAPIs.java index 51711a5d1..8c670f90e 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/TestRecipeUserIdInSignInUpAPIs.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/TestRecipeUserIdInSignInUpAPIs.java @@ -56,6 +56,9 @@ public class TestRecipeUserIdInSignInUpAPIs { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -100,11 +103,10 @@ AuthRecipeUserInfo createPasswordlessUserWithPhone(Main main, String phone) @Test public void testEmailPasswordSignUp() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -130,11 +132,10 @@ public void testEmailPasswordSignUp() throws Exception { @Test public void testEmailPasswordSignIn() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -222,11 +223,10 @@ public void testEmailPasswordSignIn() throws Exception { @Test public void testThirdPartySignInUp() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -346,11 +346,10 @@ public void testThirdPartySignInUp() throws Exception { @Test public void testPasswordlessConsumeCode() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -455,11 +454,10 @@ public void testPasswordlessConsumeCode() throws Exception { @Test public void testPasswordlessConsumeCodeForPhone() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -564,11 +562,10 @@ public void testPasswordlessConsumeCodeForPhone() throws Exception { @Test public void testPasswordlessConsumeCodeForPhoneAndEmail() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -705,11 +702,10 @@ public void testPasswordlessConsumeCodeForPhoneAndEmail() throws Exception { @Test public void testWithEmailPasswordUserWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/accountlinking/api/UnlinkAccountsAPITest.java b/src/test/java/io/supertokens/test/accountlinking/api/UnlinkAccountsAPITest.java index b0ae61018..b9b44e445 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/UnlinkAccountsAPITest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/UnlinkAccountsAPITest.java @@ -45,6 +45,9 @@ public class UnlinkAccountsAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -58,11 +61,10 @@ public void beforeEach() { @Test public void unlinkAccountSuccess() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -77,12 +79,12 @@ public void unlinkAccountSuccess() throws Exception { AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "password"); assert (!user2.isPrimaryUser); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), user.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user.getSupertokensUserId()); - Session.createNewSession(process.main, user2.getSupertokensUserId(), new JsonObject(), new JsonObject()); - String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.main, user2.getSupertokensUserId()); + Session.createNewSession(process.getProcess(), user2.getSupertokensUserId(), new JsonObject(), new JsonObject()); + String[] sessions = Session.getAllNonExpiredSessionHandlesForUser(process.getProcess(), user2.getSupertokensUserId()); assert (sessions.length == 1); { @@ -98,20 +100,20 @@ public void unlinkAccountSuccess() throws Exception { } - AuthRecipeUserInfo refetchUser2 = AuthRecipe.getUserById(process.main, user2.getSupertokensUserId()); + AuthRecipeUserInfo refetchUser2 = AuthRecipe.getUserById(process.getProcess(), user2.getSupertokensUserId()); assert (!refetchUser2.isPrimaryUser); assert (refetchUser2.getSupertokensUserId().equals(user2.getSupertokensUserId())); assert (refetchUser2.loginMethods.length == 1); assert (refetchUser2.loginMethods[0].getSupertokensUserId().equals(user2.getSupertokensUserId())); - AuthRecipeUserInfo refetchUser = AuthRecipe.getUserById(process.main, user.getSupertokensUserId()); + AuthRecipeUserInfo refetchUser = AuthRecipe.getUserById(process.getProcess(), user.getSupertokensUserId()); assert (!refetchUser2.equals(refetchUser)); assert (refetchUser.isPrimaryUser); assert (refetchUser.loginMethods.length == 1); assert (refetchUser.loginMethods[0].getSupertokensUserId().equals(user.getSupertokensUserId())); // cause linkAccounts revokes sessions for the recipe user ID - sessions = Session.getAllNonExpiredSessionHandlesForUser(process.main, user2.getSupertokensUserId()); + sessions = Session.getAllNonExpiredSessionHandlesForUser(process.getProcess(), user2.getSupertokensUserId()); assert (sessions.length == 0); process.kill(); @@ -122,11 +124,10 @@ public void unlinkAccountSuccess() throws Exception { @Test public void unlinkAccountBadRequest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -153,11 +154,10 @@ public void unlinkAccountBadRequest() throws Exception { @Test public void unlinkAccountSuccessWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -171,11 +171,11 @@ public void unlinkAccountSuccessWithUserIdMapping() throws Exception { AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "password"); assert (!user2.isPrimaryUser); - UserIdMapping.createUserIdMapping(process.main, user2.getSupertokensUserId(), "e2", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), user2.getSupertokensUserId(), "e2", null, false); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), user.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -190,13 +190,13 @@ public void unlinkAccountSuccessWithUserIdMapping() throws Exception { } - AuthRecipeUserInfo refetchUser2 = AuthRecipe.getUserById(process.main, user2.getSupertokensUserId()); + AuthRecipeUserInfo refetchUser2 = AuthRecipe.getUserById(process.getProcess(), user2.getSupertokensUserId()); assert (!refetchUser2.isPrimaryUser); assert (refetchUser2.getSupertokensUserId().equals(user2.getSupertokensUserId())); assert (refetchUser2.loginMethods.length == 1); assert (refetchUser2.loginMethods[0].getSupertokensUserId().equals(user2.getSupertokensUserId())); - AuthRecipeUserInfo refetchUser = AuthRecipe.getUserById(process.main, user.getSupertokensUserId()); + AuthRecipeUserInfo refetchUser = AuthRecipe.getUserById(process.getProcess(), user.getSupertokensUserId()); assert (!refetchUser2.equals(refetchUser)); assert (refetchUser.isPrimaryUser); assert (refetchUser.loginMethods.length == 1); @@ -209,11 +209,10 @@ public void unlinkAccountSuccessWithUserIdMapping() throws Exception { @Test public void unlinkAccountWithoutPrimaryUserId() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -243,11 +242,10 @@ public void unlinkAccountWithoutPrimaryUserId() throws Exception { @Test public void unlinkAccountWithUnknownUserId() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -274,11 +272,10 @@ public void unlinkAccountWithUnknownUserId() throws Exception { @Test public void unlinkAccountSuccessButDeletesUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -293,9 +290,9 @@ public void unlinkAccountSuccessButDeletesUser() throws Exception { AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "password"); assert (!user2.isPrimaryUser); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), user.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user.getSupertokensUserId()); { JsonObject params = new JsonObject(); diff --git a/src/test/java/io/supertokens/test/accountlinking/api/UserPaginationTest.java b/src/test/java/io/supertokens/test/accountlinking/api/UserPaginationTest.java index 59b09ecfd..5940afbc3 100644 --- a/src/test/java/io/supertokens/test/accountlinking/api/UserPaginationTest.java +++ b/src/test/java/io/supertokens/test/accountlinking/api/UserPaginationTest.java @@ -58,6 +58,9 @@ public class UserPaginationTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -138,11 +141,10 @@ private JsonArray getUsersFromAllPages(Main main, int pageSize, String[] recipeF @Test public void testUserPaginationResultJson() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -150,12 +152,19 @@ public void testUserPaginationResultJson() throws Exception { } AuthRecipeUserInfo user1 = createEmailPasswordUser(process.getProcess(), "test1@example.com", "password"); + Thread.sleep(20); AuthRecipeUserInfo user2 = createEmailPasswordUser(process.getProcess(), "test2@example.com", "password"); + Thread.sleep(20); AuthRecipeUserInfo user3 = createPasswordlessUserWithEmail(process.getProcess(), "test3@example.com"); + Thread.sleep(20); AuthRecipeUserInfo user4 = createPasswordlessUserWithEmail(process.getProcess(), "test4@example.com"); + Thread.sleep(20); AuthRecipeUserInfo user5 = createPasswordlessUserWithPhone(process.getProcess(), "+1234567890"); + Thread.sleep(20); AuthRecipeUserInfo user6 = createPasswordlessUserWithPhone(process.getProcess(), "+1234567891"); + Thread.sleep(20); AuthRecipeUserInfo user7 = createThirdPartyUser(process.getProcess(), "google", "test7", "test7@example.com"); + Thread.sleep(20); AuthRecipeUserInfo user8 = createThirdPartyUser(process.getProcess(), "google", "test8", "test8@example.com"); { @@ -237,11 +246,10 @@ public void testUserPaginationResultJson() throws Exception { @Test public void testUserPaginationWithManyUsers() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -257,11 +265,10 @@ public void testUserPaginationWithManyUsers() throws Exception { // emailpassword users for (int i = 0; i < 200; i++) { AuthRecipeUserInfo user = createEmailPasswordUser(process.getProcess(), "epuser" + i + "@gmail.com", - "password" + i); + "password1"); userInfoMap.put(user.getSupertokensUserId(), user); userIds.add(user.getSupertokensUserId()); emailPasswordUsers.add(user.getSupertokensUserId()); - Thread.sleep(10); } // passwordless users with email @@ -271,7 +278,6 @@ public void testUserPaginationWithManyUsers() throws Exception { userInfoMap.put(user.getSupertokensUserId(), user); userIds.add(user.getSupertokensUserId()); passwordlessUsers.add(user.getSupertokensUserId()); - Thread.sleep(10); } // passwordless users with phone @@ -280,7 +286,6 @@ public void testUserPaginationWithManyUsers() throws Exception { userInfoMap.put(user.getSupertokensUserId(), user); userIds.add(user.getSupertokensUserId()); passwordlessUsers.add(user.getSupertokensUserId()); - Thread.sleep(10); } // thirdparty users @@ -290,7 +295,6 @@ public void testUserPaginationWithManyUsers() throws Exception { userInfoMap.put(user.getSupertokensUserId(), user); userIds.add(user.getSupertokensUserId()); thirdPartyUsers.add(user.getSupertokensUserId()); - Thread.sleep(10); } Map primaryUserIdMap = new HashMap<>(); @@ -325,6 +329,7 @@ public void testUserPaginationWithManyUsers() throws Exception { } else { primaryUserIds.add(userIdsToLink.get(0)); } + Thread.sleep(10); } // Pagination tests @@ -400,11 +405,10 @@ public void testUserPaginationWithManyUsers() throws Exception { @Test public void testUserPaginationFromOldVersion() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/authRecipe/AuthRecipeStorageTest.java b/src/test/java/io/supertokens/test/authRecipe/AuthRecipeStorageTest.java index 0443dcbbb..54b7d6f56 100644 --- a/src/test/java/io/supertokens/test/authRecipe/AuthRecipeStorageTest.java +++ b/src/test/java/io/supertokens/test/authRecipe/AuthRecipeStorageTest.java @@ -37,6 +37,9 @@ public class AuthRecipeStorageTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -57,15 +60,15 @@ public void testIfAUserIdIsASuperTokensUserId() throws Exception { return; } - AuthRecipeStorage storage = (AuthRecipeStorage) StorageLayer.getStorage(process.main); + AuthRecipeStorage storage = (AuthRecipeStorage) StorageLayer.getStorage(process.getProcess()); // check with an unknown Userid - assertFalse(storage.doesUserIdExist(new TenantIdentifier(null, null, null), "unknownUser")); + assertFalse(storage.doesUserIdExist(process.getAppForTesting(), "unknownUser")); // create a user and check that the userId exists - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); - assertTrue(storage.doesUserIdExist(new TenantIdentifier(null, null, null), userInfo.getSupertokensUserId())); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); + assertTrue(storage.doesUserIdExist(process.getAppForTesting(), userInfo.getSupertokensUserId())); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); diff --git a/src/test/java/io/supertokens/test/authRecipe/DeleteUserAPIWithUserIdMappingTest.java b/src/test/java/io/supertokens/test/authRecipe/DeleteUserAPIWithUserIdMappingTest.java index ea19d3d38..cea74639b 100644 --- a/src/test/java/io/supertokens/test/authRecipe/DeleteUserAPIWithUserIdMappingTest.java +++ b/src/test/java/io/supertokens/test/authRecipe/DeleteUserAPIWithUserIdMappingTest.java @@ -42,6 +42,9 @@ public class DeleteUserAPIWithUserIdMappingTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -65,17 +68,17 @@ public void createAUserMapTheirIdCreateMetadataWithExternalIdAndDelete() throws // deleting with superTokensUserId { // create User - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); String superTokensUserId = userInfo.getSupertokensUserId(); String externalId = "externalId"; // map their id - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalId, null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalId, null, false); // create UserMetadata with the externalId JsonObject testData = new JsonObject(); testData.addProperty("testKey", "testValue"); - UserMetadata.updateUserMetadata(process.main, externalId, testData); + UserMetadata.updateUserMetadata(process.getProcess(), externalId, testData); JsonObject requestBody = new JsonObject(); requestBody.addProperty("userId", superTokensUserId); @@ -87,20 +90,20 @@ public void createAUserMapTheirIdCreateMetadataWithExternalIdAndDelete() throws // check that user doesnt exist { - AuthRecipeUserInfo response = EmailPassword.getUserUsingId(process.main, superTokensUserId); + AuthRecipeUserInfo response = EmailPassword.getUserUsingId(process.getProcess(), superTokensUserId); assertNull(response); } // check that userMetadata does not exist { - JsonObject response = UserMetadata.getUserMetadata(process.main, externalId); + JsonObject response = UserMetadata.getUserMetadata(process.getProcess(), externalId); assertEquals(0, response.entrySet().size()); } // check that mapping does not exist { io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS); assertNull(response); } } @@ -122,19 +125,19 @@ public void testDeleteUserBehaviorInIntermediateStateWithUser_1sUserId() throws } // create an EmailPassword User - AuthRecipeUserInfo userInfo_1 = EmailPassword.signUp(process.main, "test@example.com", "testPassword123"); + AuthRecipeUserInfo userInfo_1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPassword123"); // associate some data with user JsonObject data = new JsonObject(); data.addProperty("test", "testData"); - UserMetadata.updateUserMetadata(process.main, userInfo_1.getSupertokensUserId(), data); + UserMetadata.updateUserMetadata(process.getProcess(), userInfo_1.getSupertokensUserId(), data); // create a new User who we would like to migrate the EmailPassword user to - ThirdParty.SignInUpResponse userInfo_2 = ThirdParty.signInUp(process.main, "google", "test-google", + ThirdParty.SignInUpResponse userInfo_2 = ThirdParty.signInUp(process.getProcess(), "google", "test-google", "test123@example.com"); // force create a mapping between the thirdParty user and EmailPassword user - UserIdMapping.createUserIdMapping(process.main, userInfo_2.user.getSupertokensUserId(), + UserIdMapping.createUserIdMapping(process.getProcess(), userInfo_2.user.getSupertokensUserId(), userInfo_1.getSupertokensUserId(), null, true); // delete User with EmailPassword userId @@ -151,17 +154,17 @@ public void testDeleteUserBehaviorInIntermediateStateWithUser_1sUserId() throws // check that only auth tables for EmailPassword user have been deleted and the userMetadata table entries still // exist { - AuthRecipeUserInfo epUser = EmailPassword.getUserUsingId(process.main, userInfo_1.getSupertokensUserId()); + AuthRecipeUserInfo epUser = EmailPassword.getUserUsingId(process.getProcess(), userInfo_1.getSupertokensUserId()); assertNull(epUser); - JsonObject epUserMetadata = UserMetadata.getUserMetadata(process.main, userInfo_1.getSupertokensUserId()); + JsonObject epUserMetadata = UserMetadata.getUserMetadata(process.getProcess(), userInfo_1.getSupertokensUserId()); assertNotNull(epUserMetadata); assertEquals(epUserMetadata.get("test").getAsString(), "testData"); } // check that the mapping still exists { io.supertokens.pluginInterface.useridmapping.UserIdMapping mapping = UserIdMapping - .getUserIdMapping(process.main, userInfo_2.user.getSupertokensUserId(), UserIdType.ANY); + .getUserIdMapping(process.getProcess(), userInfo_2.user.getSupertokensUserId(), UserIdType.ANY); assertNotNull(mapping); assertEquals(mapping.superTokensUserId, userInfo_2.user.getSupertokensUserId()); assertEquals(mapping.externalUserId, userInfo_1.getSupertokensUserId()); @@ -183,19 +186,19 @@ public void testDeleteUserBehaviorInIntermediateStateWithUser_2sUserId() throws } // create an EmailPassword User - AuthRecipeUserInfo userInfo_1 = EmailPassword.signUp(process.main, "test@example.com", "testPassword123"); + AuthRecipeUserInfo userInfo_1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPassword123"); // associate some data with user JsonObject data = new JsonObject(); data.addProperty("test", "testData"); - UserMetadata.updateUserMetadata(process.main, userInfo_1.getSupertokensUserId(), data); + UserMetadata.updateUserMetadata(process.getProcess(), userInfo_1.getSupertokensUserId(), data); // create a new User who we would like to migrate the EmailPassword user to - ThirdParty.SignInUpResponse userInfo_2 = ThirdParty.signInUp(process.main, "google", "test-google", + ThirdParty.SignInUpResponse userInfo_2 = ThirdParty.signInUp(process.getProcess(), "google", "test-google", "test123@example.com"); // force create a mapping between the thirdParty user and EmailPassword user - UserIdMapping.createUserIdMapping(process.main, userInfo_2.user.getSupertokensUserId(), + UserIdMapping.createUserIdMapping(process.getProcess(), userInfo_2.user.getSupertokensUserId(), userInfo_1.getSupertokensUserId(), null, true); // delete User with ThirdParty users id @@ -212,18 +215,18 @@ public void testDeleteUserBehaviorInIntermediateStateWithUser_2sUserId() throws // check that only auth tables for thirdParty user have been deleted and the userMetadata table entries still // exist { - AuthRecipeUserInfo tpUserInfo = ThirdParty.getUser(process.main, + AuthRecipeUserInfo tpUserInfo = ThirdParty.getUser(process.getProcess(), userInfo_2.user.getSupertokensUserId()); assertNull(tpUserInfo); - JsonObject epUserMetadata = UserMetadata.getUserMetadata(process.main, userInfo_1.getSupertokensUserId()); + JsonObject epUserMetadata = UserMetadata.getUserMetadata(process.getProcess(), userInfo_1.getSupertokensUserId()); assertNotNull(epUserMetadata); assertEquals(epUserMetadata.get("test").getAsString(), "testData"); } // check that the mapping is also deleted { io.supertokens.pluginInterface.useridmapping.UserIdMapping mapping = UserIdMapping - .getUserIdMapping(process.main, userInfo_2.user.getSupertokensUserId(), UserIdType.ANY); + .getUserIdMapping(process.getProcess(), userInfo_2.user.getSupertokensUserId(), UserIdType.ANY); assertNull(mapping); } diff --git a/src/test/java/io/supertokens/test/authRecipe/GetUserByIdAPITest.java b/src/test/java/io/supertokens/test/authRecipe/GetUserByIdAPITest.java index 8d898c1f3..dcaf0255b 100644 --- a/src/test/java/io/supertokens/test/authRecipe/GetUserByIdAPITest.java +++ b/src/test/java/io/supertokens/test/authRecipe/GetUserByIdAPITest.java @@ -46,6 +46,9 @@ public class GetUserByIdAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -59,11 +62,10 @@ public void beforeEach() { @Test public void getUserSuccess() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -78,9 +80,9 @@ public void getUserSuccess() throws Exception { AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "password"); assert (!user2.isPrimaryUser); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), user.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user.getSupertokensUserId()); { Map params = new HashMap<>(); @@ -131,11 +133,10 @@ public void getUserSuccess() throws Exception { @Test public void getUserSuccessWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -144,17 +145,17 @@ public void getUserSuccessWithUserIdMapping() throws Exception { AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "password"); assert (!user.isPrimaryUser); - UserIdMapping.createUserIdMapping(process.main, user.getSupertokensUserId(), "e1", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), user.getSupertokensUserId(), "e1", null, false); Thread.sleep(50); AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "password"); assert (!user2.isPrimaryUser); - UserIdMapping.createUserIdMapping(process.main, user2.getSupertokensUserId(), "e2", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), user2.getSupertokensUserId(), "e2", null, false); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, user2.getSupertokensUserId(), user.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), user2.getSupertokensUserId(), user.getSupertokensUserId()); { Map params = new HashMap<>(); @@ -205,11 +206,10 @@ public void getUserSuccessWithUserIdMapping() throws Exception { @Test public void getUserSuccess2() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -227,9 +227,9 @@ public void getUserSuccess2() throws Exception { AuthRecipeUserInfo user2 = signInUpRespone.user; assert (!user2.isPrimaryUser); - AuthRecipe.createPrimaryUser(process.main, user2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user2.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, user.getSupertokensUserId(), user2.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), user.getSupertokensUserId(), user2.getSupertokensUserId()); { Map params = new HashMap<>(); @@ -275,11 +275,10 @@ public void getUserSuccess2() throws Exception { @Test public void getUnknownUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/authRecipe/GetUsersAPIWithUserIdMappingTest.java b/src/test/java/io/supertokens/test/authRecipe/GetUsersAPIWithUserIdMappingTest.java index 078b4efdb..bc2c42964 100644 --- a/src/test/java/io/supertokens/test/authRecipe/GetUsersAPIWithUserIdMappingTest.java +++ b/src/test/java/io/supertokens/test/authRecipe/GetUsersAPIWithUserIdMappingTest.java @@ -45,6 +45,9 @@ public class GetUsersAPIWithUserIdMappingTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -65,20 +68,21 @@ public void createMultipleUsersAndMapTheirIdsRetrieveAllUsersAndCheckThatExterna return; } - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); ArrayList externalUserIdList = new ArrayList<>(); for (int i = 1; i <= 10; i++) { // create User - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test" + i + "@example.com", + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test" + i + "@example.com", "testPass123"); String superTokensUserId = userInfo.getSupertokensUserId(); String externalUserId = "externalId" + i; externalUserIdList.add(externalUserId); // create a userId mapping - storage.createUserIdMapping(new AppIdentifier(null, null), superTokensUserId, externalUserId, + storage.createUserIdMapping(process.getAppForTesting().toAppIdentifier(), superTokensUserId, externalUserId, null); + Thread.sleep(20); } JsonObject response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", @@ -106,20 +110,21 @@ public void createMultipleUsersAndMapTheirIdsRetrieveUsersUsingPaginationTokenAn return; } - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); ArrayList externalUserIdList = new ArrayList<>(); for (int i = 1; i <= 20; i++) { // create User - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test" + i + "@example.com", + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test" + i + "@example.com", "testPass123"); String superTokensUserId = userInfo.getSupertokensUserId(); String externalUserId = "externalId" + i; externalUserIdList.add(externalUserId); // create a userId mapping - storage.createUserIdMapping(new AppIdentifier(null, null), superTokensUserId, externalUserId, + storage.createUserIdMapping(process.getAppForTesting().toAppIdentifier(), superTokensUserId, externalUserId, null); + Thread.sleep(10); } HashMap queryParams = new HashMap<>(); diff --git a/src/test/java/io/supertokens/test/authRecipe/GetUsersWithSearchTagsAPITest.java b/src/test/java/io/supertokens/test/authRecipe/GetUsersWithSearchTagsAPITest.java index a76857cb9..a257e7d23 100644 --- a/src/test/java/io/supertokens/test/authRecipe/GetUsersWithSearchTagsAPITest.java +++ b/src/test/java/io/supertokens/test/authRecipe/GetUsersWithSearchTagsAPITest.java @@ -48,6 +48,9 @@ public class GetUsersWithSearchTagsAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/authRecipe/GetUsersWithSearchTagsTest.java b/src/test/java/io/supertokens/test/authRecipe/GetUsersWithSearchTagsTest.java index 5a7542472..accbcbd23 100644 --- a/src/test/java/io/supertokens/test/authRecipe/GetUsersWithSearchTagsTest.java +++ b/src/test/java/io/supertokens/test/authRecipe/GetUsersWithSearchTagsTest.java @@ -20,6 +20,8 @@ import java.util.ArrayList; +import io.supertokens.emailpassword.PasswordHashing; +import io.supertokens.pluginInterface.StorageUtils; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; @@ -46,6 +48,9 @@ public class GetUsersWithSearchTagsTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -192,13 +197,17 @@ public void testSearchParamRegex() throws Exception { ArrayList userIds = new ArrayList<>(); userIds.add( EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123").getSupertokensUserId()); + Thread.sleep(20); userIds.add( EmailPassword.signUp(process.getProcess(), "abc@example.com", "testPass123").getSupertokensUserId()); + Thread.sleep(20); userIds.add(EmailPassword.signUp(process.getProcess(), "user@abc.com", "testPass123").getSupertokensUserId()); + Thread.sleep(20); // create thirdparty user userIds.add(ThirdParty.signInUp(process.getProcess(), "testTPID", "test", "test2@example.com").user.getSupertokensUserId()); + Thread.sleep(20); // create passwordless user CreateCodeResponse createCodeResponse = Passwordless.createCode(process.getProcess(), "test@example.com", @@ -273,10 +282,14 @@ public void testThatQueryLimitIsCappedAt1000PerTable() throws Exception { // create 1005 emailpassword users ArrayList userIds = new ArrayList<>(); + String hashedPassword = PasswordHashing.getInstance(process.getProcess()) + .createHashWithSalt(process.getAppForTesting().toAppIdentifier(), "testPass123"); + for (int i = 0; i < 1005; i++) { - userIds.add(EmailPassword.signUp(process.getProcess(), "test" + i + "@example.com", "testPass123") - .getSupertokensUserId()); - Thread.sleep(10); + String userId = io.supertokens.utils.Utils.getUUID(); + StorageUtils.getEmailPasswordStorage(StorageLayer.getBaseStorage(process.getProcess())) + .signUp(process.getAppForTesting(), userId, "test" + i + "@example.com", hashedPassword, System.currentTimeMillis()); + userIds.add(userId); } // retrieve users diff --git a/src/test/java/io/supertokens/test/authRecipe/UserPaginationTest.java b/src/test/java/io/supertokens/test/authRecipe/UserPaginationTest.java index 822784428..85e14585b 100644 --- a/src/test/java/io/supertokens/test/authRecipe/UserPaginationTest.java +++ b/src/test/java/io/supertokens/test/authRecipe/UserPaginationTest.java @@ -353,7 +353,7 @@ public void testUserPaginationWorksCorrectlyForEachTenant() throws Exception { @Test public void testUserPaginationWithSameTimeJoined() throws Exception { - if (StorageLayer.getBaseStorage(process.main).getType() != STORAGE_TYPE.SQL) { + if (StorageLayer.getBaseStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } @@ -364,7 +364,7 @@ public void testUserPaginationWithSameTimeJoined() throws Exception { long timeJoined = System.currentTimeMillis(); for (int i = 0; i < 100; i++) { String userId = io.supertokens.utils.Utils.getUUID(); - storage.signUp(TenantIdentifier.BASE_TENANT, userId, "test" + i + "@example.com", + storage.signUp(process.getAppForTesting(), userId, "test" + i + "@example.com", new LoginMethod.ThirdParty("google", userId), timeJoined); userIds.add(userId); } diff --git a/src/test/java/io/supertokens/test/bulkimport/BulkImportFlowTest.java b/src/test/java/io/supertokens/test/bulkimport/BulkImportFlowTest.java index 146101869..c20a92808 100644 --- a/src/test/java/io/supertokens/test/bulkimport/BulkImportFlowTest.java +++ b/src/test/java/io/supertokens/test/bulkimport/BulkImportFlowTest.java @@ -59,6 +59,9 @@ public class BulkImportFlowTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -155,7 +158,7 @@ public void testCoreRestartMidImportShouldResultInSuccessfulImport() throws Exce Utils.setValueInConfig("bulk_migration_batch_size", "1000"); Utils.setValueInConfig("log_level", "DEBUG"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, true); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, true); Main main = process.getProcess(); setFeatureFlags(main, new EE_FEATURES[] { EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA}); @@ -220,7 +223,7 @@ public void testCoreRestartMidImportShouldResultInSuccessfulImport() throws Exce Utils.setValueInConfig("bulk_migration_parallelism", "14"); Utils.setValueInConfig("bulk_migration_batch_size", "4000"); System.out.println("Started new core"); - process = TestingProcessManager.start(args, true); + process = TestingProcessManager.startIsolatedProcess(args, true); main = process.getProcess(); setFeatureFlags(main, new EE_FEATURES[] { EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA}); @@ -928,7 +931,7 @@ private Main startCronProcess(String parallelism, int intervalInSeconds) throws //Utils.setValueInConfig("bulk_migration_batch_size", "1000"); Utils.setValueInConfig("log_level", "DEBUG"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, true); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, true); Main main = process.getProcess(); setFeatureFlags(main, new EE_FEATURES[] { EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA}); diff --git a/src/test/java/io/supertokens/test/bulkimport/BulkImportTest.java b/src/test/java/io/supertokens/test/bulkimport/BulkImportTest.java index dc26df906..c253d81f6 100644 --- a/src/test/java/io/supertokens/test/bulkimport/BulkImportTest.java +++ b/src/test/java/io/supertokens/test/bulkimport/BulkImportTest.java @@ -67,6 +67,9 @@ public class BulkImportTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -91,7 +94,7 @@ public void shouldAddUsersInBulkImportUsersTable() throws Exception { List users = generateBulkImportUser(10); - BulkImportStorage storage = (BulkImportStorage) StorageLayer.getStorage(process.main); + BulkImportStorage storage = (BulkImportStorage) StorageLayer.getStorage(process.getProcess()); BulkImport.addUsers(new AppIdentifier(null, null), storage, users); List addedUsers = storage.getBulkImportUsers(new AppIdentifier(null, null), 100, @@ -132,7 +135,7 @@ public void shouldCreatedNewIdsIfDuplicateIdIsFound() throws Exception { List initialIds = users.stream().map(user -> user.id).collect(Collectors.toList()); - BulkImportStorage storage = (BulkImportStorage) StorageLayer.getStorage(process.main); + BulkImportStorage storage = (BulkImportStorage) StorageLayer.getStorage(process.getProcess()); AppIdentifier appIdentifier = new AppIdentifier(null, null); BulkImport.addUsers(appIdentifier, storage, users); @@ -167,8 +170,8 @@ public void testGetUsersStatusFilter() throws Exception { return; } - BulkImportSQLStorage storage = (BulkImportSQLStorage) StorageLayer.getStorage(process.main); - AppIdentifier appIdentifier = new AppIdentifier(null, null); + BulkImportSQLStorage storage = (BulkImportSQLStorage) StorageLayer.getStorage(process.getProcess()); + AppIdentifier appIdentifier = process.getAppForTesting().toAppIdentifier(); // Test with status = 'NEW' { @@ -228,7 +231,7 @@ public void testGetUsersStatusFilter() throws Exception { public void randomPaginationTest() throws Exception { String[] args = { "../" }; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); // We are setting a high initial wait time to ensure the cron job doesn't run while we are running the tests CronTaskTest.getInstance(process.getProcess()).setInitialWaitTimeInSeconds(ProcessBulkImportUsers.RESOURCE_KEY, @@ -243,7 +246,7 @@ public void randomPaginationTest() throws Exception { return; } - BulkImportStorage storage = (BulkImportStorage) StorageLayer.getStorage(process.main); + BulkImportStorage storage = (BulkImportStorage) StorageLayer.getStorage(process.getProcess()); int numberOfUsers = 500; // Insert users in batches @@ -313,7 +316,7 @@ public void testGetBulkImportUsersCount() throws Exception { return; } - BulkImportSQLStorage storage = (BulkImportSQLStorage) StorageLayer.getStorage(process.main); + BulkImportSQLStorage storage = (BulkImportSQLStorage) StorageLayer.getStorage(process.getProcess()); AppIdentifier appIdentifier = new AppIdentifier(null, null); // Test with status = 'NEW' @@ -383,7 +386,7 @@ public void shouldImportTheUserInTheSameTenant() throws Exception { new EE_FEATURES[] { EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA, EE_FEATURES.ACCOUNT_LINKING }); // Create tenants - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); // Create user roles { @@ -391,7 +394,7 @@ public void shouldImportTheUserInTheSameTenant() throws Exception { UserRoles.createNewRoleOrModifyItsPermissions(main, "role2", null); } - AppIdentifier appIdentifier = new AppIdentifier(null, null); + AppIdentifier appIdentifier = process.getAppForTesting().toAppIdentifier(); List users = generateBulkImportUser(1); AuthRecipeUserInfo importedUser = BulkImport.importUser(main, appIdentifier, users.get(0)); @@ -419,7 +422,7 @@ public void shouldImportTheUserInMultipleTenantsWithDifferentStorages() throws E new EE_FEATURES[] { EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA, EE_FEATURES.ACCOUNT_LINKING }); // Create tenants - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); // Create user roles { @@ -427,13 +430,13 @@ public void shouldImportTheUserInMultipleTenantsWithDifferentStorages() throws E UserRoles.createNewRoleOrModifyItsPermissions(main, "role2", null); } - TenantIdentifier t1 = new TenantIdentifier(null, null, "t1"); - TenantIdentifier t2 = new TenantIdentifier(null, null, "t2"); + TenantIdentifier t1 = new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"); + TenantIdentifier t2 = new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t2"); Storage storageT1 = StorageLayer.getStorage(t1, main); Storage storageT2 = StorageLayer.getStorage(t2, main); - AppIdentifier appIdentifier = new AppIdentifier(null, null); + AppIdentifier appIdentifier = process.getAppForTesting().toAppIdentifier(); List usersT1 = generateBulkImportUser(1, List.of(t1.getTenantId()), 0); List usersT2 = generateBulkImportUser(1, List.of(t2.getTenantId()), 1); @@ -471,7 +474,7 @@ public void shouldImportUsersConcurrently() throws Exception { new EE_FEATURES[] { EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA, EE_FEATURES.ACCOUNT_LINKING }); // Create tenants - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); // Create user roles { @@ -479,7 +482,7 @@ public void shouldImportUsersConcurrently() throws Exception { UserRoles.createNewRoleOrModifyItsPermissions(main, "role2", null); } - AppIdentifier appIdentifier = new AppIdentifier(null, null); + AppIdentifier appIdentifier = process.getAppForTesting().toAppIdentifier(); List users = generateBulkImportUser(10); // Concurrently import users @@ -523,7 +526,7 @@ public void shouldImportWithPlainTextPassword() throws Exception { new EE_FEATURES[] { EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA, EE_FEATURES.ACCOUNT_LINKING }); // Create tenants - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); // Create user roles { @@ -531,7 +534,7 @@ public void shouldImportWithPlainTextPassword() throws Exception { UserRoles.createNewRoleOrModifyItsPermissions(main, "role2", null); } - AppIdentifier appIdentifier = new AppIdentifier(null, null); + AppIdentifier appIdentifier = process.getAppForTesting().toAppIdentifier(); List users = generateBulkImportUser(1); BulkImportUser bulkImportUser = users.get(0); @@ -569,7 +572,7 @@ public void shouldFailIfUserWithSameEmailAlreadyExists() throws Exception { new EE_FEATURES[] { EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA, EE_FEATURES.ACCOUNT_LINKING }); // Create tenants - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); // Create user roles { @@ -609,7 +612,7 @@ public void shouldFailIfPrimaryUserWithSameEmailAlreadyExists() throws Exception new EE_FEATURES[] { EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA, EE_FEATURES.ACCOUNT_LINKING }); // Create tenants - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); // Create user roles { @@ -649,7 +652,7 @@ public void shouldFailIfPrimaryWebAuthNUserWithSameEmailAlreadyExists() throws E new EE_FEATURES[] { EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA, EE_FEATURES.ACCOUNT_LINKING }); // Create tenants - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); // Create user roles { @@ -657,10 +660,10 @@ public void shouldFailIfPrimaryWebAuthNUserWithSameEmailAlreadyExists() throws E UserRoles.createNewRoleOrModifyItsPermissions(main, "role2", null); } - AppIdentifier appIdentifier = new AppIdentifier(null, null); + AppIdentifier appIdentifier = process.getAppForTesting().toAppIdentifier(); AuthRecipeUserInfo webauthnUser = WebAuthN.saveUser(StorageLayer.getStorage(main), - new TenantIdentifier(null, null, null), + process.getAppForTesting(), "user0@example.com", io.supertokens.utils.Utils.getUUID(), "example.com"); AuthRecipe.createPrimaryUser(main, webauthnUser.getSupertokensUserId()); @@ -692,7 +695,7 @@ public void shouldSucceedIfThirdpartyUserWithSameEmailAlreadyExists() throws Exc new EE_FEATURES[] { EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA, EE_FEATURES.ACCOUNT_LINKING }); // Create tenants - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); // Create user roles { @@ -700,7 +703,7 @@ public void shouldSucceedIfThirdpartyUserWithSameEmailAlreadyExists() throws Exc UserRoles.createNewRoleOrModifyItsPermissions(main, "role2", null); } - AppIdentifier appIdentifier = new AppIdentifier(null, null); + AppIdentifier appIdentifier = process.getAppForTesting().toAppIdentifier(); ThirdParty.SignInUpResponse thirdPartyUser = ThirdParty.signInUp(main, "google", "123123", "user0@example.com"); List users = generateBulkImportUserWithEmailPasswordAndRoles(1, List.of("public", "t1"), 0, List.of("role1", "role2")); @@ -736,7 +739,7 @@ public void shouldFailIfThirdpartyUserWithSameEmailAlreadyExists() throws Except new EE_FEATURES[] { EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA, EE_FEATURES.ACCOUNT_LINKING }); // Create tenants - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); // Create user roles { @@ -776,7 +779,7 @@ public void shouldLinkBulkMigratedAccounts() throws Exception { new EE_FEATURES[] { EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA, EE_FEATURES.ACCOUNT_LINKING }); // Create tenants - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); // Create user roles { @@ -784,7 +787,7 @@ public void shouldLinkBulkMigratedAccounts() throws Exception { UserRoles.createNewRoleOrModifyItsPermissions(main, "role2", null); } - AppIdentifier appIdentifier = new AppIdentifier(null, null); + AppIdentifier appIdentifier = process.getAppForTesting().toAppIdentifier(); List users = generateBulkImportUser(1); @@ -813,7 +816,7 @@ public void shouldFailLinkingBulkMigratedAccountsOnTwoTenants() throws Exception new EE_FEATURES[] { EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA, EE_FEATURES.ACCOUNT_LINKING }); // Create tenants - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); // Create user roles { @@ -821,10 +824,10 @@ public void shouldFailLinkingBulkMigratedAccountsOnTwoTenants() throws Exception UserRoles.createNewRoleOrModifyItsPermissions(main, "role2", null); } - AppIdentifier appIdentifier = new AppIdentifier(null, null); + AppIdentifier appIdentifier = process.getAppForTesting().toAppIdentifier(); //set up an existing primary user on public tenant with email B - ThirdParty.SignInUpResponse thirdpartyResponse = ThirdParty.signInUp(new TenantIdentifier(null, null, null), + ThirdParty.SignInUpResponse thirdpartyResponse = ThirdParty.signInUp(process.getAppForTesting(), StorageLayer.getStorage(main),main, "google", "123123", "emailB@example.com", true); AuthRecipe.createPrimaryUser(main, thirdpartyResponse.user.getSupertokensUserId()); @@ -864,7 +867,7 @@ public void shouldFailLinkingBulkMigratedAccountsOnThreeTenants() throws Excepti new EE_FEATURES[] { EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA, EE_FEATURES.ACCOUNT_LINKING }); // Create tenants - BulkImportTestUtils.createTenantsWithinOneUserPool(main); + BulkImportTestUtils.createTenantsWithinOneUserPool(process); // Create user roles { @@ -872,10 +875,10 @@ public void shouldFailLinkingBulkMigratedAccountsOnThreeTenants() throws Excepti UserRoles.createNewRoleOrModifyItsPermissions(main, "role2", null); } - AppIdentifier appIdentifier = new AppIdentifier(null, null); + AppIdentifier appIdentifier = process.getAppForTesting().toAppIdentifier(); //set up an existing primary user on public tenant with email B - ThirdParty.SignInUpResponse thirdpartyResponse = ThirdParty.signInUp(new TenantIdentifier(null, null, "t1"), + ThirdParty.SignInUpResponse thirdpartyResponse = ThirdParty.signInUp(new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"), StorageLayer.getStorage(main),main, "google", "123123", "emailB@example.com", true); AuthRecipe.createPrimaryUser(main, thirdpartyResponse.user.getSupertokensUserId()); @@ -922,7 +925,7 @@ public void shouldFailLinkingBulkMigratedAccountsOnThreeTenantsWithWebAuthNUser( new EE_FEATURES[] { EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA, EE_FEATURES.ACCOUNT_LINKING }); // Create tenants - BulkImportTestUtils.createTenantsWithinOneUserPool(main); + BulkImportTestUtils.createTenantsWithinOneUserPool(process); // Create user roles { @@ -930,11 +933,11 @@ public void shouldFailLinkingBulkMigratedAccountsOnThreeTenantsWithWebAuthNUser( UserRoles.createNewRoleOrModifyItsPermissions(main, "role2", null); } - AppIdentifier appIdentifier = new AppIdentifier(null, null); + AppIdentifier appIdentifier = process.getAppForTesting().toAppIdentifier(); //set up an existing primary user on public tenant with email B AuthRecipeUserInfo webauthnUser = WebAuthN.saveUser(StorageLayer.getStorage(main), - new TenantIdentifier(null, null, null), + process.getAppForTesting(), "emailB@example.com", io.supertokens.utils.Utils.getUUID(), "example.com"); AuthRecipe.createPrimaryUser(main, webauthnUser.getSupertokensUserId()); diff --git a/src/test/java/io/supertokens/test/bulkimport/BulkImportTestUtils.java b/src/test/java/io/supertokens/test/bulkimport/BulkImportTestUtils.java index 12d5521b1..3ecccedb8 100644 --- a/src/test/java/io/supertokens/test/bulkimport/BulkImportTestUtils.java +++ b/src/test/java/io/supertokens/test/bulkimport/BulkImportTestUtils.java @@ -36,6 +36,7 @@ import io.supertokens.pluginInterface.multitenancy.exceptions.TenantOrAppNotFoundException; import io.supertokens.pluginInterface.totp.TOTPDevice; import io.supertokens.storageLayer.StorageLayer; +import io.supertokens.test.TestingProcessManager; import io.supertokens.thirdparty.InvalidProviderConfigException; import io.supertokens.totp.Totp; import io.supertokens.usermetadata.UserMetadata; @@ -195,19 +196,20 @@ public static List generateBulkImportUserWithNoExternalIdWithRol return users; } - public static void createTenants(Main main) + public static void createTenants(TestingProcessManager.TestingProcess process) throws StorageQueryException, TenantOrAppNotFoundException, InvalidProviderConfigException, FeatureNotEnabledException, IOException, InvalidConfigException, CannotModifyBaseConfigException, BadPermissionException { + Main main = process.getProcess(); // User pool 1 - (null, null, null), (null, null, t1) // User pool 2 - (null, null, t2) { // tenant 1 - TenantIdentifier tenantIdentifier = new TenantIdentifier(null, null, "t1"); + TenantIdentifier tenantIdentifier = new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"); Multitenancy.addNewOrUpdateAppOrTenant( main, - new TenantIdentifier(null, null, null), + new TenantIdentifier(null, process.getAppForTesting().getAppId(), null), new TenantConfig( tenantIdentifier, new EmailPasswordConfig(true), @@ -217,14 +219,14 @@ public static void createTenants(Main main) } { // tenant 2 JsonObject config = new JsonObject(); - TenantIdentifier tenantIdentifier = new TenantIdentifier(null, null, "t2"); + TenantIdentifier tenantIdentifier = new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t2"); - StorageLayer.getStorage(new TenantIdentifier(null, null, null), main) + StorageLayer.getStorage(new TenantIdentifier(null, process.getAppForTesting().getAppId(), null), main) .modifyConfigToAddANewUserPoolForTesting(config, 1); Multitenancy.addNewOrUpdateAppOrTenant( main, - new TenantIdentifier(null, null, null), + new TenantIdentifier(null, process.getAppForTesting().getAppId(), null), new TenantConfig( tenantIdentifier, new EmailPasswordConfig(true), @@ -234,18 +236,19 @@ public static void createTenants(Main main) } } - public static void createTenantsWithinOneUserPool(Main main) + public static void createTenantsWithinOneUserPool(TestingProcessManager.TestingProcess process) throws StorageQueryException, TenantOrAppNotFoundException, InvalidProviderConfigException, FeatureNotEnabledException, IOException, InvalidConfigException, CannotModifyBaseConfigException, BadPermissionException { // User pool 1 - (null, null, null), (null, null, t1), (null, null, t2) + Main main = process.getProcess(); { // tenant 1 - TenantIdentifier tenantIdentifier = new TenantIdentifier(null, null, "t1"); + TenantIdentifier tenantIdentifier = new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"); Multitenancy.addNewOrUpdateAppOrTenant( main, - new TenantIdentifier(null, null, null), + new TenantIdentifier(null, process.getAppForTesting().getAppId(), null), new TenantConfig( tenantIdentifier, new EmailPasswordConfig(true), @@ -254,11 +257,11 @@ public static void createTenantsWithinOneUserPool(Main main) null, null, new JsonObject())); } { // tenant 2 - TenantIdentifier tenantIdentifier = new TenantIdentifier(null, null, "t2"); + TenantIdentifier tenantIdentifier = new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t2"); Multitenancy.addNewOrUpdateAppOrTenant( main, - new TenantIdentifier(null, null, null), + new TenantIdentifier(null, process.getAppForTesting().getAppId(), null), new TenantConfig( tenantIdentifier, new EmailPasswordConfig(true), diff --git a/src/test/java/io/supertokens/test/bulkimport/ProcessBulkImportUsersCronJobTest.java b/src/test/java/io/supertokens/test/bulkimport/ProcessBulkImportUsersCronJobTest.java index 7ce859521..6e44f9acb 100644 --- a/src/test/java/io/supertokens/test/bulkimport/ProcessBulkImportUsersCronJobTest.java +++ b/src/test/java/io/supertokens/test/bulkimport/ProcessBulkImportUsersCronJobTest.java @@ -59,6 +59,9 @@ public class ProcessBulkImportUsersCronJobTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -84,7 +87,7 @@ public void shouldProcessBulkImportUsersInTheSameTenant() throws Exception { UserRoles.createNewRoleOrModifyItsPermissions(main, "role2", null); } - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); BulkImportSQLStorage storage = (BulkImportSQLStorage) StorageLayer.getStorage(main); AppIdentifier appIdentifier = new AppIdentifier(null, null); @@ -132,7 +135,7 @@ public void shouldProcessBulkImportUsersInTheSameTenantWithoutExternalIdWithRole UserRoles.createNewRoleOrModifyItsPermissions(main, "role2", null); } - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); BulkImportSQLStorage storage = (BulkImportSQLStorage) StorageLayer.getStorage(main); AppIdentifier appIdentifier = new AppIdentifier(null, null); @@ -180,7 +183,7 @@ public void shouldProcessPlainTextPasswordBulkImportUsersInTheSameTenant() throw UserRoles.createNewRoleOrModifyItsPermissions(main, "role2", null); } - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); BulkImportSQLStorage storage = (BulkImportSQLStorage) StorageLayer.getStorage(main); AppIdentifier appIdentifier = new AppIdentifier(null, null); @@ -228,7 +231,7 @@ public void shouldProcessBulkImportUsersInNotSoLargeNumbersInTheSameTenant() thr UserRoles.createNewRoleOrModifyItsPermissions(main, "role2", null); } - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); BulkImportSQLStorage storage = (BulkImportSQLStorage) StorageLayer.getStorage(main); AppIdentifier appIdentifier = new AppIdentifier(null, null); @@ -265,7 +268,7 @@ public void shouldProcessBulkImportUsersInLargeNumbersInTheSameTenant() throws E UserRoles.createNewRoleOrModifyItsPermissions(main, "role2", null); } - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); BulkImportSQLStorage storage = (BulkImportSQLStorage) StorageLayer.getStorage(main); AppIdentifier appIdentifier = new AppIdentifier(null, null); @@ -274,7 +277,7 @@ public void shouldProcessBulkImportUsersInLargeNumbersInTheSameTenant() throws E List users = generateBulkImportUser(usersCount); BulkImport.addUsers(appIdentifier, storage, users); - waitForProcessingWithTimeout(appIdentifier, storage, 300); // 5 minutes + waitForProcessingWithTimeout(appIdentifier, storage, 600); // 10 minutes List usersAfterProcessing = storage.getBulkImportUsers(appIdentifier, 1000, null, null, null); @@ -305,7 +308,7 @@ public void shouldProcessBulkImportUsersInMultipleTenantsWithDifferentStoragesOn UserRoles.createNewRoleOrModifyItsPermissions(main, "role2", null); } - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); TenantIdentifier t1 = new TenantIdentifier(null, null, "t1"); TenantIdentifier t2 = new TenantIdentifier(null, null, "t2"); @@ -367,7 +370,7 @@ public void shouldProcessBulkImportUsersInMultipleTenantsWithDifferentStoragesOn UserRoles.createNewRoleOrModifyItsPermissions(main, "role2", null); } - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); TenantIdentifier t1 = new TenantIdentifier(null, null, "t1"); TenantIdentifier t2 = new TenantIdentifier(null, null, "t2"); @@ -429,7 +432,7 @@ public void shouldProcessBulkImportUsersInLargeNumberInMultipleTenantsWithDiffer UserRoles.createNewRoleOrModifyItsPermissions(main, "role2", null); } - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); TenantIdentifier t1 = new TenantIdentifier(null, null, "t1"); TenantIdentifier t2 = new TenantIdentifier(null, null, "t2"); @@ -484,7 +487,7 @@ public void shouldProcessBulkImportUsersInLargeNumberInMultipleTenantsWithDiffer UserRoles.createNewRoleOrModifyItsPermissions(main, "role2", null); } - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); TenantIdentifier t1 = new TenantIdentifier(null, null, "t1"); TenantIdentifier t2 = new TenantIdentifier(null, null, "t2"); @@ -537,7 +540,7 @@ public void shouldDeleteEverythingFromTheDBIfAnythingFails() throws Exception { } Main main = process.getProcess(); - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); BulkImportSQLStorage storage = (BulkImportSQLStorage) StorageLayer.getStorage(main); AppIdentifier appIdentifier = new AppIdentifier(null, null); @@ -578,7 +581,7 @@ public void shouldDeleteEverythingFromTheDBIfAnythingFailsOnMultipleThreads() th } Main main = process.getProcess(); - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); Thread.sleep(1000); BulkImportSQLStorage storage = (BulkImportSQLStorage) StorageLayer.getStorage(main); @@ -621,7 +624,7 @@ public void shouldDeleteOnlyFailedFromTheDBIfAnythingFailsOnMultipleThreads() th } Main main = process.getProcess(); - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); BulkImportSQLStorage storage = (BulkImportSQLStorage) StorageLayer.getStorage(main); AppIdentifier appIdentifier = new AppIdentifier(null, null); @@ -707,7 +710,7 @@ public void shouldThrowTenantHaveDifferentStoragesError() throws Exception { UserRoles.createNewRoleOrModifyItsPermissions(main, "role1", null); UserRoles.createNewRoleOrModifyItsPermissions(main, "role2", null); } - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); List users = generateBulkImportUser(1, List.of("t1", "t2"), 0); BulkImport.addUsers(appIdentifier, storage, users); @@ -727,7 +730,7 @@ public void shouldThrowTenantHaveDifferentStoragesError() throws Exception { private TestingProcess startCronProcess() throws InterruptedException, TenantOrAppNotFoundException { String[] args = { "../" }; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); Main main = process.getProcess(); diff --git a/src/test/java/io/supertokens/test/bulkimport/apis/AddBulkImportUsersTest.java b/src/test/java/io/supertokens/test/bulkimport/apis/AddBulkImportUsersTest.java index 11c8e5839..99610d8e1 100644 --- a/src/test/java/io/supertokens/test/bulkimport/apis/AddBulkImportUsersTest.java +++ b/src/test/java/io/supertokens/test/bulkimport/apis/AddBulkImportUsersTest.java @@ -50,6 +50,9 @@ public class AddBulkImportUsersTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -160,7 +163,7 @@ public void shouldThrow400IfNonUniqueExternalIdsArePassed() throws Exception { @Test public void shouldThrow400IfTotpDevicesAreNotPassedCorrectly() throws Exception { - TestingProcessManager.TestingProcess process = TestingProcessManager.start(new String[] { "../" }); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(new String[] { "../" }); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); Main main = process.getProcess(); @@ -355,7 +358,7 @@ public void shouldThrow400IfPasswordlessRecipeHasInvalidFieldTypes() throws Exce @Test public void shouldThrow400IfAUserHasMultipleLoginMethodsAndAccountLinkingIsDisabled() throws Exception { - TestingProcessManager.TestingProcess process = TestingProcessManager.start(new String[] { "../" }); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(new String[] { "../" }); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); Main main = process.getProcess(); @@ -406,7 +409,7 @@ public void shouldThrow400IfInvalidTenantIdIsPassed() throws Exception { // CASE 3: Two or more tenants do not share the same storage - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); JsonObject requestBody3 = new JsonParser().parse( "{\"users\":[{\"loginMethods\":[{\"tenantIds\":[\"public\"],\"recipeId\":\"passwordless\",\"email\":\"johndoe@gmail.com\"}, {\"tenantIds\":[\"t2\"],\"recipeId\":\"thirdparty\", \"email\":\"johndoe@gmail.com\", \"thirdPartyId\":\"id\", \"thirdPartyUserId\":\"id\"}]}]}") diff --git a/src/test/java/io/supertokens/test/bulkimport/apis/DeleteBulkImportUsersTest.java b/src/test/java/io/supertokens/test/bulkimport/apis/DeleteBulkImportUsersTest.java index 28906ba95..8e5056c6f 100644 --- a/src/test/java/io/supertokens/test/bulkimport/apis/DeleteBulkImportUsersTest.java +++ b/src/test/java/io/supertokens/test/bulkimport/apis/DeleteBulkImportUsersTest.java @@ -53,6 +53,9 @@ public class DeleteBulkImportUsersTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -138,8 +141,8 @@ public void shouldReturn200Response() throws Exception { { - BulkImportStorage storage = (BulkImportStorage) StorageLayer.getStorage(process.main); - AppIdentifier appIdentifier = new AppIdentifier(null, null); + BulkImportStorage storage = (BulkImportStorage) StorageLayer.getStorage(process.getProcess()); + AppIdentifier appIdentifier = process.getAppForTesting().toAppIdentifier(); // Insert users List users = generateBulkImportUser(5); diff --git a/src/test/java/io/supertokens/test/bulkimport/apis/GetBulkImportUsersTest.java b/src/test/java/io/supertokens/test/bulkimport/apis/GetBulkImportUsersTest.java index 8db075610..babdda8a3 100644 --- a/src/test/java/io/supertokens/test/bulkimport/apis/GetBulkImportUsersTest.java +++ b/src/test/java/io/supertokens/test/bulkimport/apis/GetBulkImportUsersTest.java @@ -47,6 +47,9 @@ public class GetBulkImportUsersTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/bulkimport/apis/ImportUserTest.java b/src/test/java/io/supertokens/test/bulkimport/apis/ImportUserTest.java index c9da93089..9ab6d7a96 100644 --- a/src/test/java/io/supertokens/test/bulkimport/apis/ImportUserTest.java +++ b/src/test/java/io/supertokens/test/bulkimport/apis/ImportUserTest.java @@ -103,7 +103,7 @@ public void shouldReturn200Response() throws Exception { new EE_FEATURES[] { EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA, EE_FEATURES.ACCOUNT_LINKING }); // Create tenants - BulkImportTestUtils.createTenants(main); + BulkImportTestUtils.createTenants(process); // Create user roles { diff --git a/src/test/java/io/supertokens/test/dashboard/DashboardStorageTest.java b/src/test/java/io/supertokens/test/dashboard/DashboardStorageTest.java index 30f082c45..6b4ffe005 100644 --- a/src/test/java/io/supertokens/test/dashboard/DashboardStorageTest.java +++ b/src/test/java/io/supertokens/test/dashboard/DashboardStorageTest.java @@ -44,6 +44,9 @@ public class DashboardStorageTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -74,10 +77,10 @@ public void testCreateNewDashboardUser() throws Exception { { DashboardUser user = new DashboardUser(userId, email, passwordHash, System.currentTimeMillis()); - dashboardSQLStorage.createNewDashboardUser(new AppIdentifier(null, null), user); + dashboardSQLStorage.createNewDashboardUser(process.getAppForTesting().toAppIdentifier(), user); // get dashboard users to verify that user was created - DashboardUser[] users = dashboardSQLStorage.getAllDashboardUsers(new AppIdentifier(null, null)); + DashboardUser[] users = dashboardSQLStorage.getAllDashboardUsers(process.getAppForTesting().toAppIdentifier()); assertEquals(1, users.length); assertEquals(user, users[0]); } @@ -88,7 +91,7 @@ public void testCreateNewDashboardUser() throws Exception { System.currentTimeMillis()); Exception error = null; try { - dashboardSQLStorage.createNewDashboardUser(new AppIdentifier(null, null), user); + dashboardSQLStorage.createNewDashboardUser(process.getAppForTesting().toAppIdentifier(), user); throw new Exception("Should never come here"); } catch (DuplicateUserIdException e) { error = e; @@ -103,7 +106,7 @@ public void testCreateNewDashboardUser() throws Exception { System.currentTimeMillis()); Exception error = null; try { - dashboardSQLStorage.createNewDashboardUser(new AppIdentifier(null, null), user); + dashboardSQLStorage.createNewDashboardUser(process.getAppForTesting().toAppIdentifier(), user); throw new Exception("Should never come here"); } catch (DuplicateEmailException e) { error = e; @@ -137,18 +140,18 @@ public void testGetDashboardUserFunctions() throws Exception { // create a dashboardUser DashboardUser user = new DashboardUser(userId, email, passwordHash, System.currentTimeMillis()); - dashboardSQLStorage.createNewDashboardUser(new AppIdentifier(null, null), user); + dashboardSQLStorage.createNewDashboardUser(process.getAppForTesting().toAppIdentifier(), user); { // retrieve user with email - DashboardUser retrievedUser = dashboardSQLStorage.getDashboardUserByEmail(new AppIdentifier(null, null), + DashboardUser retrievedUser = dashboardSQLStorage.getDashboardUserByEmail(process.getAppForTesting().toAppIdentifier(), email); assertEquals(user, retrievedUser); } { // retrieve user with userId - DashboardUser retrievedUser = dashboardSQLStorage.getDashboardUserByUserId(new AppIdentifier(null, null), + DashboardUser retrievedUser = dashboardSQLStorage.getDashboardUserByUserId(process.getAppForTesting().toAppIdentifier(), userId); assertEquals(user, retrievedUser); } @@ -175,15 +178,15 @@ public void testGetAllDashboardUsers() throws Exception { DashboardUser user = new DashboardUser(io.supertokens.utils.Utils.getUUID(), "test" + i + "@example.com", "testPasswordHash", System.currentTimeMillis()); ((DashboardSQLStorage) StorageLayer.getStorage(process.getProcess())) - .createNewDashboardUser(new AppIdentifier(null, null), user); - Thread.sleep(2); + .createNewDashboardUser(process.getAppForTesting().toAppIdentifier(), user); + Thread.sleep(10); } // retrieve all dashboard users, check that correctly created and returned in // the correct order. DashboardUser[] users = ((DashboardSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllDashboardUsers(new AppIdentifier(null, null)); + .getAllDashboardUsers(process.getAppForTesting().toAppIdentifier()); assertEquals(10, users.length); for (int i = 0; i < 10; i++) { @@ -209,20 +212,20 @@ public void testTheDeleteDashboardUserWithUserIdFunction() throws Exception { DashboardSQLStorage dashboardSQLStorage = (DashboardSQLStorage) StorageLayer.getStorage(process.getProcess()); // check no user exists - assertEquals(0, dashboardSQLStorage.getAllDashboardUsers(new AppIdentifier(null, null)).length); + assertEquals(0, dashboardSQLStorage.getAllDashboardUsers(process.getAppForTesting().toAppIdentifier()).length); // create a user DashboardUser user = Dashboard.signUpDashboardUser(process.getProcess(), "test@example.com", "testPass123"); assertNotNull(user); // check that user was created - assertEquals(1, dashboardSQLStorage.getAllDashboardUsers(new AppIdentifier(null, null)).length); + assertEquals(1, dashboardSQLStorage.getAllDashboardUsers(process.getAppForTesting().toAppIdentifier()).length); // delete dashboard user - assertTrue(dashboardSQLStorage.deleteDashboardUserWithUserId(new AppIdentifier(null, null), user.userId)); + assertTrue(dashboardSQLStorage.deleteDashboardUserWithUserId(process.getAppForTesting().toAppIdentifier(), user.userId)); // check that no users exist - assertEquals(0, dashboardSQLStorage.getAllDashboardUsers(new AppIdentifier(null, null)).length); + assertEquals(0, dashboardSQLStorage.getAllDashboardUsers(process.getAppForTesting().toAppIdentifier()).length); process.kill(); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STOPPED)); @@ -244,7 +247,7 @@ public void testTheCreateNewDashboardUserSession() throws Exception { // create a dashboard session for a user that does not exist Exception error = null; try { - dashboardSQLStorage.createNewDashboardUserSession(new AppIdentifier(null, null), "unknownUserId", + dashboardSQLStorage.createNewDashboardUserSession(process.getAppForTesting().toAppIdentifier(), "unknownUserId", "testSessionId", 0, 0); throw new Exception("Should never come here"); } catch (UserIdNotFoundException e) { @@ -256,11 +259,11 @@ public void testTheCreateNewDashboardUserSession() throws Exception { // create a user and create a session for the user DashboardUser user = Dashboard.signUpDashboardUser(process.getProcess(), "test@example.com", "password123"); - dashboardSQLStorage.createNewDashboardUserSession(new AppIdentifier(null, null), user.userId, + dashboardSQLStorage.createNewDashboardUserSession(process.getAppForTesting().toAppIdentifier(), user.userId, io.supertokens.utils.Utils.getUUID(), 0, 0); // check that the session was successfully created - DashboardSessionInfo[] sessionInfo = dashboardSQLStorage.getAllSessionsForUserId(new AppIdentifier(null, null), + DashboardSessionInfo[] sessionInfo = dashboardSQLStorage.getAllSessionsForUserId(process.getAppForTesting().toAppIdentifier(), user.userId); assertEquals(1, sessionInfo.length); assertEquals(user.userId, sessionInfo[0].userId); @@ -290,36 +293,36 @@ public void testCreatingMultipleSessionsForAUser() throws Exception { for (int i = 0; i < 5; i++) { String sessionId = io.supertokens.utils.Utils.getUUID(); sessionIds.add(sessionId); - dashboardSQLStorage.createNewDashboardUserSession(new AppIdentifier(null, null), user.userId, sessionId, 0, + dashboardSQLStorage.createNewDashboardUserSession(process.getAppForTesting().toAppIdentifier(), user.userId, sessionId, 0, 0); } // get all sessions for userId DashboardSessionInfo[] sessionInfoArray = dashboardSQLStorage.getAllSessionsForUserId( - new AppIdentifier(null, null), user.userId); + process.getAppForTesting().toAppIdentifier(), user.userId); assertEquals(5, sessionInfoArray.length); // test retrieving sessions for (int i = 0; i < 2; i++) { DashboardSessionInfo sessionInfo = dashboardSQLStorage.getSessionInfoWithSessionId( - new AppIdentifier(null, null), sessionIds.get(i)); + process.getAppForTesting().toAppIdentifier(), sessionIds.get(i)); assertNotNull(sessionInfo); assertEquals(user.userId, sessionInfo.userId); } // delete some user sessions - dashboardSQLStorage.revokeSessionWithSessionId(new AppIdentifier(null, null), sessionIds.get(0)); - dashboardSQLStorage.revokeSessionWithSessionId(new AppIdentifier(null, null), sessionIds.get(1)); + dashboardSQLStorage.revokeSessionWithSessionId(process.getAppForTesting().toAppIdentifier(), sessionIds.get(0)); + dashboardSQLStorage.revokeSessionWithSessionId(process.getAppForTesting().toAppIdentifier(), sessionIds.get(1)); // retrieve all sessions DashboardSessionInfo[] dashboardSessionInfo = dashboardSQLStorage.getAllSessionsForUserId( - new AppIdentifier(null, null), user.userId); + process.getAppForTesting().toAppIdentifier(), user.userId); assertEquals(3, dashboardSessionInfo.length); // check that two sessions were deleted for (int i = 0; i < 2; i++) { assertNull( - dashboardSQLStorage.getSessionInfoWithSessionId(new AppIdentifier(null, null), sessionIds.get(i))); + dashboardSQLStorage.getSessionInfoWithSessionId(process.getAppForTesting().toAppIdentifier(), sessionIds.get(i))); } process.kill(); @@ -347,7 +350,7 @@ public void testRevokeExpiredSessionsFunction() throws Exception { for (int i = 0; i < 3; i++) { String sessionId = io.supertokens.utils.Utils.getUUID(); sessionIds.add(sessionId); - dashboardSQLStorage.createNewDashboardUserSession(new AppIdentifier(null, null), user.userId, sessionId, + dashboardSQLStorage.createNewDashboardUserSession(process.getAppForTesting().toAppIdentifier(), user.userId, sessionId, System.currentTimeMillis(), System.currentTimeMillis() + 3000); } @@ -356,13 +359,13 @@ public void testRevokeExpiredSessionsFunction() throws Exception { for (int i = 0; i < 3; i++) { String sessionId = io.supertokens.utils.Utils.getUUID(); sessionIds.add(sessionId); - dashboardSQLStorage.createNewDashboardUserSession(new AppIdentifier(null, null), user.userId, sessionId, + dashboardSQLStorage.createNewDashboardUserSession(process.getAppForTesting().toAppIdentifier(), user.userId, sessionId, System.currentTimeMillis(), System.currentTimeMillis() + Dashboard.DASHBOARD_SESSION_DURATION); } // check that sessions were successfully created - assertEquals(6, dashboardSQLStorage.getAllSessionsForUserId(new AppIdentifier(null, null), user.userId).length); + assertEquals(6, dashboardSQLStorage.getAllSessionsForUserId(process.getAppForTesting().toAppIdentifier(), user.userId).length); // wait for 5 seconds so sessions expire try { @@ -375,14 +378,14 @@ public void testRevokeExpiredSessionsFunction() throws Exception { dashboardSQLStorage.revokeExpiredSessions(); // check that half the sessions were revoked - assertEquals(3, dashboardSQLStorage.getAllSessionsForUserId(new AppIdentifier(null, null), user.userId).length); + assertEquals(3, dashboardSQLStorage.getAllSessionsForUserId(process.getAppForTesting().toAppIdentifier(), user.userId).length); for (int i = 0; i < sessionIds.size(); i++) { if (i < 3) { - assertNull(dashboardSQLStorage.getSessionInfoWithSessionId(new AppIdentifier(null, null), + assertNull(dashboardSQLStorage.getSessionInfoWithSessionId(process.getAppForTesting().toAppIdentifier(), sessionIds.get(i))); } else { - assertNotNull(dashboardSQLStorage.getSessionInfoWithSessionId(new AppIdentifier(null, null), + assertNotNull(dashboardSQLStorage.getSessionInfoWithSessionId(process.getAppForTesting().toAppIdentifier(), sessionIds.get(i))); } } @@ -411,7 +414,7 @@ public void testUpdatingUsersEmail() throws Exception { dashboardSQLStorage.startTransaction(transaction -> { try { dashboardSQLStorage.updateDashboardUsersEmailWithUserId_Transaction( - new AppIdentifier(null, null), transaction, + process.getAppForTesting().toAppIdentifier(), transaction, "unknownUserId", "test@example.com"); return null; } catch (Exception e) { @@ -435,7 +438,7 @@ public void testUpdatingUsersEmail() throws Exception { try { dashboardSQLStorage.startTransaction(transaction -> { try { - dashboardSQLStorage.updateDashboardUsersEmailWithUserId_Transaction(new AppIdentifier(null, null), + dashboardSQLStorage.updateDashboardUsersEmailWithUserId_Transaction(process.getAppForTesting().toAppIdentifier(), transaction, user.userId, newEmail); return null; @@ -448,10 +451,10 @@ public void testUpdatingUsersEmail() throws Exception { } // check that the retrieving the user with the original email does not work - assertNull(dashboardSQLStorage.getDashboardUserByEmail(new AppIdentifier(null, null), user.email)); + assertNull(dashboardSQLStorage.getDashboardUserByEmail(process.getAppForTesting().toAppIdentifier(), user.email)); // check that retrieving the user with the new email works - DashboardUser updatedUser = dashboardSQLStorage.getDashboardUserByEmail(new AppIdentifier(null, null), + DashboardUser updatedUser = dashboardSQLStorage.getDashboardUserByEmail(process.getAppForTesting().toAppIdentifier(), newEmail); assertNotNull(updatedUser); @@ -459,12 +462,12 @@ public void testUpdatingUsersEmail() throws Exception { assertEquals(user.userId, updatedUser.userId); // check that no additional users have been created. - assertEquals(1, dashboardSQLStorage.getAllDashboardUsers(new AppIdentifier(null, null)).length); + assertEquals(1, dashboardSQLStorage.getAllDashboardUsers(process.getAppForTesting().toAppIdentifier()).length); // create another user DashboardUser user2 = new DashboardUser(io.supertokens.utils.Utils.getUUID(), "test2@example.com", "testpassword", System.currentTimeMillis()); - dashboardSQLStorage.createNewDashboardUser(new AppIdentifier(null, null), user2); + dashboardSQLStorage.createNewDashboardUser(process.getAppForTesting().toAppIdentifier(), user2); // try updating user2s email with the user1s email @@ -475,7 +478,7 @@ public void testUpdatingUsersEmail() throws Exception { dashboardSQLStorage.startTransaction(transaction -> { try { dashboardSQLStorage.updateDashboardUsersEmailWithUserId_Transaction( - new AppIdentifier(null, null), transaction, + process.getAppForTesting().toAppIdentifier(), transaction, user2.userId, newEmail); return null; } catch (Exception e) { diff --git a/src/test/java/io/supertokens/test/dashboard/DashboardTest.java b/src/test/java/io/supertokens/test/dashboard/DashboardTest.java index eeaa3b447..4daf67a0c 100644 --- a/src/test/java/io/supertokens/test/dashboard/DashboardTest.java +++ b/src/test/java/io/supertokens/test/dashboard/DashboardTest.java @@ -29,7 +29,6 @@ import io.supertokens.pluginInterface.dashboard.DashboardUser; import io.supertokens.pluginInterface.dashboard.exceptions.DuplicateEmailException; import io.supertokens.pluginInterface.dashboard.sqlStorage.DashboardSQLStorage; -import io.supertokens.pluginInterface.multitenancy.AppIdentifier; import io.supertokens.storageLayer.StorageLayer; import io.supertokens.test.TestingProcessManager; import io.supertokens.test.Utils; @@ -48,6 +47,9 @@ public class DashboardTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -175,7 +177,7 @@ public void testDashboardCronjob() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); CronTaskTest.getInstance(process.getProcess()).setIntervalInSeconds(DeleteExpiredDashboardSessions.RESOURCE_KEY, 1); process.startProcess(); @@ -197,7 +199,7 @@ public void testDashboardCronjob() throws Exception { // create a session with low expiry ((DashboardSQLStorage) StorageLayer.getStorage(process.getProcess())) - .createNewDashboardUserSession(new AppIdentifier(null, null), user.userId, sessionId, + .createNewDashboardUserSession(process.getAppForTesting().toAppIdentifier(), user.userId, sessionId, System.currentTimeMillis(), 0); // check that session exists @@ -268,7 +270,7 @@ public void testDashboardUsageStats() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -318,7 +320,7 @@ public void testDashboardUsageStats() throws Exception { } // enable the dashboard feature - FeatureFlag.getInstance(process.main).setLicenseKeyAndSyncFeatures(OPAQUE_KEY_WITH_DASHBOARD_FEATURE); + FeatureFlag.getInstance(process.getProcess()).setLicenseKeyAndSyncFeatures(OPAQUE_KEY_WITH_DASHBOARD_FEATURE); { JsonObject response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", diff --git a/src/test/java/io/supertokens/test/dashboard/apis/CreateDashboardUserAPITests.java b/src/test/java/io/supertokens/test/dashboard/apis/CreateDashboardUserAPITests.java index 3f2d30a51..db95ad49c 100644 --- a/src/test/java/io/supertokens/test/dashboard/apis/CreateDashboardUserAPITests.java +++ b/src/test/java/io/supertokens/test/dashboard/apis/CreateDashboardUserAPITests.java @@ -39,6 +39,9 @@ public class CreateDashboardUserAPITests { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -356,7 +359,7 @@ public void testCreatingAUserWithAWeakPassword() throws Exception { public void testCreatingAUserAfterCrossingTheFreeUserThreshold() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -372,6 +375,8 @@ public void testCreatingAUserAfterCrossingTheFreeUserThreshold() throws Exceptio } } + Thread.sleep(500); + // try creating another user when max number of free users is reached { String email = "newUser@example.com"; @@ -385,9 +390,9 @@ public void testCreatingAUserAfterCrossingTheFreeUserThreshold() throws Exceptio HttpRequestForTesting.sendJsonPOSTRequest(process.getProcess(), "", "http://localhost:3567/recipe/dashboard/user", requestBody, 5000, 1000, null, SemVer.v2_18.get(), "dashboard"); - assert StorageLayer.isInMemDb(process.main); + assert StorageLayer.isInMemDb(process.getProcess()); } catch (HttpResponseException e) { - assert !StorageLayer.isInMemDb(process.main); + assert !StorageLayer.isInMemDb(process.getProcess()); assertTrue(e.statusCode == 402 && e.getMessage().equals( "Http error. Status Code: 402. Message:" + diff --git a/src/test/java/io/supertokens/test/dashboard/apis/DeleteDashboardUserAPITests.java b/src/test/java/io/supertokens/test/dashboard/apis/DeleteDashboardUserAPITests.java index 9692512ac..486ef8e99 100644 --- a/src/test/java/io/supertokens/test/dashboard/apis/DeleteDashboardUserAPITests.java +++ b/src/test/java/io/supertokens/test/dashboard/apis/DeleteDashboardUserAPITests.java @@ -45,6 +45,9 @@ public class DeleteDashboardUserAPITests { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/dashboard/apis/DeleteDashboardUserSessionAPITest.java b/src/test/java/io/supertokens/test/dashboard/apis/DeleteDashboardUserSessionAPITest.java index c3b22df73..f68ec213f 100644 --- a/src/test/java/io/supertokens/test/dashboard/apis/DeleteDashboardUserSessionAPITest.java +++ b/src/test/java/io/supertokens/test/dashboard/apis/DeleteDashboardUserSessionAPITest.java @@ -46,6 +46,9 @@ public class DeleteDashboardUserSessionAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/dashboard/apis/GetDashboardUserSessionsAPITest.java b/src/test/java/io/supertokens/test/dashboard/apis/GetDashboardUserSessionsAPITest.java index 1660a7a16..caff8b635 100644 --- a/src/test/java/io/supertokens/test/dashboard/apis/GetDashboardUserSessionsAPITest.java +++ b/src/test/java/io/supertokens/test/dashboard/apis/GetDashboardUserSessionsAPITest.java @@ -47,6 +47,9 @@ public class GetDashboardUserSessionsAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/dashboard/apis/GetDashboardUsersAPITests.java b/src/test/java/io/supertokens/test/dashboard/apis/GetDashboardUsersAPITests.java index bc69975df..10c93edc9 100644 --- a/src/test/java/io/supertokens/test/dashboard/apis/GetDashboardUsersAPITests.java +++ b/src/test/java/io/supertokens/test/dashboard/apis/GetDashboardUsersAPITests.java @@ -49,6 +49,9 @@ public class GetDashboardUsersAPITests { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/dashboard/apis/SignInAPITest.java b/src/test/java/io/supertokens/test/dashboard/apis/SignInAPITest.java index 991544e17..311e324a0 100644 --- a/src/test/java/io/supertokens/test/dashboard/apis/SignInAPITest.java +++ b/src/test/java/io/supertokens/test/dashboard/apis/SignInAPITest.java @@ -41,6 +41,9 @@ public class SignInAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -91,7 +94,7 @@ public void testSigningInAUserAndVerifyingTheirSession() throws Exception { public void testSigningInASuspendedUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -102,9 +105,11 @@ public void testSigningInASuspendedUser() throws Exception { { for (int i = 0; i < Dashboard.MAX_NUMBER_OF_FREE_DASHBOARD_USERS; i++) { Dashboard.signUpDashboardUser(process.getProcess(), "test" + i + "@example.com", "password123"); + Thread.sleep(10); } - } + + Thread.sleep(500); // create a user above the free limit String email = "suspended@example.com"; String password = "testPass123"; @@ -113,7 +118,7 @@ public void testSigningInASuspendedUser() throws Exception { PasswordHashing.getInstance(process.getProcess()).createHashWithSalt(password), System.currentTimeMillis()); ((DashboardSQLStorage) StorageLayer.getStorage(process.getProcess())) - .createNewDashboardUser(new AppIdentifier(null, null), user); + .createNewDashboardUser(process.getAppForTesting().toAppIdentifier(), user); // try signing in with the valid user { diff --git a/src/test/java/io/supertokens/test/dashboard/apis/UpdateUserAPITest.java b/src/test/java/io/supertokens/test/dashboard/apis/UpdateUserAPITest.java index c9aaa29a5..2980c8b0a 100644 --- a/src/test/java/io/supertokens/test/dashboard/apis/UpdateUserAPITest.java +++ b/src/test/java/io/supertokens/test/dashboard/apis/UpdateUserAPITest.java @@ -45,6 +45,9 @@ public class UpdateUserAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -183,7 +186,7 @@ public void testSuccessfullyUpdatingUserDataWithUserId() throws Exception { Dashboard.signUpDashboardUser(process.getProcess(), email, password); DashboardUser user = ((DashboardSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getDashboardUserByEmail(new AppIdentifier(null, null), email); + .getDashboardUserByEmail(process.getAppForTesting().toAppIdentifier(), email); assertNotNull(user); // update the user's email and password diff --git a/src/test/java/io/supertokens/test/dashboard/apis/VerifySessionAPITest.java b/src/test/java/io/supertokens/test/dashboard/apis/VerifySessionAPITest.java index a669bbf72..86eb0c8c6 100644 --- a/src/test/java/io/supertokens/test/dashboard/apis/VerifySessionAPITest.java +++ b/src/test/java/io/supertokens/test/dashboard/apis/VerifySessionAPITest.java @@ -40,6 +40,9 @@ public class VerifySessionAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/emailpassword/DeleteExpiredPasswordResetTokensCronjobTest.java b/src/test/java/io/supertokens/test/emailpassword/DeleteExpiredPasswordResetTokensCronjobTest.java index a98e51f68..7e9f64c42 100644 --- a/src/test/java/io/supertokens/test/emailpassword/DeleteExpiredPasswordResetTokensCronjobTest.java +++ b/src/test/java/io/supertokens/test/emailpassword/DeleteExpiredPasswordResetTokensCronjobTest.java @@ -24,7 +24,6 @@ import io.supertokens.pluginInterface.authRecipe.AuthRecipeUserInfo; import io.supertokens.pluginInterface.emailpassword.PasswordResetTokenInfo; import io.supertokens.pluginInterface.emailpassword.sqlStorage.EmailPasswordSQLStorage; -import io.supertokens.pluginInterface.multitenancy.AppIdentifier; import io.supertokens.storageLayer.StorageLayer; import io.supertokens.test.TestingProcessManager; import io.supertokens.test.Utils; @@ -40,6 +39,9 @@ public class DeleteExpiredPasswordResetTokensCronjobTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -54,10 +56,10 @@ public void beforeEach() { public void checkingCronJob() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + Utils.setValueInConfig("password_reset_token_lifetime", "4000"); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); CronTaskTest.getInstance(process.getProcess()) .setIntervalInSeconds(DeleteExpiredPasswordResetTokens.RESOURCE_KEY, 1); - Utils.setValueInConfig("password_reset_token_lifetime", "4000"); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -79,13 +81,13 @@ public void checkingCronJob() throws Exception { user.getSupertokensUserId()); assert (((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), + .getAllPasswordResetTokenInfoForUser(process.getAppForTesting().toAppIdentifier(), user.getSupertokensUserId()).length == 4); Thread.sleep(3500); PasswordResetTokenInfo[] tokens = ((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), user.getSupertokensUserId()); + .getAllPasswordResetTokenInfoForUser(process.getAppForTesting().toAppIdentifier(), user.getSupertokensUserId()); assert (tokens.length == 2); @@ -98,5 +100,4 @@ public void checkingCronJob() throws Exception { process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } - } diff --git a/src/test/java/io/supertokens/test/emailpassword/EmailPasswordTest.java b/src/test/java/io/supertokens/test/emailpassword/EmailPasswordTest.java index 232d03ce2..854493d50 100644 --- a/src/test/java/io/supertokens/test/emailpassword/EmailPasswordTest.java +++ b/src/test/java/io/supertokens/test/emailpassword/EmailPasswordTest.java @@ -64,6 +64,9 @@ public class EmailPasswordTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -181,7 +184,7 @@ public void testThatAfterSignUpThePasswordIsHashedAndStoredInTheDatabase() throw AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "random@gmail.com", "validPass123"); AuthRecipeUserInfo userInfo = ((AuthRecipeStorage) StorageLayer.getStorage(process.getProcess())) - .listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), user.loginMethods[0].email)[0]; + .listPrimaryUsersByEmail(process.getAppForTesting(), user.loginMethods[0].email)[0]; assertNotEquals(userInfo.loginMethods[0].passwordHash, "validPass123"); assertTrue(PasswordHashing.getInstance(process.getProcess()).verifyPasswordWithHash("validPass123", userInfo.loginMethods[0].passwordHash)); @@ -210,7 +213,7 @@ public void testThatAfterResetPasswordGenerateTokenTheTokenIsHashedInTheDatabase user.getSupertokensUserId()); PasswordResetTokenInfo resetTokenInfo = ((EmailPasswordSQLStorage) StorageLayer.getStorage( process.getProcess())) - .getPasswordResetTokenInfo(new AppIdentifier(null, null), + .getPasswordResetTokenInfo(process.getAppForTesting().toAppIdentifier(), io.supertokens.utils.Utils.hashSHA256(resetToken)); assertNotEquals(resetToken, resetTokenInfo.token); @@ -242,7 +245,7 @@ public void testThatAfterResetPasswordIsCompletedThePasswordIsHashedInTheDatabas EmailPassword.resetPassword(process.getProcess(), resetToken, "newValidPass123"); AuthRecipeUserInfo userInfo = ((AuthRecipeStorage) StorageLayer.getStorage(process.getProcess())) - .listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), user.loginMethods[0].email)[0]; + .listPrimaryUsersByEmail(process.getAppForTesting(), user.loginMethods[0].email)[0]; assertNotEquals(userInfo.loginMethods[0].passwordHash, "newValidPass123"); assertTrue(PasswordHashing.getInstance(process.getProcess()).verifyPasswordWithHash("newValidPass123", @@ -256,9 +259,8 @@ public void testThatAfterResetPasswordIsCompletedThePasswordIsHashedInTheDatabas public void passwordResetTokenExpiredCheck() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); Utils.setValueInConfig("password_reset_token_lifetime", "10"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -271,7 +273,7 @@ public void passwordResetTokenExpiredCheck() throws Exception { user.getSupertokensUserId()); assert (((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), + .getAllPasswordResetTokenInfoForUser(process.getAppForTesting().toAppIdentifier(), user.getSupertokensUserId()).length == 1); Thread.sleep(20); @@ -284,7 +286,7 @@ public void passwordResetTokenExpiredCheck() throws Exception { } assert (((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), + .getAllPasswordResetTokenInfoForUser(process.getAppForTesting().toAppIdentifier(), user.getSupertokensUserId()).length == 0); process.kill(); @@ -310,14 +312,14 @@ public void multiplePasswordResetTokensPerUserAndThenVerifyWithSignin() throws E EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), user.getSupertokensUserId()); PasswordResetTokenInfo[] tokens = ((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), user.getSupertokensUserId()); + .getAllPasswordResetTokenInfoForUser(process.getAppForTesting().toAppIdentifier(), user.getSupertokensUserId()); assert (tokens.length == 3); EmailPassword.resetPassword(process.getProcess(), tok, "newPassword"); tokens = ((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), user.getSupertokensUserId()); + .getAllPasswordResetTokenInfoForUser(process.getAppForTesting().toAppIdentifier(), user.getSupertokensUserId()); assert (tokens.length == 0); try { @@ -346,7 +348,7 @@ public void zeroPasswordTokens() throws Exception { return; } PasswordResetTokenInfo[] tokens = ((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), + .getAllPasswordResetTokenInfoForUser(process.getAppForTesting().toAppIdentifier(), "8ed86166-bfd8-4234-9dfe-abca9606dbd5"); assert (tokens.length == 0); @@ -392,14 +394,14 @@ public void clashingPassowordResetToken() throws Exception { AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test1@example.com", "password"); ((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .addPasswordResetToken(new AppIdentifier(null, null), new PasswordResetTokenInfo( + .addPasswordResetToken(process.getAppForTesting().toAppIdentifier(), new PasswordResetTokenInfo( user.getSupertokensUserId(), "token", System.currentTimeMillis() + Config.getConfig(process.getProcess()).getPasswordResetTokenLifetime(), "email")); try { ((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .addPasswordResetToken(new AppIdentifier(null, null), + .addPasswordResetToken(process.getAppForTesting().toAppIdentifier(), new PasswordResetTokenInfo(user.getSupertokensUserId(), "token", System.currentTimeMillis() + Config.getConfig(process.getProcess()).getPasswordResetTokenLifetime(), "email")); assert (false); @@ -446,13 +448,13 @@ public void clashingUserIdDuringSignUp() throws Exception { } ((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .signUp(new TenantIdentifier(null, null, null), + .signUp(process.getAppForTesting(), "8ed86166-bfd8-4234-9dfe-abca9606dbd5", "test@example.com", "password", System.currentTimeMillis()); try { ((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .signUp(new TenantIdentifier(null, null, null), + .signUp(process.getAppForTesting(), "8ed86166-bfd8-4234-9dfe-abca9606dbd5", "test1@example.com", "password", System.currentTimeMillis()); assert (false); @@ -499,13 +501,13 @@ public void clashingEmailAndUserIdDuringSignUp() throws Exception { } ((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .signUp(new TenantIdentifier(null, null, null), + .signUp(process.getAppForTesting(), "8ed86166-bfd8-4234-9dfe-abca9606dbd5", "test@example.com", "password", System.currentTimeMillis()); try { ((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .signUp(new TenantIdentifier(null, null, null), + .signUp(process.getAppForTesting(), "8ed86166-bfd8-4234-9dfe-abca9606dbd5", "test@example.com", "password", System.currentTimeMillis()); assert (false); @@ -576,7 +578,7 @@ public void changePasswordResetLifetimeTest() throws Exception { { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -594,7 +596,7 @@ public void changePasswordResetLifetimeTest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -612,7 +614,7 @@ public void changePasswordResetLifetimeTest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); assertEquals(e.exception.getCause().getMessage(), "'password_reset_token_lifetime' must be >= 0"); @@ -626,11 +628,10 @@ public void changePasswordResetLifetimeTest() throws Exception { public void testGeneratingResetPasswordTokenForNonEPUserNonPrimary() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -642,18 +643,18 @@ public void testGeneratingResetPasswordTokenForNonEPUserNonPrimary() throws Exce "test@example.com"); try { - EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.main, + EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), signInUpResponse.user.getSupertokensUserId()); assert false; } catch (UnknownUserIdException ignored) { } - String token = EmailPassword.generatePasswordResetToken(process.main, + String token = EmailPassword.generatePasswordResetToken(process.getProcess(), signInUpResponse.user.getSupertokensUserId(), "test@example.com"); - EmailPassword.ConsumeResetPasswordTokenResult res = EmailPassword.consumeResetPasswordToken(process.main, + EmailPassword.ConsumeResetPasswordTokenResult res = EmailPassword.consumeResetPasswordToken(process.getProcess(), token); assert (res.email.equals("test@example.com")); assert (res.userId.equals(signInUpResponse.user.getSupertokensUserId())); @@ -666,11 +667,10 @@ public void testGeneratingResetPasswordTokenForNonEPUserNonPrimary() throws Exce public void testGeneratingResetPasswordTokenForNonEPUserPrimary() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -681,13 +681,13 @@ public void testGeneratingResetPasswordTokenForNonEPUserPrimary() throws Excepti "user-google", "test@example.com"); - AuthRecipe.createPrimaryUser(process.main, signInUpResponse.user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), signInUpResponse.user.getSupertokensUserId()); - String token = EmailPassword.generatePasswordResetToken(process.main, + String token = EmailPassword.generatePasswordResetToken(process.getProcess(), signInUpResponse.user.getSupertokensUserId(), "test@example.com"); - EmailPassword.ConsumeResetPasswordTokenResult res = EmailPassword.consumeResetPasswordToken(process.main, + EmailPassword.ConsumeResetPasswordTokenResult res = EmailPassword.consumeResetPasswordToken(process.getProcess(), token); assert (res.email.equals("test@example.com")); assert (res.userId.equals(signInUpResponse.user.getSupertokensUserId())); @@ -700,11 +700,10 @@ public void testGeneratingResetPasswordTokenForNonEPUserPrimary() throws Excepti public void testGeneratingResetPasswordTokenForNonEPUserPrimaryButDeletedWithOtherLinked() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -719,16 +718,16 @@ public void testGeneratingResetPasswordTokenForNonEPUserPrimaryButDeletedWithOth "user-fb", "test2@example.com"); - AuthRecipe.createPrimaryUser(process.main, signInUpResponse.user.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, signInUpResponse2.user.getSupertokensUserId(), + AuthRecipe.createPrimaryUser(process.getProcess(), signInUpResponse.user.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), signInUpResponse2.user.getSupertokensUserId(), signInUpResponse.user.getSupertokensUserId()); - assert (AuthRecipe.unlinkAccounts(process.main, signInUpResponse.user.getSupertokensUserId())); + assert (AuthRecipe.unlinkAccounts(process.getProcess(), signInUpResponse.user.getSupertokensUserId())); - String token = EmailPassword.generatePasswordResetToken(process.main, + String token = EmailPassword.generatePasswordResetToken(process.getProcess(), signInUpResponse.user.getSupertokensUserId(), "test@example.com"); - EmailPassword.ConsumeResetPasswordTokenResult res = EmailPassword.consumeResetPasswordToken(process.main, + EmailPassword.ConsumeResetPasswordTokenResult res = EmailPassword.consumeResetPasswordToken(process.getProcess(), token); assert (res.email.equals("test@example.com")); assert (res.userId.equals(signInUpResponse.user.getSupertokensUserId())); @@ -741,11 +740,10 @@ public void testGeneratingResetPasswordTokenForNonEPUserPrimaryButDeletedWithOth public void deletionOfTpUserDeletesPasswordResetToken() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -757,18 +755,18 @@ public void deletionOfTpUserDeletesPasswordResetToken() throws Exception { "test@example.com"); - String token = EmailPassword.generatePasswordResetToken(process.main, + String token = EmailPassword.generatePasswordResetToken(process.getProcess(), signInUpResponse.user.getSupertokensUserId(), "test@example.com"); token = io.supertokens.utils.Utils.hashSHA256(token); - assertNotNull(((EmailPasswordSQLStorage) StorageLayer.getStorage(process.main)).getPasswordResetTokenInfo( - new AppIdentifier(null, null), token)); + assertNotNull(((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())).getPasswordResetTokenInfo( + process.getAppForTesting().toAppIdentifier(), token)); - AuthRecipe.deleteUser(process.main, signInUpResponse.user.getSupertokensUserId()); + AuthRecipe.deleteUser(process.getProcess(), signInUpResponse.user.getSupertokensUserId()); - assertNull(((EmailPasswordSQLStorage) StorageLayer.getStorage(process.main)).getPasswordResetTokenInfo( - new AppIdentifier(null, null), token)); + assertNull(((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())).getPasswordResetTokenInfo( + process.getAppForTesting().toAppIdentifier(), token)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -778,9 +776,8 @@ public void deletionOfTpUserDeletesPasswordResetToken() throws Exception { public void passwordResetTokenExpiredCheckWithConsumeCode() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); Utils.setValueInConfig("password_reset_token_lifetime", "10"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -793,7 +790,7 @@ public void passwordResetTokenExpiredCheckWithConsumeCode() throws Exception { user.getSupertokensUserId()); assert (((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), + .getAllPasswordResetTokenInfoForUser(process.getAppForTesting().toAppIdentifier(), user.getSupertokensUserId()).length == 1); Thread.sleep(20); @@ -806,7 +803,7 @@ public void passwordResetTokenExpiredCheckWithConsumeCode() throws Exception { } assert (((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), + .getAllPasswordResetTokenInfoForUser(process.getAppForTesting().toAppIdentifier(), user.getSupertokensUserId()).length == 0); process.kill(); @@ -832,14 +829,14 @@ public void multiplePasswordResetTokensPerUserAndThenVerifyWithSigninWithConsume EmailPassword.generatePasswordResetTokenBeforeCdi4_0(process.getProcess(), user.getSupertokensUserId()); PasswordResetTokenInfo[] tokens = ((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), user.getSupertokensUserId()); + .getAllPasswordResetTokenInfoForUser(process.getAppForTesting().toAppIdentifier(), user.getSupertokensUserId()); assert (tokens.length == 3); EmailPassword.consumeResetPasswordToken(process.getProcess(), tok); tokens = ((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), user.getSupertokensUserId()); + .getAllPasswordResetTokenInfoForUser(process.getAppForTesting().toAppIdentifier(), user.getSupertokensUserId()); assert (tokens.length == 0); process.kill(); @@ -872,8 +869,7 @@ public void wrongPasswordResetTokenWithConsumeCode() throws Exception { public void consumeCodeCorrectlySetsTheUserEmailForOlderTokens() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -886,10 +882,10 @@ public void consumeCodeCorrectlySetsTheUserEmailForOlderTokens() throws Exceptio user.getSupertokensUserId()); assert (((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), + .getAllPasswordResetTokenInfoForUser(process.getAppForTesting().toAppIdentifier(), user.getSupertokensUserId()).length == 1); assert (((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), + .getAllPasswordResetTokenInfoForUser(process.getAppForTesting().toAppIdentifier(), user.getSupertokensUserId())[0].email == null); EmailPassword.ConsumeResetPasswordTokenResult result = EmailPassword.consumeResetPasswordToken( @@ -898,7 +894,7 @@ public void consumeCodeCorrectlySetsTheUserEmailForOlderTokens() throws Exceptio assert (result.userId.equals(user.getSupertokensUserId())); assert (((EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllPasswordResetTokenInfoForUser(new AppIdentifier(null, null), + .getAllPasswordResetTokenInfoForUser(process.getAppForTesting().toAppIdentifier(), user.getSupertokensUserId()).length == 0); process.kill(); @@ -909,11 +905,10 @@ public void consumeCodeCorrectlySetsTheUserEmailForOlderTokens() throws Exceptio @Test public void updateEmailFailsIfEmailUsedByOtherPrimaryUserInSameTenant() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -921,13 +916,13 @@ public void updateEmailFailsIfEmailUsedByOtherPrimaryUserInSameTenant() throws E } AuthRecipeUserInfo user0 = EmailPassword.signUp(process.getProcess(), "someemail1@gmail.com", "somePass"); - AuthRecipe.createPrimaryUser(process.main, user0.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user0.getSupertokensUserId()); AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "someemail@gmail.com", "somePass"); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); try { - EmailPassword.updateUsersEmailOrPassword(process.main, user.getSupertokensUserId(), "someemail1@gmail.com", + EmailPassword.updateUsersEmailOrPassword(process.getProcess(), user.getSupertokensUserId(), "someemail1@gmail.com", null); assert (false); } catch (EmailChangeNotAllowedException ignored) { @@ -942,37 +937,38 @@ public void updateEmailFailsIfEmailUsedByOtherPrimaryUserInSameTenant() throws E public void updateEmailSucceedsIfEmailUsedByOtherPrimaryUserInDifferentTenantWhichThisUserIsNotAPartOf() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - Multitenancy.addNewOrUpdateAppOrTenant(process.main, new TenantIdentifier(null, null, null), - new TenantConfig(new TenantIdentifier(null, null, "t1"), new EmailPasswordConfig(true), + Multitenancy.addNewOrUpdateAppOrTenant(process.getProcess(), process.getAppForTesting(), + new TenantConfig(new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"), new EmailPasswordConfig(true), new ThirdPartyConfig(true, new ThirdPartyConfig.Provider[0]), new PasswordlessConfig(true), null, null, new JsonObject())); - Storage storage = (StorageLayer.getStorage(process.main)); + Storage storage = (StorageLayer.getStorage(process.getProcess())); AuthRecipeUserInfo user0 = EmailPassword.signUp( - new TenantIdentifier(null, null, "t1"), storage, process.getProcess(), + new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"), storage, process.getProcess(), "someemail1@gmail.com", "pass1234"); - AuthRecipe.createPrimaryUser(process.main, user0.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user0.getSupertokensUserId()); AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "someemail@gmail.com", "somePass"); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); - EmailPassword.updateUsersEmailOrPassword(process.main, user.getSupertokensUserId(), "someemail1@gmail.com", + EmailPassword.updateUsersEmailOrPassword(process.getProcess(), user.getSupertokensUserId(), "someemail1@gmail.com", null); + Multitenancy.deleteTenant(new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"), process.getProcess()); + process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } @@ -981,45 +977,46 @@ public void updateEmailSucceedsIfEmailUsedByOtherPrimaryUserInDifferentTenantWhi public void updateEmailFailsIfEmailUsedByOtherPrimaryUserInDifferentTenant() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - Multitenancy.addNewOrUpdateAppOrTenant(process.main, new TenantIdentifier(null, null, null), - new TenantConfig(new TenantIdentifier(null, null, "t1"), new EmailPasswordConfig(true), + Multitenancy.addNewOrUpdateAppOrTenant(process.getProcess(), process.getAppForTesting(), + new TenantConfig(new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"), new EmailPasswordConfig(true), new ThirdPartyConfig(true, new ThirdPartyConfig.Provider[0]), new PasswordlessConfig(true), null, null, new JsonObject())); - Storage storage = (StorageLayer.getStorage(process.main)); + Storage storage = (StorageLayer.getStorage(process.getProcess())); AuthRecipeUserInfo user0 = EmailPassword.signUp( - new TenantIdentifier(null, null, "t1"), storage, process.getProcess(), + new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"), storage, process.getProcess(), "someemail1@gmail.com", "pass1234"); - AuthRecipe.createPrimaryUser(process.main, user0.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user0.getSupertokensUserId()); AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "someemail@gmail.com", "somePass"); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); - Multitenancy.addUserIdToTenant(process.main, - new TenantIdentifier(null, null, "t1"), storage, user.getSupertokensUserId()); + Multitenancy.addUserIdToTenant(process.getProcess(), + new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"), storage, user.getSupertokensUserId()); try { - EmailPassword.updateUsersEmailOrPassword(process.main, user.getSupertokensUserId(), "someemail1@gmail.com", + EmailPassword.updateUsersEmailOrPassword(process.getProcess(), user.getSupertokensUserId(), "someemail1@gmail.com", null); assert (false); } catch (EmailChangeNotAllowedException ignored) { } + Multitenancy.deleteTenant(new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"), process.getProcess()); + process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } diff --git a/src/test/java/io/supertokens/test/emailpassword/MultitenantEmailPasswordTest.java b/src/test/java/io/supertokens/test/emailpassword/MultitenantEmailPasswordTest.java index 88ca1efd3..c43324885 100644 --- a/src/test/java/io/supertokens/test/emailpassword/MultitenantEmailPasswordTest.java +++ b/src/test/java/io/supertokens/test/emailpassword/MultitenantEmailPasswordTest.java @@ -71,7 +71,7 @@ private void createTenants(TestingProcessManager.TestingProcess process) { // tenant 1 JsonObject config = new JsonObject(); - TenantIdentifier tenantIdentifier = new TenantIdentifier(null, "a1", null); + TenantIdentifier tenantIdentifier = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", null); StorageLayer.getStorage(new TenantIdentifier(null, null, null), process.getProcess()) .modifyConfigToAddANewUserPoolForTesting(config, 1); @@ -92,14 +92,14 @@ private void createTenants(TestingProcessManager.TestingProcess process) { // tenant 2 JsonObject config = new JsonObject(); - TenantIdentifier tenantIdentifier = new TenantIdentifier(null, "a1", "t1"); + TenantIdentifier tenantIdentifier = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", "t1"); StorageLayer.getStorage(new TenantIdentifier(null, null, null), process.getProcess()) .modifyConfigToAddANewUserPoolForTesting(config, 2); Multitenancy.addNewOrUpdateAppOrTenant( process.getProcess(), - new TenantIdentifier(null, "a1", null), + new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", null), new TenantConfig( tenantIdentifier, new EmailPasswordConfig(true), @@ -113,14 +113,14 @@ private void createTenants(TestingProcessManager.TestingProcess process) { // tenant 3 JsonObject config = new JsonObject(); - TenantIdentifier tenantIdentifier = new TenantIdentifier(null, "a1", "t2"); + TenantIdentifier tenantIdentifier = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", "t2"); StorageLayer.getStorage(new TenantIdentifier(null, null, null), process.getProcess()) .modifyConfigToAddANewUserPoolForTesting(config, 2); Multitenancy.addNewOrUpdateAppOrTenant( process.getProcess(), - new TenantIdentifier(null, "a1", null), + new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", null), new TenantConfig( tenantIdentifier, new EmailPasswordConfig(true), @@ -153,11 +153,11 @@ public void testSignUpAndLoginInDifferentTenants() createTenants(process); - TenantIdentifier t1 = new TenantIdentifier(null, "a1", null); + TenantIdentifier t1 = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", null); Storage t1storage = (StorageLayer.getStorage(t1, process.getProcess())); - TenantIdentifier t2 = new TenantIdentifier(null, "a1", "t1"); + TenantIdentifier t2 = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", "t1"); Storage t2storage = (StorageLayer.getStorage(t2, process.getProcess())); - TenantIdentifier t3 = new TenantIdentifier(null, "a1", "t2"); + TenantIdentifier t3 = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", "t2"); Storage t3storage = (StorageLayer.getStorage(t3, process.getProcess())); { @@ -196,7 +196,6 @@ public void testSameEmailWithDifferentPasswordsOnDifferentTenantsWorksCorrectly( TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -205,11 +204,11 @@ public void testSameEmailWithDifferentPasswordsOnDifferentTenantsWorksCorrectly( createTenants(process); - TenantIdentifier t1 = new TenantIdentifier(null, "a1", null); + TenantIdentifier t1 = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", null); Storage t1storage = (StorageLayer.getStorage(t1, process.getProcess())); - TenantIdentifier t2 = new TenantIdentifier(null, "a1", "t1"); + TenantIdentifier t2 = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", "t1"); Storage t2storage = (StorageLayer.getStorage(t2, process.getProcess())); - TenantIdentifier t3 = new TenantIdentifier(null, "a1", "t2"); + TenantIdentifier t3 = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", "t2"); Storage t3storage = (StorageLayer.getStorage(t3, process.getProcess())); @@ -259,11 +258,11 @@ public void testGetUserUsingIdReturnsCorrectUser() createTenants(process); - TenantIdentifier t1 = new TenantIdentifier(null, "a1", null); + TenantIdentifier t1 = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", null); Storage t1storage = (StorageLayer.getStorage(t1, process.getProcess())); - TenantIdentifier t2 = new TenantIdentifier(null, "a1", "t1"); + TenantIdentifier t2 = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", "t1"); Storage t2storage = (StorageLayer.getStorage(t2, process.getProcess())); - TenantIdentifier t3 = new TenantIdentifier(null, "a1", "t2"); + TenantIdentifier t3 = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", "t2"); Storage t3storage = (StorageLayer.getStorage(t3, process.getProcess())); AuthRecipeUserInfo user1 = EmailPassword.signUp(t1, t1storage, process.getProcess(), "user1@example.com", @@ -273,13 +272,13 @@ public void testGetUserUsingIdReturnsCorrectUser() AuthRecipeUserInfo user3 = EmailPassword.signUp(t3, t3storage, process.getProcess(), "user3@example.com", "password3"); - Storage[] storages = StorageLayer.getStoragesForApp(process.getProcess(), new AppIdentifier(null, "a1")); + Storage[] storages = StorageLayer.getStoragesForApp(process.getProcess(), new AppIdentifier(null, process.getAppForTesting().getAppId() + "a1")); { AuthRecipeUserInfo userInfo = EmailPassword.getUserUsingId( - new AppIdentifier(null, "a1"), + new AppIdentifier(null, process.getAppForTesting().getAppId() + "a1"), StorageLayer.findStorageAndUserIdMappingForUser( - new AppIdentifier(null, "a1"), storages, + new AppIdentifier(null, process.getAppForTesting().getAppId() + "a1"), storages, user1.getSupertokensUserId(), UserIdType.SUPERTOKENS).storage, user1.getSupertokensUserId()); assertEquals(user1, userInfo); @@ -287,9 +286,9 @@ public void testGetUserUsingIdReturnsCorrectUser() { AuthRecipeUserInfo userInfo = EmailPassword.getUserUsingId( - new AppIdentifier(null, "a1"), + new AppIdentifier(null, process.getAppForTesting().getAppId() + "a1"), StorageLayer.findStorageAndUserIdMappingForUser( - new AppIdentifier(null, "a1"), storages, + new AppIdentifier(null, process.getAppForTesting().getAppId() + "a1"), storages, user2.getSupertokensUserId(), UserIdType.SUPERTOKENS).storage, user2.getSupertokensUserId()); assertEquals(user2, userInfo); @@ -297,9 +296,9 @@ public void testGetUserUsingIdReturnsCorrectUser() { AuthRecipeUserInfo userInfo = EmailPassword.getUserUsingId( - new AppIdentifier(null, "a1"), + new AppIdentifier(null, process.getAppForTesting().getAppId() + "a1"), StorageLayer.findStorageAndUserIdMappingForUser( - new AppIdentifier(null, "a1"), storages, + new AppIdentifier(null, process.getAppForTesting().getAppId() + "a1"), storages, user3.getSupertokensUserId(), UserIdType.SUPERTOKENS).storage, user3.getSupertokensUserId()); assertEquals(user3, userInfo); @@ -328,11 +327,11 @@ public void testGetUserUsingEmailReturnsTheUserFromTheSpecificTenant() createTenants(process); - TenantIdentifier t1 = new TenantIdentifier(null, "a1", null); + TenantIdentifier t1 = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", null); Storage t1storage = (StorageLayer.getStorage(t1, process.getProcess())); - TenantIdentifier t2 = new TenantIdentifier(null, "a1", "t1"); + TenantIdentifier t2 = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", "t1"); Storage t2storage = (StorageLayer.getStorage(t2, process.getProcess())); - TenantIdentifier t3 = new TenantIdentifier(null, "a1", "t2"); + TenantIdentifier t3 = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", "t2"); Storage t3storage = (StorageLayer.getStorage(t3, process.getProcess())); AuthRecipeUserInfo user1 = EmailPassword.signUp(t1, t1storage, process.getProcess(), "user@example.com", @@ -370,10 +369,9 @@ public void testUpdatePasswordWorksCorrectlyAcrossAllTenants() EmailChangeNotAllowedException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -382,11 +380,11 @@ public void testUpdatePasswordWorksCorrectlyAcrossAllTenants() createTenants(process); - TenantIdentifier t1 = new TenantIdentifier(null, "a1", null); + TenantIdentifier t1 = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", null); Storage t1storage = (StorageLayer.getStorage(t1, process.getProcess())); - TenantIdentifier t2 = new TenantIdentifier(null, "a1", "t1"); + TenantIdentifier t2 = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", "t1"); Storage t2storage = (StorageLayer.getStorage(t2, process.getProcess())); - TenantIdentifier t3 = new TenantIdentifier(null, "a1", "t2"); + TenantIdentifier t3 = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", "t2"); Storage t3storage = (StorageLayer.getStorage(t3, process.getProcess())); AuthRecipeUserInfo user1 = EmailPassword.signUp(t1, t1storage, process.getProcess(), "user@example.com", @@ -396,26 +394,26 @@ public void testUpdatePasswordWorksCorrectlyAcrossAllTenants() AuthRecipeUserInfo user3 = EmailPassword.signUp(t3, t3storage, process.getProcess(), "user@example.com", "password3"); - Storage[] storages = StorageLayer.getStoragesForApp(process.getProcess(), new AppIdentifier(null, "a1")); + Storage[] storages = StorageLayer.getStoragesForApp(process.getProcess(), new AppIdentifier(null, process.getAppForTesting().getAppId() + "a1")); EmailPassword.updateUsersEmailOrPassword( - new AppIdentifier(null, "a1"), + new AppIdentifier(null, process.getAppForTesting().getAppId() + "a1"), StorageLayer.findStorageAndUserIdMappingForUser( - new AppIdentifier(null, "a1"), storages, + new AppIdentifier(null, process.getAppForTesting().getAppId() + "a1"), storages, user1.getSupertokensUserId(), UserIdType.SUPERTOKENS).storage, process.getProcess(), user1.getSupertokensUserId(), null, "newpassword1"); EmailPassword.updateUsersEmailOrPassword( - new AppIdentifier(null, "a1"), + new AppIdentifier(null, process.getAppForTesting().getAppId() + "a1"), StorageLayer.findStorageAndUserIdMappingForUser( - new AppIdentifier(null, "a1"), storages, + new AppIdentifier(null, process.getAppForTesting().getAppId() + "a1"), storages, user2.getSupertokensUserId(), UserIdType.SUPERTOKENS).storage, process.getProcess(), user2.getSupertokensUserId(), null, "newpassword2"); EmailPassword.updateUsersEmailOrPassword( - new AppIdentifier(null, "a1"), + new AppIdentifier(null, process.getAppForTesting().getAppId() + "a1"), StorageLayer.findStorageAndUserIdMappingForUser( - new AppIdentifier(null, "a1"), storages, + new AppIdentifier(null, process.getAppForTesting().getAppId() + "a1"), storages, user3.getSupertokensUserId(), UserIdType.SUPERTOKENS).storage, process.getProcess(), user3.getSupertokensUserId(), null, "newpassword3"); diff --git a/src/test/java/io/supertokens/test/emailpassword/ParsedFirebaseSCryptResponseTest.java b/src/test/java/io/supertokens/test/emailpassword/ParsedFirebaseSCryptResponseTest.java index cfa9dc3c9..8997e37b1 100644 --- a/src/test/java/io/supertokens/test/emailpassword/ParsedFirebaseSCryptResponseTest.java +++ b/src/test/java/io/supertokens/test/emailpassword/ParsedFirebaseSCryptResponseTest.java @@ -36,6 +36,9 @@ public class ParsedFirebaseSCryptResponseTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/emailpassword/PasswordHashingTest.java b/src/test/java/io/supertokens/test/emailpassword/PasswordHashingTest.java index a6504d60b..12dc99145 100644 --- a/src/test/java/io/supertokens/test/emailpassword/PasswordHashingTest.java +++ b/src/test/java/io/supertokens/test/emailpassword/PasswordHashingTest.java @@ -16,6 +16,7 @@ package io.supertokens.test.emailpassword; +import io.supertokens.Main; import io.supertokens.ProcessState; import io.supertokens.config.Config; import io.supertokens.config.CoreConfig; @@ -48,6 +49,9 @@ public class PasswordHashingTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -65,7 +69,7 @@ public void importUserWithFireBaseSCrypt() throws Exception { Utils.setValueInConfig("firebase_password_hashing_signer_key", "gRhC3eDeQOdyEn4bMd9c6kxguWVmcIVq/SKa0JDPFeM6TcEevkaW56sIWfx88OHbJKnCXdWscZx0l2WbCJ1wbg=="); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -84,11 +88,11 @@ public void importUserWithFireBaseSCrypt() throws Exception { String combinedPasswordHash = "$" + ParsedFirebaseSCryptResponse.FIREBASE_SCRYPT_PREFIX + "$" + passwordHash + "$" + salt + "$m=" + firebaseMemCost + "$r=" + firebaseRounds + "$s=" + firebaseSaltSeparator; - EmailPassword.importUserWithPasswordHash(process.main, email, combinedPasswordHash, + EmailPassword.importUserWithPasswordHash(process.getProcess(), email, combinedPasswordHash, CoreConfig.PASSWORD_HASHING_ALG.FIREBASE_SCRYPT); // try signing in - AuthRecipeUserInfo user = EmailPassword.signIn(process.main, email, password); + AuthRecipeUserInfo user = EmailPassword.signIn(process.getProcess(), email, password); assertEquals(user.loginMethods[0].email, email); assertEquals(user.loginMethods[0].passwordHash, combinedPasswordHash); @@ -100,7 +104,7 @@ public void importUserWithFireBaseSCrypt() throws Exception { public void hashAndVerifyWithBcrypt() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -131,7 +135,7 @@ public void hashAndVerifyWithArgon() throws Exception { Utils.setValueInConfig("password_hashing_alg", "ARGON2"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -163,7 +167,7 @@ public void hashAndVerifyWithBcryptChangeToArgon() throws Exception { { - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -180,7 +184,7 @@ public void hashAndVerifyWithBcryptChangeToArgon() throws Exception { } { Utils.setValueInConfig("password_hashing_alg", "ARGON2"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); assert (Config.getConfig(process.getProcess()) .getPasswordHashingAlg() == CoreConfig.PASSWORD_HASHING_ALG.ARGON2); @@ -202,7 +206,7 @@ public void hashAndVerifyWithArgonChangeToBcrypt() throws Exception { { Utils.setValueInConfig("password_hashing_alg", "ARGON2"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -219,7 +223,7 @@ public void hashAndVerifyWithArgonChangeToBcrypt() throws Exception { } { Utils.setValueInConfig("password_hashing_alg", "BCRYPT"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); assert (Config.getConfig(process.getProcess()) .getPasswordHashingAlg() == CoreConfig.PASSWORD_HASHING_ALG.BCRYPT); @@ -237,7 +241,7 @@ public void hashAndVerifyWithArgonChangeToBcrypt() throws Exception { public void defaultConfigs() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -266,7 +270,7 @@ public void invalidConfigArgonButUsingBcryptShouldAllowStartingServer() throws E Utils.setValueInConfig("argon2_iterations", "-1"); Utils.setValueInConfig("argon2_hashing_pool_size", "-1"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -287,7 +291,7 @@ public void lowercaseConfig() throws Exception { String[] args = {"../"}; Utils.setValueInConfig("password_hashing_alg", "argon2"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); assert (Config.getConfig(process.getProcess()) .getPasswordHashingAlg() == CoreConfig.PASSWORD_HASHING_ALG.ARGON2); @@ -302,7 +306,7 @@ public void lowercaseConfig() throws Exception { String[] args = {"../"}; Utils.setValueInConfig("password_hashing_alg", "bcrypt"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); assert (Config.getConfig(process.getProcess()) .getPasswordHashingAlg() == CoreConfig.PASSWORD_HASHING_ALG.BCRYPT); @@ -318,7 +322,7 @@ public void invalidConfig() throws Exception { String[] args = {"../"}; Utils.setValueInConfig("password_hashing_alg", "RANDOM"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); assertEquals(e.exception.getCause().getMessage(), @@ -335,7 +339,7 @@ public void invalidConfig() throws Exception { Utils.setValueInConfig("argon2_iterations", "-1"); Utils.setValueInConfig("password_hashing_alg", "argon2"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); assertEquals(e.exception.getCause().getMessage(), "'argon2_iterations' must be >= 1"); @@ -351,7 +355,7 @@ public void invalidConfig() throws Exception { Utils.setValueInConfig("argon2_parallelism", "-1"); Utils.setValueInConfig("password_hashing_alg", "ARGON2"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); assertEquals(e.exception.getCause().getMessage(), "'argon2_parallelism' must be >= 1"); @@ -367,7 +371,7 @@ public void invalidConfig() throws Exception { Utils.setValueInConfig("argon2_memory_kb", "-1"); Utils.setValueInConfig("password_hashing_alg", "ARGON2"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); assertEquals(e.exception.getCause().getMessage(), "'argon2_memory_kb' must be >= 1"); @@ -383,7 +387,7 @@ public void invalidConfig() throws Exception { Utils.setValueInConfig("argon2_hashing_pool_size", "-1"); Utils.setValueInConfig("password_hashing_alg", "argon2"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); assertEquals(e.exception.getCause().getMessage(), "'argon2_hashing_pool_size' must be >= 1"); @@ -399,7 +403,7 @@ public void invalidConfig() throws Exception { Utils.setValueInConfig("argon2_hashing_pool_size", "100"); Utils.setValueInConfig("password_hashing_alg", "ARGON2"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); assertEquals(e.exception.getCause().getMessage(), @@ -416,7 +420,7 @@ public void invalidConfig() throws Exception { Utils.setValueInConfig("bcrypt_log_rounds", "-1"); Utils.setValueInConfig("password_hashing_alg", "BCRYPT"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); assertEquals(e.exception.getCause().getMessage(), "'bcrypt_log_rounds' must be >= 1"); @@ -433,7 +437,7 @@ public void hashAndVerifyArgon2HashWithDifferentConfigs() throws Exception { Utils.setValueInConfig("password_hashing_alg", "ARGON2"); { - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -453,7 +457,7 @@ public void hashAndVerifyArgon2HashWithDifferentConfigs() throws Exception { Utils.setValueInConfig("argon2_parallelism", "2"); Utils.setValueInConfig("argon2_iterations", "10"); Utils.setValueInConfig("argon2_hashing_pool_size", "5"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); assert (PasswordHashing.getInstance(process.getProcess()).verifyPasswordWithHash("somePassword", hash)); @@ -477,7 +481,7 @@ public void hashAndVerifyBcryptHashWithDifferentConfigs() throws Exception { String hash = ""; { - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -495,7 +499,7 @@ public void hashAndVerifyBcryptHashWithDifferentConfigs() throws Exception { } { Utils.setValueInConfig("bcrypt_log_rounds", "12"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); assert (PasswordHashing.getInstance(process.getProcess()).verifyPasswordWithHash("somePassword", hash)); @@ -515,7 +519,7 @@ public void hashAndVerifyBcryptHashWithDifferentConfigs() throws Exception { public void hashAndVerifyWithBcryptChangeToArgonPasswordWithResetFlow() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -547,7 +551,7 @@ public void hashAndVerifyWithArgonChangeToBcryptPasswordWithResetFlow() throws E String[] args = {"../"}; Utils.setValueInConfig("password_hashing_alg", "ARGON2"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -578,7 +582,7 @@ public void hashAndVerifyWithArgonChangeToBcryptPasswordWithResetFlow() throws E public void hashAndVerifyWithBcryptChangeToArgonChangePassword() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -608,7 +612,7 @@ public void hashAndVerifyWithArgonChangeToBcryptChangePassword() throws Exceptio String[] args = {"../"}; Utils.setValueInConfig("password_hashing_alg", "ARGON2"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -638,13 +642,15 @@ public void differentPasswordHashGeneratedArgon() throws Exception { String[] args = {"../"}; Utils.setValueInConfig("password_hashing_alg", "ARGON2"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } + PasswordHashing.bypassHashCachingInTesting = true; // ensure password hashing does not use the cache + String hash = PasswordHashing.getInstance(process.getProcess()).createHashWithSalt("somePass"); String hash2 = PasswordHashing.getInstance(process.getProcess()).createHashWithSalt("somePass"); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.PASSWORD_HASH_ARGON)); @@ -659,13 +665,15 @@ public void differentPasswordHashGeneratedArgon() throws Exception { public void differentPasswordHashGeneratedBcrypt() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } + PasswordHashing.bypassHashCachingInTesting = true; // ensure password hashing does not use the cache + String hash = PasswordHashing.getInstance(process.getProcess()).createHashWithSalt("somePass"); String hash2 = PasswordHashing.getInstance(process.getProcess()).createHashWithSalt("somePass"); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.PASSWORD_HASH_BCRYPT)); @@ -683,7 +691,7 @@ public void parallelImportUserSignInFirebaseScrypt() throws Exception { Utils.setValueInConfig("firebase_password_hashing_signer_key", "gRhC3eDeQOdyEn4bMd9c6kxguWVmcIVq/SKa0JDPFeM6TcEevkaW56sIWfx88OHbJKnCXdWscZx0l2WbCJ1wbg=="); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL @@ -720,10 +728,10 @@ public void parallelImportUserSignInFirebaseScrypt() throws Exception { localCounter++; try { - EmailPassword.importUserWithPasswordHash(process.main, uniqueEmail, combinedPasswordHash, + EmailPassword.importUserWithPasswordHash(process.getProcess(), uniqueEmail, combinedPasswordHash, CoreConfig.PASSWORD_HASHING_ALG.FIREBASE_SCRYPT); // try signing in - AuthRecipeUserInfo user = EmailPassword.signIn(process.main, uniqueEmail, password); + AuthRecipeUserInfo user = EmailPassword.signIn(process.getProcess(), uniqueEmail, password); assertEquals(user.loginMethods[0].passwordHash, combinedPasswordHash); assertNotNull(process .checkOrWaitForEvent(ProcessState.PROCESS_STATE.PASSWORD_VERIFY_FIREBASE_SCRYPT)); @@ -765,7 +773,7 @@ public void parallelImportUserSignInFirebaseScryptWithPoolSize4() throws Excepti "gRhC3eDeQOdyEn4bMd9c6kxguWVmcIVq/SKa0JDPFeM6TcEevkaW56sIWfx88OHbJKnCXdWscZx0l2WbCJ1wbg=="); Utils.setValueInConfig("firebase_password_hashing_pool_size", "4"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL @@ -802,10 +810,10 @@ public void parallelImportUserSignInFirebaseScryptWithPoolSize4() throws Excepti localCounter++; try { - EmailPassword.importUserWithPasswordHash(process.main, uniqueEmail, combinedPasswordHash, + EmailPassword.importUserWithPasswordHash(process.getProcess(), uniqueEmail, combinedPasswordHash, CoreConfig.PASSWORD_HASHING_ALG.FIREBASE_SCRYPT); // try signing in - AuthRecipeUserInfo user = EmailPassword.signIn(process.main, uniqueEmail, password); + AuthRecipeUserInfo user = EmailPassword.signIn(process.getProcess(), uniqueEmail, password); assertEquals(user.loginMethods[0].passwordHash, combinedPasswordHash); assertNotNull(process .checkOrWaitForEvent(ProcessState.PROCESS_STATE.PASSWORD_VERIFY_FIREBASE_SCRYPT)); @@ -844,7 +852,7 @@ public void parallelSignUpSignIn() throws Exception { String[] args = {"../"}; Utils.setValueInConfig("password_hashing_alg", "ARGON2"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL diff --git a/src/test/java/io/supertokens/test/emailpassword/UpdateUsersEmailAndPasswordTest.java b/src/test/java/io/supertokens/test/emailpassword/UpdateUsersEmailAndPasswordTest.java index bad7bc880..cad037818 100644 --- a/src/test/java/io/supertokens/test/emailpassword/UpdateUsersEmailAndPasswordTest.java +++ b/src/test/java/io/supertokens/test/emailpassword/UpdateUsersEmailAndPasswordTest.java @@ -35,6 +35,9 @@ public class UpdateUsersEmailAndPasswordTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -47,7 +50,7 @@ public void beforeEach() { @Test public void testUpdateInfoWithoutUser() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { Main main = process.getProcess(); if (StorageLayer.getStorage(main).getType() != STORAGE_TYPE.SQL) { @@ -64,7 +67,7 @@ public void testUpdateInfoWithoutUser() throws Exception { @Test public void testUpdateEmailOnly() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { Main main = process.getProcess(); if (StorageLayer.getStorage(main).getType() != STORAGE_TYPE.SQL) { @@ -88,7 +91,7 @@ public void testUpdateEmailOnly() throws Exception { @Test public void testUpdateEmailToAnotherThatAlreadyExists() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { Main main = process.getProcess(); if (StorageLayer.getStorage(main).getType() != STORAGE_TYPE.SQL) { @@ -112,7 +115,7 @@ public void testUpdateEmailToAnotherThatAlreadyExists() throws Exception { @Test public void testUpdatePasswordOnly() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { Main main = process.getProcess(); if (StorageLayer.getStorage(main).getType() != STORAGE_TYPE.SQL) { @@ -134,7 +137,7 @@ public void testUpdatePasswordOnly() throws Exception { @Test public void testUpdateEmailAndPassword() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { Main main = process.getProcess(); if (StorageLayer.getStorage(main).getType() != STORAGE_TYPE.SQL) { @@ -160,7 +163,7 @@ public void testUpdateEmailAndPassword() throws Exception { @Test public void testUpdateEmailAndPasswordFromVerifiedToNotVerified() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { Main main = process.getProcess(); if (StorageLayer.getStorage(main).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/emailpassword/UserMigrationTest.java b/src/test/java/io/supertokens/test/emailpassword/UserMigrationTest.java index dea91f847..c7671552d 100644 --- a/src/test/java/io/supertokens/test/emailpassword/UserMigrationTest.java +++ b/src/test/java/io/supertokens/test/emailpassword/UserMigrationTest.java @@ -38,6 +38,9 @@ public class UserMigrationTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -129,12 +132,12 @@ public void testBasicUserMigration() throws Exception { String passwordHash = "$2a$10$GzEm3vKoAqnJCTWesRARCe/ovjt/07qjvcH9jbLUg44Fn77gMZkmm"; // migrate user with passwordHash - EmailPassword.ImportUserResponse importUserResponse = EmailPassword.importUserWithPasswordHash(process.main, + EmailPassword.ImportUserResponse importUserResponse = EmailPassword.importUserWithPasswordHash(process.getProcess(), email, passwordHash); // check that the user was created assertFalse(importUserResponse.didUserAlreadyExist); // try and sign in with plainTextPassword - AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.main, email, plainTextPassword); + AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.getProcess(), email, plainTextPassword); assertEquals(userInfo.getSupertokensUserId(), importUserResponse.user.getSupertokensUserId()); assertEquals(userInfo.loginMethods[0].passwordHash, passwordHash); @@ -148,12 +151,12 @@ public void testBasicUserMigration() throws Exception { String passwordHash = "$argon2id$v=19$m=16,t=2,p=1$VG1Oa1lMbzZLbzk5azQ2Qg$kjcNNtZ/b0t/8HgXUiQ76A"; // migrate user with passwordHash - EmailPassword.ImportUserResponse importUserResponse = EmailPassword.importUserWithPasswordHash(process.main, + EmailPassword.ImportUserResponse importUserResponse = EmailPassword.importUserWithPasswordHash(process.getProcess(), email, passwordHash); // check that the user was created assertFalse(importUserResponse.didUserAlreadyExist); // try and sign in with plainTextPassword - AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.main, email, plainTextPassword); + AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.getProcess(), email, plainTextPassword); assertEquals(userInfo.getSupertokensUserId(), importUserResponse.user.getSupertokensUserId()); assertEquals(userInfo.loginMethods[0].passwordHash, passwordHash); @@ -178,13 +181,13 @@ public void testUpdatingAUsersPasswordHash() throws Exception { String email = "test@example.com"; String originalPassword = "testPass123"; - AuthRecipeUserInfo signUpUserInfo = EmailPassword.signUp(process.main, email, originalPassword); + AuthRecipeUserInfo signUpUserInfo = EmailPassword.signUp(process.getProcess(), email, originalPassword); // update passwordHash with new passwordHash String newPassword = "newTestPass123"; String newPasswordHash = "$2a$10$uV17z2rVB3W5Rp4MeJeB4OdRX/Z7oFMLpUbdzyX9bDrk6kvZiOT1G"; - EmailPassword.ImportUserResponse response = EmailPassword.importUserWithPasswordHash(process.main, email, + EmailPassword.ImportUserResponse response = EmailPassword.importUserWithPasswordHash(process.getProcess(), email, newPasswordHash); // check that the user already exists assertTrue(response.didUserAlreadyExist); @@ -192,14 +195,14 @@ public void testUpdatingAUsersPasswordHash() throws Exception { // try signing in with the old password and check that it does not work Exception error = null; try { - EmailPassword.signIn(process.main, email, originalPassword); + EmailPassword.signIn(process.getProcess(), email, originalPassword); } catch (WrongCredentialsException e) { error = e; } assertNotNull(error); // sign in with the newPassword and check that it works - AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.main, email, newPassword); + AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.getProcess(), email, newPassword); assertEquals(userInfo.loginMethods[0].email, signUpUserInfo.loginMethods[0].email); assertEquals(userInfo.getSupertokensUserId(), signUpUserInfo.getSupertokensUserId()); assertEquals(userInfo.timeJoined, signUpUserInfo.timeJoined); @@ -227,12 +230,12 @@ public void testAddingBcryptHashesWithDifferentSaltRounds() throws Exception { String password = "testPass123"; String passwordHash = "$2a$05$vTNtOWhKVVLxCQDePmmsa.Loz9RuwwWajZtkchIVLIu4/.ncSTwfq"; - EmailPassword.ImportUserResponse response = EmailPassword.importUserWithPasswordHash(process.main, email, + EmailPassword.ImportUserResponse response = EmailPassword.importUserWithPasswordHash(process.getProcess(), email, passwordHash); assertFalse(response.didUserAlreadyExist); // test that sign in works - AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.main, email, password); + AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.getProcess(), email, password); assertEquals(userInfo.loginMethods[0].email, email); assertEquals(userInfo.loginMethods[0].passwordHash, passwordHash); @@ -257,12 +260,12 @@ public void testUsingArgon2HashesWithDifferentConfigValues() throws Exception { // length =16 String passwordHash = "$argon2id$v=19$m=16,t=2,p=1$alJQU1VpOG9VWXlqV0dlYw$Z/a978a9nPSlmwIFb5Mrjw"; - EmailPassword.ImportUserResponse response = EmailPassword.importUserWithPasswordHash(process.main, email, + EmailPassword.ImportUserResponse response = EmailPassword.importUserWithPasswordHash(process.getProcess(), email, passwordHash); assertFalse(response.didUserAlreadyExist); // test that sign in works - AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.main, email, password); + AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.getProcess(), email, password); assertEquals(userInfo.loginMethods[0].email, email); assertEquals(userInfo.loginMethods[0].passwordHash, passwordHash); @@ -287,12 +290,12 @@ public void testAddingArgon2WithDifferentVersions() throws Exception { String password = "testing123"; String passwordHash = "$argon2i$v=19$m=16,t=2,p=1$alJQU1VpOG9VWXlqV0dlYw$mThT4E5LULSyn/XhCZc9Hw"; - EmailPassword.ImportUserResponse response = EmailPassword.importUserWithPasswordHash(process.main, email, + EmailPassword.ImportUserResponse response = EmailPassword.importUserWithPasswordHash(process.getProcess(), email, passwordHash); assertFalse(response.didUserAlreadyExist); // test that sign in works - AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.main, email, password); + AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.getProcess(), email, password); assertEquals(userInfo.loginMethods[0].email, email); assertEquals(userInfo.loginMethods[0].passwordHash, passwordHash); } @@ -303,12 +306,12 @@ public void testAddingArgon2WithDifferentVersions() throws Exception { String password = "testing123"; String passwordHash = "$argon2d$v=19$m=16,t=2,p=1$alJQU1VpOG9VWXlqV0dlYw$Ktlqf9xi1Toyx1XcbCwVUQ"; - EmailPassword.ImportUserResponse response = EmailPassword.importUserWithPasswordHash(process.main, email, + EmailPassword.ImportUserResponse response = EmailPassword.importUserWithPasswordHash(process.getProcess(), email, passwordHash); assertFalse(response.didUserAlreadyExist); // test that sign in works - AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.main, email, password); + AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.getProcess(), email, password); assertEquals(userInfo.loginMethods[0].email, email); assertEquals(userInfo.loginMethods[0].passwordHash, passwordHash); } @@ -335,12 +338,12 @@ public void testAddingBcryptHashesWithDifferentVersions() throws Exception { String password = "testPass123"; String passwordHash = "$2a$05$vTNtOWhKVVLxCQDePmmsa.Loz9RuwwWajZtkchIVLIu4/.ncSTwfq"; - EmailPassword.ImportUserResponse response = EmailPassword.importUserWithPasswordHash(process.main, email, + EmailPassword.ImportUserResponse response = EmailPassword.importUserWithPasswordHash(process.getProcess(), email, passwordHash); assertFalse(response.didUserAlreadyExist); // test that sign in works - AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.main, email, password); + AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.getProcess(), email, password); assertEquals(userInfo.loginMethods[0].email, email); assertEquals(userInfo.loginMethods[0].passwordHash, passwordHash); } @@ -351,12 +354,12 @@ public void testAddingBcryptHashesWithDifferentVersions() throws Exception { String password = "testPass123"; String passwordHash = "$2b$10$Tix3Vpu93kiaZRLPPzD6QOIm62x0l5gRdvlyark5S.MLn/NY6t4gS"; - EmailPassword.ImportUserResponse response = EmailPassword.importUserWithPasswordHash(process.main, email, + EmailPassword.ImportUserResponse response = EmailPassword.importUserWithPasswordHash(process.getProcess(), email, passwordHash); assertFalse(response.didUserAlreadyExist); // test that sign in works - AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.main, email, password); + AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.getProcess(), email, password); assertEquals(userInfo.loginMethods[0].email, email); assertEquals(userInfo.loginMethods[0].passwordHash, passwordHash); } @@ -367,12 +370,12 @@ public void testAddingBcryptHashesWithDifferentVersions() throws Exception { String password = "testPass123"; String passwordHash = "$2x$05$vTNtOWhKVVLxCQDePmmsa.Loz9RuwwWajZtkchIVLIu4/.ncSTwfq"; - EmailPassword.ImportUserResponse response = EmailPassword.importUserWithPasswordHash(process.main, email, + EmailPassword.ImportUserResponse response = EmailPassword.importUserWithPasswordHash(process.getProcess(), email, passwordHash); assertFalse(response.didUserAlreadyExist); // test that sign in works - AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.main, email, password); + AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.getProcess(), email, password); assertEquals(userInfo.loginMethods[0].email, email); assertEquals(userInfo.loginMethods[0].passwordHash, passwordHash); } @@ -383,12 +386,12 @@ public void testAddingBcryptHashesWithDifferentVersions() throws Exception { String password = "testPass123"; String passwordHash = "$2y$10$lib5x4nbosKuK31FI8gG1OPVi/EuVHRVM7qmg1EiGADYYcIxTMJfa"; - EmailPassword.ImportUserResponse response = EmailPassword.importUserWithPasswordHash(process.main, email, + EmailPassword.ImportUserResponse response = EmailPassword.importUserWithPasswordHash(process.getProcess(), email, passwordHash); assertFalse(response.didUserAlreadyExist); // test that sign in works - AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.main, email, password); + AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.getProcess(), email, password); assertEquals(userInfo.loginMethods[0].email, email); assertEquals(userInfo.loginMethods[0].passwordHash, passwordHash); } diff --git a/src/test/java/io/supertokens/test/emailpassword/api/ConsumeResetPasswordAPITest4_0.java b/src/test/java/io/supertokens/test/emailpassword/api/ConsumeResetPasswordAPITest4_0.java index bb973959d..e3dd7b77e 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/ConsumeResetPasswordAPITest4_0.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/ConsumeResetPasswordAPITest4_0.java @@ -40,6 +40,9 @@ public class ConsumeResetPasswordAPITest4_0 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -103,11 +106,11 @@ public void testGoodInput() throws Exception { return; } - AuthRecipeUserInfo user = EmailPassword.signUp(process.main, "random@gmail.com", "validPass123"); + AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "random@gmail.com", "validPass123"); String userId = user.getSupertokensUserId(); - String token = EmailPassword.generatePasswordResetToken(process.main, userId, "random@gmail.com"); + String token = EmailPassword.generatePasswordResetToken(process.getProcess(), userId, "random@gmail.com"); JsonObject resetPasswordBody = new JsonObject(); resetPasswordBody.addProperty("token", token); @@ -135,12 +138,12 @@ public void testGoodInputWithUserIdMapping() throws Exception { return; } - AuthRecipeUserInfo user = EmailPassword.signUp(process.main, "random@gmail.com", "validPass123"); - UserIdMapping.createUserIdMapping(process.main, user.getSupertokensUserId(), "e1", null, false); + AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "random@gmail.com", "validPass123"); + UserIdMapping.createUserIdMapping(process.getProcess(), user.getSupertokensUserId(), "e1", null, false); String userId = user.getSupertokensUserId(); - String token = EmailPassword.generatePasswordResetToken(process.main, userId, "random@gmail.com"); + String token = EmailPassword.generatePasswordResetToken(process.getProcess(), userId, "random@gmail.com"); JsonObject resetPasswordBody = new JsonObject(); resetPasswordBody.addProperty("token", token); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/EmailPasswordGetUserAPITest2_7.java b/src/test/java/io/supertokens/test/emailpassword/api/EmailPasswordGetUserAPITest2_7.java index ae617e4b7..c3086e2a9 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/EmailPasswordGetUserAPITest2_7.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/EmailPasswordGetUserAPITest2_7.java @@ -42,6 +42,9 @@ public class EmailPasswordGetUserAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/GenerateEmailVerificationTokenAPITest2_7.java b/src/test/java/io/supertokens/test/emailpassword/api/GenerateEmailVerificationTokenAPITest2_7.java index dd50ce5f7..ba80ad31d 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/GenerateEmailVerificationTokenAPITest2_7.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/GenerateEmailVerificationTokenAPITest2_7.java @@ -38,6 +38,9 @@ public class GenerateEmailVerificationTokenAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/GeneratePasswordResetTokenAPITest2_7.java b/src/test/java/io/supertokens/test/emailpassword/api/GeneratePasswordResetTokenAPITest2_7.java index 44f6c0de9..0b51be124 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/GeneratePasswordResetTokenAPITest2_7.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/GeneratePasswordResetTokenAPITest2_7.java @@ -38,6 +38,9 @@ public class GeneratePasswordResetTokenAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -174,7 +177,7 @@ public void testUnknownUserWithUserIdFromNonEp() throws Exception { return; } - ThirdParty.SignInUpResponse res = ThirdParty.signInUp(process.main, "google", "ug", "t@example.com"); + ThirdParty.SignInUpResponse res = ThirdParty.signInUp(process.getProcess(), "google", "ug", "t@example.com"); JsonObject requestBody = new JsonObject(); requestBody.addProperty("userId", res.user.getSupertokensUserId()); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/GeneratePasswordResetTokenAPITest4_0.java b/src/test/java/io/supertokens/test/emailpassword/api/GeneratePasswordResetTokenAPITest4_0.java index 5e5a96814..52df292e6 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/GeneratePasswordResetTokenAPITest4_0.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/GeneratePasswordResetTokenAPITest4_0.java @@ -41,6 +41,9 @@ public class GeneratePasswordResetTokenAPITest4_0 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -104,7 +107,7 @@ public void testBadInput() throws Exception { } { - AuthRecipeUserInfo user = EmailPassword.signUp(process.main, "a@a.com", "p1234"); + AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "a@a.com", "p1234"); JsonObject requestBody = new JsonObject(); requestBody.addProperty("userId", user.getSupertokensUserId()); try { @@ -166,8 +169,8 @@ public void testGoodInputWithUserIdMapping() throws Exception { return; } - AuthRecipeUserInfo user = EmailPassword.signUp(process.main, "a@a.com", "p1234"); - UserIdMapping.createUserIdMapping(process.main, user.getSupertokensUserId(), "e1", null, false); + AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "a@a.com", "p1234"); + UserIdMapping.createUserIdMapping(process.getProcess(), user.getSupertokensUserId(), "e1", null, false); JsonObject requestBody = new JsonObject(); requestBody.addProperty("userId", "e1"); @@ -223,7 +226,7 @@ public void testUnknownUserWithUserIdFromNonEp() throws Exception { return; } - ThirdParty.SignInUpResponse res = ThirdParty.signInUp(process.main, "google", "ug", "t@example.com"); + ThirdParty.SignInUpResponse res = ThirdParty.signInUp(process.getProcess(), "google", "ug", "t@example.com"); JsonObject requestBody = new JsonObject(); requestBody.addProperty("userId", res.user.getSupertokensUserId()); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/GetUsersByEmailAPITest2_8.java b/src/test/java/io/supertokens/test/emailpassword/api/GetUsersByEmailAPITest2_8.java index 7869f40cf..6dfdd1a10 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/GetUsersByEmailAPITest2_8.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/GetUsersByEmailAPITest2_8.java @@ -41,6 +41,9 @@ public class GetUsersByEmailAPITest2_8 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -53,7 +56,7 @@ public void beforeEach() { @Test public void testReturnTwoUsersWithSameEmail() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } @@ -103,7 +106,7 @@ public void testReturnTwoUsersWithSameEmail() throws Exception { @Test public void testReturnOnlyUsersWithGivenEmail() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } @@ -149,7 +152,7 @@ public void testReturnOnlyUsersWithGivenEmail() throws Exception { @Test public void testNotReturnUsersIfEmailNotExists() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } @@ -185,7 +188,7 @@ public void testNotReturnUsersIfEmailNotExists() throws Exception { @Test public void testShouldThrowOnBadInput() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } diff --git a/src/test/java/io/supertokens/test/emailpassword/api/ImportUserWithPasswordHashAPITest.java b/src/test/java/io/supertokens/test/emailpassword/api/ImportUserWithPasswordHashAPITest.java index caa0d7c99..07acd48a2 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/ImportUserWithPasswordHashAPITest.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/ImportUserWithPasswordHashAPITest.java @@ -42,6 +42,9 @@ public class ImportUserWithPasswordHashAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -333,7 +336,7 @@ public void testSigningInAUserWhenStoredPasswordHashIsIncorrect() throws Excepti EmailPasswordSQLStorage storage = (EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess()); - storage.signUp(new TenantIdentifier(null, null, null), "userId", email, combinedPasswordHash, timeJoined); + storage.signUp(process.getAppForTesting(), "userId", email, combinedPasswordHash, timeJoined); JsonObject signInRequestBody = new JsonObject(); signInRequestBody.addProperty("email", email); @@ -375,7 +378,7 @@ public void testSigningInAUserWithFirebasePasswordHashWithoutSettingTheSignerKey EmailPasswordSQLStorage storage = (EmailPasswordSQLStorage) StorageLayer.getStorage(process.getProcess()); - storage.signUp(new TenantIdentifier(null, null, null), "userId", email, combinedPasswordHash, timeJoined); + storage.signUp(process.getAppForTesting(), "userId", email, combinedPasswordHash, timeJoined); // sign in should result in 500 error since the firebase signer key is not set JsonObject signInRequestBody = new JsonObject(); @@ -518,7 +521,7 @@ public void testUpdatingAUsersPasswordHash() throws Exception { String email = "test@example.com"; String password = "testPass123"; - AuthRecipeUserInfo initialUserInfo = EmailPassword.signUp(process.main, email, password); + AuthRecipeUserInfo initialUserInfo = EmailPassword.signUp(process.getProcess(), email, password); // update a user's passwordHash @@ -540,7 +543,7 @@ public void testUpdatingAUsersPasswordHash() throws Exception { response.get("user").getAsJsonObject().get("id").getAsString()); // sign in with the new password to check if the password hash got updated - AuthRecipeUserInfo updatedUserInfo = EmailPassword.signIn(process.main, email, newPassword); + AuthRecipeUserInfo updatedUserInfo = EmailPassword.signIn(process.getProcess(), email, newPassword); assertEquals(updatedUserInfo.loginMethods[0].passwordHash, passwordHash); process.kill(); @@ -576,7 +579,7 @@ public void testImportingUsersWithHashingAlgorithmFieldWithMixedLowerAndUpperCas assertFalse(response.get("didUserAlreadyExist").getAsBoolean()); // check that the user is created by signing in - AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.main, email, password); + AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.getProcess(), email, password); assertEquals(email, userInfo.loginMethods[0].email); assertEquals(userInfo.loginMethods[0].passwordHash, passwordHash); @@ -600,7 +603,7 @@ public void testImportingUsersWithHashingAlgorithmFieldWithMixedLowerAndUpperCas assertFalse(response.get("didUserAlreadyExist").getAsBoolean()); // check that the user is created by signing in - AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.main, email, password); + AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.getProcess(), email, password); assertEquals(email, userInfo.loginMethods[0].email); assertEquals(userInfo.loginMethods[0].passwordHash, passwordHash); } @@ -637,7 +640,7 @@ public void testImportingUsersWithHashingAlgorithmField() throws Exception { assertFalse(response.get("didUserAlreadyExist").getAsBoolean()); // check that the user is created by signing in - AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.main, email, password); + AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.getProcess(), email, password); assertEquals(email, userInfo.loginMethods[0].email); assertEquals(userInfo.loginMethods[0].passwordHash, passwordHash); @@ -661,7 +664,7 @@ public void testImportingUsersWithHashingAlgorithmField() throws Exception { assertFalse(response.get("didUserAlreadyExist").getAsBoolean()); // check that the user is created by signing in - AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.main, email, password); + AuthRecipeUserInfo userInfo = EmailPassword.signIn(process.getProcess(), email, password); assertEquals(email, userInfo.loginMethods[0].email); assertEquals(userInfo.loginMethods[0].passwordHash, passwordHash); } diff --git a/src/test/java/io/supertokens/test/emailpassword/api/MultitenantAPITest.java b/src/test/java/io/supertokens/test/emailpassword/api/MultitenantAPITest.java index 11e484202..0b9a856c9 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/MultitenantAPITest.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/MultitenantAPITest.java @@ -39,10 +39,8 @@ import io.supertokens.test.httpRequest.HttpResponseException; import io.supertokens.thirdparty.InvalidProviderConfigException; import io.supertokens.utils.SemVer; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.junit.rules.TestRule; import java.io.IOException; import java.util.HashMap; @@ -54,6 +52,9 @@ public class MultitenantAPITest { TestingProcessManager.TestingProcess process; TenantIdentifier t1, t2, t3; + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -685,7 +686,7 @@ public void testImportUsersWorksCorrectlyAcrossTenants() throws Exception { EmailPasswordSQLStorage storage = (EmailPasswordSQLStorage) StorageLayer.getStorage(t2, process.getProcess()); - storage.signUp(t2, "userId", email, combinedPasswordHash, timeJoined); + storage.signUp(t2, "userId2", email, combinedPasswordHash, timeJoined); successfulSignIn(t2, email, password); wrongCredentialsSignIn(t1, email, password); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/ResetPasswordAPITest2_12.java b/src/test/java/io/supertokens/test/emailpassword/api/ResetPasswordAPITest2_12.java index 473d4cdae..6bd0aa434 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/ResetPasswordAPITest2_12.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/ResetPasswordAPITest2_12.java @@ -47,6 +47,9 @@ public class ResetPasswordAPITest2_12 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/ResetPasswordAPITest2_7.java b/src/test/java/io/supertokens/test/emailpassword/api/ResetPasswordAPITest2_7.java index 164a75901..3cc8bc6e4 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/ResetPasswordAPITest2_7.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/ResetPasswordAPITest2_7.java @@ -46,6 +46,9 @@ public class ResetPasswordAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/SignInAPITest2_7.java b/src/test/java/io/supertokens/test/emailpassword/api/SignInAPITest2_7.java index 6f7f7f8b5..8f6d8f8dd 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/SignInAPITest2_7.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/SignInAPITest2_7.java @@ -49,6 +49,9 @@ public class SignInAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/SignInAPITest4_0.java b/src/test/java/io/supertokens/test/emailpassword/api/SignInAPITest4_0.java index c2c081f61..1e22c033e 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/SignInAPITest4_0.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/SignInAPITest4_0.java @@ -45,6 +45,9 @@ public class SignInAPITest4_0 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -67,7 +70,7 @@ public void testGoodInput() throws Exception { return; } - AuthRecipeUserInfo user = EmailPassword.signUp(process.main, "random@gmail.com", "validPass123"); + AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "random@gmail.com", "validPass123"); JsonObject responseBody = new JsonObject(); responseBody.addProperty("email", "random@gmail.com"); @@ -118,8 +121,8 @@ public void testGoodInputWithUserIdMapping() throws Exception { return; } - AuthRecipeUserInfo user = EmailPassword.signUp(process.main, "random@gmail.com", "validPass123"); - UserIdMapping.createUserIdMapping(process.main, user.getSupertokensUserId(), "e1", null, false); + AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "random@gmail.com", "validPass123"); + UserIdMapping.createUserIdMapping(process.getProcess(), user.getSupertokensUserId(), "e1", null, false); JsonObject responseBody = new JsonObject(); responseBody.addProperty("email", "random@gmail.com"); @@ -163,26 +166,25 @@ public void testGoodInputWithUserIdMapping() throws Exception { public void testGoodInputWithUserIdMappingAndMultipleLinkedAccounts() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - AuthRecipeUserInfo user0 = EmailPassword.signUp(process.main, "random1@gmail.com", "validPass123"); - UserIdMapping.createUserIdMapping(process.main, user0.getSupertokensUserId(), "e0", null, false); + AuthRecipeUserInfo user0 = EmailPassword.signUp(process.getProcess(), "random1@gmail.com", "validPass123"); + UserIdMapping.createUserIdMapping(process.getProcess(), user0.getSupertokensUserId(), "e0", null, false); Thread.sleep(1); // add a small delay to ensure a unique timestamp - AuthRecipeUserInfo user = EmailPassword.signUp(process.main, "random@gmail.com", "validPass123"); - UserIdMapping.createUserIdMapping(process.main, user.getSupertokensUserId(), "e1", null, false); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, user0.getSupertokensUserId(), user.getSupertokensUserId()); + AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "random@gmail.com", "validPass123"); + UserIdMapping.createUserIdMapping(process.getProcess(), user.getSupertokensUserId(), "e1", null, false); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), user0.getSupertokensUserId(), user.getSupertokensUserId()); JsonObject responseBody = new JsonObject(); responseBody.addProperty("email", "random@gmail.com"); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/SignUpAPITest2_7.java b/src/test/java/io/supertokens/test/emailpassword/api/SignUpAPITest2_7.java index 7705ee413..8b93fa081 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/SignUpAPITest2_7.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/SignUpAPITest2_7.java @@ -51,6 +51,9 @@ public class SignUpAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -146,7 +149,7 @@ public void testGoodInput() throws Exception { int activeUsers = ActiveUsers.countUsersActiveSince(process.getProcess(), startTS); assert (activeUsers == 1); AuthRecipeUserInfo user = ((AuthRecipeStorage) StorageLayer.getStorage(process.getProcess())) - .listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), "random@gmail.com")[0]; + .listPrimaryUsersByEmail(process.getAppForTesting(), "random@gmail.com")[0]; assertEquals(user.loginMethods[0].email, signUpUser.get("email").getAsString()); assertEquals(user.getSupertokensUserId(), signUpUser.get("id").getAsString()); @@ -196,7 +199,7 @@ public void testTheNormaliseEmailFunction() throws Exception { assertNotNull(signUpUser.get("id")); AuthRecipeUserInfo userInfo = ((AuthRecipeStorage) StorageLayer.getStorage(process.getProcess())) - .getPrimaryUserById(new AppIdentifier(null, null), signUpUser.get("id").getAsString()); + .getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), signUpUser.get("id").getAsString()); assertEquals(userInfo.loginMethods[0].email, "random@gmail.com"); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/SignUpAPITest3_0.java b/src/test/java/io/supertokens/test/emailpassword/api/SignUpAPITest3_0.java index 1b5bbb995..a38f286c3 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/SignUpAPITest3_0.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/SignUpAPITest3_0.java @@ -51,6 +51,9 @@ public class SignUpAPITest3_0 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -86,7 +89,7 @@ public void testGoodInput() throws Exception { int activeUsers = ActiveUsers.countUsersActiveSince(process.getProcess(), startTS); assert (activeUsers == 1); AuthRecipeUserInfo user = ((AuthRecipeStorage) StorageLayer.getStorage(process.getProcess())) - .listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), "random@gmail.com")[0]; + .listPrimaryUsersByEmail(process.getAppForTesting(), "random@gmail.com")[0]; assertEquals(user.loginMethods[0].email, signUpUser.get("email").getAsString()); assertEquals(user.getSupertokensUserId(), signUpUser.get("id").getAsString()); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/SignUpAPITest4_0.java b/src/test/java/io/supertokens/test/emailpassword/api/SignUpAPITest4_0.java index 1dc7cc2ef..a58b5d232 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/SignUpAPITest4_0.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/SignUpAPITest4_0.java @@ -39,6 +39,9 @@ public class SignUpAPITest4_0 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/SignUpAPITest5_0.java b/src/test/java/io/supertokens/test/emailpassword/api/SignUpAPITest5_0.java index e8f19f6b3..499db9c46 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/SignUpAPITest5_0.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/SignUpAPITest5_0.java @@ -41,6 +41,9 @@ public class SignUpAPITest5_0 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/emailpassword/api/UserPutAPITest2_8.java b/src/test/java/io/supertokens/test/emailpassword/api/UserPutAPITest2_8.java index a04258162..8aa1b85ed 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/UserPutAPITest2_8.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/UserPutAPITest2_8.java @@ -38,6 +38,9 @@ public class UserPutAPITest2_8 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -50,7 +53,7 @@ public void beforeEach() { @Test public void testQueryingOfUnknownUserId() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } @@ -70,7 +73,7 @@ public void testQueryingOfUnknownUserId() throws Exception { @Test public void testQueryingWithEmailThatAlreadyExists() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } @@ -93,7 +96,7 @@ public void testQueryingWithEmailThatAlreadyExists() throws Exception { @Test public void testUpdatingEmailNormalisesIt() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } @@ -117,7 +120,7 @@ public void testUpdatingEmailNormalisesIt() throws Exception { @Test public void testQueryingWithoutEmailAndPassword() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } @@ -139,7 +142,7 @@ public void testQueryingWithoutEmailAndPassword() throws Exception { @Test public void testSuccessfulUpdate() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } @@ -157,13 +160,13 @@ public void testSuccessfulUpdate() throws Exception { assertEquals("OK", response.get("status").getAsString()); assertEquals(1, response.entrySet().size()); - EmailPassword.signIn(process.main, "someotheremail@gmail.com", "somePass"); + EmailPassword.signIn(process.getProcess(), "someotheremail@gmail.com", "somePass"); }); } @Test public void testSuccessfulUpdateWithOnlyPassword() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } @@ -181,7 +184,7 @@ public void testSuccessfulUpdateWithOnlyPassword() throws Exception { assertEquals("OK", response.get("status").getAsString()); assertEquals(1, response.entrySet().size()); - EmailPassword.signIn(process.main, "someemail@gmail.com", "somePass123"); + EmailPassword.signIn(process.getProcess(), "someemail@gmail.com", "somePass123"); }); } diff --git a/src/test/java/io/supertokens/test/emailpassword/api/UserPutAPITest4_0.java b/src/test/java/io/supertokens/test/emailpassword/api/UserPutAPITest4_0.java index 4754a04b1..a59b57812 100644 --- a/src/test/java/io/supertokens/test/emailpassword/api/UserPutAPITest4_0.java +++ b/src/test/java/io/supertokens/test/emailpassword/api/UserPutAPITest4_0.java @@ -43,6 +43,9 @@ public class UserPutAPITest4_0 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -56,11 +59,10 @@ public void beforeEach() { @Test public void testThatAPIReturnsEmailUpdateNotPossibleWithSingleTenant() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -68,10 +70,10 @@ public void testThatAPIReturnsEmailUpdateNotPossibleWithSingleTenant() throws Ex } AuthRecipeUserInfo user0 = EmailPassword.signUp(process.getProcess(), "someemail1@gmail.com", "somePass"); - AuthRecipe.createPrimaryUser(process.main, user0.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user0.getSupertokensUserId()); AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "someemail@gmail.com", "somePass"); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); JsonObject body = new JsonObject(); body.addProperty("recipeUserId", user.getSupertokensUserId()); diff --git a/src/test/java/io/supertokens/test/emailverification/DeleteExpiredEmailVerificationTokensCronjobTest.java b/src/test/java/io/supertokens/test/emailverification/DeleteExpiredEmailVerificationTokensCronjobTest.java index e3fcd7a0e..6ed20f4e2 100644 --- a/src/test/java/io/supertokens/test/emailverification/DeleteExpiredEmailVerificationTokensCronjobTest.java +++ b/src/test/java/io/supertokens/test/emailverification/DeleteExpiredEmailVerificationTokensCronjobTest.java @@ -25,7 +25,6 @@ import io.supertokens.pluginInterface.authRecipe.AuthRecipeUserInfo; import io.supertokens.pluginInterface.emailverification.EmailVerificationTokenInfo; import io.supertokens.pluginInterface.emailverification.sqlStorage.EmailVerificationSQLStorage; -import io.supertokens.pluginInterface.multitenancy.TenantIdentifier; import io.supertokens.storageLayer.StorageLayer; import io.supertokens.test.TestingProcessManager; import io.supertokens.test.Utils; @@ -41,6 +40,9 @@ public class DeleteExpiredEmailVerificationTokensCronjobTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -55,8 +57,8 @@ public void beforeEach() { public void checkingCronJob() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); Utils.setValueInConfig("email_verification_token_lifetime", "4000"); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); CronTaskTest.getInstance(process.getProcess()) .setIntervalInSeconds(DeleteExpiredEmailVerificationTokens.RESOURCE_KEY, 1); process.startProcess(); @@ -80,7 +82,7 @@ public void checkingCronJob() throws Exception { user.getSupertokensUserId(), user.loginMethods[0].email); assert (((EmailVerificationSQLStorage) StorageLayer.getStorage(process.getProcess())) - .getAllEmailVerificationTokenInfoForUser(new TenantIdentifier(null, null, null), + .getAllEmailVerificationTokenInfoForUser(process.getAppForTesting(), user.getSupertokensUserId(), user.loginMethods[0].email).length == 4); @@ -88,7 +90,7 @@ public void checkingCronJob() throws Exception { EmailVerificationTokenInfo[] tokens = ((EmailVerificationSQLStorage) StorageLayer.getStorage( process.getProcess())) - .getAllEmailVerificationTokenInfoForUser(new TenantIdentifier(null, null, null), + .getAllEmailVerificationTokenInfoForUser(process.getAppForTesting(), user.getSupertokensUserId(), user.loginMethods[0].email); assert (tokens.length == 2); diff --git a/src/test/java/io/supertokens/test/emailverification/EmailVerificationTest.java b/src/test/java/io/supertokens/test/emailverification/EmailVerificationTest.java index 4b4ff156b..5fc58f3f7 100644 --- a/src/test/java/io/supertokens/test/emailverification/EmailVerificationTest.java +++ b/src/test/java/io/supertokens/test/emailverification/EmailVerificationTest.java @@ -27,8 +27,6 @@ import io.supertokens.pluginInterface.emailverification.EmailVerificationTokenInfo; import io.supertokens.pluginInterface.emailverification.exception.DuplicateEmailVerificationTokenException; import io.supertokens.pluginInterface.emailverification.sqlStorage.EmailVerificationSQLStorage; -import io.supertokens.pluginInterface.multitenancy.AppIdentifier; -import io.supertokens.pluginInterface.multitenancy.TenantIdentifier; import io.supertokens.pluginInterface.multitenancy.exceptions.TenantOrAppNotFoundException; import io.supertokens.storageLayer.StorageLayer; import io.supertokens.test.TestingProcessManager; @@ -56,6 +54,9 @@ public class EmailVerificationTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -89,7 +90,7 @@ public void testGeneratingEmailVerificationTokenTwoTimes() throws Exception { EmailVerificationTokenInfo[] tokenInfo = ((EmailVerificationSQLStorage) StorageLayer.getStorage( process.getProcess())) - .getAllEmailVerificationTokenInfoForUser(new TenantIdentifier(null, null, null), + .getAllEmailVerificationTokenInfoForUser(process.getAppForTesting(), user.getSupertokensUserId(), user.loginMethods[0].email); assertEquals(tokenInfo.length, 2); @@ -194,8 +195,8 @@ public void testGeneratingTwoTokenVerifyOtherTokenShouldThrowAnError() throws Ex public void useAnExpiredTokenItShouldThrowAnError() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); Utils.setValueInConfig("email_verification_token_lifetime", "10"); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -263,7 +264,7 @@ public void clashingEmailVerificationToken() throws Exception { AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test1@example.com", "password"); ((EmailVerificationSQLStorage) StorageLayer.getStorage(process.getProcess())) - .addEmailVerificationToken(new TenantIdentifier(null, null, null), + .addEmailVerificationToken(process.getAppForTesting(), new EmailVerificationTokenInfo(user.getSupertokensUserId(), "token", System.currentTimeMillis() + Config.getConfig(process.getProcess()).getEmailVerificationTokenLifetime(), @@ -271,7 +272,7 @@ public void clashingEmailVerificationToken() throws Exception { try { ((EmailVerificationSQLStorage) StorageLayer.getStorage(process.getProcess())) - .addEmailVerificationToken(new TenantIdentifier(null, null, null), + .addEmailVerificationToken(process.getAppForTesting(), new EmailVerificationTokenInfo(user.getSupertokensUserId(), "token", System.currentTimeMillis() + @@ -369,7 +370,7 @@ public void testVerifyingEmailAndThenUnverify() throws Exception { ((EmailVerificationSQLStorage) StorageLayer.getStorage(process.getProcess())).startTransaction(con -> { try { ((EmailVerificationSQLStorage) StorageLayer.getStorage(process.getProcess())) - .updateIsEmailVerified_Transaction(new AppIdentifier(null, null), con, + .updateIsEmailVerified_Transaction(process.getAppForTesting().toAppIdentifier(), con, user.getSupertokensUserId(), user.loginMethods[0].email, false); } catch (TenantOrAppNotFoundException e) { throw new RuntimeException(e); @@ -407,7 +408,7 @@ public void testVerifyingSameEmailTwice() throws Exception { ((EmailVerificationSQLStorage) StorageLayer.getStorage(process.getProcess())).startTransaction(con -> { try { ((EmailVerificationSQLStorage) StorageLayer.getStorage(process.getProcess())) - .updateIsEmailVerified_Transaction(new AppIdentifier(null, null), con, + .updateIsEmailVerified_Transaction(process.getAppForTesting().toAppIdentifier(), con, user.getSupertokensUserId(), user.loginMethods[0].email, true); } catch (TenantOrAppNotFoundException e) { throw new RuntimeException(e); @@ -428,7 +429,7 @@ public void changeEmailVerificationTokenLifetimeTest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -447,7 +448,7 @@ public void changeEmailVerificationTokenLifetimeTest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -465,7 +466,7 @@ public void changeEmailVerificationTokenLifetimeTest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); assertEquals(e.exception.getCause().getMessage(), "'email_verification_token_lifetime' must be >= 0"); diff --git a/src/test/java/io/supertokens/test/emailverification/EmailVerificationWithUserIdMappingTest.java b/src/test/java/io/supertokens/test/emailverification/EmailVerificationWithUserIdMappingTest.java index b85e4425f..0ce09a429 100644 --- a/src/test/java/io/supertokens/test/emailverification/EmailVerificationWithUserIdMappingTest.java +++ b/src/test/java/io/supertokens/test/emailverification/EmailVerificationWithUserIdMappingTest.java @@ -41,6 +41,9 @@ public class EmailVerificationWithUserIdMappingTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/emailverification/RevokeTokenTest.java b/src/test/java/io/supertokens/test/emailverification/RevokeTokenTest.java index d85d20a1f..45d5482c2 100644 --- a/src/test/java/io/supertokens/test/emailverification/RevokeTokenTest.java +++ b/src/test/java/io/supertokens/test/emailverification/RevokeTokenTest.java @@ -29,6 +29,9 @@ public class RevokeTokenTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -41,7 +44,7 @@ public void beforeEach() { @Test public void testTokenCannotBeUsedToVerifyIfRevoked() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; @@ -71,7 +74,7 @@ public void testTokenCannotBeUsedToVerifyIfRevoked() throws Exception { @Test public void testRevokingNonExistingTokenShouldPass() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } diff --git a/src/test/java/io/supertokens/test/emailverification/UnverifyEmailTest.java b/src/test/java/io/supertokens/test/emailverification/UnverifyEmailTest.java index d9cb3b345..d5ec48135 100644 --- a/src/test/java/io/supertokens/test/emailverification/UnverifyEmailTest.java +++ b/src/test/java/io/supertokens/test/emailverification/UnverifyEmailTest.java @@ -35,6 +35,9 @@ public class UnverifyEmailTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -47,7 +50,7 @@ public void beforeEach() { @Test public void testEmailIsUnverified() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; diff --git a/src/test/java/io/supertokens/test/emailverification/api/IsEmailVerifiedAPITest2_7.java b/src/test/java/io/supertokens/test/emailverification/api/IsEmailVerifiedAPITest2_7.java index e33c8246e..b2f36a22a 100644 --- a/src/test/java/io/supertokens/test/emailverification/api/IsEmailVerifiedAPITest2_7.java +++ b/src/test/java/io/supertokens/test/emailverification/api/IsEmailVerifiedAPITest2_7.java @@ -39,6 +39,9 @@ public class IsEmailVerifiedAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/emailverification/api/MultitenantAPITest.java b/src/test/java/io/supertokens/test/emailverification/api/MultitenantAPITest.java index 5969995d2..0a678da01 100644 --- a/src/test/java/io/supertokens/test/emailverification/api/MultitenantAPITest.java +++ b/src/test/java/io/supertokens/test/emailverification/api/MultitenantAPITest.java @@ -72,7 +72,6 @@ public void beforeEach() throws InterruptedException, InvalidProviderConfigExcep this.process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -92,7 +91,7 @@ private void createTenants() { // tenant 1 JsonObject config = new JsonObject(); - TenantIdentifier tenantIdentifier = new TenantIdentifier(null, "a1", null); + TenantIdentifier tenantIdentifier = new TenantIdentifier(null, process.getAppForTesting().getAppId(), null); StorageLayer.getStorage(new TenantIdentifier(null, null, null), process.getProcess()) .modifyConfigToAddANewUserPoolForTesting(config, 1); @@ -113,14 +112,14 @@ private void createTenants() { // tenant 2 JsonObject config = new JsonObject(); - TenantIdentifier tenantIdentifier = new TenantIdentifier(null, "a1", "t1"); + TenantIdentifier tenantIdentifier = new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"); StorageLayer.getStorage(new TenantIdentifier(null, null, null), process.getProcess()) .modifyConfigToAddANewUserPoolForTesting(config, 2); Multitenancy.addNewOrUpdateAppOrTenant( process.getProcess(), - new TenantIdentifier(null, "a1", null), + new TenantIdentifier(null, process.getAppForTesting().getAppId(), null), new TenantConfig( tenantIdentifier, new EmailPasswordConfig(false), @@ -134,14 +133,14 @@ private void createTenants() { // tenant 3 JsonObject config = new JsonObject(); - TenantIdentifier tenantIdentifier = new TenantIdentifier(null, "a1", "t2"); + TenantIdentifier tenantIdentifier = new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t2"); StorageLayer.getStorage(new TenantIdentifier(null, null, null), process.getProcess()) .modifyConfigToAddANewUserPoolForTesting(config, 2); Multitenancy.addNewOrUpdateAppOrTenant( process.getProcess(), - new TenantIdentifier(null, "a1", null), + new TenantIdentifier(null, process.getAppForTesting().getAppId(), null), new TenantConfig( tenantIdentifier, new EmailPasswordConfig(false), @@ -153,9 +152,9 @@ private void createTenants() ); } - t1 = new TenantIdentifier(null, "a1", null); - t2 = new TenantIdentifier(null, "a1", "t1"); - t3 = new TenantIdentifier(null, "a1", "t2"); + t1 = new TenantIdentifier(null, process.getAppForTesting().getAppId(), null); + t2 = new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"); + t3 = new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t2"); } private void verifyEmail(TenantIdentifier tenantIdentifier, String userId, String email) diff --git a/src/test/java/io/supertokens/test/emailverification/api/RevokeTokenAPITest2_8.java b/src/test/java/io/supertokens/test/emailverification/api/RevokeTokenAPITest2_8.java index 4cdb66e51..db34b0566 100644 --- a/src/test/java/io/supertokens/test/emailverification/api/RevokeTokenAPITest2_8.java +++ b/src/test/java/io/supertokens/test/emailverification/api/RevokeTokenAPITest2_8.java @@ -43,6 +43,9 @@ public class RevokeTokenAPITest2_8 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -55,7 +58,7 @@ public void beforeEach() { @Test public void testThrowBadRequest() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } @@ -74,14 +77,14 @@ public void testThrowBadRequest() throws Exception { @Test public void testRevokeTokenForValidParameters() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { Main main = process.getProcess(); if (StorageLayer.getStorage(main).getType() != STORAGE_TYPE.SQL) { return; } - String token = EmailVerification.generateEmailVerificationToken(process.main, "someUserId", + String token = EmailVerification.generateEmailVerificationToken(process.getProcess(), "someUserId", "someemail@gmail.com"); JsonObject body = new JsonObject(); @@ -94,7 +97,7 @@ public void testRevokeTokenForValidParameters() throws Exception { assertEquals("OK", responseStatus); try { - EmailVerification.verifyEmail(process.main, token); + EmailVerification.verifyEmail(process.getProcess(), token); assert (false); } catch (EmailVerificationInvalidTokenException ignored) { diff --git a/src/test/java/io/supertokens/test/emailverification/api/UnverifyEmailAPITest2_8.java b/src/test/java/io/supertokens/test/emailverification/api/UnverifyEmailAPITest2_8.java index 2e12df01f..01a19f473 100644 --- a/src/test/java/io/supertokens/test/emailverification/api/UnverifyEmailAPITest2_8.java +++ b/src/test/java/io/supertokens/test/emailverification/api/UnverifyEmailAPITest2_8.java @@ -38,6 +38,9 @@ public class UnverifyEmailAPITest2_8 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -50,7 +53,7 @@ public void beforeEach() { @Test public void testThrowBadRequestRequest() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { Main main = process.getProcess(); if (StorageLayer.getStorage(main).getType() != STORAGE_TYPE.SQL) { @@ -72,7 +75,7 @@ public void testThrowBadRequestRequest() throws Exception { @Test public void testSucceedUnverifyEmail() throws Exception { - TestingProcessManager.withProcess(process -> { + TestingProcessManager.withSharedProcess(process -> { Main main = process.getProcess(); if (StorageLayer.getStorage(main).getType() != STORAGE_TYPE.SQL) { @@ -87,7 +90,7 @@ public void testSucceedUnverifyEmail() throws Exception { String token = EmailVerification.generateEmailVerificationToken(main, "mockUserId", "john.doe@example.com"); EmailVerification.verifyEmail(main, token); - assert (EmailVerification.isEmailVerified(process.main, "mockUserId", "john.doe@example.com")); + assert (EmailVerification.isEmailVerified(process.getProcess(), "mockUserId", "john.doe@example.com")); // when JsonObject response = unverifyEmail(main, body); @@ -97,7 +100,7 @@ public void testSucceedUnverifyEmail() throws Exception { // then Assert.assertEquals("OK", responseStatus); - assertFalse(EmailVerification.isEmailVerified(process.main, "mockUserId", "john.doe@example.com")); + assertFalse(EmailVerification.isEmailVerified(process.getProcess(), "mockUserId", "john.doe@example.com")); }); } diff --git a/src/test/java/io/supertokens/test/emailverification/api/VerifyEmailAPITest2_7.java b/src/test/java/io/supertokens/test/emailverification/api/VerifyEmailAPITest2_7.java index aa1c451ca..3827703a8 100644 --- a/src/test/java/io/supertokens/test/emailverification/api/VerifyEmailAPITest2_7.java +++ b/src/test/java/io/supertokens/test/emailverification/api/VerifyEmailAPITest2_7.java @@ -37,6 +37,9 @@ public class VerifyEmailAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/httpRequest/HttpRequestForTesting.java b/src/test/java/io/supertokens/test/httpRequest/HttpRequestForTesting.java index fdd7b434f..7cdb71fc9 100644 --- a/src/test/java/io/supertokens/test/httpRequest/HttpRequestForTesting.java +++ b/src/test/java/io/supertokens/test/httpRequest/HttpRequestForTesting.java @@ -19,17 +19,18 @@ import com.google.gson.JsonElement; import com.google.gson.JsonParser; import io.supertokens.Main; +import io.supertokens.ResourceDistributor; import io.supertokens.pluginInterface.multitenancy.TenantIdentifier; import java.io.*; import java.net.*; -import java.net.http.HttpClient; -import java.net.http.HttpResponse; import java.nio.charset.StandardCharsets; import java.util.Map; public class HttpRequestForTesting { private static final int STATUS_CODE_ERROR_THRESHOLD = 400; + public static boolean disableAddingAppId = false; + public static Integer corePort = null; private static URL getURL(Main main, String requestID, String url) throws MalformedURLException { URL obj = new URL(url); @@ -64,6 +65,16 @@ public static T sendGETRequest(Main main, String requestID, String url, Map< int connectionTimeoutMS, int readTimeoutMS, Integer version, String cdiVersion, String rid) throws IOException, io.supertokens.test.httpRequest.HttpResponseException { + + if (!disableAddingAppId && !url.contains("appid-") && !url.contains(":3567/config")) { + String appId = ResourceDistributor.getAppForTesting().getAppId(); + url = url.replace(":3567", ":3567/appid-" + appId); + } + + if (corePort != null) { + url = url.replace(":3567", ":" + corePort); + } + StringBuilder paramBuilder = new StringBuilder(); if (params != null) { @@ -134,9 +145,20 @@ public static T sendJsonRequest(Main main, String requestID, String url, Jso String method, String apiKey, String rid) throws IOException, io.supertokens.test.httpRequest.HttpResponseException { + // If the url doesn't contain the app id deliberately, add app id used for testing + if (!disableAddingAppId && !url.contains("appid-")) { + String appId = ResourceDistributor.getAppForTesting().getAppId(); + url = url.replace(":3567", ":3567/appid-" + appId); + } + + if (corePort != null) { + url = url.replace(":3567", ":" + corePort); + } + URL obj = getURL(main, requestID, url); InputStream inputStream = null; HttpURLConnection con = null; + try { con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod(method); @@ -236,6 +258,16 @@ public static T sendJsonDELETERequestWithQueryParams(Main main, String reque int connectionTimeoutMS, int readTimeoutMS, Integer version, String cdiVersion, String rid) throws IOException, HttpResponseException { + // If the url doesn't contain the app id deliberately, add app id used for testing + if (!disableAddingAppId && !url.contains("appid-")) { + String appId = ResourceDistributor.getAppForTesting().getAppId(); + url = url.replace(":3567", ":3567/appid-" + appId); + } + + if (corePort != null) { + url = url.replace(":3567", ":" + corePort); + } + StringBuilder paramBuilder = new StringBuilder(); if (params != null) { diff --git a/src/test/java/io/supertokens/test/jwt/JWKSTest.java b/src/test/java/io/supertokens/test/jwt/JWKSTest.java index 758da024a..44702049f 100644 --- a/src/test/java/io/supertokens/test/jwt/JWKSTest.java +++ b/src/test/java/io/supertokens/test/jwt/JWKSTest.java @@ -48,6 +48,9 @@ public class JWKSTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -64,7 +67,7 @@ public void beforeEach() { @Test public void testThatThereAreTheSameNumberOfJWKSAsSupportedAlgorithmsBeforeJWTCreation() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); List keysFromStorage = SigningKeys.getInstance(process.getProcess()).getJWKS(); @@ -82,7 +85,7 @@ public void testThatThereAreTheSameNumberOfJWKSAsSupportedAlgorithmsBeforeJWTCre @Test public void testThatNoNewJWKIsCreatedDuringJWTCreation() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); List keysFromStorageBeforeJWTCreation = SigningKeys.getInstance(process.getProcess()).getJWKS(); diff --git a/src/test/java/io/supertokens/test/jwt/JWTCreateTest.java b/src/test/java/io/supertokens/test/jwt/JWTCreateTest.java index fdebac573..6c0386e4f 100644 --- a/src/test/java/io/supertokens/test/jwt/JWTCreateTest.java +++ b/src/test/java/io/supertokens/test/jwt/JWTCreateTest.java @@ -39,6 +39,9 @@ public class JWTCreateTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/jwt/api/JWKSAPITest2_21.java b/src/test/java/io/supertokens/test/jwt/api/JWKSAPITest2_21.java index 9bc89b71a..ed10ea000 100644 --- a/src/test/java/io/supertokens/test/jwt/api/JWKSAPITest2_21.java +++ b/src/test/java/io/supertokens/test/jwt/api/JWKSAPITest2_21.java @@ -42,6 +42,9 @@ public class JWKSAPITest2_21 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -86,7 +89,7 @@ public void testThatNewDynamicKeysAreAdded() throws Exception { public void testThatNewDynamicKeysAreReflectedIfAddedByAnotherCore() throws Exception { Utils.setValueInConfig("access_token_dynamic_signing_key_update_interval", "0.00027"); // 1 second String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); JsonObject oldResponse = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", diff --git a/src/test/java/io/supertokens/test/jwt/api/JWKSAPITest2_9.java b/src/test/java/io/supertokens/test/jwt/api/JWKSAPITest2_9.java index 44acf84f3..8e07d1ab7 100644 --- a/src/test/java/io/supertokens/test/jwt/api/JWKSAPITest2_9.java +++ b/src/test/java/io/supertokens/test/jwt/api/JWKSAPITest2_9.java @@ -47,6 +47,9 @@ public class JWKSAPITest2_9 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/jwt/api/JWTSigningAPITest2_21.java b/src/test/java/io/supertokens/test/jwt/api/JWTSigningAPITest2_21.java index 53a984c5c..c92528030 100644 --- a/src/test/java/io/supertokens/test/jwt/api/JWTSigningAPITest2_21.java +++ b/src/test/java/io/supertokens/test/jwt/api/JWTSigningAPITest2_21.java @@ -37,6 +37,9 @@ public class JWTSigningAPITest2_21 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/jwt/api/JWTSigningAPITest2_9.java b/src/test/java/io/supertokens/test/jwt/api/JWTSigningAPITest2_9.java index 794dbfeb0..047138749 100644 --- a/src/test/java/io/supertokens/test/jwt/api/JWTSigningAPITest2_9.java +++ b/src/test/java/io/supertokens/test/jwt/api/JWTSigningAPITest2_9.java @@ -45,6 +45,9 @@ public class JWTSigningAPITest2_9 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/jwt/storage/JWTKeyStorageTest.java b/src/test/java/io/supertokens/test/jwt/storage/JWTKeyStorageTest.java index 6d093cb41..8608b6eaf 100644 --- a/src/test/java/io/supertokens/test/jwt/storage/JWTKeyStorageTest.java +++ b/src/test/java/io/supertokens/test/jwt/storage/JWTKeyStorageTest.java @@ -48,6 +48,9 @@ public class JWTKeyStorageTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/mfa/api/CreatePrimaryUserAPITest.java b/src/test/java/io/supertokens/test/mfa/api/CreatePrimaryUserAPITest.java index 2b80f332d..cddafb4c7 100644 --- a/src/test/java/io/supertokens/test/mfa/api/CreatePrimaryUserAPITest.java +++ b/src/test/java/io/supertokens/test/mfa/api/CreatePrimaryUserAPITest.java @@ -49,6 +49,9 @@ public class CreatePrimaryUserAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -62,11 +65,10 @@ public void beforeEach() { @Test public void createReturnsSucceeds() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MFA, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -107,7 +109,7 @@ public void createReturnsSucceeds() throws Exception { userObj = jsonUser; } - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -129,11 +131,10 @@ public void createReturnsSucceeds() throws Exception { @Test public void createReturnsTrueWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MFA, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -141,7 +142,7 @@ public void createReturnsTrueWithUserIdMapping() throws Exception { } AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "abcd1234"); - UserIdMapping.createUserIdMapping(process.main, user.getSupertokensUserId(), "r1", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), user.getSupertokensUserId(), "r1", null, false); JsonObject userObj; { @@ -174,7 +175,7 @@ public void createReturnsTrueWithUserIdMapping() throws Exception { userObj = jsonUser; } - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -209,11 +210,10 @@ public void createReturnsTrueWithUserIdMapping() throws Exception { @Test public void createPrimaryUserBadInput() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MFA, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -259,11 +259,10 @@ public void createPrimaryUserBadInput() throws Exception { @Test public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MFA, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -273,11 +272,11 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); - ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", + ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), "google", "user-google", "test@example.com"); { @@ -302,11 +301,10 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU @Test public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccount() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MFA, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -318,8 +316,8 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccount() throws Ex AuthRecipeUserInfo emailPasswordUser2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass1234"); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); { @@ -345,11 +343,10 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccount() throws Ex public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUserWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MFA, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -358,13 +355,13 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - UserIdMapping.createUserIdMapping(process.main, emailPasswordUser.getSupertokensUserId(), "r1", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), emailPasswordUser.getSupertokensUserId(), "r1", null, false); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); - ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", + ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), "google", "user-google", "test@example.com"); { @@ -389,11 +386,10 @@ public void makePrimaryUserFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryU @Test public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MFA, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -402,12 +398,12 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMa AuthRecipeUserInfo emailPasswordUser1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - UserIdMapping.createUserIdMapping(process.main, emailPasswordUser1.getSupertokensUserId(), "r1", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), emailPasswordUser1.getSupertokensUserId(), "r1", null, false); AuthRecipeUserInfo emailPasswordUser2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass1234"); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); { @@ -432,11 +428,10 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMa @Test public void createPrimaryUserInTenantWithAnotherStorage() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MFA, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -444,13 +439,13 @@ public void createPrimaryUserInTenantWithAnotherStorage() throws Exception { } JsonObject coreConfig = new JsonObject(); - StorageLayer.getStorage(new TenantIdentifier(null, null, null), process.getProcess()) + StorageLayer.getStorage(new TenantIdentifier(null, process.getAppForTesting().getAppId(), null), process.getProcess()) .modifyConfigToAddANewUserPoolForTesting(coreConfig, 2); - TenantIdentifier tenantIdentifier = new TenantIdentifier(null, null, "t1"); + TenantIdentifier tenantIdentifier = new TenantIdentifier(null, process.getAppForTesting().getAppId(), "t1"); Multitenancy.addNewOrUpdateAppOrTenant( process.getProcess(), - new TenantIdentifier(null, null, null), + new TenantIdentifier(null, process.getAppForTesting().getAppId(), null), new TenantConfig( tenantIdentifier, new EmailPasswordConfig(true), @@ -461,7 +456,7 @@ public void createPrimaryUserInTenantWithAnotherStorage() throws Exception { ); AuthRecipeUserInfo user = EmailPassword.signUp( - tenantIdentifier, (StorageLayer.getStorage(tenantIdentifier, process.main)), + tenantIdentifier, (StorageLayer.getStorage(tenantIdentifier, process.getProcess())), process.getProcess(), "test@example.com", "abcd1234"); JsonObject userObj; @@ -500,8 +495,8 @@ public void createPrimaryUserInTenantWithAnotherStorage() throws Exception { userObj = jsonUser; } - AuthRecipe.createPrimaryUser(process.main, - tenantIdentifier.toAppIdentifier(), (StorageLayer.getStorage(tenantIdentifier, process.main)), + AuthRecipe.createPrimaryUser(process.getProcess(), + tenantIdentifier.toAppIdentifier(), (StorageLayer.getStorage(tenantIdentifier, process.getProcess())), user.getSupertokensUserId()); { @@ -524,8 +519,7 @@ public void createPrimaryUserInTenantWithAnotherStorage() throws Exception { @Test public void createReturnsFailsWithoutFeatureEnabled() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/mfa/api/LinkAccountsAPITest.java b/src/test/java/io/supertokens/test/mfa/api/LinkAccountsAPITest.java index 07a803d0a..75ef1bf00 100644 --- a/src/test/java/io/supertokens/test/mfa/api/LinkAccountsAPITest.java +++ b/src/test/java/io/supertokens/test/mfa/api/LinkAccountsAPITest.java @@ -48,6 +48,9 @@ public class LinkAccountsAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -61,11 +64,10 @@ public void beforeEach() { @Test public void linkReturnsTrue() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MFA, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -76,7 +78,7 @@ public void linkReturnsTrue() throws Exception { AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "abcd1234"); - AuthRecipe.createPrimaryUser(process.main, user2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user2.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -92,7 +94,7 @@ public void linkReturnsTrue() throws Exception { assertTrue(response.has("user")); } - AuthRecipe.linkAccounts(process.main, user.getSupertokensUserId(), user2.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), user.getSupertokensUserId(), user2.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -115,11 +117,10 @@ public void linkReturnsTrue() throws Exception { @Test public void canLinkReturnsTrueWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MFA, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -127,12 +128,12 @@ public void canLinkReturnsTrueWithUserIdMapping() throws Exception { } AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "abcd1234"); - UserIdMapping.createUserIdMapping(process.main, user.getSupertokensUserId(), "r1", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), user.getSupertokensUserId(), "r1", null, false); AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "abcd1234"); - UserIdMapping.createUserIdMapping(process.main, user2.getSupertokensUserId(), "r2", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), user2.getSupertokensUserId(), "r2", null, false); - AuthRecipe.createPrimaryUser(process.main, user2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user2.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -148,7 +149,7 @@ public void canLinkReturnsTrueWithUserIdMapping() throws Exception { assertTrue(response.has("user")); } - AuthRecipe.linkAccounts(process.main, user.getSupertokensUserId(), user2.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), user.getSupertokensUserId(), user2.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -171,11 +172,10 @@ public void canLinkReturnsTrueWithUserIdMapping() throws Exception { @Test public void canLinkUserBadInput() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MFA, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -216,7 +216,7 @@ public void canLinkUserBadInput() throws Exception { } AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "abcd1234"); - AuthRecipe.createPrimaryUser(process.main, user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user.getSupertokensUserId()); AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "abcd1234"); @@ -261,11 +261,10 @@ public void canLinkUserBadInput() throws Exception { @Test public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MFA, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -275,16 +274,16 @@ public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); - ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", + ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), "google", "user-google", "test2@example.com"); - AuthRecipe.createPrimaryUser(process.main, signInUpResponse.user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), signInUpResponse.user.getSupertokensUserId()); - ThirdParty.SignInUpResponse signInUpResponse2 = ThirdParty.signInUp(process.main, "fb", "user-fb", + ThirdParty.SignInUpResponse signInUpResponse2 = ThirdParty.signInUp(process.getProcess(), "fb", "user-fb", "test@example.com"); @@ -312,11 +311,10 @@ public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUserWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MFA, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -325,22 +323,22 @@ public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser AuthRecipeUserInfo emailPasswordUser = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - UserIdMapping.createUserIdMapping(process.main, emailPasswordUser.getSupertokensUserId(), "e1", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), emailPasswordUser.getSupertokensUserId(), "e1", null, false); - AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.main, + AuthRecipe.CreatePrimaryUserResult result = AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser.getSupertokensUserId()); assert (!result.wasAlreadyAPrimaryUser); - ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, "google", "user-google", + ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), "google", "user-google", "test2@example.com"); - UserIdMapping.createUserIdMapping(process.main, signInUpResponse.user.getSupertokensUserId(), "e2", null, + UserIdMapping.createUserIdMapping(process.getProcess(), signInUpResponse.user.getSupertokensUserId(), "e2", null, false); - AuthRecipe.createPrimaryUser(process.main, signInUpResponse.user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), signInUpResponse.user.getSupertokensUserId()); - ThirdParty.SignInUpResponse signInUpResponse2 = ThirdParty.signInUp(process.main, "fb", "user-fb", + ThirdParty.SignInUpResponse signInUpResponse2 = ThirdParty.signInUp(process.getProcess(), "fb", "user-fb", "test@example.com"); - UserIdMapping.createUserIdMapping(process.main, signInUpResponse2.user.getSupertokensUserId(), "e3", null, + UserIdMapping.createUserIdMapping(process.getProcess(), signInUpResponse2.user.getSupertokensUserId(), "e3", null, false); @@ -367,11 +365,10 @@ public void linkingUsersFailsCauseAnotherAccountWithSameEmailAlreadyAPrimaryUser @Test public void linkingUserFailsCauseAlreadyLinkedToAnotherAccount() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MFA, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -383,14 +380,14 @@ public void linkingUserFailsCauseAlreadyLinkedToAnotherAccount() throws Exceptio AuthRecipeUserInfo emailPasswordUser2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass1234"); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); AuthRecipeUserInfo emailPasswordUser3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "pass1234"); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser3.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser3.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -417,11 +414,10 @@ public void linkingUserFailsCauseAlreadyLinkedToAnotherAccount() throws Exceptio @Test public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MFA, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -430,20 +426,20 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMa AuthRecipeUserInfo emailPasswordUser1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "pass1234"); - UserIdMapping.createUserIdMapping(process.main, emailPasswordUser1.getSupertokensUserId(), "r1", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), emailPasswordUser1.getSupertokensUserId(), "r1", null, false); AuthRecipeUserInfo emailPasswordUser2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass1234"); - UserIdMapping.createUserIdMapping(process.main, emailPasswordUser2.getSupertokensUserId(), "r2", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), emailPasswordUser2.getSupertokensUserId(), "r2", null, false); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); AuthRecipeUserInfo emailPasswordUser3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "pass1234"); - UserIdMapping.createUserIdMapping(process.main, emailPasswordUser3.getSupertokensUserId(), "r3", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), emailPasswordUser3.getSupertokensUserId(), "r3", null, false); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser3.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser3.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -469,11 +465,10 @@ public void makingPrimaryUserFailsCauseAlreadyLinkedToAnotherAccountWithUserIdMa @Test public void inputUserIsNotAPrimaryUserTest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MFA, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -503,8 +498,7 @@ public void inputUserIsNotAPrimaryUserTest() throws Exception { @Test public void linkReturnsFailsWithoutFeatureEnabled() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -542,11 +536,10 @@ public void linkReturnsFailsWithoutFeatureEnabled() throws Exception { @Test public void testUserObjectInLinkAccountsResponse() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MFA, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -557,7 +550,7 @@ public void testUserObjectInLinkAccountsResponse() throws Exception { AuthRecipeUserInfo user2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "abcd1234"); - AuthRecipe.createPrimaryUser(process.main, user2.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user2.getSupertokensUserId()); { JsonObject params = new JsonObject(); @@ -588,11 +581,10 @@ public void testUserObjectInLinkAccountsResponse() throws Exception { @Test public void linkingUserFailsCauseAlreadyLinkedToAnotherAccountReturnsUserObject() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MFA, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -604,14 +596,14 @@ public void linkingUserFailsCauseAlreadyLinkedToAnotherAccountReturnsUserObject( AuthRecipeUserInfo emailPasswordUser2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "pass1234"); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser1.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, emailPasswordUser2.getSupertokensUserId(), + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser1.getSupertokensUserId()); + AuthRecipe.linkAccounts(process.getProcess(), emailPasswordUser2.getSupertokensUserId(), emailPasswordUser1.getSupertokensUserId()); AuthRecipeUserInfo emailPasswordUser3 = EmailPassword.signUp(process.getProcess(), "test3@example.com", "pass1234"); - AuthRecipe.createPrimaryUser(process.main, emailPasswordUser3.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), emailPasswordUser3.getSupertokensUserId()); { JsonObject params = new JsonObject(); diff --git a/src/test/java/io/supertokens/test/multitenant/AppTenantUserTest.java b/src/test/java/io/supertokens/test/multitenant/AppTenantUserTest.java index cca62b70c..ead561993 100644 --- a/src/test/java/io/supertokens/test/multitenant/AppTenantUserTest.java +++ b/src/test/java/io/supertokens/test/multitenant/AppTenantUserTest.java @@ -54,6 +54,9 @@ public class AppTenantUserTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -67,11 +70,10 @@ public void beforeEach() { @Test public void testDeletingAppDeleteNonAuthRecipeData() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -133,7 +135,7 @@ null, null, new JsonObject() String userId = user.getSupertokensUserId(); // create entry in nonAuth table - StorageLayer.getStorage(process.main).addInfoToNonAuthRecipesBasedOnUserId(app, className, userId); + StorageLayer.getStorage(process.getProcess()).addInfoToNonAuthRecipesBasedOnUserId(app, className, userId); try { UserIdMapping.findNonAuthStoragesWhereUserIdIsUsedOrAssertIfUsed( @@ -176,11 +178,10 @@ null, null, new JsonObject() @Test public void testDisassociationOfUserDeletesNonAuthRecipeData() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -268,11 +269,10 @@ null, null, new JsonObject() @Test public void deletingTenantKeepsTheUserInTheApp() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/multitenant/ConfigTest.java b/src/test/java/io/supertokens/test/multitenant/ConfigTest.java index ee4a14e44..b15c96b31 100644 --- a/src/test/java/io/supertokens/test/multitenant/ConfigTest.java +++ b/src/test/java/io/supertokens/test/multitenant/ConfigTest.java @@ -65,6 +65,9 @@ public class ConfigTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -81,10 +84,9 @@ public void normalConfigContinuesToWork() throws InterruptedException, IOExcepti Utils.setValueInConfig("refresh_token_validity", "144001"); Utils.setValueInConfig("access_token_signing_key_dynamic", "false"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.LOADING_ALL_TENANT_CONFIG)); @@ -109,10 +111,9 @@ public void normalConfigErrorContinuesToWork() throws InterruptedException, IOEx String[] args = {"../"}; Utils.setValueInConfig("access_token_validity", "-1"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); ProcessState.EventAndException e = process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.INIT_FAILURE); assertNotNull(e); @@ -133,10 +134,9 @@ public void mergingTenantWithBaseConfigWorks() Utils.setValueInConfig("refresh_token_validity", "144001"); Utils.setValueInConfig("access_token_signing_key_dynamic", "false"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -192,12 +192,11 @@ public void mergingTenantWithBaseConfigWithInvalidConfigThrowsErrorWorks() Utils.setValueInConfig("refresh_token_validity", "144001"); Utils.setValueInConfig("access_token_signing_key_dynamic", "false"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - CoreConfigTestContent.getInstance(process.main) + CoreConfigTestContent.getInstance(process.getProcess()) .setKeyValue(CoreConfigTestContent.VALIDITY_TESTING, true); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); JsonObject tenantConfig = new JsonObject(); @@ -225,12 +224,11 @@ public void mergingTenantWithBaseConfigWithConflictingConfigsThrowsError() throws InterruptedException, IOException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - CoreConfigTestContent.getInstance(process.main) + CoreConfigTestContent.getInstance(process.getProcess()) .setKeyValue(CoreConfigTestContent.VALIDITY_TESTING, true); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -261,12 +259,11 @@ public void mergingDifferentUserPoolTenantWithBaseConfigWithConflictingConfigsSh throws InterruptedException, IOException, InvalidConfigException, TenantOrAppNotFoundException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - CoreConfigTestContent.getInstance(process.main) + CoreConfigTestContent.getInstance(process.getProcess()) .setKeyValue(CoreConfigTestContent.VALIDITY_TESTING, true); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -319,10 +316,9 @@ public void testDifferentWaysToGetConfigBasedOnConnectionURIAndTenantId() String[] args = {"../"}; Utils.setValueInConfig("email_verification_token_lifetime", "144001"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -414,10 +410,9 @@ public void testMappingSameUserPoolToDifferentConnectionURIThrowsError() String[] args = {"../"}; Utils.setValueInConfig("email_verification_token_lifetime", "144001"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -472,10 +467,9 @@ public void testCreationOfTenantsUsingValidSourceTenant() InvalidConfigException, CannotModifyBaseConfigException, TenantOrAppNotFoundException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -662,10 +656,9 @@ public void testInvalidCasesOfTenantCreation() InvalidConfigException, CannotModifyBaseConfigException, TenantOrAppNotFoundException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -906,7 +899,7 @@ public void testInvalidCasesOfTenantCreation() } TenantConfig[] allTenants = Multitenancy.getAllTenants(process.getProcess()); - assertEquals(3, allTenants.length); + assertEquals(3 + 1, allTenants.length); // + one app created for test process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -919,10 +912,9 @@ public void testUpdationOfDefaultTenant() InvalidConfigException, CannotModifyBaseConfigException, TenantOrAppNotFoundException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -953,10 +945,9 @@ null, null, new JsonObject() public void testThatDifferentTenantsInSameAppCannotHaveDifferentAPIKeys() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1050,7 +1041,6 @@ null, null, new JsonObject() process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); - } @Test @@ -1090,10 +1080,9 @@ public void testConfigNormalisation() throws Exception { String[] args = {"../"}; Utils.setValueInConfig("email_verification_token_lifetime", "1000"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1157,10 +1146,9 @@ public void testTenantConfigIsNormalisedFromCUD1() throws Exception { String[] args = {"../"}; Utils.setValueInConfig("email_verification_token_lifetime", "1000"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1212,10 +1200,9 @@ public void testTenantConfigIsNormalisedFromCUD2() throws Exception { String[] args = {"../"}; Utils.setValueInConfig("email_verification_token_lifetime", "1000"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1288,10 +1275,9 @@ public void testTenantConfigIsNormalisedFromCUD2() throws Exception { @Test public void testInvalidConfigWhileCreatingNewTenant() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1320,10 +1306,9 @@ public void testInvalidConfigWhileCreatingNewTenant() throws Exception { @Test public void testThatConfigChangesReloadsConfig() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1389,10 +1374,9 @@ public void testThatConfigChangesReloadsConfig() throws Exception { @Test public void testThatConfigChangesInAppReloadsConfigInTenant() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1473,10 +1457,9 @@ public void testThatConfigChangesInAppReloadsConfigInTenant() throws Exception { @Test public void testThatConfigChangesReloadsStorageLayer() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1560,10 +1543,9 @@ public void testThatConfigChangesReloadsStorageLayer() throws Exception { @Test public void testThatConfigChangesReloadsFeatureFlag() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1628,10 +1610,9 @@ public void testThatConfigChangesReloadsFeatureFlag() throws Exception { @Test public void testThatConfigChangesReloadsSigningKeys() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1722,10 +1703,9 @@ public void testLoadAllTenantConfigWithDifferentConfigSavedInTheDb() throws Exce // New apps/tenants are added to the loaded config String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1810,10 +1790,9 @@ public void testThatMistypedConfigThrowsError() throws Exception { String[] args = {"../"}; Utils.setValueInConfig("email_verification_token_lifetime", "144001"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1844,10 +1823,9 @@ public void testThatMistypedConfigThrowsError() throws Exception { public void testCoreSpecificConfigIsNotAllowedForNewTenants() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1898,10 +1876,9 @@ public void testCoreSpecificConfigIsNotAllowedForNewTenants() throws Exception { public void testAllConflictingConfigs() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1947,7 +1924,7 @@ public void testAllConflictingConfigs() throws Exception { assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); for (int i = 0; i < disallowed.length; i++) { - process = TestingProcessManager.start(args, false); + process = TestingProcessManager.startIsolatedProcess(args, false); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); process.startProcess(); @@ -2011,7 +1988,7 @@ public void testAllConflictingConfigs() throws Exception { }; for (int i = 0; i < conflictingInSameUserPool.length; i++) { - process = TestingProcessManager.start(args, false); + process = TestingProcessManager.startIsolatedProcess(args, false); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); process.startProcess(); diff --git a/src/test/java/io/supertokens/test/multitenant/LoadOnlyCUDTest.java b/src/test/java/io/supertokens/test/multitenant/LoadOnlyCUDTest.java index 0b40dd2ab..d507422fa 100644 --- a/src/test/java/io/supertokens/test/multitenant/LoadOnlyCUDTest.java +++ b/src/test/java/io/supertokens/test/multitenant/LoadOnlyCUDTest.java @@ -50,6 +50,9 @@ public class LoadOnlyCUDTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -63,10 +66,9 @@ public void beforeEach() { @Test public void testAPIChecksForLoadOnlyCUD() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -91,7 +93,7 @@ public void testAPIChecksForLoadOnlyCUD() throws Exception { assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); Utils.setValueInConfig("supertokens_saas_load_only_cud", "127.0.0.1:3567"); - process = TestingProcessManager.start(args, false); + process = TestingProcessManager.startIsolatedProcess(args, false); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -116,7 +118,7 @@ public void testCreationOfCUDWithLoadOnlyCUD() throws Exception { String[] args = {"../"}; Utils.setValueInConfig("supertokens_saas_load_only_cud", "127.0.0.1:3567"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); @@ -153,10 +155,9 @@ public void testCreationOfCUDWithLoadOnlyCUD() throws Exception { @Test public void testThatResourcesAreNotLoadedWithLoadOnlyCUD() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -180,7 +181,7 @@ public void testThatResourcesAreNotLoadedWithLoadOnlyCUD() throws Exception { assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); Utils.setValueInConfig("supertokens_saas_load_only_cud", "127.0.0.1:3567"); - process = TestingProcessManager.start(args, false); + process = TestingProcessManager.startIsolatedProcess(args, false); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -200,10 +201,9 @@ public void testThatResourcesAreNotLoadedWithLoadOnlyCUD() throws Exception { @Test public void testCronDoesNotRunForOtherCUDsWithLoadOnlyCUD() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -227,7 +227,7 @@ public void testCronDoesNotRunForOtherCUDsWithLoadOnlyCUD() throws Exception { assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); Utils.setValueInConfig("supertokens_saas_load_only_cud", "127.0.0.1:3567"); - process = TestingProcessManager.start(args, false); + process = TestingProcessManager.startIsolatedProcess(args, false); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); diff --git a/src/test/java/io/supertokens/test/multitenant/LoadTest.java b/src/test/java/io/supertokens/test/multitenant/LoadTest.java index 5d4ea1f32..fbf877279 100644 --- a/src/test/java/io/supertokens/test/multitenant/LoadTest.java +++ b/src/test/java/io/supertokens/test/multitenant/LoadTest.java @@ -45,6 +45,9 @@ public class LoadTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -60,10 +63,9 @@ public void testCreating100TenantsAndCheckOnlyOneInstanceOfStorageLayerIsCreated throws InterruptedException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); TenantConfig[] tenants = new TenantConfig[1000]; @@ -107,7 +109,7 @@ public void testCreating100TenantsAndCheckOnlyOneInstanceOfStorageLayerIsCreated // InvalidConfigException, CannotModifyBaseConfigException, BadPermissionException { // String[] args = {"../"}; // -// TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); +// TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); // FeatureFlagTestContent.getInstance(process.getProcess()) // .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); // process.startProcess(); diff --git a/src/test/java/io/supertokens/test/multitenant/LogTest.java b/src/test/java/io/supertokens/test/multitenant/LogTest.java index 5c3e1ea10..1a923dccc 100644 --- a/src/test/java/io/supertokens/test/multitenant/LogTest.java +++ b/src/test/java/io/supertokens/test/multitenant/LogTest.java @@ -46,6 +46,9 @@ public class LogTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -61,10 +64,9 @@ public void testLogThatEachLineIsUniqueOnStartup() throws Exception { String[] args = {"../"}; Utils.setValueInConfig("log_level", "DEBUG"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -126,7 +128,7 @@ public void testLogThatEachLineIsUniqueOnStartup() throws Exception { System.setOut(new PrintStream(stdOutput)); System.setErr(new PrintStream(errorOutput)); - process = TestingProcessManager.start(args, false); + process = TestingProcessManager.startIsolatedProcess(args, false); Main.makeConsolePrintSilent = false; FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); diff --git a/src/test/java/io/supertokens/test/multitenant/RandomConfigTest.java b/src/test/java/io/supertokens/test/multitenant/RandomConfigTest.java index 678093185..76e08e5ce 100644 --- a/src/test/java/io/supertokens/test/multitenant/RandomConfigTest.java +++ b/src/test/java/io/supertokens/test/multitenant/RandomConfigTest.java @@ -50,6 +50,9 @@ public class RandomConfigTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -68,10 +71,9 @@ public void randomlyTestLoadConfig() TenantOrAppNotFoundException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/multitenant/RequestConnectionUriDomainTest.java b/src/test/java/io/supertokens/test/multitenant/RequestConnectionUriDomainTest.java index e86800142..cb0812d65 100644 --- a/src/test/java/io/supertokens/test/multitenant/RequestConnectionUriDomainTest.java +++ b/src/test/java/io/supertokens/test/multitenant/RequestConnectionUriDomainTest.java @@ -57,6 +57,9 @@ public class RequestConnectionUriDomainTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -72,10 +75,9 @@ public void basicTesting() throws InterruptedException, IOException, HttpRespons String[] args = {"../"}; Utils.setValueInConfig("host", "\"0.0.0.0\""); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); Webserver.getInstance(process.getProcess()).addAPI(new WebserverAPI(process.getProcess(), "") { @@ -96,15 +98,17 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO } }); + int port = HttpRequestForTesting.corePort; + { String response = HttpRequest.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/test", null, 1000, 1000, null); + "http://localhost:" + port + "/test", null, 1000, 1000, null); assertEquals("", response); } { String response = HttpRequest.sendGETRequest(process.getProcess(), "", - "http://127.0.0.1:3567/test", null, 1000, 1000, null); + "http://127.0.0.1:" + port + "/test", null, 1000, 1000, null); assertEquals("", response); } @@ -121,10 +125,9 @@ public void basicTestingWithDifferentAPIKey() String[] args = {"../"}; Utils.setValueInConfig("host", "\"0.0.0.0\""); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -229,10 +232,9 @@ public void basicTestingWithDifferentAPIKeyAndTenantId() String[] args = {"../"}; Utils.setValueInConfig("host", "\"0.0.0.0\""); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/multitenant/SigningKeysTest.java b/src/test/java/io/supertokens/test/multitenant/SigningKeysTest.java index e456f1f56..306d21f8e 100644 --- a/src/test/java/io/supertokens/test/multitenant/SigningKeysTest.java +++ b/src/test/java/io/supertokens/test/multitenant/SigningKeysTest.java @@ -55,6 +55,9 @@ public class SigningKeysTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -71,16 +74,15 @@ public void normalConfigContinuesToWork() TenantOrAppNotFoundException, UnsupportedJWTSigningAlgorithmException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.LOADING_ALL_TENANT_CONFIG)); assertEquals( - SigningKeys.getInstance(new AppIdentifier(null, null), process.main).getAllKeys() + SigningKeys.getInstance(new AppIdentifier(null, null), process.getProcess()).getAllKeys() .size(), 2); process.kill(); @@ -95,10 +97,9 @@ public void keysAreGeneratedForAllUserPoolIds() BadPermissionException, UnsupportedJWTSigningAlgorithmException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -133,16 +134,16 @@ public void keysAreGeneratedForAllUserPoolIds() AccessTokenSigningKey.loadForAllTenants(process.getProcess(), apps, new ArrayList<>()); assertEquals( - SigningKeys.getInstance(new AppIdentifier(null, null), process.main).getDynamicKeys() + SigningKeys.getInstance(new AppIdentifier(null, null), process.getProcess()).getDynamicKeys() .size(), 1); assertEquals( - SigningKeys.getInstance(new AppIdentifier("c1", null), process.main).getDynamicKeys() + SigningKeys.getInstance(new AppIdentifier("c1", null), process.getProcess()).getDynamicKeys() .size(), 1); SigningKeys.KeyInfo baseTenant = SigningKeys.getInstance( - new AppIdentifier(null, null), process.main) + new AppIdentifier(null, null), process.getProcess()) .getDynamicKeys().get(0); SigningKeys.KeyInfo c1Tenant = SigningKeys.getInstance( - new AppIdentifier("c1", null), process.main) + new AppIdentifier("c1", null), process.getProcess()) .getDynamicKeys().get(0); assertNotEquals(baseTenant.createdAtTime, c1Tenant.createdAtTime); @@ -162,10 +163,9 @@ public void signingKeyClassesAreThereForAllTenants() BadPermissionException, UnsupportedJWTSigningAlgorithmException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -208,22 +208,22 @@ public void signingKeyClassesAreThereForAllTenants() AccessTokenSigningKey.loadForAllTenants(process.getProcess(), apps, new ArrayList<>()); assertEquals( - SigningKeys.getInstance(new AppIdentifier(null, null), process.main).getDynamicKeys() + SigningKeys.getInstance(new AppIdentifier(null, null), process.getProcess()).getDynamicKeys() .size(), 1); assertEquals( - SigningKeys.getInstance(new AppIdentifier("c1", null), process.main).getDynamicKeys() + SigningKeys.getInstance(new AppIdentifier("c1", null), process.getProcess()).getDynamicKeys() .size(), 1); SigningKeys.KeyInfo baseTenant = SigningKeys.getInstance( - new AppIdentifier(null, null), process.main) + new AppIdentifier(null, null), process.getProcess()) .getDynamicKeys().get(0); SigningKeys.KeyInfo c1Tenant = SigningKeys.getInstance( - new AppIdentifier("c1", null), process.main) + new AppIdentifier("c1", null), process.getProcess()) .getDynamicKeys().get(0); SigningKeys.KeyInfo c2Tenant = SigningKeys.getInstance( - new AppIdentifier("c2", null), process.main) + new AppIdentifier("c2", null), process.getProcess()) .getDynamicKeys().get(0); SigningKeys.KeyInfo c3Tenant = SigningKeys.getInstance( - new AppIdentifier("c3", null), process.main) + new AppIdentifier("c3", null), process.getProcess()) .getDynamicKeys().get(0); assertNotEquals(baseTenant.createdAtTime, c1Tenant.createdAtTime); diff --git a/src/test/java/io/supertokens/test/multitenant/StorageLayerTest.java b/src/test/java/io/supertokens/test/multitenant/StorageLayerTest.java index 8f33ec1b5..7f06bdfa9 100644 --- a/src/test/java/io/supertokens/test/multitenant/StorageLayerTest.java +++ b/src/test/java/io/supertokens/test/multitenant/StorageLayerTest.java @@ -55,6 +55,9 @@ public class StorageLayerTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -69,10 +72,9 @@ public void beforeEach() { public void normalConfigContinuesToWork() throws InterruptedException, IOException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.LOADING_ALL_TENANT_STORAGE)); @@ -89,10 +91,9 @@ public void normalConfigContinuesToWork() throws InterruptedException, IOExcepti public void testDefaultTenant() throws InterruptedException, StorageQueryException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -123,10 +124,9 @@ public void testUpdationOfDefaultTenant() DuplicateThirdPartyIdException, DuplicateClientTypeException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -228,10 +228,9 @@ public void testUpdationOfDefaultTenantWithNullClientType() DuplicateThirdPartyIdException, DuplicateClientTypeException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -292,8 +291,8 @@ null, null, new JsonObject() TenantConfig[] tenantConfigs = mtStorage.getAllTenants(); - assertEquals(1, tenantConfigs.length); - TenantConfig baseTenantConfig = tenantConfigs[0]; + assertEquals(1 + 1, tenantConfigs.length); // + 1 app created for test + TenantConfig baseTenantConfig = tenantConfigs[0].tenantIdentifier.equals(TenantIdentifier.BASE_TENANT) ? tenantConfigs[0] : tenantConfigs[1]; assertEquals(new TenantIdentifier(null, null, null), baseTenantConfig.tenantIdentifier); assertTrue(baseTenantConfig.emailPasswordConfig.enabled); @@ -343,10 +342,9 @@ public void testForNullsInUpdationOfDefaultTenant() DuplicateThirdPartyIdException, DuplicateClientTypeException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -395,8 +393,8 @@ null, null, new JsonObject() TenantConfig[] tenantConfigs = mtStorage.getAllTenants(); - assertEquals(1, tenantConfigs.length); - TenantConfig baseTenantConfig = tenantConfigs[0]; + assertEquals(1 + 1, tenantConfigs.length); // + 1 app created for test + TenantConfig baseTenantConfig = tenantConfigs[0].tenantIdentifier.equals(TenantIdentifier.BASE_TENANT) ? tenantConfigs[0] : tenantConfigs[1]; assertEquals(new TenantIdentifier(null, null, null), baseTenantConfig.tenantIdentifier); assertTrue(baseTenantConfig.emailPasswordConfig.enabled); @@ -446,10 +444,9 @@ public void testForNullClientsListInUpdationOfDefaultTenant() DuplicateThirdPartyIdException, DuplicateClientTypeException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -489,8 +486,8 @@ null, null, new JsonObject() TenantConfig[] tenantConfigs = mtStorage.getAllTenants(); - assertEquals(1, tenantConfigs.length); - TenantConfig baseTenantConfig = tenantConfigs[0]; + assertEquals(1 + 1, tenantConfigs.length); // + 1 app created for test + TenantConfig baseTenantConfig = tenantConfigs[0].tenantIdentifier.equals(TenantIdentifier.BASE_TENANT) ? tenantConfigs[0] : tenantConfigs[1]; assertEquals(new TenantIdentifier(null, null, null), baseTenantConfig.tenantIdentifier); assertTrue(baseTenantConfig.emailPasswordConfig.enabled); @@ -533,10 +530,9 @@ public void testForNullProvidersListInUpdationOfDefaultTenant() DuplicateThirdPartyIdException, DuplicateClientTypeException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -556,8 +552,8 @@ null, null, new JsonObject() TenantConfig[] tenantConfigs = mtStorage.getAllTenants(); - assertEquals(1, tenantConfigs.length); - TenantConfig baseTenantConfig = tenantConfigs[0]; + assertEquals(1, tenantConfigs.length); // + 1 app created for test + TenantConfig baseTenantConfig = tenantConfigs[0].tenantIdentifier.equals(TenantIdentifier.BASE_TENANT) ? tenantConfigs[0] : tenantConfigs[1]; assertEquals(new TenantIdentifier(null, null, null), baseTenantConfig.tenantIdentifier); assertTrue(baseTenantConfig.emailPasswordConfig.enabled); @@ -575,10 +571,9 @@ public void testCreateTenantPersistsDataCorrectly() DuplicateThirdPartyIdException, DuplicateClientTypeException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -691,10 +686,9 @@ public void testCreationOfDuplicationTenantThrowsDuplicateTenantException() DuplicateThirdPartyIdException, DuplicateClientTypeException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -798,7 +792,7 @@ null, null, new JsonObject() TenantConfig[] tenantConfigs = mtStorage.getAllTenants(); - assertEquals(2, tenantConfigs.length); + assertEquals(2, tenantConfigs.length); // + 1 app created for test TenantConfig newTenantConfig = tenantConfigs[1]; assertEquals(new TenantIdentifier(null, null, "t1"), newTenantConfig.tenantIdentifier); @@ -839,10 +833,9 @@ public void testOverwriteTenantOfNonExistantTenantThrowsTenantOrAppNotFoundExcep DuplicateClientTypeException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -916,10 +909,9 @@ public void testCreateTenantWithDuplicateProviderIdThrowsException() throws DuplicateTenantException, InterruptedException, StorageQueryException, DuplicateClientTypeException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1022,10 +1014,9 @@ public void testCreateDuplicateTenantWithDuplicateProviderIdThrowsDuplicateTenan DuplicateThirdPartyIdException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1170,10 +1161,9 @@ public void testCreateDuplicateTenantWithDuplicateProviderClientTypeThrowsDuplic DuplicateThirdPartyIdException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1297,10 +1287,9 @@ public void testCreateTenantWithDuplicateClientTypeThrowsException() DuplicateThirdPartyIdException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1411,10 +1400,9 @@ public void testOverwriteTenantWithDuplicateProviderIdThrowsException() TenantOrAppNotFoundException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1517,10 +1505,9 @@ public void testOverwriteTenantWithDuplicateClientTypeThrowsException() DuplicateThirdPartyIdException, TenantOrAppNotFoundException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1630,10 +1617,9 @@ public void testOverwriteTenantForRaceConditions() throws StorageQueryException, InterruptedException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1768,10 +1754,9 @@ null, null, new JsonObject() public void testThatStoragePointingToSameDbSharesThInstance() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1844,10 +1829,9 @@ public void testThatStoragePointingToSameDbSharesThInstance() throws Exception { public void testThatStorageIsClosedAfterTenantDeletion() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1889,10 +1873,9 @@ public void testThatStorageIsClosedAfterTenantDeletion() throws Exception { public void testThatStorageIsClosedOnlyWhenNoMoreTenantsArePointingToIt() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1947,10 +1930,9 @@ public void testThatStorageIsClosedOnlyWhenNoMoreTenantsArePointingToIt() throws public void testStorageDoesNotLoadAgainAfterTenantDeletionWhenRefreshedFromDb() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -2038,10 +2020,9 @@ public void testThatOriginalStorageIsNotClosedIfTheStorageForATenantChangesAndTh throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/multitenant/TestAppData.java b/src/test/java/io/supertokens/test/multitenant/TestAppData.java index ad3ac0230..3277321a0 100644 --- a/src/test/java/io/supertokens/test/multitenant/TestAppData.java +++ b/src/test/java/io/supertokens/test/multitenant/TestAppData.java @@ -82,6 +82,9 @@ public class TestAppData { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -111,7 +114,7 @@ private static String generateTotpCode(Main main, TOTPDevice device, int step) public void testThatDeletingAppDeleteDataFromAllTables() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY, EE_FEATURES.MFA}); diff --git a/src/test/java/io/supertokens/test/multitenant/api/GetTenantCoreConfigForDashboardAPITest.java b/src/test/java/io/supertokens/test/multitenant/api/GetTenantCoreConfigForDashboardAPITest.java index b1a600e11..ce4e9dd69 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/GetTenantCoreConfigForDashboardAPITest.java +++ b/src/test/java/io/supertokens/test/multitenant/api/GetTenantCoreConfigForDashboardAPITest.java @@ -28,6 +28,7 @@ import io.supertokens.test.TestingProcessManager; import io.supertokens.test.Utils; +import io.supertokens.test.httpRequest.HttpRequestForTesting; import org.junit.AfterClass; import org.junit.Before; import org.junit.Rule; @@ -48,6 +49,9 @@ public class GetTenantCoreConfigForDashboardAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -62,15 +66,17 @@ public void beforeEach() { public void testRetrievingConfigProperties() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } + int port = HttpRequestForTesting.corePort; + JsonObject response = HttpRequest.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/recipe/dashboard/tenant/core-config", null, + "http://localhost:" + port + "/recipe/dashboard/tenant/core-config", null, 1000, 1000, null); assertEquals(response.get("status").getAsString(), "OK"); @@ -115,7 +121,7 @@ public void testRetrievingConfigProperties() throws Exception { public void testMatchConfigPropertiesDescription() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); // access_token_signing_key_update_interval is an alias for @@ -173,6 +179,21 @@ private void matchYamlAndConfigDescriptions(String path, String[] ignoreProperti } propertyDescription = propertyDescription.trim(); + propertyDescriptions.put(propertyKey, propertyDescription); + } else if (lines[lines.length - 1].contains(": ") && ( + !lines[lines.length - 1].contains("Default:") && + !lines[lines.length - 1].contains("Important:") + )) { + String propertyKeyString = lines[lines.length - 1]; + String propertyKey = propertyKeyString.split(":")[0].trim(); + String propertyDescription = ""; + // Remove the comment "# " from the start and merge all the lines to form the + // description + for (int j = 0; j < lines.length - 1; j++) { + propertyDescription = propertyDescription + " " + lines[j].substring(2); + } + propertyDescription = propertyDescription.trim(); + propertyDescriptions.put(propertyKey, propertyDescription); } } diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestApp3_0.java b/src/test/java/io/supertokens/test/multitenant/api/TestApp3_0.java index e970010ee..44ba31cca 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestApp3_0.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestApp3_0.java @@ -44,10 +44,8 @@ import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.junit.rules.TestRule; import java.io.IOException; @@ -56,6 +54,9 @@ public class TestApp3_0 { TestingProcessManager.TestingProcess process; + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -75,7 +76,7 @@ public void beforeEach() throws InterruptedException, InvalidProviderConfigExcep String[] args = {"../"}; - this.process = TestingProcessManager.start(args); + this.process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); process.startProcess(); diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestApp5_0.java b/src/test/java/io/supertokens/test/multitenant/api/TestApp5_0.java index 7e6da758c..903779c34 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestApp5_0.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestApp5_0.java @@ -45,10 +45,8 @@ import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.junit.rules.TestRule; import java.io.IOException; import java.util.Set; @@ -58,6 +56,9 @@ public class TestApp5_0 { TestingProcessManager.TestingProcess process; + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -77,7 +78,7 @@ public void beforeEach() throws InterruptedException, InvalidProviderConfigExcep String[] args = {"../"}; - this.process = TestingProcessManager.start(args); + this.process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); process.startProcess(); diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestApp5_1.java b/src/test/java/io/supertokens/test/multitenant/api/TestApp5_1.java index 623ce71fc..771cbf087 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestApp5_1.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestApp5_1.java @@ -45,10 +45,8 @@ import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.junit.rules.TestRule; import java.io.IOException; import java.util.Set; @@ -58,6 +56,9 @@ public class TestApp5_1 { TestingProcessManager.TestingProcess process; + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -77,7 +78,7 @@ public void beforeEach() throws InterruptedException, InvalidProviderConfigExcep String[] args = {"../"}; - this.process = TestingProcessManager.start(args); + this.process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); process.startProcess(); diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain3_0.java b/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain3_0.java index 4418ebd30..5d1b147b9 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain3_0.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain3_0.java @@ -43,19 +43,19 @@ import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.junit.rules.TestRule; import java.io.IOException; -import java.util.Set; import static org.junit.Assert.*; public class TestConnectionUriDomain3_0 { TestingProcessManager.TestingProcess process; + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -75,7 +75,7 @@ public void beforeEach() throws InterruptedException, InvalidProviderConfigExcep String[] args = {"../"}; - this.process = TestingProcessManager.start(args); + this.process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); process.startProcess(); @@ -377,7 +377,7 @@ public void testDifferentValuesForCUDThatShouldWork() throws Exception { for (int i = 0; i < valueForCreate.length; i++) { String[] args = {"../"}; - this.process = TestingProcessManager.start(args); + this.process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); process.startProcess(); diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain5_0.java b/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain5_0.java index 186f8fafa..b51c891b0 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain5_0.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain5_0.java @@ -43,10 +43,8 @@ import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.junit.rules.TestRule; import java.io.IOException; import java.util.Set; @@ -56,6 +54,9 @@ public class TestConnectionUriDomain5_0 { TestingProcessManager.TestingProcess process; + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -75,7 +76,7 @@ public void beforeEach() throws InterruptedException, InvalidProviderConfigExcep String[] args = {"../"}; - this.process = TestingProcessManager.start(args); + this.process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); process.startProcess(); @@ -377,7 +378,7 @@ public void testDifferentValuesForCUDThatShouldWork() throws Exception { for (int i = 0; i < valueForCreate.length; i++) { String[] args = {"../"}; - this.process = TestingProcessManager.start(args); + this.process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); process.startProcess(); diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain5_1.java b/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain5_1.java index 087e0ae8e..9244a5753 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain5_1.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestConnectionUriDomain5_1.java @@ -43,10 +43,8 @@ import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.junit.rules.TestRule; import java.io.IOException; import java.util.Set; @@ -56,6 +54,9 @@ public class TestConnectionUriDomain5_1 { TestingProcessManager.TestingProcess process; + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -75,7 +76,7 @@ public void beforeEach() throws InterruptedException, InvalidProviderConfigExcep String[] args = {"../"}; - this.process = TestingProcessManager.start(args); + this.process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); process.startProcess(); @@ -362,7 +363,7 @@ public void testDifferentValuesForCUDThatShouldWork() throws Exception { for (int i = 0; i < valueForCreate.length; i++) { String[] args = {"../"}; - this.process = TestingProcessManager.start(args); + this.process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES .MULTI_TENANCY}); diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestLicenseBehaviour.java b/src/test/java/io/supertokens/test/multitenant/api/TestLicenseBehaviour.java index ffcfd7964..043b48940 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestLicenseBehaviour.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestLicenseBehaviour.java @@ -32,10 +32,8 @@ import io.supertokens.test.Utils; import io.supertokens.test.httpRequest.HttpResponseException; import io.supertokens.thirdparty.InvalidProviderConfigException; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.junit.rules.TestRule; import java.io.IOException; @@ -44,6 +42,9 @@ public class TestLicenseBehaviour { TestingProcessManager.TestingProcess process; + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -63,7 +64,7 @@ public void beforeEach() throws InterruptedException, InvalidProviderConfigExcep String[] args = {"../"}; - this.process = TestingProcessManager.start(args); + this.process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); } @@ -184,7 +185,7 @@ public void testThatCoreCanRestartWithAllTheTenantsWithoutLicenseKey() throws Ex assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); String[] args = {"../"}; - this.process = TestingProcessManager.start(args); + this.process = TestingProcessManager.startIsolatedProcess(args); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -327,7 +328,7 @@ public void testUpdationOfBaseTenantIsAllowedWithoutLicense() throws Exception { TestMultitenancyAPIHelper.removeLicense(process.getProcess()); JsonObject config = new JsonObject(); - TestMultitenancyAPIHelper.createConnectionUriDomain(process.main, new TenantIdentifier(null, null, null), null, + TestMultitenancyAPIHelper.createConnectionUriDomain(process.getProcess(), new TenantIdentifier(null, null, null), null, true, true, true, new JsonObject()); TestMultitenancyAPIHelper.addOrUpdateThirdPartyProviderConfig( new TenantIdentifier(null, null, null), diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestPermissionChecks.java b/src/test/java/io/supertokens/test/multitenant/api/TestPermissionChecks.java index 0538e2c63..ac33396ab 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestPermissionChecks.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestPermissionChecks.java @@ -43,6 +43,9 @@ public class TestPermissionChecks { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -110,10 +113,9 @@ public void testPermissionsForListConnectionUriDomains() throws Exception { Utils.reset(); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -180,10 +182,9 @@ public void testPermissionsForListApps() throws Exception { Utils.reset(); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -253,10 +254,9 @@ public void testPermissionsForListTenants() throws Exception { Utils.reset(); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -322,10 +322,9 @@ public void testPermissionsForCreateOrUpdateConnectionUriDomain() throws Excepti Utils.reset(); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -439,10 +438,9 @@ public void testValidConnectionUriDomains() throws Exception { Utils.reset(); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.isInMemDb(process.getProcess())) { @@ -578,10 +576,9 @@ public void testPermissionsForCreateOrUpdateApp() throws Exception { Utils.reset(); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -657,10 +654,9 @@ public void testValidationOfAppId() throws Exception { Utils.reset(); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -750,10 +746,9 @@ public void testPermissionsForCreateOrUpdateTenant() throws Exception { Utils.reset(); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -829,10 +824,9 @@ public void testValidationOfTenantId() throws Exception { Utils.reset(); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -893,10 +887,9 @@ public void testPermissionsForDeleteConnectionUriDomain() throws Exception { Utils.reset(); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -973,10 +966,9 @@ public void testPermissionsForDeleteApp() throws Exception { Utils.reset(); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -1085,10 +1077,9 @@ public void testPermissionsForDeleteTenant() throws Exception { Utils.reset(); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestSkipValidationInCreateThirdParty.java b/src/test/java/io/supertokens/test/multitenant/api/TestSkipValidationInCreateThirdParty.java index 4afd19185..f46c9b589 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestSkipValidationInCreateThirdParty.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestSkipValidationInCreateThirdParty.java @@ -39,6 +39,9 @@ public class TestSkipValidationInCreateThirdParty { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -53,10 +56,9 @@ public void beforeEach() { public void testSkipValidation() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestTenant3_0.java b/src/test/java/io/supertokens/test/multitenant/api/TestTenant3_0.java index 345a12c91..b326ea971 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestTenant3_0.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestTenant3_0.java @@ -41,10 +41,8 @@ import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.junit.rules.TestRule; import java.io.IOException; import java.util.Set; @@ -54,6 +52,9 @@ public class TestTenant3_0 { TestingProcessManager.TestingProcess process; + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -275,7 +276,7 @@ public boolean checkAPIKey(HttpServletRequest req) { @Override public String getPath() { - return "/get-tenant-id"; + return "/get-tenant-id-aaa"; } @Override @@ -307,7 +308,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IO new JsonObject()); String response = HttpRequestForTesting.sendGETRequest(process.getProcess(), "", - "http://localhost:3567/" + valueForQuery[i] + "/get-tenant-id", null, 1000, 1000, + "http://localhost:3567/" + valueForQuery[i] + "/get-tenant-id-aaa", null, 1000, 1000, null, WebserverAPI.getLatestCDIVersion().get(), null); assertEquals(valueForCreate[i].toLowerCase(), response); diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestTenant5_0.java b/src/test/java/io/supertokens/test/multitenant/api/TestTenant5_0.java index 32df2f0d0..b8c7cbde6 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestTenant5_0.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestTenant5_0.java @@ -43,10 +43,8 @@ import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.junit.rules.TestRule; import java.io.IOException; import java.util.Set; @@ -56,6 +54,9 @@ public class TestTenant5_0 { TestingProcessManager.TestingProcess process; + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestTenant5_1.java b/src/test/java/io/supertokens/test/multitenant/api/TestTenant5_1.java index 1ef07d4f2..7675cbb6a 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestTenant5_1.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestTenant5_1.java @@ -43,10 +43,8 @@ import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.junit.rules.TestRule; import java.io.IOException; import java.util.Set; @@ -56,6 +54,9 @@ public class TestTenant5_1 { TestingProcessManager.TestingProcess process; + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestTenantCreationAndRecipeEnabledChecksAcrossVersions.java b/src/test/java/io/supertokens/test/multitenant/api/TestTenantCreationAndRecipeEnabledChecksAcrossVersions.java index 8fb3720ae..5fe3b031a 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestTenantCreationAndRecipeEnabledChecksAcrossVersions.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestTenantCreationAndRecipeEnabledChecksAcrossVersions.java @@ -39,10 +39,8 @@ import io.supertokens.test.httpRequest.HttpResponseException; import io.supertokens.thirdparty.InvalidProviderConfigException; import io.supertokens.utils.SemVer; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.junit.rules.TestRule; import java.io.IOException; @@ -51,6 +49,9 @@ public class TestTenantCreationAndRecipeEnabledChecksAcrossVersions { TestingProcessManager.TestingProcess process; + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -70,7 +71,7 @@ public void beforeEach() throws InterruptedException, InvalidProviderConfigExcep String[] args = {"../"}; - this.process = TestingProcessManager.start(args); + this.process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); process.startProcess(); diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestTenantCreationBehaviour.java b/src/test/java/io/supertokens/test/multitenant/api/TestTenantCreationBehaviour.java index 8ddcb9f0b..98a7dbbab 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestTenantCreationBehaviour.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestTenantCreationBehaviour.java @@ -43,10 +43,8 @@ import io.supertokens.webserver.WebserverAPI; import io.supertokens.webserver.api.multitenancy.BaseCreateOrUpdate; import jakarta.servlet.ServletException; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.junit.rules.TestRule; import java.io.BufferedReader; import java.io.FileReader; @@ -60,6 +58,9 @@ public class TestTenantCreationBehaviour { TestingProcessManager.TestingProcess process; + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -79,7 +80,7 @@ public void beforeEach() throws InterruptedException, InvalidProviderConfigExcep String[] args = {"../"}; - this.process = TestingProcessManager.start(args); + this.process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); process.startProcess(); diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestTenantIdIsNotPresentForOlderCDI.java b/src/test/java/io/supertokens/test/multitenant/api/TestTenantIdIsNotPresentForOlderCDI.java index 8c97dd948..31fdca65f 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestTenantIdIsNotPresentForOlderCDI.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestTenantIdIsNotPresentForOlderCDI.java @@ -49,10 +49,8 @@ import io.supertokens.thirdparty.InvalidProviderConfigException; import io.supertokens.thirdparty.ThirdParty; import io.supertokens.utils.SemVer; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.junit.rules.TestRule; import java.io.IOException; import java.security.InvalidKeyException; @@ -65,6 +63,9 @@ public class TestTenantIdIsNotPresentForOlderCDI { TestingProcessManager.TestingProcess process; TenantIdentifier t1, t2, t3; + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestTenantUserAssociation.java b/src/test/java/io/supertokens/test/multitenant/api/TestTenantUserAssociation.java index a495687da..b014344ea 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestTenantUserAssociation.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestTenantUserAssociation.java @@ -48,10 +48,8 @@ import io.supertokens.test.httpRequest.HttpResponseException; import io.supertokens.thirdparty.InvalidProviderConfigException; import io.supertokens.thirdparty.ThirdParty; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.junit.rules.TestRule; import org.reflections.Reflections; import java.io.IOException; @@ -65,6 +63,9 @@ public class TestTenantUserAssociation { TestingProcessManager.TestingProcess process; + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -84,7 +85,7 @@ public void beforeEach() throws InterruptedException, InvalidProviderConfigExcep String[] args = {"../"}; - this.process = TestingProcessManager.start(args); + this.process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); process.startProcess(); @@ -219,7 +220,7 @@ public void testUserDisassociationForNotAuthRecipes() throws Exception { for (String className : classNames) { String userId = "userId"; - StorageLayer.getStorage(t2, process.main).addInfoToNonAuthRecipesBasedOnUserId(t2, className, userId); + StorageLayer.getStorage(t2, process.getProcess()).addInfoToNonAuthRecipesBasedOnUserId(t2, className, userId); JsonObject response = TestMultitenancyAPIHelper.disassociateUserFromTenant(t2, userId, process.getProcess()); diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestThirdPartyProvider.java b/src/test/java/io/supertokens/test/multitenant/api/TestThirdPartyProvider.java index 2c1e56c01..0eb5e3855 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestThirdPartyProvider.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestThirdPartyProvider.java @@ -35,10 +35,8 @@ import io.supertokens.test.TestingProcessManager; import io.supertokens.test.Utils; import io.supertokens.thirdparty.InvalidProviderConfigException; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.junit.rules.TestRule; import java.io.IOException; import java.util.HashMap; @@ -49,6 +47,9 @@ public class TestThirdPartyProvider { TestingProcessManager.TestingProcess process; + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/multitenant/api/TestWithNonAuthRecipes.java b/src/test/java/io/supertokens/test/multitenant/api/TestWithNonAuthRecipes.java index 8c403b05d..325702b82 100644 --- a/src/test/java/io/supertokens/test/multitenant/api/TestWithNonAuthRecipes.java +++ b/src/test/java/io/supertokens/test/multitenant/api/TestWithNonAuthRecipes.java @@ -44,10 +44,8 @@ import io.supertokens.thirdparty.InvalidProviderConfigException; import io.supertokens.useridmapping.UserIdMapping; import io.supertokens.utils.SemVer; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.junit.rules.TestRule; import java.io.IOException; import java.util.HashMap; @@ -58,6 +56,9 @@ public class TestWithNonAuthRecipes { TestingProcessManager.TestingProcess process; + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -77,7 +78,7 @@ public void beforeEach() throws InterruptedException, InvalidProviderConfigExcep String[] args = {"../"}; - this.process = TestingProcessManager.start(args); + this.process = TestingProcessManager.startIsolatedProcess(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MULTI_TENANCY}); process.startProcess(); diff --git a/src/test/java/io/supertokens/test/oauth/OAuthStorageTest.java b/src/test/java/io/supertokens/test/oauth/OAuthStorageTest.java index aff9f9b72..ed7523871 100644 --- a/src/test/java/io/supertokens/test/oauth/OAuthStorageTest.java +++ b/src/test/java/io/supertokens/test/oauth/OAuthStorageTest.java @@ -43,6 +43,9 @@ public class OAuthStorageTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -66,7 +69,7 @@ public void testClientCRUD() throws Exception { OAuthStorage storage = (OAuthStorage) StorageLayer.getStorage(process.getProcess()); - AppIdentifier appIdentifier = new AppIdentifier(null, null); + AppIdentifier appIdentifier = process.getAppForTesting().toAppIdentifier(); assertEquals(0, storage.getOAuthClients(appIdentifier, new ArrayList<>()).size()); // TODO fix me storage.addOrUpdateOauthClient(appIdentifier, "clientid1", "secret123", false, false); @@ -123,7 +126,7 @@ public void testLogoutChallenge() throws Exception { OAuthStorage storage = (OAuthStorage) StorageLayer.getStorage(process.getProcess()); - AppIdentifier appIdentifier = new AppIdentifier(null, null); + AppIdentifier appIdentifier = process.getAppForTesting().toAppIdentifier(); storage.addOrUpdateOauthClient(appIdentifier, "clientid", "secret123", false, false); @@ -174,7 +177,7 @@ public void testRevoke() throws Exception { OAuthStorage storage = (OAuthStorage) StorageLayer.getStorage(process.getProcess()); - AppIdentifier appIdentifier = new AppIdentifier(null, null); + AppIdentifier appIdentifier = process.getAppForTesting().toAppIdentifier(); storage.addOrUpdateOauthClient(appIdentifier, "clientid", "clientSecret", false, true); storage.createOrUpdateOAuthSession(appIdentifier, "abcd", "clientid", "externalRefreshToken", @@ -225,7 +228,7 @@ public void testM2MTokenAndStats() throws Exception { } OAuthStorage storage = (OAuthStorage) StorageLayer.getStorage(process.getProcess()); - AppIdentifier appIdentifier = new AppIdentifier(null, null); + AppIdentifier appIdentifier = process.getAppForTesting().toAppIdentifier(); long now = System.currentTimeMillis() / 1000; @@ -257,7 +260,7 @@ public void testConstraints() throws Exception { } OAuthStorage storage = (OAuthStorage) StorageLayer.getStorage(process.getProcess()); - AppIdentifier appIdentifier = new AppIdentifier(null, null); + AppIdentifier appIdentifier = process.getAppForTesting().toAppIdentifier(); storage.addOrUpdateOauthClient(appIdentifier, "clientid", "secret123", false, false); diff --git a/src/test/java/io/supertokens/test/oauth/api/OAuthAPIHelper.java b/src/test/java/io/supertokens/test/oauth/api/OAuthAPIHelper.java index 43ce47561..b1b21155e 100644 --- a/src/test/java/io/supertokens/test/oauth/api/OAuthAPIHelper.java +++ b/src/test/java/io/supertokens/test/oauth/api/OAuthAPIHelper.java @@ -16,38 +16,18 @@ package io.supertokens.test.oauth.api; -import com.google.gson.JsonElement; import com.google.gson.JsonObject; import io.supertokens.Main; -import io.supertokens.oauth.HttpRequestForOAuthProvider; import io.supertokens.test.httpRequest.HttpRequestForTesting; import io.supertokens.utils.SemVer; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; -import java.util.HashMap; import java.util.Map; public class OAuthAPIHelper { public static void resetOAuthProvider() { - try { - HttpRequestForOAuthProvider.Response clientsResponse = HttpRequestForOAuthProvider - .doGet("http://localhost:4445/admin/clients", new HashMap<>(), new HashMap<>()); - - for (JsonElement client : clientsResponse.jsonResponse.getAsJsonArray()) { - HttpRequestForOAuthProvider.doJsonDelete( - "http://localhost:4445/admin/clients/" - + client.getAsJsonObject().get("client_id").getAsString(), - new HashMap<>(), new HashMap<>(), new JsonObject()); - } - // We query these in an effort to help with possible warm up issues - HttpRequestForOAuthProvider.doGet("http://localhost:4444/.well-known/openid-configuration", new HashMap<>(), new HashMap<>()); - HttpRequestForOAuthProvider.doGet("http://localhost:4444/.well-known/jwks.json", new HashMap<>(), new HashMap<>()); - Thread.sleep(1000); - } catch (Exception e) { - //ignore error. later on the tests would fail anyway - } } public static JsonObject createClient(Main main, JsonObject createClientBody) throws Exception { diff --git a/src/test/java/io/supertokens/test/oauth/api/TestAuthCodeFlow.java b/src/test/java/io/supertokens/test/oauth/api/TestAuthCodeFlow.java index 841f69de8..efc90273b 100644 --- a/src/test/java/io/supertokens/test/oauth/api/TestAuthCodeFlow.java +++ b/src/test/java/io/supertokens/test/oauth/api/TestAuthCodeFlow.java @@ -47,6 +47,9 @@ public class TestAuthCodeFlow { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -62,21 +65,16 @@ public void beforeEach() { public void testAuthCodeGrantFlow() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlag.getInstance(process.main) + FeatureFlag.getInstance(process.getProcess()) .setLicenseKeyAndSyncFeatures(TotpLicenseTest.OPAQUE_KEY_WITH_MFA_FEATURE); - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.OAUTH}); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/oauth/api/TestClientCreate5_2.java b/src/test/java/io/supertokens/test/oauth/api/TestClientCreate5_2.java index a256fd981..16bb32bf3 100644 --- a/src/test/java/io/supertokens/test/oauth/api/TestClientCreate5_2.java +++ b/src/test/java/io/supertokens/test/oauth/api/TestClientCreate5_2.java @@ -39,12 +39,17 @@ import org.junit.Test; import org.junit.rules.TestRule; +import java.util.Random; + import static org.junit.Assert.*; public class TestClientCreate5_2 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -60,27 +65,23 @@ public void beforeEach() { public void testInvalidInputs() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlag.getInstance(process.main) + FeatureFlag.getInstance(process.getProcess()) .setLicenseKeyAndSyncFeatures(TotpLicenseTest.OPAQUE_KEY_WITH_MFA_FEATURE); - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.OAUTH}); { // Duplicate client id + String clientId = "test-client-id-" + new Random().nextInt(100000); JsonObject createBody = new JsonObject(); - createBody.addProperty("clientId", "test-client-id"); + createBody.addProperty("clientId", clientId); JsonObject resp = createClient(process.getProcess(), createBody); assertEquals("OK", resp.get("status").getAsString()); @@ -97,21 +98,16 @@ public void testInvalidInputs() throws Exception { public void testDefaultClientIdGeneration() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlag.getInstance(process.main) + FeatureFlag.getInstance(process.getProcess()) .setLicenseKeyAndSyncFeatures(TotpLicenseTest.OPAQUE_KEY_WITH_MFA_FEATURE); - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.OAUTH}); JsonObject createBody = new JsonObject(); @@ -131,21 +127,16 @@ public void testDefaultClientIdGeneration() throws Exception { public void testAllFields() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlag.getInstance(process.main) + FeatureFlag.getInstance(process.getProcess()) .setLicenseKeyAndSyncFeatures(TotpLicenseTest.OPAQUE_KEY_WITH_MFA_FEATURE); - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.OAUTH}); String[] FIELDS = new String[]{ @@ -214,7 +205,7 @@ public void testAllFields() throws Exception { metadata.addProperty("nonce", "test-nonce"); JsonElement[] VALUES = new JsonElement[]{ - new JsonPrimitive("test-client-id"), // clientId + new JsonPrimitive("test-client-id--" + new Random().nextInt(100000)), // clientId new JsonPrimitive("kEdQVPNLsl_FHOFBO_nWnj7P3."), // clientSecret new JsonPrimitive("Test Client"), // clientName new JsonPrimitive("offline_access offline openid"), // scope diff --git a/src/test/java/io/supertokens/test/oauth/api/TestClientDelete5_2.java b/src/test/java/io/supertokens/test/oauth/api/TestClientDelete5_2.java index 523ee699f..6028954ba 100644 --- a/src/test/java/io/supertokens/test/oauth/api/TestClientDelete5_2.java +++ b/src/test/java/io/supertokens/test/oauth/api/TestClientDelete5_2.java @@ -32,14 +32,12 @@ import io.supertokens.Main; import io.supertokens.ProcessState; import io.supertokens.featureflag.EE_FEATURES; -import io.supertokens.featureflag.FeatureFlag; import io.supertokens.featureflag.FeatureFlagTestContent; import io.supertokens.pluginInterface.STORAGE_TYPE; import io.supertokens.storageLayer.StorageLayer; import io.supertokens.test.TestingProcessManager; import io.supertokens.test.Utils; import io.supertokens.test.httpRequest.HttpRequestForTesting; -import io.supertokens.test.totp.TotpLicenseTest; import io.supertokens.utils.SemVer; import java.util.HashMap; @@ -50,6 +48,9 @@ public class TestClientDelete5_2 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -65,19 +66,14 @@ public void beforeEach() { public void testClientDelete() throws Exception { String[] args = { "../" }; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[] { EE_FEATURES.OAUTH }); Set clientIds = new HashSet<>(); @@ -107,19 +103,14 @@ public void testClientDelete() throws Exception { public void testClientDeleteWithInvalidClientId() throws Exception { String[] args = { "../" }; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[] { EE_FEATURES.OAUTH }); JsonObject resp = deleteClient(process.getProcess(), "non-existent-client-id"); diff --git a/src/test/java/io/supertokens/test/oauth/api/TestClientList5_2.java b/src/test/java/io/supertokens/test/oauth/api/TestClientList5_2.java index e94d878c4..5a0ed1c16 100644 --- a/src/test/java/io/supertokens/test/oauth/api/TestClientList5_2.java +++ b/src/test/java/io/supertokens/test/oauth/api/TestClientList5_2.java @@ -50,6 +50,9 @@ public class TestClientList5_2 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -65,19 +68,14 @@ public void beforeEach() { public void testClientList() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.OAUTH}); Set clientIds = new HashSet<>(); @@ -103,21 +101,16 @@ public void testClientList() throws Exception { public void testClientListWithPagination() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlag.getInstance(process.main) + FeatureFlag.getInstance(process.getProcess()) .setLicenseKeyAndSyncFeatures(TotpLicenseTest.OPAQUE_KEY_WITH_MFA_FEATURE); - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.OAUTH}); Set clientIds = new HashSet<>(); @@ -157,21 +150,16 @@ public void testClientListWithPagination() throws Exception { public void testClientListWithClientNameFilter() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlag.getInstance(process.main) + FeatureFlag.getInstance(process.getProcess()) .setLicenseKeyAndSyncFeatures(TotpLicenseTest.OPAQUE_KEY_WITH_MFA_FEATURE); - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.OAUTH}); Set clientIds = new HashSet<>(); diff --git a/src/test/java/io/supertokens/test/oauth/api/TestClientUpdate5_2.java b/src/test/java/io/supertokens/test/oauth/api/TestClientUpdate5_2.java index 50ac96d52..a0f2931f7 100644 --- a/src/test/java/io/supertokens/test/oauth/api/TestClientUpdate5_2.java +++ b/src/test/java/io/supertokens/test/oauth/api/TestClientUpdate5_2.java @@ -47,6 +47,9 @@ public class TestClientUpdate5_2 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -62,21 +65,16 @@ public void beforeEach() { public void testAllFields() throws Exception { String[] args = { "../" }; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlag.getInstance(process.main) + FeatureFlag.getInstance(process.getProcess()) .setLicenseKeyAndSyncFeatures(TotpLicenseTest.OPAQUE_KEY_WITH_MFA_FEATURE); - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[] { EE_FEATURES.OAUTH }); String[] FIELDS = new String[] { diff --git a/src/test/java/io/supertokens/test/oauth/api/TestImplicitFlow.java b/src/test/java/io/supertokens/test/oauth/api/TestImplicitFlow.java index 21e6a1133..e1751af3d 100644 --- a/src/test/java/io/supertokens/test/oauth/api/TestImplicitFlow.java +++ b/src/test/java/io/supertokens/test/oauth/api/TestImplicitFlow.java @@ -48,6 +48,9 @@ public class TestImplicitFlow { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -63,21 +66,16 @@ public void beforeEach() { public void testImplicitGrantFlow() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlag.getInstance(process.main) + FeatureFlag.getInstance(process.getProcess()) .setLicenseKeyAndSyncFeatures(TotpLicenseTest.OPAQUE_KEY_WITH_MFA_FEATURE); - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.OAUTH}); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/oauth/api/TestIssueTokens.java b/src/test/java/io/supertokens/test/oauth/api/TestIssueTokens.java index 2484ea4ee..d40434286 100644 --- a/src/test/java/io/supertokens/test/oauth/api/TestIssueTokens.java +++ b/src/test/java/io/supertokens/test/oauth/api/TestIssueTokens.java @@ -51,6 +51,9 @@ public class TestIssueTokens { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -66,19 +69,14 @@ public void beforeEach() { public void testAccessToken() throws Exception { String[] args = { "../" }; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[] { EE_FEATURES.OAUTH }); JsonObject client = createClient(process.getProcess()); diff --git a/src/test/java/io/supertokens/test/oauth/api/TestLoginRequest5_2.java b/src/test/java/io/supertokens/test/oauth/api/TestLoginRequest5_2.java index be54fc4ba..fd5cb8bd3 100644 --- a/src/test/java/io/supertokens/test/oauth/api/TestLoginRequest5_2.java +++ b/src/test/java/io/supertokens/test/oauth/api/TestLoginRequest5_2.java @@ -36,6 +36,9 @@ public class TestLoginRequest5_2 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -51,19 +54,14 @@ public void beforeEach() { public void testLoginRequestCreationAndGet() throws Exception { String[] args = { "../" }; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[] { EE_FEATURES.OAUTH }); JsonObject client = createClient(process.getProcess()); @@ -126,19 +124,14 @@ public void testLoginRequestCreationAndGet() throws Exception { public void testLoginRequestGetWithDeletedClient() throws Exception { String[] args = { "../" }; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[] { EE_FEATURES.OAUTH }); JsonObject client = createClient(process.getProcess()); @@ -179,19 +172,14 @@ public void testLoginRequestGetWithDeletedClient() throws Exception { public void testAcceptLoginRequest() throws Exception { String[] args = { "../" }; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[] { EE_FEATURES.OAUTH }); JsonObject client = createClient(process.getProcess()); @@ -251,19 +239,14 @@ public void testAcceptLoginRequest() throws Exception { public void testAcceptNonExistantLoginRequest() throws Exception { String[] args = { "../" }; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[] { EE_FEATURES.OAUTH }); JsonObject client = createClient(process.getProcess()); @@ -303,19 +286,14 @@ public void testAcceptNonExistantLoginRequest() throws Exception { public void testRejectLoginRequest() throws Exception { String[] args = { "../" }; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[] { EE_FEATURES.OAUTH }); JsonObject client = createClient(process.getProcess()); diff --git a/src/test/java/io/supertokens/test/oauth/api/TestRefreshTokenFlowWithTokenRotationOptions.java b/src/test/java/io/supertokens/test/oauth/api/TestRefreshTokenFlowWithTokenRotationOptions.java index 967862d1b..7993266fb 100644 --- a/src/test/java/io/supertokens/test/oauth/api/TestRefreshTokenFlowWithTokenRotationOptions.java +++ b/src/test/java/io/supertokens/test/oauth/api/TestRefreshTokenFlowWithTokenRotationOptions.java @@ -48,6 +48,9 @@ public class TestRefreshTokenFlowWithTokenRotationOptions { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -226,21 +229,16 @@ private static JsonObject refreshToken(Main main, JsonObject client, String refr public void testRefreshTokenWithRotationDisabled() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlag.getInstance(process.main) + FeatureFlag.getInstance(process.getProcess()) .setLicenseKeyAndSyncFeatures(TotpLicenseTest.OPAQUE_KEY_WITH_MFA_FEATURE); - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.OAUTH}); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -266,21 +264,16 @@ public void testRefreshTokenWithRotationDisabled() throws Exception { public void testRefreshTokenWithRotationEnabled() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlag.getInstance(process.main) + FeatureFlag.getInstance(process.getProcess()) .setLicenseKeyAndSyncFeatures(TotpLicenseTest.OPAQUE_KEY_WITH_MFA_FEATURE); - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.OAUTH}); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -312,21 +305,16 @@ public void testRefreshTokenWithRotationEnabled() throws Exception { public void testRefreshTokenWhenRotationIsEnabledAfter() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlag.getInstance(process.main) + FeatureFlag.getInstance(process.getProcess()) .setLicenseKeyAndSyncFeatures(TotpLicenseTest.OPAQUE_KEY_WITH_MFA_FEATURE); - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.OAUTH}); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -364,21 +352,16 @@ public void testRefreshTokenWhenRotationIsEnabledAfter() throws Exception { public void testRefreshTokenWithRotationIsDisabledAfter() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlag.getInstance(process.main) + FeatureFlag.getInstance(process.getProcess()) .setLicenseKeyAndSyncFeatures(TotpLicenseTest.OPAQUE_KEY_WITH_MFA_FEATURE); - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.OAUTH}); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/oauth/api/TestRevoke5_2.java b/src/test/java/io/supertokens/test/oauth/api/TestRevoke5_2.java index c0eece257..f4368e3d0 100644 --- a/src/test/java/io/supertokens/test/oauth/api/TestRevoke5_2.java +++ b/src/test/java/io/supertokens/test/oauth/api/TestRevoke5_2.java @@ -34,6 +34,9 @@ public class TestRevoke5_2 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -49,19 +52,14 @@ public void beforeEach() { public void testRevokeAccessToken() throws Exception { String[] args = { "../" }; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[] { EE_FEATURES.OAUTH }); JsonObject client = createClient(process.getProcess()); @@ -94,19 +92,14 @@ public void testRevokeAccessToken() throws Exception { public void testRevokeRefreshToken() throws Exception { String[] args = { "../" }; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[] { EE_FEATURES.OAUTH }); JsonObject client = createClient(process.getProcess()); @@ -149,19 +142,14 @@ public void testRevokeRefreshToken() throws Exception { public void testRevokeClientId() throws Exception { String[] args = { "../" }; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[] { EE_FEATURES.OAUTH }); JsonObject client = createClient(process.getProcess()); @@ -231,19 +219,14 @@ private JsonObject revokeClientId(Main process, JsonObject client) throws Except public void testRevokeSessionHandle() throws Exception { String[] args = { "../" }; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); - Utils.setValueInConfig("oauth_provider_public_service_url", "http://localhost:4444"); - Utils.setValueInConfig("oauth_provider_admin_service_url", "http://localhost:4445"); - Utils.setValueInConfig("oauth_provider_consent_login_base_url", "http://localhost:3001/auth"); - Utils.setValueInConfig("oauth_client_secret_encryption_key", "secret"); - process.startProcess(); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[] { EE_FEATURES.OAUTH }); JsonObject client = createClient(process.getProcess()); diff --git a/src/test/java/io/supertokens/test/passwordless/DeleteExpiredPasswordlessDevicesTest.java b/src/test/java/io/supertokens/test/passwordless/DeleteExpiredPasswordlessDevicesTest.java index ab41e5cf0..0d32624bc 100644 --- a/src/test/java/io/supertokens/test/passwordless/DeleteExpiredPasswordlessDevicesTest.java +++ b/src/test/java/io/supertokens/test/passwordless/DeleteExpiredPasswordlessDevicesTest.java @@ -21,7 +21,6 @@ import io.supertokens.cronjobs.CronTaskTest; import io.supertokens.cronjobs.deleteExpiredPasswordlessDevices.DeleteExpiredPasswordlessDevices; import io.supertokens.pluginInterface.STORAGE_TYPE; -import io.supertokens.pluginInterface.multitenancy.TenantIdentifier; import io.supertokens.pluginInterface.passwordless.PasswordlessCode; import io.supertokens.pluginInterface.passwordless.PasswordlessStorage; import io.supertokens.storageLayer.StorageLayer; @@ -40,6 +39,9 @@ public class DeleteExpiredPasswordlessDevicesTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -54,7 +56,7 @@ public void beforeEach() { public void jobDeletesDevicesWithOnlyExpiredCodesTest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); CronTaskTest.getInstance(process.getProcess()) .setIntervalInSeconds(DeleteExpiredPasswordlessDevices.RESOURCE_KEY, 1); process.startProcess(); @@ -71,13 +73,13 @@ public void jobDeletesDevicesWithOnlyExpiredCodesTest() throws Exception { String codeId = "deletedCode"; String deviceIdHash = "deviceIdHash"; - passwordlessStorage.createDeviceWithCode(new TenantIdentifier(null, null, null), "test@example.com", null, + passwordlessStorage.createDeviceWithCode(process.getAppForTesting(), "test@example.com", null, "linkCodeSalt", new PasswordlessCode(codeId, deviceIdHash, "linkCodeHash", System.currentTimeMillis() - codeLifetime)); Thread.sleep(1500); - assertNull(passwordlessStorage.getDevice(new TenantIdentifier(null, null, null), deviceIdHash)); + assertNull(passwordlessStorage.getDevice(process.getAppForTesting(), deviceIdHash)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -104,16 +106,16 @@ public void jobKeepsDevicesWithActiveCodesTest() throws Exception { String codeId = "expiredCode"; String deviceIdHash = "deviceIdHash"; - passwordlessStorage.createDeviceWithCode(new TenantIdentifier(null, null, null), "test@example.com", null, + passwordlessStorage.createDeviceWithCode(process.getAppForTesting(), "test@example.com", null, "linkCodeSalt", new PasswordlessCode(codeId, deviceIdHash, "linkCodeHash", System.currentTimeMillis() - codeLifetime)); passwordlessStorage - .createCode(new TenantIdentifier(null, null, null), + .createCode(process.getAppForTesting(), new PasswordlessCode("id", deviceIdHash, "linkCodeHash2", System.currentTimeMillis())); Thread.sleep(1500); - assertNotNull(passwordlessStorage.getDevice(new TenantIdentifier(null, null, null), deviceIdHash)); + assertNotNull(passwordlessStorage.getDevice(process.getAppForTesting(), deviceIdHash)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); diff --git a/src/test/java/io/supertokens/test/passwordless/PasswordlessConsumeCodeTest.java b/src/test/java/io/supertokens/test/passwordless/PasswordlessConsumeCodeTest.java index 1f91a0b07..8a957a278 100644 --- a/src/test/java/io/supertokens/test/passwordless/PasswordlessConsumeCodeTest.java +++ b/src/test/java/io/supertokens/test/passwordless/PasswordlessConsumeCodeTest.java @@ -27,7 +27,6 @@ import io.supertokens.pluginInterface.authRecipe.AuthRecipeUserInfo; import io.supertokens.pluginInterface.exceptions.StorageQueryException; import io.supertokens.pluginInterface.multitenancy.AppIdentifier; -import io.supertokens.pluginInterface.multitenancy.TenantIdentifier; import io.supertokens.pluginInterface.passwordless.PasswordlessDevice; import io.supertokens.pluginInterface.passwordless.PasswordlessStorage; import io.supertokens.storageLayer.StorageLayer; @@ -51,6 +50,9 @@ public class PasswordlessConsumeCodeTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -87,9 +89,9 @@ public void testConsumeLinkCode() throws Exception { Passwordless.ConsumeCodeResponse consumeCodeResponse = Passwordless.consumeCode(process.getProcess(), null, createCodeResponse.deviceIdHash, null, createCodeResponse.linkCode); assertNotNull(consumeCodeResponse); - checkUserWithConsumeResponse(storage, consumeCodeResponse, EMAIL, null, consumeStart); + checkUserWithConsumeResponse(process, storage, consumeCodeResponse, EMAIL, null, consumeStart); - PasswordlessDevice[] devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + PasswordlessDevice[] devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertEquals(0, devices.length); process.kill(); @@ -126,9 +128,9 @@ public void testConsumeLinkCodeWithoutEqualSigns() throws Exception { createCodeResponse.deviceIdHash, null, createCodeResponse.linkCode); assertNotNull(consumeCodeResponse); - checkUserWithConsumeResponse(storage, consumeCodeResponse, EMAIL, null, consumeStart); + checkUserWithConsumeResponse(process, storage, consumeCodeResponse, EMAIL, null, consumeStart); - PasswordlessDevice[] devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + PasswordlessDevice[] devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertEquals(0, devices.length); process.kill(); @@ -162,9 +164,9 @@ public void testConsumeLinkCodeWithEqualSigns() throws Exception { createCodeResponse.deviceIdHash + "=", null, createCodeResponse.linkCode + "="); assertNotNull(consumeCodeResponse); - checkUserWithConsumeResponse(storage, consumeCodeResponse, EMAIL, null, consumeStart); + checkUserWithConsumeResponse(process, storage, consumeCodeResponse, EMAIL, null, consumeStart); - PasswordlessDevice[] devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + PasswordlessDevice[] devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertEquals(0, devices.length); process.kill(); @@ -198,9 +200,9 @@ public void testConsumeUserInputCode() throws Exception { createCodeResponse.deviceId, createCodeResponse.deviceIdHash, createCodeResponse.userInputCode, null); assertNotNull(consumeCodeResponse); assert (consumeCodeResponse.createdNewUser); - checkUserWithConsumeResponse(storage, consumeCodeResponse, EMAIL, null, consumeStart); + checkUserWithConsumeResponse(process, storage, consumeCodeResponse, EMAIL, null, consumeStart); - PasswordlessDevice[] devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + PasswordlessDevice[] devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertEquals(0, devices.length); process.kill(); @@ -236,7 +238,7 @@ public void testConsumeUserInputCodeWithExistingUser() throws Exception { createCodeResponse.deviceId, createCodeResponse.deviceIdHash, createCodeResponse.userInputCode, null); assertNotNull(consumeCodeResponse); - user = checkUserWithConsumeResponse(storage, consumeCodeResponse, EMAIL, null, consumeStart); + user = checkUserWithConsumeResponse(process, storage, consumeCodeResponse, EMAIL, null, consumeStart); } { Passwordless.CreateCodeResponse createCodeResponse = Passwordless.createCode(process.getProcess(), EMAIL, @@ -248,12 +250,12 @@ public void testConsumeUserInputCodeWithExistingUser() throws Exception { null); assertNotNull(consumeCodeResponse); assert (!consumeCodeResponse.createdNewUser); - AuthRecipeUserInfo user2 = checkUserWithConsumeResponse(storage, consumeCodeResponse, EMAIL, null, 0); + AuthRecipeUserInfo user2 = checkUserWithConsumeResponse(process, storage, consumeCodeResponse, EMAIL, null, 0); assert (user.equals(user2)); } - PasswordlessDevice[] devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + PasswordlessDevice[] devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertEquals(0, devices.length); process.kill(); @@ -288,7 +290,7 @@ public void testConsumeLinkCodeWithExistingUser() throws Exception { Passwordless.ConsumeCodeResponse consumeCodeResponse = Passwordless.consumeCode(process.getProcess(), createCodeResponse.deviceId, createCodeResponse.deviceIdHash, null, createCodeResponse.linkCode); assertNotNull(consumeCodeResponse); - user = checkUserWithConsumeResponse(storage, consumeCodeResponse, EMAIL, null, consumeStart); + user = checkUserWithConsumeResponse(process, storage, consumeCodeResponse, EMAIL, null, consumeStart); } { Passwordless.CreateCodeResponse createCodeResponse = Passwordless.createCode(process.getProcess(), EMAIL, @@ -299,12 +301,12 @@ public void testConsumeLinkCodeWithExistingUser() throws Exception { createCodeResponse.deviceId, createCodeResponse.deviceIdHash, null, createCodeResponse.linkCode); assertNotNull(consumeCodeResponse); assert (!consumeCodeResponse.createdNewUser); - AuthRecipeUserInfo user2 = checkUserWithConsumeResponse(storage, consumeCodeResponse, EMAIL, null, 0); + AuthRecipeUserInfo user2 = checkUserWithConsumeResponse(process, storage, consumeCodeResponse, EMAIL, null, 0); assert (user.equals(user2)); } - PasswordlessDevice[] devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + PasswordlessDevice[] devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertEquals(0, devices.length); process.kill(); @@ -340,11 +342,11 @@ public void testConsumeCodeCleanupUserInputCodeWithEmailAndPhoneNumber() throws createCodeResponse.deviceId, createCodeResponse.deviceIdHash, createCodeResponse.userInputCode, null); assertNotNull(consumeCodeResponse); - AuthRecipeUserInfo authUser = storage.getPrimaryUserById(new AppIdentifier(null, null), + AuthRecipeUserInfo authUser = storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), consumeCodeResponse.user.getSupertokensUserId()); Passwordless.updateUser(process.getProcess(), authUser.getSupertokensUserId(), null, new Passwordless.FieldUpdate(PHONE_NUMBER)); - authUser = storage.getPrimaryUserById(new AppIdentifier(null, null), + authUser = storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), consumeCodeResponse.user.getSupertokensUserId()); assertEquals(authUser.loginMethods[0].phoneNumber, PHONE_NUMBER); @@ -368,21 +370,21 @@ public void testConsumeCodeCleanupUserInputCodeWithEmailAndPhoneNumber() throws null, null); // 4 codes should be available - PasswordlessDevice[] devices = storage.getDevicesByPhoneNumber(new TenantIdentifier(null, null, null), + PasswordlessDevice[] devices = storage.getDevicesByPhoneNumber(process.getAppForTesting(), PHONE_NUMBER); assertEquals(2, devices.length); - devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertEquals(2, devices.length); // consume code Passwordless.consumeCode(process.getProcess(), codeResponse.deviceId, codeResponse.deviceIdHash, codeResponse.userInputCode, null); - devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertEquals(0, devices.length); - devices = storage.getDevicesByPhoneNumber(new TenantIdentifier(null, null, null), PHONE_NUMBER); + devices = storage.getDevicesByPhoneNumber(process.getAppForTesting(), PHONE_NUMBER); assertEquals(0, devices.length); process.kill(); @@ -417,11 +419,11 @@ public void testConsumeCodeCleanupLinkCodeWithEmailAndPhoneNumber() throws Excep createCodeResponse.deviceId, createCodeResponse.deviceIdHash, createCodeResponse.userInputCode, null); assertNotNull(consumeCodeResponse); - AuthRecipeUserInfo authUser = storage.getPrimaryUserById(new AppIdentifier(null, null), + AuthRecipeUserInfo authUser = storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), consumeCodeResponse.user.getSupertokensUserId()); Passwordless.updateUser(process.getProcess(), authUser.getSupertokensUserId(), null, new Passwordless.FieldUpdate(PHONE_NUMBER)); - authUser = storage.getPrimaryUserById(new AppIdentifier(null, null), + authUser = storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), consumeCodeResponse.user.getSupertokensUserId()); assertEquals(authUser.loginMethods[0].phoneNumber, PHONE_NUMBER); @@ -445,21 +447,21 @@ public void testConsumeCodeCleanupLinkCodeWithEmailAndPhoneNumber() throws Excep null, null); // 4 codes should be available - PasswordlessDevice[] devices = storage.getDevicesByPhoneNumber(new TenantIdentifier(null, null, null), + PasswordlessDevice[] devices = storage.getDevicesByPhoneNumber(process.getAppForTesting(), PHONE_NUMBER); assertEquals(2, devices.length); - devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertEquals(2, devices.length); // consume code Passwordless.consumeCode(process.getProcess(), codeResponse.deviceId, codeResponse.deviceIdHash, null, codeResponse.linkCode); - devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertEquals(0, devices.length); - devices = storage.getDevicesByPhoneNumber(new TenantIdentifier(null, null, null), PHONE_NUMBER); + devices = storage.getDevicesByPhoneNumber(process.getAppForTesting(), PHONE_NUMBER); assertEquals(0, devices.length); process.kill(); @@ -498,7 +500,7 @@ public void testConsumeMalformedLinkCode() throws Exception { assertNotNull(error); assert (error instanceof Base64EncodingException); - PasswordlessDevice[] devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + PasswordlessDevice[] devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertNotEquals(0, devices.length); process.kill(); @@ -540,7 +542,7 @@ public void testConsumeNonExistingLinkCode() throws Exception { assert (error instanceof RestartFlowException); // verify that devices have not been cleared - PasswordlessDevice[] devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + PasswordlessDevice[] devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertNotEquals(0, devices.length); process.kill(); @@ -580,7 +582,7 @@ public void testConsumeWrongUserInputCode() throws Exception { assert (error instanceof IncorrectUserInputCodeException); // verify that devices have not been cleared - PasswordlessDevice[] devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + PasswordlessDevice[] devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertNotEquals(0, devices.length); process.kill(); @@ -622,7 +624,7 @@ public void testConsumeExpiredLinkCode() throws Exception { assert (error instanceof RestartFlowException); // verify that devices have not been cleared - PasswordlessDevice[] devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + PasswordlessDevice[] devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertNotEquals(0, devices.length); process.kill(); @@ -664,7 +666,7 @@ public void testConsumeExpiredUserInputCode() throws Exception { assert (error instanceof ExpiredUserInputCodeException); // verify that devices have not been cleared - PasswordlessDevice[] devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + PasswordlessDevice[] devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertNotEquals(0, devices.length); process.kill(); @@ -702,7 +704,7 @@ public void testConsumeExpiredUserInputCodeAfterResend() throws Exception { assert (error instanceof ExpiredUserInputCodeException); // verify that devices have not been cleared - PasswordlessDevice[] devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + PasswordlessDevice[] devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertNotEquals(0, devices.length); Passwordless.CreateCodeResponse newCodeResponse = Passwordless.createCode(process.getProcess(), null, null, @@ -764,7 +766,7 @@ public void testConsumeWrongUserInputCodeExceedingMaxAttempts() throws Exception assert (error instanceof RestartFlowException); // verify that devices have been cleared, since max attempt reached - PasswordlessDevice[] devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + PasswordlessDevice[] devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertEquals(0, devices.length); process.kill(); @@ -811,7 +813,7 @@ public void testConsumeWrongLinkCodeExceedingMaxAttempts() throws Exception { assert (error instanceof RestartFlowException); // verify that devices have not been cleared - PasswordlessDevice[] devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + PasswordlessDevice[] devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertNotEquals(0, devices.length); process.kill(); @@ -863,7 +865,7 @@ public void testConsumeWrongUserInputCodeExceedingMaxAttemptsWithConfigUpdate() } // verify that devices have not been cleared - PasswordlessDevice[] devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + PasswordlessDevice[] devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertNotEquals(0, devices.length); // kill process and restart with increased max code input attempts @@ -890,18 +892,18 @@ public void testConsumeWrongUserInputCodeExceedingMaxAttemptsWithConfigUpdate() assertNotNull(error); assert (error instanceof RestartFlowException); - devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertEquals(0, devices.length); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } - private AuthRecipeUserInfo checkUserWithConsumeResponse(PasswordlessStorage storage, + private AuthRecipeUserInfo checkUserWithConsumeResponse(TestingProcessManager.TestingProcess process, PasswordlessStorage storage, Passwordless.ConsumeCodeResponse resp, String email, String phoneNumber, long joinedAfter) throws StorageQueryException { - AuthRecipeUserInfo user = storage.getPrimaryUserById(new AppIdentifier(null, null), + AuthRecipeUserInfo user = storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), resp.user.getSupertokensUserId()); assertNotNull(user); diff --git a/src/test/java/io/supertokens/test/passwordless/PasswordlessCreateCodeTest.java b/src/test/java/io/supertokens/test/passwordless/PasswordlessCreateCodeTest.java index bf62094be..8caa521e0 100644 --- a/src/test/java/io/supertokens/test/passwordless/PasswordlessCreateCodeTest.java +++ b/src/test/java/io/supertokens/test/passwordless/PasswordlessCreateCodeTest.java @@ -47,6 +47,9 @@ public class PasswordlessCreateCodeTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -81,7 +84,7 @@ public void testCreateCodeWithEmail() throws Exception { assertNotNull(createCodeResponse); // verify single device created - PasswordlessDevice[] devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + PasswordlessDevice[] devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertEquals(1, devices.length); // device assertions @@ -92,7 +95,7 @@ public void testCreateCodeWithEmail() throws Exception { assertEquals(0, device.failedAttempts); // code assertions - PasswordlessCode[] codes = storage.getCodesOfDevice(new TenantIdentifier(null, null, null), + PasswordlessCode[] codes = storage.getCodesOfDevice(process.getAppForTesting(), device.deviceIdHash); assertEquals(1, codes.length); @@ -131,7 +134,7 @@ public void testCreateCodeForMultipleDevicesWithSingleEmail() throws Exception { assertNotNull(codeResponse); } - PasswordlessDevice[] devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + PasswordlessDevice[] devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertEquals(NUMBER_OF_DEVICES_TO_CREATE, devices.length); for (int counter = 0; counter < NUMBER_OF_DEVICES_TO_CREATE; counter++) { @@ -140,7 +143,7 @@ public void testCreateCodeForMultipleDevicesWithSingleEmail() throws Exception { assertNull(device.phoneNumber); assertEquals(0, device.failedAttempts); - PasswordlessCode[] codes = storage.getCodesOfDevice(new TenantIdentifier(null, null, null), + PasswordlessCode[] codes = storage.getCodesOfDevice(process.getAppForTesting(), device.deviceIdHash); assertEquals(1, codes.length); @@ -174,7 +177,7 @@ public void testCreateCodeWithPhoneNumber() throws Exception { PHONE_NUMBER, null, null); assertNotNull(createCodeResponse); - PasswordlessDevice[] devices = storage.getDevicesByPhoneNumber(new TenantIdentifier(null, null, null), + PasswordlessDevice[] devices = storage.getDevicesByPhoneNumber(process.getAppForTesting(), PHONE_NUMBER); assertEquals(1, devices.length); @@ -184,7 +187,7 @@ public void testCreateCodeWithPhoneNumber() throws Exception { assertEquals(PHONE_NUMBER, device.phoneNumber); assertEquals(0, device.failedAttempts); - PasswordlessCode[] codes = storage.getCodesOfDevice(new TenantIdentifier(null, null, null), + PasswordlessCode[] codes = storage.getCodesOfDevice(process.getAppForTesting(), device.deviceIdHash); assertEquals(1, codes.length); @@ -223,7 +226,7 @@ public void testCreateCodeForMultipleDevicesWithSinglePhoneNumber() throws Excep assertNotNull(codeResponse); } - PasswordlessDevice[] devices = storage.getDevicesByPhoneNumber(new TenantIdentifier(null, null, null), + PasswordlessDevice[] devices = storage.getDevicesByPhoneNumber(process.getAppForTesting(), PHONE_NUMBER); assertEquals(NUMBER_OF_DEVICES_TO_CREATE, devices.length); @@ -234,7 +237,7 @@ public void testCreateCodeForMultipleDevicesWithSinglePhoneNumber() throws Excep assertEquals(PHONE_NUMBER, device.phoneNumber); assertEquals(0, device.failedAttempts); - PasswordlessCode[] codes = storage.getCodesOfDevice(new TenantIdentifier(null, null, null), + PasswordlessCode[] codes = storage.getCodesOfDevice(process.getAppForTesting(), device.deviceIdHash); assertEquals(1, codes.length); @@ -271,7 +274,7 @@ public void testCreateCodeWithDeviceId() throws Exception { assertNotNull(resendCodeResponse); - PasswordlessDevice[] devices = storage.getDevicesByPhoneNumber(new TenantIdentifier(null, null, null), + PasswordlessDevice[] devices = storage.getDevicesByPhoneNumber(process.getAppForTesting(), PHONE_NUMBER); assertEquals(1, devices.length); @@ -281,7 +284,7 @@ public void testCreateCodeWithDeviceId() throws Exception { assertEquals(PHONE_NUMBER, device.phoneNumber); assertEquals(0, device.failedAttempts); - PasswordlessCode[] codes = storage.getCodesOfDevice(new TenantIdentifier(null, null, null), + PasswordlessCode[] codes = storage.getCodesOfDevice(process.getAppForTesting(), device.deviceIdHash); assertEquals(2, codes.length); diff --git a/src/test/java/io/supertokens/test/passwordless/PasswordlessDevicesTest.java b/src/test/java/io/supertokens/test/passwordless/PasswordlessDevicesTest.java index 9f317fe6f..5efb223b3 100644 --- a/src/test/java/io/supertokens/test/passwordless/PasswordlessDevicesTest.java +++ b/src/test/java/io/supertokens/test/passwordless/PasswordlessDevicesTest.java @@ -44,6 +44,9 @@ public class PasswordlessDevicesTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/passwordless/PasswordlessGetUserTest.java b/src/test/java/io/supertokens/test/passwordless/PasswordlessGetUserTest.java index b321509e1..6c86ab661 100644 --- a/src/test/java/io/supertokens/test/passwordless/PasswordlessGetUserTest.java +++ b/src/test/java/io/supertokens/test/passwordless/PasswordlessGetUserTest.java @@ -41,6 +41,9 @@ public class PasswordlessGetUserTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/passwordless/PasswordlessRemoveCodeTest.java b/src/test/java/io/supertokens/test/passwordless/PasswordlessRemoveCodeTest.java index 5c054aecb..9411af6fd 100644 --- a/src/test/java/io/supertokens/test/passwordless/PasswordlessRemoveCodeTest.java +++ b/src/test/java/io/supertokens/test/passwordless/PasswordlessRemoveCodeTest.java @@ -45,6 +45,9 @@ public class PasswordlessRemoveCodeTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -91,7 +94,7 @@ public void deleteCodeAndLeaveDevices() throws Exception { Passwordless.removeCode(process.getProcess(), createCodeResponse.codeId); - PasswordlessDevice[] devices = storage.getDevicesByPhoneNumber(new TenantIdentifier(null, null, null), + PasswordlessDevice[] devices = storage.getDevicesByPhoneNumber(process.getAppForTesting(), PHONE_NUMBER); for (int counter = 0; counter < devices.length; counter++) { @@ -104,7 +107,7 @@ public void deleteCodeAndLeaveDevices() throws Exception { assertEquals(PHONE_NUMBER, device.phoneNumber); assertEquals(0, device.failedAttempts); - PasswordlessCode[] codes = storage.getCodesOfDevice(new TenantIdentifier(null, null, null), + PasswordlessCode[] codes = storage.getCodesOfDevice(process.getAppForTesting(), device.deviceIdHash); assertEquals(NUMBER_OF_CODES_TO_GENERATE, codes.length); @@ -146,7 +149,7 @@ public void deleteCodeAndCleansDevice() throws Exception { Passwordless.removeCode(process.getProcess(), createCodeResponse.codeId); - PasswordlessDevice[] devices = storage.getDevicesByPhoneNumber(new TenantIdentifier(null, null, null), + PasswordlessDevice[] devices = storage.getDevicesByPhoneNumber(process.getAppForTesting(), PHONE_NUMBER); assertEquals(0, devices.length); @@ -180,11 +183,11 @@ public void doNothingIfCodeDoesNotExist() throws Exception { Passwordless.removeCode(process.getProcess(), "1234"); - PasswordlessDevice[] devices = storage.getDevicesByPhoneNumber(new TenantIdentifier(null, null, null), + PasswordlessDevice[] devices = storage.getDevicesByPhoneNumber(process.getAppForTesting(), PHONE_NUMBER); assertEquals(1, devices.length); - PasswordlessCode[] codes = storage.getCodesOfDevice(new TenantIdentifier(null, null, null), + PasswordlessCode[] codes = storage.getCodesOfDevice(process.getAppForTesting(), createCodeResponse.deviceIdHash); assertEquals(1, codes.length); @@ -227,13 +230,13 @@ public void removeDevicesFromEmail() throws Exception { Passwordless.removeCodesByEmail(process.getProcess(), EMAIL); - PasswordlessDevice[] devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), EMAIL); + PasswordlessDevice[] devices = storage.getDevicesByEmail(process.getAppForTesting(), EMAIL); assertEquals(0, devices.length); - devices = storage.getDevicesByEmail(new TenantIdentifier(null, null, null), alternate_email); + devices = storage.getDevicesByEmail(process.getAppForTesting(), alternate_email); assertEquals(1, devices.length); - PasswordlessCode[] codes = storage.getCodesOfDevice(new TenantIdentifier(null, null, null), + PasswordlessCode[] codes = storage.getCodesOfDevice(process.getAppForTesting(), devices[0].deviceIdHash); assertEquals(1, codes.length); @@ -276,14 +279,14 @@ public void removeDevicesFromPhoneNumber() throws Exception { Passwordless.removeCodesByPhoneNumber(process.getProcess(), PHONE_NUMBER); - PasswordlessDevice[] devices = storage.getDevicesByPhoneNumber(new TenantIdentifier(null, null, null), + PasswordlessDevice[] devices = storage.getDevicesByPhoneNumber(process.getAppForTesting(), PHONE_NUMBER); assertEquals(0, devices.length); - devices = storage.getDevicesByPhoneNumber(new TenantIdentifier(null, null, null), alternate_phoneNumber); + devices = storage.getDevicesByPhoneNumber(process.getAppForTesting(), alternate_phoneNumber); assertEquals(1, devices.length); - PasswordlessCode[] codes = storage.getCodesOfDevice(new TenantIdentifier(null, null, null), + PasswordlessCode[] codes = storage.getCodesOfDevice(process.getAppForTesting(), devices[0].deviceIdHash); assertEquals(1, codes.length); diff --git a/src/test/java/io/supertokens/test/passwordless/PasswordlessStorageTest.java b/src/test/java/io/supertokens/test/passwordless/PasswordlessStorageTest.java index 9257e741f..2676f92b3 100644 --- a/src/test/java/io/supertokens/test/passwordless/PasswordlessStorageTest.java +++ b/src/test/java/io/supertokens/test/passwordless/PasswordlessStorageTest.java @@ -24,8 +24,6 @@ import io.supertokens.pluginInterface.emailpassword.exceptions.UnknownUserIdException; import io.supertokens.pluginInterface.exceptions.StorageQueryException; import io.supertokens.pluginInterface.exceptions.StorageTransactionLogicException; -import io.supertokens.pluginInterface.multitenancy.AppIdentifier; -import io.supertokens.pluginInterface.multitenancy.TenantIdentifier; import io.supertokens.pluginInterface.passwordless.PasswordlessCode; import io.supertokens.pluginInterface.passwordless.exception.*; import io.supertokens.pluginInterface.passwordless.sqlStorage.PasswordlessSQLStorage; @@ -50,6 +48,9 @@ public class PasswordlessStorageTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -77,13 +78,13 @@ public void testCreateDeviceWithCodeExceptions() throws Exception { PasswordlessCode code1 = getRandomCodeInfo(); PasswordlessCode code2 = getRandomCodeInfo(); - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), email, null, "linkCodeSalt", code1); - assertEquals(1, storage.getDevicesByEmail(new TenantIdentifier(null, null, null), email).length); + storage.createDeviceWithCode(process.getAppForTesting(), email, null, "linkCodeSalt", code1); + assertEquals(1, storage.getDevicesByEmail(process.getAppForTesting(), email).length); { Exception error = null; try { - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), email, null, "linkCodeSalt", + storage.createDeviceWithCode(process.getAppForTesting(), email, null, "linkCodeSalt", new PasswordlessCode(code1.id, code2.deviceIdHash, code2.linkCodeHash, System.currentTimeMillis())); } catch (Exception e) { @@ -92,16 +93,16 @@ public void testCreateDeviceWithCodeExceptions() throws Exception { assertNotNull(error); assert (error instanceof DuplicateCodeIdException); - assertEquals(1, storage.getDevicesByEmail(new TenantIdentifier(null, null, null), email).length); + assertEquals(1, storage.getDevicesByEmail(process.getAppForTesting(), email).length); assertEquals(1, - storage.getCodesOfDevice(new TenantIdentifier(null, null, null), code1.deviceIdHash).length); - assertNull(storage.getDevice(new TenantIdentifier(null, null, null), code2.deviceIdHash)); + storage.getCodesOfDevice(process.getAppForTesting(), code1.deviceIdHash).length); + assertNull(storage.getDevice(process.getAppForTesting(), code2.deviceIdHash)); } { Exception error = null; try { - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), email, null, "linkCodeSalt", + storage.createDeviceWithCode(process.getAppForTesting(), email, null, "linkCodeSalt", new PasswordlessCode(code2.id, code1.deviceIdHash, code2.linkCodeHash, System.currentTimeMillis())); } catch (Exception e) { @@ -110,15 +111,15 @@ public void testCreateDeviceWithCodeExceptions() throws Exception { assertNotNull(error); assert (error instanceof DuplicateDeviceIdHashException); - assertEquals(1, storage.getDevicesByEmail(new TenantIdentifier(null, null, null), email).length); + assertEquals(1, storage.getDevicesByEmail(process.getAppForTesting(), email).length); assertEquals(1, - storage.getCodesOfDevice(new TenantIdentifier(null, null, null), code1.deviceIdHash).length); + storage.getCodesOfDevice(process.getAppForTesting(), code1.deviceIdHash).length); } { Exception error = null; try { - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), email, null, "linkCodeSalt", + storage.createDeviceWithCode(process.getAppForTesting(), email, null, "linkCodeSalt", new PasswordlessCode(code2.id, code2.deviceIdHash, code1.linkCodeHash, System.currentTimeMillis())); } catch (Exception e) { @@ -127,26 +128,26 @@ public void testCreateDeviceWithCodeExceptions() throws Exception { assertNotNull(error); assert (error instanceof DuplicateLinkCodeHashException); - assertEquals(1, storage.getDevicesByEmail(new TenantIdentifier(null, null, null), email).length); - assertNull(storage.getDevice(new TenantIdentifier(null, null, null), code2.deviceIdHash)); + assertEquals(1, storage.getDevicesByEmail(process.getAppForTesting(), email).length); + assertNull(storage.getDevice(process.getAppForTesting(), code2.deviceIdHash)); } { Exception error = null; try { - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), null, null, "linkCodeSalt", code2); + storage.createDeviceWithCode(process.getAppForTesting(), null, null, "linkCodeSalt", code2); } catch (Exception e) { error = e; } assertNotNull(error); assert (error instanceof IllegalArgumentException); - assertNull(storage.getDevice(new TenantIdentifier(null, null, null), code2.deviceIdHash)); + assertNull(storage.getDevice(process.getAppForTesting(), code2.deviceIdHash)); } - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), email, null, "linkCodeSalt", code2); + storage.createDeviceWithCode(process.getAppForTesting(), email, null, "linkCodeSalt", code2); - assertEquals(2, storage.getDevicesByEmail(new TenantIdentifier(null, null, null), email).length); + assertEquals(2, storage.getDevicesByEmail(process.getAppForTesting(), email).length); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -172,7 +173,7 @@ public void testCreateCodeExceptions() throws Exception { { Exception error = null; try { - storage.createCode(new TenantIdentifier(null, null, null), + storage.createCode(process.getAppForTesting(), new PasswordlessCode(code1.id, code1.deviceIdHash, code1.linkCodeHash, System.currentTimeMillis())); } catch (Exception e) { @@ -181,17 +182,17 @@ public void testCreateCodeExceptions() throws Exception { assertNotNull(error); assert (error instanceof UnknownDeviceIdHash); - assertEquals(0, storage.getDevicesByEmail(new TenantIdentifier(null, null, null), email).length); - assertNull(storage.getCode(new TenantIdentifier(null, null, null), code1.id)); + assertEquals(0, storage.getDevicesByEmail(process.getAppForTesting(), email).length); + assertNull(storage.getCode(process.getAppForTesting(), code1.id)); } - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), email, null, "linkCodeSalt", code1); - assertEquals(1, storage.getDevicesByEmail(new TenantIdentifier(null, null, null), email).length); + storage.createDeviceWithCode(process.getAppForTesting(), email, null, "linkCodeSalt", code1); + assertEquals(1, storage.getDevicesByEmail(process.getAppForTesting(), email).length); { Exception error = null; try { - storage.createCode(new TenantIdentifier(null, null, null), + storage.createCode(process.getAppForTesting(), new PasswordlessCode(code1.id, code1.deviceIdHash, code2.linkCodeHash, System.currentTimeMillis())); } catch (Exception e) { @@ -201,13 +202,13 @@ public void testCreateCodeExceptions() throws Exception { assertNotNull(error); assert (error instanceof DuplicateCodeIdException); assertEquals(1, - storage.getCodesOfDevice(new TenantIdentifier(null, null, null), code1.deviceIdHash).length); + storage.getCodesOfDevice(process.getAppForTesting(), code1.deviceIdHash).length); } { Exception error = null; try { - storage.createCode(new TenantIdentifier(null, null, null), + storage.createCode(process.getAppForTesting(), new PasswordlessCode(code2.id, code1.deviceIdHash, code1.linkCodeHash, System.currentTimeMillis())); } catch (Exception e) { @@ -217,13 +218,13 @@ public void testCreateCodeExceptions() throws Exception { assertNotNull(error); assert (error instanceof DuplicateLinkCodeHashException); assertEquals(1, - storage.getCodesOfDevice(new TenantIdentifier(null, null, null), code1.deviceIdHash).length); - assertNull(storage.getCode(new TenantIdentifier(null, null, null), code2.id)); + storage.getCodesOfDevice(process.getAppForTesting(), code1.deviceIdHash).length); + assertNull(storage.getCode(process.getAppForTesting(), code2.id)); } - storage.createCode(new TenantIdentifier(null, null, null), code2); + storage.createCode(process.getAppForTesting(), code2); - assertEquals(2, storage.getCodesOfDevice(new TenantIdentifier(null, null, null), code1.deviceIdHash).length); + assertEquals(2, storage.getCodesOfDevice(process.getAppForTesting(), code1.deviceIdHash).length); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -254,15 +255,15 @@ public void testCreateUserExceptions() throws Exception { long timeJoined = System.currentTimeMillis(); - storage.createUser(new TenantIdentifier(null, null, null), userId, email, null, timeJoined); - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userId, email, null, timeJoined); + storage.createUser(process.getAppForTesting(), userId2, null, phoneNumber, timeJoined); - assertNotNull(storage.getPrimaryUserById(new AppIdentifier(null, null), userId)); + assertNotNull(storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), userId)); { Exception error = null; try { - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userId, email2, null, timeJoined); } catch (Exception e) { error = e; @@ -270,13 +271,13 @@ public void testCreateUserExceptions() throws Exception { assertNotNull(error); assert (error instanceof DuplicateUserIdException); - assertEquals(0, storage.listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), email2).length); + assertEquals(0, storage.listPrimaryUsersByEmail(process.getAppForTesting(), email2).length); } { Exception error = null; try { - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userId, null, phoneNumber2, timeJoined); } catch (Exception e) { error = e; @@ -284,14 +285,14 @@ public void testCreateUserExceptions() throws Exception { assertNotNull(error); assert (error instanceof DuplicateUserIdException); - assert (storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), + assert (storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), phoneNumber2).length == 0); } { Exception error = null; try { - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userId3, email, null, timeJoined); } catch (Exception e) { error = e; @@ -299,13 +300,13 @@ public void testCreateUserExceptions() throws Exception { assertNotNull(error); assert (error instanceof DuplicateEmailException); - assertNull(storage.getPrimaryUserById(new AppIdentifier(null, null), userId3)); + assertNull(storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), userId3)); } { Exception error = null; try { - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userId3, null, phoneNumber, timeJoined); } catch (Exception e) { error = e; @@ -313,13 +314,13 @@ public void testCreateUserExceptions() throws Exception { assertNotNull(error); assert (error instanceof DuplicatePhoneNumberException); - assertNull(storage.getPrimaryUserById(new AppIdentifier(null, null), userId3)); + assertNull(storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), userId3)); } { Exception error = null; try { - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userId3, null, null, timeJoined); } catch (Exception e) { error = e; @@ -327,7 +328,7 @@ public void testCreateUserExceptions() throws Exception { assertNotNull(error); assert (error instanceof IllegalArgumentException); - assertNull(storage.getPrimaryUserById(new AppIdentifier(null, null), userId3)); + assertNull(storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), userId3)); } process.kill(); @@ -363,22 +364,22 @@ public void testUpdateUserExceptions() throws Exception { long timeJoined = System.currentTimeMillis(); - storage.createUser(new TenantIdentifier(null, null, null), userIdEmail1, email, null, timeJoined); - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userIdEmail1, email, null, timeJoined); + storage.createUser(process.getAppForTesting(), userIdEmail2, email2, null, timeJoined); - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userIdPhone1, null, phoneNumber, timeJoined); - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userIdPhone2, null, phoneNumber2, timeJoined); - assertNotNull(storage.getPrimaryUserById(new AppIdentifier(null, null), userIdEmail1)); + assertNotNull(storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), userIdEmail1)); { Exception error = null; try { storage.startTransaction(con -> { try { - storage.updateUserEmail_Transaction(new AppIdentifier(null, null), con, userIdNotExists, + storage.updateUserEmail_Transaction(process.getAppForTesting().toAppIdentifier(), con, userIdNotExists, email3); } catch (UnknownUserIdException | DuplicateEmailException e) { throw new StorageTransactionLogicException(e); @@ -392,7 +393,7 @@ public void testUpdateUserExceptions() throws Exception { assertNotNull(error); assert (error instanceof UnknownUserIdException); - assertNull(storage.getPrimaryUserById(new AppIdentifier(null, null), userIdNotExists)); + assertNull(storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), userIdNotExists)); } { @@ -400,7 +401,7 @@ public void testUpdateUserExceptions() throws Exception { try { storage.startTransaction(con -> { try { - storage.updateUserPhoneNumber_Transaction(new AppIdentifier(null, null), con, userIdNotExists, + storage.updateUserPhoneNumber_Transaction(process.getAppForTesting().toAppIdentifier(), con, userIdNotExists, phoneNumber3); } catch (UnknownUserIdException | DuplicatePhoneNumberException e) { throw new StorageTransactionLogicException(e); @@ -414,7 +415,7 @@ public void testUpdateUserExceptions() throws Exception { assertNotNull(error); assert (error instanceof UnknownUserIdException); - assertNull(storage.getPrimaryUserById(new AppIdentifier(null, null), userIdNotExists)); + assertNull(storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), userIdNotExists)); } { @@ -423,7 +424,7 @@ public void testUpdateUserExceptions() throws Exception { storage.startTransaction(con -> { try { storage.updateUserEmail_Transaction( - new AppIdentifier(null, null), con, userIdEmail1, email2); + process.getAppForTesting().toAppIdentifier(), con, userIdEmail1, email2); } catch (UnknownUserIdException | DuplicateEmailException e) { throw new StorageTransactionLogicException(e); } @@ -437,7 +438,7 @@ public void testUpdateUserExceptions() throws Exception { assertNotNull(error); assert (error instanceof DuplicateEmailException); assertEquals(email, - storage.getPrimaryUserById(new AppIdentifier(null, null), userIdEmail1).loginMethods[0].email); + storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), userIdEmail1).loginMethods[0].email); } { @@ -445,7 +446,7 @@ public void testUpdateUserExceptions() throws Exception { try { storage.startTransaction(con -> { try { - storage.updateUserEmail_Transaction(new AppIdentifier(null, null), con, userIdEmail1, email2); + storage.updateUserEmail_Transaction(process.getAppForTesting().toAppIdentifier(), con, userIdEmail1, email2); } catch (UnknownUserIdException | DuplicateEmailException e) { throw new StorageTransactionLogicException(e); } @@ -459,7 +460,7 @@ public void testUpdateUserExceptions() throws Exception { assertNotNull(error); assert (error instanceof DuplicateEmailException); assertEquals(email, - storage.getPrimaryUserById(new AppIdentifier(null, null), userIdEmail1).loginMethods[0].email); + storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), userIdEmail1).loginMethods[0].email); } { @@ -467,7 +468,7 @@ public void testUpdateUserExceptions() throws Exception { try { storage.startTransaction(con -> { try { - storage.updateUserPhoneNumber_Transaction(new AppIdentifier(null, null), con, userIdPhone1, + storage.updateUserPhoneNumber_Transaction(process.getAppForTesting().toAppIdentifier(), con, userIdPhone1, phoneNumber2); } catch (UnknownUserIdException | DuplicatePhoneNumberException e) { throw new StorageTransactionLogicException(e); @@ -482,7 +483,7 @@ public void testUpdateUserExceptions() throws Exception { assertNotNull(error); assert (error instanceof DuplicatePhoneNumberException); assertEquals(phoneNumber, - storage.getPrimaryUserById(new AppIdentifier(null, null), + storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), userIdPhone1).loginMethods[0].phoneNumber); } @@ -491,7 +492,7 @@ public void testUpdateUserExceptions() throws Exception { try { storage.startTransaction(con -> { try { - storage.updateUserPhoneNumber_Transaction(new AppIdentifier(null, null), con, userIdEmail1, + storage.updateUserPhoneNumber_Transaction(process.getAppForTesting().toAppIdentifier(), con, userIdEmail1, phoneNumber); } catch (UnknownUserIdException | DuplicatePhoneNumberException e) { throw new StorageTransactionLogicException(e); @@ -505,7 +506,7 @@ public void testUpdateUserExceptions() throws Exception { assertNotNull(error); assert (error instanceof DuplicatePhoneNumberException); - AuthRecipeUserInfo userInDb = storage.getPrimaryUserById(new AppIdentifier(null, null), userIdEmail1); + AuthRecipeUserInfo userInDb = storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), userIdEmail1); assertEquals(email, userInDb.loginMethods[0].email); assertNull(userInDb.loginMethods[0].phoneNumber); } @@ -515,7 +516,7 @@ public void testUpdateUserExceptions() throws Exception { try { storage.startTransaction(con -> { try { - storage.updateUserEmail_Transaction(new AppIdentifier(null, null), con, userIdPhone1, email); + storage.updateUserEmail_Transaction(process.getAppForTesting().toAppIdentifier(), con, userIdPhone1, email); } catch (UnknownUserIdException | DuplicateEmailException e) { throw new StorageTransactionLogicException(e); } @@ -528,7 +529,7 @@ public void testUpdateUserExceptions() throws Exception { assertNotNull(error); assert (error instanceof DuplicateEmailException); - AuthRecipeUserInfo userInDb = storage.getPrimaryUserById(new AppIdentifier(null, null), userIdPhone1); + AuthRecipeUserInfo userInDb = storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), userIdPhone1); assertNull(userInDb.loginMethods[0].email); assertEquals(phoneNumber, userInDb.loginMethods[0].phoneNumber); } @@ -560,56 +561,56 @@ public void testUpdateUser() throws Exception { long timeJoined = System.currentTimeMillis(); - storage.createUser(new TenantIdentifier(null, null, null), userId, email, null, timeJoined); + storage.createUser(process.getAppForTesting(), userId, email, null, timeJoined); - assertNotNull(storage.getPrimaryUserById(new AppIdentifier(null, null), userId)); + assertNotNull(storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), userId)); storage.startTransaction(con -> { try { - storage.updateUserEmail_Transaction(new AppIdentifier(null, null), con, userId, email2); + storage.updateUserEmail_Transaction(process.getAppForTesting().toAppIdentifier(), con, userId, email2); } catch (UnknownUserIdException | DuplicateEmailException e) { throw new StorageTransactionLogicException(e); } storage.commitTransaction(con); return null; }); - checkUser(storage, userId, email2, null); + checkUser(process, storage, userId, email2, null); storage.startTransaction(con -> { try { - storage.updateUserEmail_Transaction(new AppIdentifier(null, null), con, userId, null); + storage.updateUserEmail_Transaction(process.getAppForTesting().toAppIdentifier(), con, userId, null); } catch (UnknownUserIdException | DuplicateEmailException e) { throw new StorageTransactionLogicException(e); } try { - storage.updateUserPhoneNumber_Transaction(new AppIdentifier(null, null), con, userId, phoneNumber); + storage.updateUserPhoneNumber_Transaction(process.getAppForTesting().toAppIdentifier(), con, userId, phoneNumber); } catch (UnknownUserIdException | DuplicatePhoneNumberException e) { throw new StorageTransactionLogicException(e); } storage.commitTransaction(con); return null; }); - checkUser(storage, userId, null, phoneNumber); + checkUser(process, storage, userId, null, phoneNumber); storage.startTransaction(con -> { try { - storage.updateUserPhoneNumber_Transaction(new AppIdentifier(null, null), con, userId, phoneNumber2); + storage.updateUserPhoneNumber_Transaction(process.getAppForTesting().toAppIdentifier(), con, userId, phoneNumber2); } catch (UnknownUserIdException | DuplicatePhoneNumberException e) { throw new StorageTransactionLogicException(e); } storage.commitTransaction(con); return null; }); - checkUser(storage, userId, null, phoneNumber2); + checkUser(process, storage, userId, null, phoneNumber2); storage.startTransaction(con -> { try { - storage.updateUserEmail_Transaction(new AppIdentifier(null, null), con, userId, email); + storage.updateUserEmail_Transaction(process.getAppForTesting().toAppIdentifier(), con, userId, email); } catch (UnknownUserIdException | DuplicateEmailException e) { throw new StorageTransactionLogicException(e); } try { - storage.updateUserPhoneNumber_Transaction(new AppIdentifier(null, null), con, userId, null); + storage.updateUserPhoneNumber_Transaction(process.getAppForTesting().toAppIdentifier(), con, userId, null); } catch (UnknownUserIdException | DuplicatePhoneNumberException e) { throw new StorageTransactionLogicException(e); } @@ -617,7 +618,7 @@ public void testUpdateUser() throws Exception { return null; }); - checkUser(storage, userId, email, null); + checkUser(process, storage, userId, email, null); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } @@ -639,20 +640,20 @@ public void testDeleteDeviceCascades() throws Exception { PasswordlessCode code1 = getRandomCodeInfo(); PasswordlessCode code2 = getRandomCodeInfo(code1.deviceIdHash); - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), email, null, "linkCodeSalt", code1); - assertEquals(1, storage.getDevicesByEmail(new TenantIdentifier(null, null, null), email).length); + storage.createDeviceWithCode(process.getAppForTesting(), email, null, "linkCodeSalt", code1); + assertEquals(1, storage.getDevicesByEmail(process.getAppForTesting(), email).length); - storage.createCode(new TenantIdentifier(null, null, null), code2); + storage.createCode(process.getAppForTesting(), code2); storage.startTransaction(con -> { - storage.deleteDevice_Transaction(new TenantIdentifier(null, null, null), con, code1.deviceIdHash); + storage.deleteDevice_Transaction(process.getAppForTesting(), con, code1.deviceIdHash); storage.commitTransaction(con); return null; }); - assertNull(storage.getDevice(new TenantIdentifier(null, null, null), code1.deviceIdHash)); - assertNull(storage.getCode(new TenantIdentifier(null, null, null), code1.id)); - assertNull(storage.getCode(new TenantIdentifier(null, null, null), code2.id)); + assertNull(storage.getDevice(process.getAppForTesting(), code1.deviceIdHash)); + assertNull(storage.getCode(process.getAppForTesting(), code1.id)); + assertNull(storage.getCode(process.getAppForTesting(), code2.id)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -677,22 +678,22 @@ public void testDeleteDevicesByEmailCascades() throws Exception { PasswordlessCode code1 = getRandomCodeInfo(); PasswordlessCode code2 = getRandomCodeInfo(); - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), email, null, "linkCodeSalt", code1); - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), email2, null, "linkCodeSalt", code2); + storage.createDeviceWithCode(process.getAppForTesting(), email, null, "linkCodeSalt", code1); + storage.createDeviceWithCode(process.getAppForTesting(), email2, null, "linkCodeSalt", code2); storage.startTransaction(con -> { - storage.deleteDevicesByEmail_Transaction(new TenantIdentifier(null, null, null), con, email); + storage.deleteDevicesByEmail_Transaction(process.getAppForTesting(), con, email); storage.commitTransaction(con); return null; }); - assertEquals(0, storage.getDevicesByEmail(new TenantIdentifier(null, null, null), email).length); - assertNull(storage.getDevice(new TenantIdentifier(null, null, null), code1.deviceIdHash)); - assertNull(storage.getCode(new TenantIdentifier(null, null, null), code1.id)); + assertEquals(0, storage.getDevicesByEmail(process.getAppForTesting(), email).length); + assertNull(storage.getDevice(process.getAppForTesting(), code1.deviceIdHash)); + assertNull(storage.getCode(process.getAppForTesting(), code1.id)); - assertEquals(1, storage.getDevicesByEmail(new TenantIdentifier(null, null, null), email2).length); - assertNotNull(storage.getDevice(new TenantIdentifier(null, null, null), code2.deviceIdHash)); - assertNotNull(storage.getCode(new TenantIdentifier(null, null, null), code2.id)); + assertEquals(1, storage.getDevicesByEmail(process.getAppForTesting(), email2).length); + assertNotNull(storage.getDevice(process.getAppForTesting(), code2.deviceIdHash)); + assertNotNull(storage.getCode(process.getAppForTesting(), code2.id)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -717,22 +718,22 @@ public void testDeleteDevicesByPhoneNumberCascades() throws Exception { PasswordlessCode code1 = getRandomCodeInfo(); PasswordlessCode code2 = getRandomCodeInfo(); - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), null, phoneNumber, "linkCodeSalt", code1); - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), null, phoneNumber2, "linkCodeSalt", code2); + storage.createDeviceWithCode(process.getAppForTesting(), null, phoneNumber, "linkCodeSalt", code1); + storage.createDeviceWithCode(process.getAppForTesting(), null, phoneNumber2, "linkCodeSalt", code2); storage.startTransaction(con -> { - storage.deleteDevicesByPhoneNumber_Transaction(new TenantIdentifier(null, null, null), con, phoneNumber); + storage.deleteDevicesByPhoneNumber_Transaction(process.getAppForTesting(), con, phoneNumber); storage.commitTransaction(con); return null; }); - assertEquals(0, storage.getDevicesByPhoneNumber(new TenantIdentifier(null, null, null), phoneNumber).length); - assertNull(storage.getDevice(new TenantIdentifier(null, null, null), code1.deviceIdHash)); - assertNull(storage.getCode(new TenantIdentifier(null, null, null), code1.id)); + assertEquals(0, storage.getDevicesByPhoneNumber(process.getAppForTesting(), phoneNumber).length); + assertNull(storage.getDevice(process.getAppForTesting(), code1.deviceIdHash)); + assertNull(storage.getCode(process.getAppForTesting(), code1.id)); - assertEquals(1, storage.getDevicesByPhoneNumber(new TenantIdentifier(null, null, null), phoneNumber2).length); - assertNotNull(storage.getDevice(new TenantIdentifier(null, null, null), code2.deviceIdHash)); - assertNotNull(storage.getCode(new TenantIdentifier(null, null, null), code2.id)); + assertEquals(1, storage.getDevicesByPhoneNumber(process.getAppForTesting(), phoneNumber2).length); + assertNotNull(storage.getDevice(process.getAppForTesting(), code2.deviceIdHash)); + assertNotNull(storage.getCode(process.getAppForTesting(), code2.id)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -741,7 +742,7 @@ public void testDeleteDevicesByPhoneNumberCascades() throws Exception { @Test public void testLocking() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); process.getProcess().setForceInMemoryDB(); process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); @@ -756,13 +757,13 @@ public void testLocking() throws Exception { // These functions are called in a transaction and they all add a lock on code1 TestFunction[] lockingFuncs = new TestFunction[]{(con) -> { - storage.getDevice_Transaction(new TenantIdentifier(null, null, null), con, code1.deviceIdHash); + storage.getDevice_Transaction(process.getAppForTesting(), con, code1.deviceIdHash); }, (con) -> { - storage.deleteDevicesByEmail_Transaction(new TenantIdentifier(null, null, null), con, email); + storage.deleteDevicesByEmail_Transaction(process.getAppForTesting(), con, email); }, (con) -> { - storage.deleteDevicesByPhoneNumber_Transaction(new TenantIdentifier(null, null, null), con, phoneNumber); + storage.deleteDevicesByPhoneNumber_Transaction(process.getAppForTesting(), con, phoneNumber); }, (con) -> { - storage.deleteDevice_Transaction(new TenantIdentifier(null, null, null), con, code1.deviceIdHash); + storage.deleteDevice_Transaction(process.getAppForTesting(), con, code1.deviceIdHash); },}; // We don't have createCode and createDeviceWithCode here, because in implementations with foreign key checking @@ -772,16 +773,16 @@ public void testLocking() throws Exception { // We are intentionally testing: AB, BA and AA as well, since these are all different testcases for (TestFunction func2 : lockingFuncs) { // Setup - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), email, null, "linkCodeSalt", + storage.createDeviceWithCode(process.getAppForTesting(), email, null, "linkCodeSalt", code1); - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), null, phoneNumber, "linkCodeSalt", + storage.createDeviceWithCode(process.getAppForTesting(), null, phoneNumber, "linkCodeSalt", code2); checkLockingCalls(storage, func1, func2); storage.startTransaction(con -> { - storage.deleteDevicesByEmail_Transaction(new TenantIdentifier(null, null, null), con, email); - storage.deleteDevicesByPhoneNumber_Transaction(new TenantIdentifier(null, null, null), con, + storage.deleteDevicesByEmail_Transaction(process.getAppForTesting(), con, email); + storage.deleteDevicesByPhoneNumber_Transaction(process.getAppForTesting(), con, phoneNumber); storage.commitTransaction(con); return null; @@ -890,17 +891,17 @@ private void checkLockingCalls(PasswordlessSQLStorage storage, TestFunction func t1.join(); } - private void checkUser(PasswordlessSQLStorage storage, String userId, String email, String phoneNumber) + private void checkUser(TestingProcessManager.TestingProcess process, PasswordlessSQLStorage storage, String userId, String email, String phoneNumber) throws StorageQueryException { - AuthRecipeUserInfo userById = storage.getPrimaryUserById(new AppIdentifier(null, null), userId); + AuthRecipeUserInfo userById = storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), userId); assertEquals(email, userById.loginMethods[0].email); assertEquals(phoneNumber, userById.loginMethods[0].phoneNumber); if (email != null) { - AuthRecipeUserInfo[] user = storage.listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), email); + AuthRecipeUserInfo[] user = storage.listPrimaryUsersByEmail(process.getAppForTesting(), email); assert (user.length == 1 && user[0].equals(userById)); } if (phoneNumber != null) { - AuthRecipeUserInfo[] user = storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), + AuthRecipeUserInfo[] user = storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), phoneNumber); assert (user[0].equals(userById)); } diff --git a/src/test/java/io/supertokens/test/passwordless/PasswordlessUpdateUserTest.java b/src/test/java/io/supertokens/test/passwordless/PasswordlessUpdateUserTest.java index 5575a128b..2c32b698c 100644 --- a/src/test/java/io/supertokens/test/passwordless/PasswordlessUpdateUserTest.java +++ b/src/test/java/io/supertokens/test/passwordless/PasswordlessUpdateUserTest.java @@ -46,6 +46,9 @@ public class PasswordlessUpdateUserTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -78,10 +81,10 @@ public void updateEmailToAnExistingOne() throws Exception { createUserWith(process, EMAIL, null); createUserWith(process, alternate_email, null); - AuthRecipeUserInfo[] user = storage.listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), EMAIL); + AuthRecipeUserInfo[] user = storage.listPrimaryUsersByEmail(process.getAppForTesting(), EMAIL); assert (user.length == 1); - AuthRecipeUserInfo[] user_two = storage.listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), + AuthRecipeUserInfo[] user_two = storage.listPrimaryUsersByEmail(process.getAppForTesting(), alternate_email); assert (user_two.length == 1); @@ -98,7 +101,7 @@ public void updateEmailToAnExistingOne() throws Exception { assert (ex instanceof DuplicateEmailException); assertEquals(EMAIL, - storage.listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), + storage.listPrimaryUsersByEmail(process.getAppForTesting(), EMAIL)[0].loginMethods[0].email); process.kill(); @@ -127,10 +130,10 @@ public void updatePhoneNumberToAnExistingOne() throws Exception { createUserWith(process, null, PHONE_NUMBER); createUserWith(process, null, alternate_phoneNumber); - AuthRecipeUserInfo[] user = storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), + AuthRecipeUserInfo[] user = storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), PHONE_NUMBER); assert (user.length == 1); - AuthRecipeUserInfo[] user_two = storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), + AuthRecipeUserInfo[] user_two = storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), alternate_phoneNumber); assert (user_two.length == 1); @@ -146,7 +149,7 @@ public void updatePhoneNumberToAnExistingOne() throws Exception { assert (ex instanceof DuplicatePhoneNumberException); assertEquals(PHONE_NUMBER, - storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), + storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), PHONE_NUMBER)[0].loginMethods[0].phoneNumber); process.kill(); @@ -175,14 +178,14 @@ public void updateEmail() throws Exception { createUserWith(process, EMAIL, null); - AuthRecipeUserInfo[] user = storage.listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), EMAIL); + AuthRecipeUserInfo[] user = storage.listPrimaryUsersByEmail(process.getAppForTesting(), EMAIL); assert (user.length == 1); Passwordless.updateUser(process.getProcess(), user[0].getSupertokensUserId(), new Passwordless.FieldUpdate(alternate_email), null); assertEquals(alternate_email, - storage.getPrimaryUserById(new AppIdentifier(null, null), + storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), user[0].getSupertokensUserId()).loginMethods[0].email); process.kill(); @@ -211,7 +214,7 @@ public void updatePhoneNumber() throws Exception { createUserWith(process, null, PHONE_NUMBER); - AuthRecipeUserInfo[] user = storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), + AuthRecipeUserInfo[] user = storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), PHONE_NUMBER); assert (user.length == 1); @@ -219,7 +222,7 @@ public void updatePhoneNumber() throws Exception { new Passwordless.FieldUpdate(alternate_phoneNumber)); assertEquals(alternate_phoneNumber, - storage.getPrimaryUserById(new AppIdentifier(null, null), + storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), user[0].getSupertokensUserId()).loginMethods[0].phoneNumber); process.kill(); @@ -247,7 +250,7 @@ public void clearEmailSetPhoneNumber() throws Exception { createUserWith(process, EMAIL, null); - AuthRecipeUserInfo[] user = storage.listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), EMAIL); + AuthRecipeUserInfo[] user = storage.listPrimaryUsersByEmail(process.getAppForTesting(), EMAIL); assert (user.length == 1); Passwordless.updateUser(process.getProcess(), user[0].getSupertokensUserId(), @@ -255,9 +258,9 @@ public void clearEmailSetPhoneNumber() throws Exception { new Passwordless.FieldUpdate(PHONE_NUMBER)); assertEquals(PHONE_NUMBER, - storage.getPrimaryUserById(new AppIdentifier(null, null), + storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), user[0].getSupertokensUserId()).loginMethods[0].phoneNumber); - assertNull(storage.getPrimaryUserById(new AppIdentifier(null, null), + assertNull(storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), user[0].getSupertokensUserId()).loginMethods[0].email); process.kill(); @@ -285,7 +288,7 @@ public void clearPhoneNumberSetEmail() throws Exception { createUserWith(process, null, PHONE_NUMBER); - AuthRecipeUserInfo[] user = storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), + AuthRecipeUserInfo[] user = storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), PHONE_NUMBER); assert (user.length == 1); @@ -294,9 +297,9 @@ public void clearPhoneNumberSetEmail() throws Exception { new Passwordless.FieldUpdate(null)); assertEquals(EMAIL, - storage.getPrimaryUserById(new AppIdentifier(null, null), + storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), user[0].getSupertokensUserId()).loginMethods[0].email); - assertNull(storage.getPrimaryUserById(new AppIdentifier(null, null), + assertNull(storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), user[0].getSupertokensUserId()).loginMethods[0].phoneNumber); process.kill(); @@ -324,7 +327,7 @@ public void clearPhoneNumberAndEmail() throws Exception { createUserWith(process, null, PHONE_NUMBER); - AuthRecipeUserInfo[] user = storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), + AuthRecipeUserInfo[] user = storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), PHONE_NUMBER); assert (user.length == 1); Exception ex = null; @@ -365,7 +368,7 @@ public void clearEmailOfEmailOnlyUser() throws Exception { createUserWith(process, EMAIL, null); - AuthRecipeUserInfo[] user = storage.listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), EMAIL); + AuthRecipeUserInfo[] user = storage.listPrimaryUsersByEmail(process.getAppForTesting(), EMAIL); assert (user.length == 1); Exception ex = null; @@ -405,7 +408,7 @@ public void clearPhoneOfPhoneOnlyUser() throws Exception { createUserWith(process, null, PHONE_NUMBER); - AuthRecipeUserInfo[] user = storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), + AuthRecipeUserInfo[] user = storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), PHONE_NUMBER); assert (user.length == 1); @@ -447,7 +450,7 @@ public void setPhoneNumberSetEmail() throws Exception { createUserWith(process, null, PHONE_NUMBER); - AuthRecipeUserInfo[] user = storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), + AuthRecipeUserInfo[] user = storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), PHONE_NUMBER); assert (user.length == 1); @@ -456,10 +459,10 @@ public void setPhoneNumberSetEmail() throws Exception { new Passwordless.FieldUpdate(alternate_phoneNumber)); assertEquals(EMAIL, - storage.getPrimaryUserById(new AppIdentifier(null, null), + storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), user[0].getSupertokensUserId()).loginMethods[0].email); assertEquals(alternate_phoneNumber, - storage.getPrimaryUserById(new AppIdentifier(null, null), + storage.getPrimaryUserById(process.getAppForTesting().toAppIdentifier(), user[0].getSupertokensUserId()).loginMethods[0].phoneNumber); process.kill(); diff --git a/src/test/java/io/supertokens/test/passwordless/api/EmailVerificationTest.java b/src/test/java/io/supertokens/test/passwordless/api/EmailVerificationTest.java index eacab45aa..27bfaf669 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/EmailVerificationTest.java +++ b/src/test/java/io/supertokens/test/passwordless/api/EmailVerificationTest.java @@ -55,6 +55,9 @@ public class EmailVerificationTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -167,11 +170,10 @@ public void testPasswordlessLoginSetsEmailVerified_v4_0() throws Exception { @Test public void testWithAccountLinking() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCheckCodeAPITest5_0.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCheckCodeAPITest5_0.java index 597246d98..146d558c4 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCheckCodeAPITest5_0.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCheckCodeAPITest5_0.java @@ -41,6 +41,9 @@ public class PasswordlessCheckCodeAPITest5_0 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessConsumeCodeAPITest2_11.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessConsumeCodeAPITest2_11.java index ab91ab835..fa887f0bb 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessConsumeCodeAPITest2_11.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessConsumeCodeAPITest2_11.java @@ -43,6 +43,9 @@ public class PasswordlessConsumeCodeAPITest2_11 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessConsumeCodeAPITest5_0.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessConsumeCodeAPITest5_0.java index b0e29aa69..b2711ab86 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessConsumeCodeAPITest5_0.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessConsumeCodeAPITest5_0.java @@ -40,6 +40,9 @@ public class PasswordlessConsumeCodeAPITest5_0 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCreateCodeAPITest.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCreateCodeAPITest.java index dc1f79f61..e0c71a432 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCreateCodeAPITest.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCreateCodeAPITest.java @@ -41,6 +41,9 @@ public class PasswordlessCreateCodeAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCreateCodeAPITest2_11.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCreateCodeAPITest2_11.java index 2d3cb7215..740844b05 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCreateCodeAPITest2_11.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessCreateCodeAPITest2_11.java @@ -41,6 +41,9 @@ public class PasswordlessCreateCodeAPITest2_11 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessDeleteCodeAPITest2_11.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessDeleteCodeAPITest2_11.java index c0840836f..f00d6aa1c 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessDeleteCodeAPITest2_11.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessDeleteCodeAPITest2_11.java @@ -40,6 +40,9 @@ public class PasswordlessDeleteCodeAPITest2_11 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -69,7 +72,7 @@ public void testDeleteCode() throws Exception { String deviceIdHash = "pZ9SP0USbXbejGFO6qx7x3JBjupJZVtw4RkFiNtJGqc"; String linkCodeHash = "wo5UcFFVSblZEd1KOUOl-dpJ5zpSr_Qsor1Eg4TzDRE"; - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), null, phoneNumber, "linkCodeSalt", + storage.createDeviceWithCode(process.getAppForTesting(), null, phoneNumber, "linkCodeSalt", new PasswordlessCode(codeId, deviceIdHash, linkCodeHash, System.currentTimeMillis())); JsonObject createCodeRequestBody = new JsonObject(); @@ -81,8 +84,8 @@ public void testDeleteCode() throws Exception { assertEquals("OK", response.get("status").getAsString()); - assertNull(storage.getCode(new TenantIdentifier(null, null, null), codeId)); - assertNull(storage.getDevice(new TenantIdentifier(null, null, null), deviceIdHash)); + assertNull(storage.getCode(process.getAppForTesting(), codeId)); + assertNull(storage.getDevice(process.getAppForTesting(), deviceIdHash)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessDeleteCodeAPITest5_0.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessDeleteCodeAPITest5_0.java index 9270d05b5..fade069eb 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessDeleteCodeAPITest5_0.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessDeleteCodeAPITest5_0.java @@ -40,6 +40,9 @@ public class PasswordlessDeleteCodeAPITest5_0 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -69,7 +72,7 @@ public void testDeleteCode() throws Exception { String deviceIdHash = "pZ9SP0USbXbejGFO6qx7x3JBjupJZVtw4RkFiNtJGqc"; String linkCodeHash = "wo5UcFFVSblZEd1KOUOl-dpJ5zpSr_Qsor1Eg4TzDRE"; - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), null, phoneNumber, "linkCodeSalt", + storage.createDeviceWithCode(process.getAppForTesting(), null, phoneNumber, "linkCodeSalt", new PasswordlessCode(codeId, deviceIdHash, linkCodeHash, System.currentTimeMillis())); JsonObject createCodeRequestBody = new JsonObject(); @@ -81,8 +84,8 @@ public void testDeleteCode() throws Exception { assertEquals("OK", response.get("status").getAsString()); - assertNull(storage.getCode(new TenantIdentifier(null, null, null), codeId)); - assertNull(storage.getDevice(new TenantIdentifier(null, null, null), deviceIdHash)); + assertNull(storage.getCode(process.getAppForTesting(), codeId)); + assertNull(storage.getDevice(process.getAppForTesting(), deviceIdHash)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } @@ -195,7 +198,7 @@ public void testDeleteDeviceIdHash() throws Exception { String deviceIdHash = "pZ9SP0USbXbejGFO6qx7x3JBjupJZVtw4RkFiNtJGqc"; String linkCodeHash = "wo5UcFFVSblZEd1KOUOl-dpJ5zpSr_Qsor1Eg4TzDRE"; - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), null, phoneNumber, "linkCodeSalt", + storage.createDeviceWithCode(process.getAppForTesting(), null, phoneNumber, "linkCodeSalt", new PasswordlessCode(codeId, deviceIdHash, linkCodeHash, System.currentTimeMillis())); JsonObject createCodeRequestBody = new JsonObject(); @@ -207,8 +210,8 @@ public void testDeleteDeviceIdHash() throws Exception { assertEquals("OK", response.get("status").getAsString()); - assertNull(storage.getCode(new TenantIdentifier(null, null, null), codeId)); - assertNull(storage.getDevice(new TenantIdentifier(null, null, null), deviceIdHash)); + assertNull(storage.getCode(process.getAppForTesting(), codeId)); + assertNull(storage.getDevice(process.getAppForTesting(), deviceIdHash)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessDeleteCodesAPITest.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessDeleteCodesAPITest.java index 9d80fefd4..cf15ce18e 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessDeleteCodesAPITest.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessDeleteCodesAPITest.java @@ -41,6 +41,9 @@ public class PasswordlessDeleteCodesAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -71,7 +74,7 @@ public void testDeleteByUnnormalisedPhoneNumber() throws Exception { String deviceIdHash = "pZ9SP0USbXbejGFO6qx7x3JBjupJZVtw4RkFiNtJGqc"; String linkCodeHash = "wo5UcFFVSblZEd1KOUOl-dpJ5zpSr_Qsor1Eg4TzDRE"; - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), null, normalisedPhoneNumber, + storage.createDeviceWithCode(process.getAppForTesting(), null, normalisedPhoneNumber, "linkCodeSalt", new PasswordlessCode(codeId, deviceIdHash, linkCodeHash, System.currentTimeMillis())); @@ -84,8 +87,8 @@ public void testDeleteByUnnormalisedPhoneNumber() throws Exception { assertEquals("OK", response.get("status").getAsString()); - assertNull(storage.getDevice(new TenantIdentifier(null, null, null), deviceIdHash)); - assertNull(storage.getCode(new TenantIdentifier(null, null, null), codeId)); + assertNull(storage.getDevice(process.getAppForTesting(), deviceIdHash)); + assertNull(storage.getCode(process.getAppForTesting(), codeId)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessDeleteCodesAPITest2_11.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessDeleteCodesAPITest2_11.java index fffb547b0..2c429ce68 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessDeleteCodesAPITest2_11.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessDeleteCodesAPITest2_11.java @@ -41,6 +41,9 @@ public class PasswordlessDeleteCodesAPITest2_11 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -169,9 +172,9 @@ public void testDeleteByEmail() throws Exception { String linkCodeHash = "wo5UcFFVSblZEd1KOUOl-dpJ5zpSr_Qsor1Eg4TzDRE"; String linkCodeHash2 = "F0aZHCBYSJIghP5e0flGa8gvoUYEgGus2yIJYmdpFY4"; - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), email, null, "linkCodeSalt", + storage.createDeviceWithCode(process.getAppForTesting(), email, null, "linkCodeSalt", new PasswordlessCode(codeId, deviceIdHash, linkCodeHash, System.currentTimeMillis())); - storage.createCode(new TenantIdentifier(null, null, null), + storage.createCode(process.getAppForTesting(), new PasswordlessCode(codeId2, deviceIdHash, linkCodeHash2, System.currentTimeMillis())); JsonObject createCodeRequestBody = new JsonObject(); @@ -183,9 +186,9 @@ public void testDeleteByEmail() throws Exception { assertEquals("OK", response.get("status").getAsString()); - assertNull(storage.getDevice(new TenantIdentifier(null, null, null), deviceIdHash)); - assertNull(storage.getCode(new TenantIdentifier(null, null, null), codeId)); - assertNull(storage.getCode(new TenantIdentifier(null, null, null), codeId2)); + assertNull(storage.getDevice(process.getAppForTesting(), deviceIdHash)); + assertNull(storage.getCode(process.getAppForTesting(), codeId)); + assertNull(storage.getCode(process.getAppForTesting(), codeId2)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -212,9 +215,9 @@ public void testDeleteByPhoneNumber() throws Exception { String linkCodeHash = "wo5UcFFVSblZEd1KOUOl-dpJ5zpSr_Qsor1Eg4TzDRE"; String linkCodeHash2 = "F0aZHCBYSJIghP5e0flGa8gvoUYEgGus2yIJYmdpFY4"; - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), null, phoneNumber, "linkCodeSalt", + storage.createDeviceWithCode(process.getAppForTesting(), null, phoneNumber, "linkCodeSalt", new PasswordlessCode(codeId, deviceIdHash, linkCodeHash, System.currentTimeMillis())); - storage.createCode(new TenantIdentifier(null, null, null), + storage.createCode(process.getAppForTesting(), new PasswordlessCode(codeId2, deviceIdHash, linkCodeHash2, System.currentTimeMillis())); JsonObject createCodeRequestBody = new JsonObject(); @@ -226,9 +229,9 @@ public void testDeleteByPhoneNumber() throws Exception { assertEquals("OK", response.get("status").getAsString()); - assertNull(storage.getDevice(new TenantIdentifier(null, null, null), deviceIdHash)); - assertNull(storage.getCode(new TenantIdentifier(null, null, null), codeId)); - assertNull(storage.getCode(new TenantIdentifier(null, null, null), codeId2)); + assertNull(storage.getDevice(process.getAppForTesting(), deviceIdHash)); + assertNull(storage.getCode(process.getAppForTesting(), codeId)); + assertNull(storage.getCode(process.getAppForTesting(), codeId2)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessGetCodesAPITest.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessGetCodesAPITest.java index f2a57bfc7..4df490b72 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessGetCodesAPITest.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessGetCodesAPITest.java @@ -47,6 +47,9 @@ public class PasswordlessGetCodesAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -76,11 +79,11 @@ public void testGetCodesWithUnnormalisedPhoneNumber() throws Exception { String deviceIdHash = "pZ9SP0USbXbejGFO6qx7x3JBjupJZVtw4RkFiNtJGqc="; String linkCodeHash = "wo5UcFFVSblZEd1KOUOl-dpJ5zpSr_Qsor1Eg4TzDRE"; - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), null, normalisedPhoneNumber, + storage.createDeviceWithCode(process.getAppForTesting(), null, normalisedPhoneNumber, "linkCodeSalt", new PasswordlessCode(codeId, deviceIdHash, linkCodeHash, System.currentTimeMillis())); assertEquals(1, - storage.getDevicesByPhoneNumber(new TenantIdentifier(null, null, null), normalisedPhoneNumber).length); + storage.getDevicesByPhoneNumber(process.getAppForTesting(), normalisedPhoneNumber).length); HashMap map = new HashMap<>(); map.put("phoneNumber", phoneNumber); diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessGetCodesAPITest2_11.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessGetCodesAPITest2_11.java index aa52b54bc..aad4c86f3 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessGetCodesAPITest2_11.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessGetCodesAPITest2_11.java @@ -46,6 +46,9 @@ public class PasswordlessGetCodesAPITest2_11 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -186,9 +189,9 @@ public void testGetCodes() throws Exception { assertEquals(0, response.get("devices").getAsJsonArray().size()); } - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), email, null, "linkCodeSalt", + storage.createDeviceWithCode(process.getAppForTesting(), email, null, "linkCodeSalt", new PasswordlessCode(codeId, deviceIdHash, linkCodeHash, System.currentTimeMillis())); - assertEquals(1, storage.getDevicesByEmail(new TenantIdentifier(null, null, null), email).length); + assertEquals(1, storage.getDevicesByEmail(process.getAppForTesting(), email).length); // match @@ -245,9 +248,9 @@ public void testGetCodesWithEmail() throws Exception { // OK with matching codes { - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), email, null, "linkCodeSalt", + storage.createDeviceWithCode(process.getAppForTesting(), email, null, "linkCodeSalt", new PasswordlessCode(codeId, deviceIdHash, linkCodeHash, System.currentTimeMillis())); - assertEquals(1, storage.getDevicesByEmail(new TenantIdentifier(null, null, null), email).length); + assertEquals(1, storage.getDevicesByEmail(process.getAppForTesting(), email).length); { HashMap map = new HashMap<>(); @@ -302,10 +305,10 @@ public void testGetCodesWithPhoneNumber() throws Exception { // OK with matching codes { - storage.createDeviceWithCode(new TenantIdentifier(null, null, null), null, phoneNumber, "linkCodeSalt", + storage.createDeviceWithCode(process.getAppForTesting(), null, phoneNumber, "linkCodeSalt", new PasswordlessCode(codeId, deviceIdHash, linkCodeHash, System.currentTimeMillis())); assertEquals(1, - storage.getDevicesByPhoneNumber(new TenantIdentifier(null, null, null), phoneNumber).length); + storage.getDevicesByPhoneNumber(process.getAppForTesting(), phoneNumber).length); { HashMap map = new HashMap<>(); @@ -364,7 +367,7 @@ public void testGetCodesWithDeviceID() throws Exception { deviceID = createCodeResponse.deviceId; assertEquals(1, - storage.getDevicesByPhoneNumber(new TenantIdentifier(null, null, null), phoneNumber).length); + storage.getDevicesByPhoneNumber(process.getAppForTesting(), phoneNumber).length); // TODO: deviceID = { HashMap map = new HashMap<>(); diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserGetAPITest.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserGetAPITest.java index f73f29831..ee82a619b 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserGetAPITest.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserGetAPITest.java @@ -43,6 +43,9 @@ public class PasswordlessUserGetAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -72,7 +75,7 @@ public void testGetUserWithUnnormalisedPhoneNumber() throws Exception { String phoneNumber = "+44-207 183 8750"; String normalisedPhoneNumber = io.supertokens.utils.Utils.normalizeIfPhoneNumber(phoneNumber); - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userId, null, normalisedPhoneNumber, System.currentTimeMillis()); { HashMap map = new HashMap<>(); diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserGetAPITest2_11.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserGetAPITest2_11.java index 2684715ac..4ae9500e2 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserGetAPITest2_11.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserGetAPITest2_11.java @@ -47,6 +47,9 @@ public class PasswordlessUserGetAPITest2_11 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -173,7 +176,7 @@ public void testGoodInput() throws Exception { String email = "random@gmail.com"; String phoneNumber = "1234"; - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userIdEmail, email, null, System.currentTimeMillis()); { HashMap map = new HashMap<>(); @@ -199,7 +202,7 @@ public void testGoodInput() throws Exception { /* * get user with phone number */ - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userIdPhone, null, phoneNumber, System.currentTimeMillis()); { HashMap map = new HashMap<>(); diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserPutAPITest.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserPutAPITest.java index 0ea5cf86b..52445879d 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserPutAPITest.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserPutAPITest.java @@ -40,6 +40,9 @@ public class PasswordlessUserPutAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -67,7 +70,7 @@ public void testIfPhoneNumberIsNormalisedInUpdate() throws Exception { String normalisedUpdatedPhoneNumber = io.supertokens.utils.Utils.normalizeIfPhoneNumber(updatedPhoneNumber); PasswordlessStorage storage = (PasswordlessStorage) StorageLayer.getStorage(process.getProcess()); - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userId, null, phoneNumber, System.currentTimeMillis()); JsonObject updateUserRequestBody = new JsonObject(); @@ -80,10 +83,10 @@ public void testIfPhoneNumberIsNormalisedInUpdate() throws Exception { assertEquals("OK", response.get("status").getAsString()); - assert (storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), phoneNumber).length == 0); - assert (storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), + assert (storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), phoneNumber).length == 0); + assert (storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), updatedPhoneNumber).length == 0); - assert (storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), + assert (storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), normalisedUpdatedPhoneNumber).length == 1); process.kill(); diff --git a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserPutAPITest2_11.java b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserPutAPITest2_11.java index f620edc0f..d0818abfb 100644 --- a/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserPutAPITest2_11.java +++ b/src/test/java/io/supertokens/test/passwordless/api/PasswordlessUserPutAPITest2_11.java @@ -41,6 +41,9 @@ public class PasswordlessUserPutAPITest2_11 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -69,11 +72,11 @@ public void testBadInput() throws Exception { String phoneNumber = "+442071838750"; PasswordlessStorage storage = (PasswordlessStorage) StorageLayer.getStorage(process.getProcess()); - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userId, email, null, System.currentTimeMillis()); - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), "userId2", email2, null, System.currentTimeMillis()); - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), "userId3", null, phoneNumber, System.currentTimeMillis()); { @@ -151,7 +154,7 @@ public void testEmailToPhone() throws Exception { PasswordlessStorage storage = (PasswordlessStorage) StorageLayer.getStorage(process.getProcess()); String email = "email"; - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userId, email, null, System.currentTimeMillis()); JsonObject updateUserRequestBody = new JsonObject(); @@ -165,8 +168,8 @@ public void testEmailToPhone() throws Exception { assertEquals("OK", response.get("status").getAsString()); - assert (storage.listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), email).length == 0); - assert (storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), phoneNumber).length == 1); + assert (storage.listPrimaryUsersByEmail(process.getAppForTesting(), email).length == 0); + assert (storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), phoneNumber).length == 1); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } @@ -192,7 +195,7 @@ public void testPhoneToEmail() throws Exception { String email = "email"; PasswordlessStorage storage = (PasswordlessStorage) StorageLayer.getStorage(process.getProcess()); - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userId, null, phoneNumber, System.currentTimeMillis()); JsonObject updateUserRequestBody = new JsonObject(); @@ -206,8 +209,8 @@ public void testPhoneToEmail() throws Exception { assertEquals("OK", response.get("status").getAsString()); - assert (storage.listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), email).length == 1); - assert (storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), phoneNumber).length == 0); + assert (storage.listPrimaryUsersByEmail(process.getAppForTesting(), email).length == 1); + assert (storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), phoneNumber).length == 0); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } @@ -235,7 +238,7 @@ public void testPhoneAndEmail() throws Exception { String updatedEmail = "test@example.com"; PasswordlessStorage storage = (PasswordlessStorage) StorageLayer.getStorage(process.getProcess()); - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userId, email, phoneNumber, System.currentTimeMillis()); JsonObject updateUserRequestBody = new JsonObject(); @@ -249,11 +252,11 @@ public void testPhoneAndEmail() throws Exception { assertEquals("OK", response.get("status").getAsString()); - assert (storage.listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), email).length == 0); - assert (storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), phoneNumber).length == 0); + assert (storage.listPrimaryUsersByEmail(process.getAppForTesting(), email).length == 0); + assert (storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), phoneNumber).length == 0); - assert (storage.listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), updatedEmail).length == 1); - assert (storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), + assert (storage.listPrimaryUsersByEmail(process.getAppForTesting(), updatedEmail).length == 1); + assert (storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), updatedPhoneNumber).length == 1); @@ -282,7 +285,7 @@ public void clearEmailAndPhone() throws Exception { String email = "email"; PasswordlessStorage storage = (PasswordlessStorage) StorageLayer.getStorage(process.getProcess()); - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userId, email, phoneNumber, System.currentTimeMillis()); JsonObject updateUserRequestBody = new JsonObject(); @@ -330,7 +333,7 @@ public void clearEmailOfEmailOnlyUser() throws Exception { String email = "email"; PasswordlessStorage storage = (PasswordlessStorage) StorageLayer.getStorage(process.getProcess()); - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userId, email, null, System.currentTimeMillis()); JsonObject updateUserRequestBody = new JsonObject(); @@ -378,7 +381,7 @@ public void clearPhoneNUmberOfPhoneNumberOnlyUser() throws Exception { String phoneNumber = "+91898989898"; PasswordlessStorage storage = (PasswordlessStorage) StorageLayer.getStorage(process.getProcess()); - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userId, null, phoneNumber, System.currentTimeMillis()); JsonObject updateUserRequestBody = new JsonObject(); @@ -426,7 +429,7 @@ public void clearEmail() throws Exception { String phoneNumber = "+9189898989"; PasswordlessStorage storage = (PasswordlessStorage) StorageLayer.getStorage(process.getProcess()); - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userId, email, phoneNumber, System.currentTimeMillis()); JsonObject updateUserRequestBody = new JsonObject(); @@ -439,8 +442,8 @@ public void clearEmail() throws Exception { assertEquals("OK", response.get("status").getAsString()); - assert (storage.listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), email).length == 0); - assert (storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), phoneNumber).length == 1); + assert (storage.listPrimaryUsersByEmail(process.getAppForTesting(), email).length == 0); + assert (storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), phoneNumber).length == 1); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -467,7 +470,7 @@ public void clearPhone() throws Exception { String phoneNumber = "+9189898989"; PasswordlessStorage storage = (PasswordlessStorage) StorageLayer.getStorage(process.getProcess()); - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userId, email, phoneNumber, System.currentTimeMillis()); JsonObject updateUserRequestBody = new JsonObject(); @@ -480,8 +483,8 @@ public void clearPhone() throws Exception { assertEquals("OK", response.get("status").getAsString()); - assert (storage.listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), email).length == 1); - assert (storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), phoneNumber).length == 0); + assert (storage.listPrimaryUsersByEmail(process.getAppForTesting(), email).length == 1); + assert (storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), phoneNumber).length == 0); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -508,7 +511,7 @@ public void updateNothing() throws Exception { String phoneNumber = "+9189898989"; PasswordlessStorage storage = (PasswordlessStorage) StorageLayer.getStorage(process.getProcess()); - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userId, email, phoneNumber, System.currentTimeMillis()); JsonObject updateUserRequestBody = new JsonObject(); @@ -520,8 +523,8 @@ public void updateNothing() throws Exception { assertEquals("OK", response.get("status").getAsString()); - assert (storage.listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), email).length == 1); - assert (storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), phoneNumber).length == 1); + assert (storage.listPrimaryUsersByEmail(process.getAppForTesting(), email).length == 1); + assert (storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), phoneNumber).length == 1); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -548,7 +551,7 @@ public void testUpdateEmail() throws Exception { PasswordlessStorage storage = (PasswordlessStorage) StorageLayer.getStorage(process.getProcess()); String email = "email"; String updated_email = "test@example.com"; - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userId, email, null, System.currentTimeMillis()); JsonObject updateUserRequestBody = new JsonObject(); @@ -561,8 +564,8 @@ public void testUpdateEmail() throws Exception { assertEquals("OK", response.get("status").getAsString()); - assert (storage.listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), updated_email).length == 1); - assert (storage.listPrimaryUsersByEmail(new TenantIdentifier(null, null, null), email).length == 0); + assert (storage.listPrimaryUsersByEmail(process.getAppForTesting(), updated_email).length == 1); + assert (storage.listPrimaryUsersByEmail(process.getAppForTesting(), email).length == 0); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -589,7 +592,7 @@ public void testUpdatePhoneNumber() throws Exception { String updatedPhoneNumber = "+442071838751"; PasswordlessStorage storage = (PasswordlessStorage) StorageLayer.getStorage(process.getProcess()); - storage.createUser(new TenantIdentifier(null, null, null), + storage.createUser(process.getAppForTesting(), userId, null, phoneNumber, System.currentTimeMillis()); JsonObject updateUserRequestBody = new JsonObject(); @@ -602,9 +605,9 @@ public void testUpdatePhoneNumber() throws Exception { assertEquals("OK", response.get("status").getAsString()); - assert (storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), + assert (storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), updatedPhoneNumber).length == 1); - assert (storage.listPrimaryUsersByPhoneNumber(new TenantIdentifier(null, null, null), phoneNumber).length == 0); + assert (storage.listPrimaryUsersByPhoneNumber(process.getAppForTesting(), phoneNumber).length == 0); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); diff --git a/src/test/java/io/supertokens/test/session/AccessTokenSigningKeyTest.java b/src/test/java/io/supertokens/test/session/AccessTokenSigningKeyTest.java index 6fc311ef8..c5ff6c8bc 100644 --- a/src/test/java/io/supertokens/test/session/AccessTokenSigningKeyTest.java +++ b/src/test/java/io/supertokens/test/session/AccessTokenSigningKeyTest.java @@ -54,6 +54,9 @@ public class AccessTokenSigningKeyTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -69,7 +72,7 @@ public void legacySigningKeysAreMigratedProperly() throws InterruptedException, StorageQueryException, StorageTransactionLogicException, TenantOrAppNotFoundException, UnsupportedJWTSigningAlgorithmException { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); EventAndException e = process.checkOrWaitForEvent(PROCESS_STATE.STARTED); assertNotNull(e); @@ -78,9 +81,9 @@ public void legacySigningKeysAreMigratedProperly() throws InterruptedException, String signingKey = rsaKeys.toString(); KeyValueInfo newKey = new KeyValueInfo(signingKey, System.currentTimeMillis()); SessionStorage sessionStorage = (SessionStorage) StorageLayer.getStorage(process.getProcess()); - sessionStorage.removeAccessTokenSigningKeysBefore(new AppIdentifier(null, null), + sessionStorage.removeAccessTokenSigningKeysBefore(process.getAppForTesting().toAppIdentifier(), System.currentTimeMillis() + 1000); - sessionStorage.setKeyValue(new TenantIdentifier(null, null, null), "access_token_signing_key", newKey); + sessionStorage.setKeyValue(process.getAppForTesting(), "access_token_signing_key", newKey); AccessTokenSigningKey accessTokenSigningKeyInstance = AccessTokenSigningKey.getInstance(process.getProcess()); accessTokenSigningKeyInstance.transferLegacyKeyToNewTable(); assertEquals(SigningKeys.getInstance(process.getProcess()).getAllKeys().size(), 2); @@ -88,7 +91,7 @@ public void legacySigningKeysAreMigratedProperly() throws InterruptedException, assertEquals(keys.size(), 1); assertEquals(keys.get(0).createdAtTime, newKey.createdAtTime); assertEquals(keys.get(0).value, newKey.value); - assertNull(sessionStorage.getKeyValue(new TenantIdentifier(null, null, null), "access_token_signing_key")); + assertNull(sessionStorage.getKeyValue(process.getAppForTesting(), "access_token_signing_key")); process.kill(); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STOPPED)); } @@ -98,7 +101,7 @@ public void getDynamicKeysReturnsOrdered() throws Exception { Utils.setValueInConfig("access_token_dynamic_signing_key_update_interval", "0.00027"); // 1 seconds String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); EventAndException e = process.checkOrWaitForEvent(PROCESS_STATE.STARTED); assertNotNull(e); @@ -109,9 +112,9 @@ public void getDynamicKeysReturnsOrdered() throws Exception { // 2 seconds in the past SessionStorage sessionStorage = (SessionStorage) StorageLayer.getStorage(process.getProcess()); - sessionStorage.removeAccessTokenSigningKeysBefore(new AppIdentifier(null, null), + sessionStorage.removeAccessTokenSigningKeysBefore(process.getAppForTesting().toAppIdentifier(), System.currentTimeMillis() + 1000); - sessionStorage.setKeyValue(new TenantIdentifier(null, null, null), "access_token_signing_key", legacyKey); + sessionStorage.setKeyValue(process.getAppForTesting(), "access_token_signing_key", legacyKey); AccessTokenSigningKey accessTokenSigningKeyInstance = AccessTokenSigningKey.getInstance(process.getProcess()); accessTokenSigningKeyInstance.transferLegacyKeyToNewTable(); @@ -152,7 +155,7 @@ public void getAllKeysFiltersOldKeys() Utils.setValueInConfig("access_token_validity", "1"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); EventAndException e = process.checkOrWaitForEvent(PROCESS_STATE.STARTED); assertNotNull(e); @@ -179,7 +182,7 @@ public void migratingStaticSigningKeys() throws Exception { Utils.setValueInConfig("access_token_signing_key_dynamic", "false"); String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); EventAndException e = process.checkOrWaitForEvent(PROCESS_STATE.STARTED); assertNotNull(e); @@ -194,7 +197,7 @@ public void migratingStaticSigningKeys() throws Exception { sessionStorage.deleteAllInformation(); expectedSize = 1; } - sessionStorage.setKeyValue(new TenantIdentifier(null, null, null), "access_token_signing_key", legacyKey); + sessionStorage.setKeyValue(process.getAppForTesting(), "access_token_signing_key", legacyKey); AccessTokenSigningKey accessTokenSigningKeyInstance = AccessTokenSigningKey.getInstance(process.getProcess()); accessTokenSigningKeyInstance.transferLegacyKeyToNewTable(); diff --git a/src/test/java/io/supertokens/test/session/AccessTokenTest.java b/src/test/java/io/supertokens/test/session/AccessTokenTest.java index 30247227a..2bce0031e 100644 --- a/src/test/java/io/supertokens/test/session/AccessTokenTest.java +++ b/src/test/java/io/supertokens/test/session/AccessTokenTest.java @@ -63,6 +63,9 @@ public class AccessTokenTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -394,7 +397,7 @@ public void signingKeyShortInterval() Utils.setValueInConfig("access_token_dynamic_signing_key_update_interval", "0.00027"); // 1 second String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); EventAndException e = process.checkOrWaitForEvent(PROCESS_STATE.STARTED); assertNotNull(e); String keyBefore = SigningKeys.getInstance(process.getProcess()).getLatestIssuedDynamicKey().toString(); @@ -436,7 +439,7 @@ public void accessTokenShortLifetimeThrowsRefreshTokenError() Utils.setValueInConfig("access_token_validity", "1"); // 1 second String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); EventAndException e = process.checkOrWaitForEvent(PROCESS_STATE.STARTED); assertNotNull(e); @@ -482,7 +485,7 @@ public void keyChangeThreadSafetyTest() throws Exception { Utils.setValueInConfig("access_token_validity", "1"); // 1 second String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); EventAndException e = process.checkOrWaitForEvent(PROCESS_STATE.STARTED); assertNotNull(e); JsonObject jsonObj = new JsonObject(); @@ -543,7 +546,7 @@ public void testThatWeUseLatestVersionIfHeaderHasNoVersion() throws Exception { String jwksDomain = "http://localhost"; long validity = 3600; - String jwt = JWTSigningFunctions.createJWTToken(process.main, algorithm, accessTokenPayload, jwksDomain, + String jwt = JWTSigningFunctions.createJWTToken(process.getProcess(), algorithm, accessTokenPayload, jwksDomain, validity, false); String header = jwt.split("\\.")[0]; diff --git a/src/test/java/io/supertokens/test/session/DeleteExpiredAccessTokenSigningKeysTest.java b/src/test/java/io/supertokens/test/session/DeleteExpiredAccessTokenSigningKeysTest.java index 80f190714..74a08db4c 100644 --- a/src/test/java/io/supertokens/test/session/DeleteExpiredAccessTokenSigningKeysTest.java +++ b/src/test/java/io/supertokens/test/session/DeleteExpiredAccessTokenSigningKeysTest.java @@ -22,7 +22,6 @@ import io.supertokens.cronjobs.deleteExpiredAccessTokenSigningKeys.DeleteExpiredAccessTokenSigningKeys; import io.supertokens.pluginInterface.KeyValueInfo; import io.supertokens.pluginInterface.STORAGE_TYPE; -import io.supertokens.pluginInterface.multitenancy.AppIdentifier; import io.supertokens.pluginInterface.multitenancy.exceptions.TenantOrAppNotFoundException; import io.supertokens.pluginInterface.session.SessionStorage; import io.supertokens.pluginInterface.session.sqlStorage.SessionSQLStorage; @@ -41,6 +40,9 @@ public class DeleteExpiredAccessTokenSigningKeysTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -69,7 +71,7 @@ public void intervalTimeSecondsCleanExpiredAccessTokenSigningKeysTest() throws E public void jobCleansOldKeysTest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); CronTaskTest.getInstance(process.getProcess()) .setIntervalInSeconds(DeleteExpiredAccessTokenSigningKeys.RESOURCE_KEY, 1); process.startProcess(); @@ -88,20 +90,20 @@ public void jobCleansOldKeysTest() throws Exception { SessionSQLStorage sqlStorage = (SessionSQLStorage) sessionStorage; sqlStorage.startTransaction(con -> { try { - sqlStorage.addAccessTokenSigningKey_Transaction(new AppIdentifier(null, null), con, + sqlStorage.addAccessTokenSigningKey_Transaction(process.getAppForTesting().toAppIdentifier(), con, new KeyValueInfo("clean!", 100)); - sqlStorage.addAccessTokenSigningKey_Transaction(new AppIdentifier(null, null), con, + sqlStorage.addAccessTokenSigningKey_Transaction(process.getAppForTesting().toAppIdentifier(), con, new KeyValueInfo("clean!", System.currentTimeMillis() - signingKeyUpdateInterval - 3 * accessTokenValidity)); - sqlStorage.addAccessTokenSigningKey_Transaction(new AppIdentifier(null, null), con, + sqlStorage.addAccessTokenSigningKey_Transaction(process.getAppForTesting().toAppIdentifier(), con, new KeyValueInfo("clean!", System.currentTimeMillis() - signingKeyUpdateInterval - 2 * accessTokenValidity)); - sqlStorage.addAccessTokenSigningKey_Transaction(new AppIdentifier(null, null), con, + sqlStorage.addAccessTokenSigningKey_Transaction(process.getAppForTesting().toAppIdentifier(), con, new KeyValueInfo("keep!", System.currentTimeMillis() - signingKeyUpdateInterval - 1 * accessTokenValidity)); - sqlStorage.addAccessTokenSigningKey_Transaction(new AppIdentifier(null, null), con, + sqlStorage.addAccessTokenSigningKey_Transaction(process.getAppForTesting().toAppIdentifier(), con, new KeyValueInfo("keep!", System.currentTimeMillis() - signingKeyUpdateInterval)); - sqlStorage.addAccessTokenSigningKey_Transaction(new AppIdentifier(null, null), con, + sqlStorage.addAccessTokenSigningKey_Transaction(process.getAppForTesting().toAppIdentifier(), con, new KeyValueInfo("keep!", System.currentTimeMillis())); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -112,7 +114,7 @@ public void jobCleansOldKeysTest() throws Exception { Thread.sleep(1500); sqlStorage.startTransaction(con -> { - KeyValueInfo[] keys = sqlStorage.getAccessTokenSigningKeys_Transaction(new AppIdentifier(null, null), con); + KeyValueInfo[] keys = sqlStorage.getAccessTokenSigningKeys_Transaction(process.getAppForTesting().toAppIdentifier(), con); assertEquals(keys.length, 4); for (KeyValueInfo key : keys) { assertNotEquals("clean!", key.value); diff --git a/src/test/java/io/supertokens/test/session/DeleteExpiredSessionsTest.java b/src/test/java/io/supertokens/test/session/DeleteExpiredSessionsTest.java index dc609a1c4..8e6924f22 100644 --- a/src/test/java/io/supertokens/test/session/DeleteExpiredSessionsTest.java +++ b/src/test/java/io/supertokens/test/session/DeleteExpiredSessionsTest.java @@ -33,6 +33,9 @@ public class DeleteExpiredSessionsTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/session/JWTDataTest.java b/src/test/java/io/supertokens/test/session/JWTDataTest.java index d4a0e6c0b..308c2730a 100644 --- a/src/test/java/io/supertokens/test/session/JWTDataTest.java +++ b/src/test/java/io/supertokens/test/session/JWTDataTest.java @@ -37,6 +37,9 @@ public class JWTDataTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/session/JWTTest.java b/src/test/java/io/supertokens/test/session/JWTTest.java index c4519e4e2..e67192d40 100644 --- a/src/test/java/io/supertokens/test/session/JWTTest.java +++ b/src/test/java/io/supertokens/test/session/JWTTest.java @@ -38,6 +38,9 @@ public class JWTTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/session/RefreshTokenTest.java b/src/test/java/io/supertokens/test/session/RefreshTokenTest.java index 4bedf4e62..3c1020e1f 100644 --- a/src/test/java/io/supertokens/test/session/RefreshTokenTest.java +++ b/src/test/java/io/supertokens/test/session/RefreshTokenTest.java @@ -50,6 +50,9 @@ public class RefreshTokenTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -107,7 +110,7 @@ public void createRefreshTokenAndLoadAfterProcessRestart() NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, StorageQueryException, StorageTransactionLogicException, UnauthorisedException { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); TokenInfo tokenInfo = RefreshToken.createNewRefreshToken(process.getProcess(), "sessionHandle", "userId", @@ -121,7 +124,7 @@ public void createRefreshTokenAndLoadAfterProcessRestart() return; } - process = TestingProcessManager.start(args); + process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); RefreshTokenInfo infoFromToken = RefreshToken.getInfoFromRefreshToken(process.getProcess(), tokenInfo.token); @@ -137,7 +140,6 @@ public void createRefreshTokenAndLoadAfterProcessRestart() process.kill(); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STOPPED)); - } @Test @@ -146,7 +148,7 @@ public void createRefreshTokenButVerifyWithDifferentSigningKeyFailure() NoSuchPaddingException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, StorageQueryException, StorageTransactionLogicException { String[] args = {"../"}; - TestingProcess process = TestingProcessManager.start(args); + TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); TokenInfo tokenInfo = RefreshToken.createNewRefreshToken(process.getProcess(), "sessionHandle", "userId", @@ -157,7 +159,7 @@ public void createRefreshTokenButVerifyWithDifferentSigningKeyFailure() Utils.reset(); - process = TestingProcessManager.start(args); + process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(PROCESS_STATE.STARTED)); try { diff --git a/src/test/java/io/supertokens/test/session/RegenerateTokenTest.java b/src/test/java/io/supertokens/test/session/RegenerateTokenTest.java index 68405ed34..5c7d2ad26 100644 --- a/src/test/java/io/supertokens/test/session/RegenerateTokenTest.java +++ b/src/test/java/io/supertokens/test/session/RegenerateTokenTest.java @@ -36,6 +36,9 @@ public class RegenerateTokenTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -202,7 +205,7 @@ public void testSessionRegenerateWithTokenExpiryAndRefresh() throws Exception { Utils.setValueInConfig("access_token_validity", "2");// 1 second validity - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; diff --git a/src/test/java/io/supertokens/test/session/SessionGetJWTDataTest.java b/src/test/java/io/supertokens/test/session/SessionGetJWTDataTest.java index ac1a9f07a..6c7db1719 100644 --- a/src/test/java/io/supertokens/test/session/SessionGetJWTDataTest.java +++ b/src/test/java/io/supertokens/test/session/SessionGetJWTDataTest.java @@ -36,6 +36,9 @@ public class SessionGetJWTDataTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -161,7 +164,7 @@ public void testExpireSessionCallGetAndCheckUnauthorised() throws Exception { Utils.setValueInConfig("refresh_token_validity", "" + 1.0 / 60);// 1 second validity (value in mins) - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); // createSession with JWT payload diff --git a/src/test/java/io/supertokens/test/session/SessionGetSessionDataTest.java b/src/test/java/io/supertokens/test/session/SessionGetSessionDataTest.java index bca8f54d0..43e897f66 100644 --- a/src/test/java/io/supertokens/test/session/SessionGetSessionDataTest.java +++ b/src/test/java/io/supertokens/test/session/SessionGetSessionDataTest.java @@ -41,6 +41,9 @@ public class SessionGetSessionDataTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/session/SessionGetUserIDTest.java b/src/test/java/io/supertokens/test/session/SessionGetUserIDTest.java index 5886bcf59..97d9f832c 100644 --- a/src/test/java/io/supertokens/test/session/SessionGetUserIDTest.java +++ b/src/test/java/io/supertokens/test/session/SessionGetUserIDTest.java @@ -48,6 +48,9 @@ public class SessionGetUserIDTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/session/SessionTest1.java b/src/test/java/io/supertokens/test/session/SessionTest1.java index bd8a7ce0a..549b03213 100644 --- a/src/test/java/io/supertokens/test/session/SessionTest1.java +++ b/src/test/java/io/supertokens/test/session/SessionTest1.java @@ -23,7 +23,6 @@ import io.supertokens.ProcessState; import io.supertokens.exceptions.TryRefreshTokenException; import io.supertokens.exceptions.UnauthorisedException; -import io.supertokens.pluginInterface.multitenancy.TenantIdentifier; import io.supertokens.pluginInterface.session.SessionStorage; import io.supertokens.session.Session; import io.supertokens.session.accessToken.AccessToken; @@ -45,6 +44,9 @@ public class SessionTest1 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -59,7 +61,7 @@ public void beforeEach() { public void createAndGetSession() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; @@ -74,7 +76,7 @@ public void createAndGetSession() throws Exception { assertEquals(sessionInfo.session.userId, userId); assertEquals(sessionInfo.session.userDataInJWT.toString(), userDataInJWT.toString()); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); + .getNumberOfSessions(process.getAppForTesting()), 1); assert sessionInfo.accessToken != null; assertNull(sessionInfo.antiCsrfToken); assert sessionInfo.idRefreshToken != null; @@ -95,7 +97,7 @@ public void createAndGetSession() throws Exception { public void createAndGetSessionNoAntiCSRF() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; @@ -110,7 +112,7 @@ public void createAndGetSessionNoAntiCSRF() throws Exception { assertEquals(sessionInfo.session.userId, userId); assertEquals(sessionInfo.session.userDataInJWT.toString(), userDataInJWT.toString()); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); + .getNumberOfSessions(process.getAppForTesting()), 1); assert sessionInfo.accessToken != null; assertNull(sessionInfo.antiCsrfToken); @@ -163,7 +165,7 @@ public void createSessionWhichExpiresInOneSecondCheck() throws Exception { public void createNewSessionAndAlterJWTPayload() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; @@ -178,7 +180,7 @@ public void createNewSessionAndAlterJWTPayload() throws Exception { assertEquals(sessionInfo.session.userId, userId); assertEquals(sessionInfo.session.userDataInJWT.toString(), userDataInJWT.toString()); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); + .getNumberOfSessions(process.getAppForTesting()), 1); assert sessionInfo.accessToken != null; assertNull(sessionInfo.antiCsrfToken); @@ -204,7 +206,7 @@ public void createNewSessionAndAlterJWTPayload() throws Exception { public void createAndGetSessionWithEmptyJWTPayload() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; @@ -217,7 +219,7 @@ public void createAndGetSessionWithEmptyJWTPayload() throws Exception { assertEquals(sessionInfo.session.userId, userId); assertEquals(sessionInfo.session.userDataInJWT.toString(), userDataInJWT.toString()); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); + .getNumberOfSessions(process.getAppForTesting()), 1); assert sessionInfo.accessToken != null; assertNull(sessionInfo.antiCsrfToken); @@ -237,7 +239,7 @@ public void createAndGetSessionWithEmptyJWTPayload() throws Exception { public void createAndGetSessionWithComplexJWTPayload() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; @@ -260,7 +262,7 @@ public void createAndGetSessionWithComplexJWTPayload() throws Exception { assertEquals(sessionInfo.session.userId, userId); assertEquals(sessionInfo.session.userDataInJWT.toString(), userDataInJWT.toString()); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); + .getNumberOfSessions(process.getAppForTesting()), 1); assert sessionInfo.accessToken != null; assertNull(sessionInfo.antiCsrfToken); @@ -337,7 +339,7 @@ public void createAndGetSessionWithSigningKeyChangeV2() throws Exception { Utils.setValueInConfig("access_token_validity", "1"); // 1 second String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; @@ -391,7 +393,7 @@ public void refreshSessionTestWithAntiCsrf() throws Exception { Utils.setValueInConfig("access_token_validity", "1"); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; @@ -428,7 +430,7 @@ public void refreshSessionTestWithAntiCsrf() throws Exception { assertEquals(refreshedSession.session.userId, sessionInfo.session.userId); assertEquals(refreshedSession.session.userDataInJWT.toString(), sessionInfo.session.userDataInJWT.toString()); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); + .getNumberOfSessions(process.getAppForTesting()), 1); SessionInformationHolder newSession = Session.getSession(process.getProcess(), refreshedSession.accessToken.token, refreshedSession.antiCsrfToken, true, true, false); @@ -454,7 +456,7 @@ public void refreshSessionTestWithAntiCsrf() throws Exception { refreshedSession.refreshToken.token, refreshedSession.antiCsrfToken, true, AccessToken.getLatestVersion()); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); + .getNumberOfSessions(process.getAppForTesting()), 1); assert refreshedSession2.accessToken != null; assertNotEquals(refreshedSession2.accessToken.token, newSession.accessToken.token); @@ -478,7 +480,7 @@ public void refreshSessionTestWithNoAntiCsrf() throws Exception { Utils.setValueInConfig("access_token_validity", "1"); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; @@ -515,7 +517,7 @@ public void refreshSessionTestWithNoAntiCsrf() throws Exception { assertEquals(refreshedSession.session.userId, sessionInfo.session.userId); assertEquals(refreshedSession.session.userDataInJWT.toString(), sessionInfo.session.userDataInJWT.toString()); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); + .getNumberOfSessions(process.getAppForTesting()), 1); SessionInformationHolder newSession = Session.getSession(process.getProcess(), refreshedSession.accessToken.token, null, false, true, false); @@ -540,7 +542,7 @@ public void refreshSessionTestWithNoAntiCsrf() throws Exception { refreshedSession.refreshToken.token, refreshedSession.antiCsrfToken, false, AccessToken.getLatestVersion()); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); + .getNumberOfSessions(process.getAppForTesting()), 1); assert refreshedSession2.accessToken != null; assertNotEquals(refreshedSession2.accessToken.token, newSession.accessToken.token); @@ -592,7 +594,7 @@ public void refreshTokenExpiresAfterShortTime() throws Exception { Utils.setValueInConfig("refresh_token_validity", "" + 1.5 / 60.0); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); Main main = process.getProcess(); @@ -615,7 +617,7 @@ public void refreshTokenExpiresAfterShortTime() throws Exception { assert newRefreshedSession.refreshToken != null; assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); + .getNumberOfSessions(process.getAppForTesting()), 1); Session.getSession(main, sessionInfo.accessToken.token, sessionInfo.antiCsrfToken, false, true, false); @@ -629,7 +631,7 @@ public void refreshTokenExpiresAfterShortTime() throws Exception { } assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); + .getNumberOfSessions(process.getAppForTesting()), 1); } // Part 2 @@ -639,7 +641,7 @@ public void refreshTokenExpiresAfterShortTime() throws Exception { assert sessionInfo.refreshToken != null; assert sessionInfo.accessToken != null; assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 2); + .getNumberOfSessions(process.getAppForTesting()), 2); SessionInformationHolder newRefreshedSession = Session.refreshSession(main, sessionInfo.refreshToken.token, sessionInfo.antiCsrfToken, false, AccessToken.getLatestVersion()); @@ -648,7 +650,7 @@ public void refreshTokenExpiresAfterShortTime() throws Exception { assertNotEquals(newRefreshedSession.accessToken.token, sessionInfo.accessToken.token); assertNotEquals(newRefreshedSession.refreshToken.token, sessionInfo.refreshToken.token); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 2); + .getNumberOfSessions(process.getAppForTesting()), 2); Thread.sleep(500); @@ -660,7 +662,7 @@ public void refreshTokenExpiresAfterShortTime() throws Exception { assertNotEquals(newRefreshedSession.accessToken.token, newRefreshedSession2.accessToken.token); assertNotEquals(newRefreshedSession.refreshToken.token, newRefreshedSession2.refreshToken.token); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 2); + .getNumberOfSessions(process.getAppForTesting()), 2); Thread.sleep(500); @@ -672,12 +674,11 @@ public void refreshTokenExpiresAfterShortTime() throws Exception { assertNotEquals(newRefreshedSession3.accessToken.token, newRefreshedSession2.accessToken.token); assertNotEquals(newRefreshedSession3.refreshToken.token, newRefreshedSession2.refreshToken.token); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 2); + .getNumberOfSessions(process.getAppForTesting()), 2); } process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); - } } diff --git a/src/test/java/io/supertokens/test/session/SessionTest2.java b/src/test/java/io/supertokens/test/session/SessionTest2.java index 5643cfc16..43d817100 100644 --- a/src/test/java/io/supertokens/test/session/SessionTest2.java +++ b/src/test/java/io/supertokens/test/session/SessionTest2.java @@ -44,6 +44,9 @@ public class SessionTest2 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -182,7 +185,7 @@ public void updateSessionInfo() throws Exception { public void revokeSessionWithoutBlacklisting() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; @@ -199,11 +202,11 @@ public void revokeSessionWithoutBlacklisting() throws Exception { Session.createNewSession(process.getProcess(), userId, userDataInJWT, userDataInDatabase); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 2); + .getNumberOfSessions(process.getAppForTesting()), 2); Session.revokeSessionUsingSessionHandles(process.getProcess(), new String[]{sessionInfo.session.handle}); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); + .getNumberOfSessions(process.getAppForTesting()), 1); try { Session.refreshSession(process.getProcess(), sessionInfo.refreshToken.token, sessionInfo.antiCsrfToken, diff --git a/src/test/java/io/supertokens/test/session/SessionTest3.java b/src/test/java/io/supertokens/test/session/SessionTest3.java index 6b15047ef..ab6393e86 100644 --- a/src/test/java/io/supertokens/test/session/SessionTest3.java +++ b/src/test/java/io/supertokens/test/session/SessionTest3.java @@ -20,12 +20,8 @@ import io.supertokens.ProcessState; import io.supertokens.cronjobs.CronTaskTest; import io.supertokens.cronjobs.deleteExpiredSessions.DeleteExpiredSessions; -import io.supertokens.exceptions.TokenTheftDetectedException; import io.supertokens.exceptions.TryRefreshTokenException; import io.supertokens.exceptions.UnauthorisedException; -import io.supertokens.pluginInterface.exceptions.StorageQueryException; -import io.supertokens.pluginInterface.exceptions.StorageTransactionLogicException; -import io.supertokens.pluginInterface.multitenancy.TenantIdentifier; import io.supertokens.pluginInterface.session.SessionStorage; import io.supertokens.session.Session; import io.supertokens.session.accessToken.AccessToken; @@ -39,16 +35,6 @@ import org.junit.Test; import org.junit.rules.TestRule; -import javax.crypto.BadPaddingException; -import javax.crypto.IllegalBlockSizeException; -import javax.crypto.NoSuchPaddingException; -import java.io.IOException; -import java.security.InvalidAlgorithmParameterException; -import java.security.InvalidKeyException; -import java.security.NoSuchAlgorithmException; -import java.security.SignatureException; -import java.security.spec.InvalidKeySpecException; - import static junit.framework.TestCase.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; @@ -58,6 +44,9 @@ public class SessionTest3 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -88,11 +77,11 @@ public void revokeSessionWithBlacklistingRefreshSessionAndGetSessionThrows() thr Session.createNewSession(process.getProcess(), userId, userDataInJWT, userDataInDatabase); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 2); + .getNumberOfSessions(process.getAppForTesting()), 2); Session.revokeSessionUsingSessionHandles(process.getProcess(), new String[]{sessionInfo.session.handle}); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); + .getNumberOfSessions(process.getAppForTesting()), 1); try { Session.refreshSession(process.getProcess(), sessionInfo.refreshToken.token, sessionInfo.antiCsrfToken, @@ -167,7 +156,7 @@ public void removeSessionFromDbButAccessTokenStillValidUntilExpiry() throws Exce public void revokeAllSessionsForUserWithoutBlacklisting() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; @@ -194,12 +183,12 @@ public void revokeAllSessionsForUserWithoutBlacklisting() throws Exception { Session.createNewSession(process.getProcess(), "userId2", userDataInJWT, userDataInDatabase); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 4); + .getNumberOfSessions(process.getAppForTesting()), 4); assertEquals(Session.revokeAllSessionsForUser(process.getProcess(), userId).length, 3); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); + .getNumberOfSessions(process.getAppForTesting()), 1); Session.getSession(process.getProcess(), sessionInfo.accessToken.token, sessionInfo.antiCsrfToken, false, true, false); @@ -219,7 +208,7 @@ public void removeExpiredSessions() throws Exception { Utils.setValueInConfig("refresh_token_validity", "" + 1.0 / 60.0); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args, false); CronTaskTest.getInstance(process.getProcess()).setIntervalInSeconds(DeleteExpiredSessions.RESOURCE_KEY, 1); @@ -248,13 +237,13 @@ public void removeExpiredSessions() throws Exception { assert sessionInfo3.accessToken != null; assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 3); + .getNumberOfSessions(process.getAppForTesting()), 3); Thread.sleep(2500); Session.createNewSession(process.getProcess(), userId, userDataInJWT, userDataInDatabase); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); + .getNumberOfSessions(process.getAppForTesting()), 1); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); diff --git a/src/test/java/io/supertokens/test/session/SessionTest4.java b/src/test/java/io/supertokens/test/session/SessionTest4.java index 6295cc7c5..c185c1c5f 100644 --- a/src/test/java/io/supertokens/test/session/SessionTest4.java +++ b/src/test/java/io/supertokens/test/session/SessionTest4.java @@ -40,6 +40,9 @@ public class SessionTest4 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -54,7 +57,7 @@ public void beforeEach() { public void checkForNumberOfDeletedSessions() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; @@ -92,7 +95,7 @@ public void checkForNumberOfDeletedSessions() throws Exception { assertTrue(revokedAll); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 2); + .getNumberOfSessions(process.getAppForTesting()), 2); Session.createNewSession(process.getProcess(), userId, userDataInJWT, userDataInDatabase); Session.createNewSession(process.getProcess(), userId, userDataInJWT, userDataInDatabase); @@ -101,12 +104,12 @@ public void checkForNumberOfDeletedSessions() throws Exception { assertEquals(Session.revokeAllSessionsForUser(process.getProcess(), userId).length, 4); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); + .getNumberOfSessions(process.getAppForTesting()), 1); assertEquals(Session.revokeAllSessionsForUser(process.getProcess(), "userId2").length, 1); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 0); + .getNumberOfSessions(process.getAppForTesting()), 0); assertEquals(Session.revokeSessionUsingSessionHandles(process.getProcess(), handles).length, 0); assertEquals(Session.revokeAllSessionsForUser(process.getProcess(), "userId2").length, 0); @@ -150,7 +153,7 @@ public void createVerifyRefreshVerifyRefresh() throws Exception { Utils.setValueInConfig("access_token_validity", "3"); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; @@ -164,7 +167,7 @@ public void createVerifyRefreshVerifyRefresh() throws Exception { assertEquals(sessionInfo.session.userId, userId); assertEquals(sessionInfo.session.userDataInJWT.toString(), userDataInJWT.toString()); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); + .getNumberOfSessions(process.getAppForTesting()), 1); assert sessionInfo.accessToken != null; assert sessionInfo.refreshToken != null; assertNull(sessionInfo.antiCsrfToken); @@ -199,7 +202,7 @@ public void createVerifyRefreshVerifyRefresh() throws Exception { assert sessionInfo.accessToken != null; assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); + .getNumberOfSessions(process.getAppForTesting()), 1); } process.kill(); @@ -210,7 +213,7 @@ public void createVerifyRefreshVerifyRefresh() throws Exception { public void verifyAccessTokenThatIsBelongsToGrandparentRefreshToken() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; @@ -224,7 +227,7 @@ public void verifyAccessTokenThatIsBelongsToGrandparentRefreshToken() throws Exc assertEquals(sessionInfo.session.userId, userId); assertEquals(sessionInfo.session.userDataInJWT.toString(), userDataInJWT.toString()); assertEquals(((SessionStorage) StorageLayer.getStorage(process.getProcess())) - .getNumberOfSessions(new TenantIdentifier(null, null, null)), 1); + .getNumberOfSessions(process.getAppForTesting()), 1); assert sessionInfo.accessToken != null; assert sessionInfo.refreshToken != null; assertNull(sessionInfo.antiCsrfToken); @@ -294,7 +297,7 @@ public void checkThatExpiredSessionIsNotReturnedForUserNorCanItBeUpdated() throw Utils.setValueInConfig("refresh_token_validity", "0.08"); // 5 seconds String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); SessionInformationHolder expiredSession = Session.createNewSession(process.getProcess(), "user", @@ -342,7 +345,7 @@ public void testCreatingSessionsWithLongAccessAndRefreshTokenLifeTimes() throws Utils.setValueInConfig("refresh_token_validity", "1051200"); // 2 years in minutes String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); SessionInformationHolder sessionInfo = Session.createNewSession(process.getProcess(), "user", new JsonObject(), @@ -363,7 +366,7 @@ public void testCreatingSessionsWithLongAccessAndRefreshTokenLifeTimesAndRefresh Utils.setValueInConfig("refresh_token_validity", "1051200"); // 2 years in minutes String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); SessionInformationHolder sessionInfo = Session.createNewSession(process.getProcess(), "user", new JsonObject(), @@ -373,7 +376,7 @@ public void testCreatingSessionsWithLongAccessAndRefreshTokenLifeTimesAndRefresh assertEquals(sessionInfo.accessToken.expiry - sessionInfo.accessToken.createdTime, twoYearsInSeconds * 1000); assertEquals(sessionInfo.refreshToken.expiry - sessionInfo.refreshToken.createdTime, twoYearsInSeconds * 1000); - SessionInformationHolder sessionInfo2 = Session.refreshSession(process.main, sessionInfo.refreshToken.token, + SessionInformationHolder sessionInfo2 = Session.refreshSession(process.getProcess(), sessionInfo.refreshToken.token, null, false, AccessToken.getLatestVersion()); assertFalse(sessionInfo.accessToken.token.equals(sessionInfo2.accessToken.token)); @@ -393,7 +396,7 @@ public void createNewSessionAndUpdateSession() throws Exception { Utils.setValueInConfig("access_token_validity", "63072000"); // 2 years in seconds Utils.setValueInConfig("refresh_token_validity", "1051200"); // 2 years in minutes String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); SessionInformationHolder sessionInfo = Session.createNewSession(process.getProcess(), "user", new JsonObject(), @@ -408,10 +411,10 @@ public void createNewSessionAndUpdateSession() throws Exception { JsonObject jwtData = new JsonObject(); jwtData.addProperty("test", "value"); - Session.updateSession(process.main, sessionInfo.session.handle, sessionData, jwtData, + Session.updateSession(process.getProcess(), sessionInfo.session.handle, sessionData, jwtData, AccessToken.getLatestVersion()); - io.supertokens.pluginInterface.session.SessionInfo sessionInfo2 = Session.getSession(process.main, + io.supertokens.pluginInterface.session.SessionInfo sessionInfo2 = Session.getSession(process.getProcess(), sessionInfo.session.handle); assertEquals(sessionInfo2.expiry - sessionInfo2.timeCreated, twoYearsInSeconds * 1000); diff --git a/src/test/java/io/supertokens/test/session/SessionTest5.java b/src/test/java/io/supertokens/test/session/SessionTest5.java index 2bb2c6c7a..98f54a1eb 100644 --- a/src/test/java/io/supertokens/test/session/SessionTest5.java +++ b/src/test/java/io/supertokens/test/session/SessionTest5.java @@ -44,6 +44,9 @@ public class SessionTest5 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -298,7 +301,7 @@ public void checkRefreshKidChangesAfterDynamicSigningKeyChange() throws Exceptio Utils.setValueInConfig("access_token_dynamic_signing_key_update_interval", "0.00027"); // 1 second String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; @@ -341,7 +344,7 @@ public void checkDynamicKeyOverlap() throws Exception { Utils.setValueInConfig("access_token_dynamic_signing_key_update_interval", "0.00081"); // 3 seconds String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); AccessTokenSigningKey.getInstance(process.getProcess()).setDynamicSigningKeyOverlapMS(1000); diff --git a/src/test/java/io/supertokens/test/session/SessionTest6.java b/src/test/java/io/supertokens/test/session/SessionTest6.java index 5db3fa98e..85a60314d 100644 --- a/src/test/java/io/supertokens/test/session/SessionTest6.java +++ b/src/test/java/io/supertokens/test/session/SessionTest6.java @@ -42,6 +42,9 @@ public class SessionTest6 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -68,7 +71,7 @@ public void createRefreshSwitchVerify() throws Exception { userDataInDatabase, false, AccessToken.getLatestVersion(), false); checkIfUsingStaticKey(sessionInfo, false); - sessionInfo = Session.refreshSession(new AppIdentifier(null, null), process.getProcess(), + sessionInfo = Session.refreshSession(process.getAppForTesting().toAppIdentifier(), process.getProcess(), sessionInfo.refreshToken.token, sessionInfo.antiCsrfToken, false, AccessToken.getLatestVersion(), true); assert sessionInfo.refreshToken != null; @@ -102,7 +105,7 @@ public void createRefreshSwitchRegen() throws Exception { userDataInDatabase, false, AccessToken.getLatestVersion(), false); checkIfUsingStaticKey(sessionInfo, false); - sessionInfo = Session.refreshSession(new AppIdentifier(null, null), process.getProcess(), + sessionInfo = Session.refreshSession(process.getAppForTesting().toAppIdentifier(), process.getProcess(), sessionInfo.refreshToken.token, sessionInfo.antiCsrfToken, false, AccessToken.getLatestVersion(), true); assert sessionInfo.refreshToken != null; @@ -137,11 +140,11 @@ public void createRefreshRefreshSwitchVerify() throws Exception { userDataInDatabase, false, AccessToken.getLatestVersion(), false); checkIfUsingStaticKey(sessionInfo, false); - sessionInfo = Session.refreshSession(new AppIdentifier(null, null), process.getProcess(), + sessionInfo = Session.refreshSession(process.getAppForTesting().toAppIdentifier(), process.getProcess(), sessionInfo.refreshToken.token, sessionInfo.antiCsrfToken, false, AccessToken.getLatestVersion(), false); - sessionInfo = Session.refreshSession(new AppIdentifier(null, null), process.getProcess(), + sessionInfo = Session.refreshSession(process.getAppForTesting().toAppIdentifier(), process.getProcess(), sessionInfo.refreshToken.token, sessionInfo.antiCsrfToken, false, AccessToken.getLatestVersion(), true); assert sessionInfo.refreshToken != null; @@ -175,11 +178,11 @@ public void createRefreshRefreshSwitchRegen() throws Exception { userDataInDatabase, false, AccessToken.getLatestVersion(), false); checkIfUsingStaticKey(sessionInfo, false); - sessionInfo = Session.refreshSession(new AppIdentifier(null, null), process.getProcess(), + sessionInfo = Session.refreshSession(process.getAppForTesting().toAppIdentifier(), process.getProcess(), sessionInfo.refreshToken.token, sessionInfo.antiCsrfToken, false, AccessToken.getLatestVersion(), false); - sessionInfo = Session.refreshSession(new AppIdentifier(null, null), process.getProcess(), + sessionInfo = Session.refreshSession(process.getAppForTesting().toAppIdentifier(), process.getProcess(), sessionInfo.refreshToken.token, sessionInfo.antiCsrfToken, false, AccessToken.getLatestVersion(), true); assert sessionInfo.refreshToken != null; diff --git a/src/test/java/io/supertokens/test/session/UserIdMappingTest.java b/src/test/java/io/supertokens/test/session/UserIdMappingTest.java index 0e75251ab..6e345b2c6 100644 --- a/src/test/java/io/supertokens/test/session/UserIdMappingTest.java +++ b/src/test/java/io/supertokens/test/session/UserIdMappingTest.java @@ -44,6 +44,9 @@ public class UserIdMappingTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -58,26 +61,25 @@ public void beforeEach() { public void testCreatingAUserIdMappingAndSession() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); // create a User - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); - AuthRecipeUserInfo userInfo2 = EmailPassword.signUp(process.main, "test2@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "testPass123"); - AuthRecipe.createPrimaryUser(process.main, userInfo.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), userInfo.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, userInfo2.getSupertokensUserId(), + AuthRecipe.linkAccounts(process.getProcess(), userInfo2.getSupertokensUserId(), userInfo.getSupertokensUserId()); String superTokensUserId = userInfo.getSupertokensUserId(); @@ -99,7 +101,7 @@ public void testCreatingAUserIdMappingAndSession() throws Exception { // check that userIdMapping was created - UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), + UserIdMapping userIdMapping = storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), superTokensUserId, true); assertEquals(superTokensUserId, userIdMapping.superTokensUserId); @@ -166,26 +168,25 @@ public void testCreatingAUserIdMappingAndSession() throws Exception { public void testCreatingAUserIdMappingAndSessionWithRecipeUserId() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); // create a User - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); - AuthRecipeUserInfo userInfo2 = EmailPassword.signUp(process.main, "test2@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "testPass123"); - AuthRecipe.createPrimaryUser(process.main, userInfo.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), userInfo.getSupertokensUserId()); - AuthRecipe.linkAccounts(process.main, userInfo2.getSupertokensUserId(), + AuthRecipe.linkAccounts(process.getProcess(), userInfo2.getSupertokensUserId(), userInfo.getSupertokensUserId()); String superTokensUserId = userInfo2.getSupertokensUserId(); @@ -207,7 +208,7 @@ public void testCreatingAUserIdMappingAndSessionWithRecipeUserId() throws Except // check that userIdMapping was created - UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), + UserIdMapping userIdMapping = storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), superTokensUserId, true); assertEquals(superTokensUserId, userIdMapping.superTokensUserId); diff --git a/src/test/java/io/supertokens/test/session/api/HandshakeAPITest2_21.java b/src/test/java/io/supertokens/test/session/api/HandshakeAPITest2_21.java index 113351bc0..e76caf370 100644 --- a/src/test/java/io/supertokens/test/session/api/HandshakeAPITest2_21.java +++ b/src/test/java/io/supertokens/test/session/api/HandshakeAPITest2_21.java @@ -32,6 +32,9 @@ public class HandshakeAPITest2_21 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/session/api/HandshakeAPITest2_7.java b/src/test/java/io/supertokens/test/session/api/HandshakeAPITest2_7.java index 33e8e938e..eef7e535a 100644 --- a/src/test/java/io/supertokens/test/session/api/HandshakeAPITest2_7.java +++ b/src/test/java/io/supertokens/test/session/api/HandshakeAPITest2_7.java @@ -42,6 +42,9 @@ public class HandshakeAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -146,7 +149,7 @@ public void changingSigningKeyHandshakeAPITest() throws Exception { String[] args = {"../"}; Utils.setValueInConfig("access_token_dynamic_signing_key_update_interval", "0.00081"); // 0.00027*3 = 3 seconds - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String jsonInput = "{" + "\"deviceDriverInfo\": {" + "\"frontendSDK\": [{" + "\"name\": \"hName\"," @@ -159,7 +162,7 @@ public void changingSigningKeyHandshakeAPITest() throws Exception { assertEquals(response.entrySet().size(), 6); assertEquals(response.get("jwtSigningPublicKey").getAsString(), new io.supertokens.utils.Utils.PubPriKey( - SigningKeys.getInstance(process.main).getLatestIssuedDynamicKey().value).publicKey); + SigningKeys.getInstance(process.getProcess()).getLatestIssuedDynamicKey().value).publicKey); Thread.sleep(4000); @@ -173,7 +176,7 @@ public void changingSigningKeyHandshakeAPITest() throws Exception { // the previous signing key assertTrue(changedResponse.get("jwtSigningPublicKey").getAsString() .equals(new io.supertokens.utils.Utils.PubPriKey( - SigningKeys.getInstance(process.main).getLatestIssuedDynamicKey().value).publicKey) + SigningKeys.getInstance(process.getProcess()).getLatestIssuedDynamicKey().value).publicKey) && !(changedResponse.get("jwtSigningPublicKey").getAsString() .equals(response.get("jwtSigningPublicKey").getAsString()))); @@ -189,7 +192,7 @@ private static void checkHandshakeAPIResponse(JsonObject response, TestingProces // check jwtSigningPublicKey assertEquals(response.get("jwtSigningPublicKey").getAsString(), new io.supertokens.utils.Utils.PubPriKey( - SigningKeys.getInstance(process.main).getLatestIssuedDynamicKey().value).publicKey); + SigningKeys.getInstance(process.getProcess()).getLatestIssuedDynamicKey().value).publicKey); // check jwtSigningPublicKeyExpiryTime assertEquals(response.get("jwtSigningPublicKeyExpiryTime").getAsLong(), diff --git a/src/test/java/io/supertokens/test/session/api/HandshakeAPITest2_9.java b/src/test/java/io/supertokens/test/session/api/HandshakeAPITest2_9.java index d500205ca..9a828ee51 100644 --- a/src/test/java/io/supertokens/test/session/api/HandshakeAPITest2_9.java +++ b/src/test/java/io/supertokens/test/session/api/HandshakeAPITest2_9.java @@ -46,6 +46,9 @@ public class HandshakeAPITest2_9 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -151,7 +154,7 @@ public void changingSigningKeyHandshakeAPITest() throws Exception { Utils.setValueInConfig("access_token_dynamic_signing_key_update_interval", "0.00081"); // 0.00027*3 = 3 seconds Utils.setValueInConfig("access_token_validity", "1"); // 1 second - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String jsonInput = "{" + "\"deviceDriverInfo\": {" + "\"frontendSDK\": [{" + "\"name\": \"hName\"," @@ -163,7 +166,7 @@ public void changingSigningKeyHandshakeAPITest() throws Exception { assertEquals(response.entrySet().size(), 7); - List keys = SigningKeys.getInstance(process.main).getDynamicKeys().stream() + List keys = SigningKeys.getInstance(process.getProcess()).getDynamicKeys().stream() .map(key -> new io.supertokens.utils.Utils.PubPriKey(key.value).publicKey).collect(Collectors.toList()); assertEquals(response.get("jwtSigningPublicKey").getAsString(), keys.get(0)); @@ -186,7 +189,7 @@ public void changingSigningKeyHandshakeAPITest() throws Exception { // check that changed response has the same signing key as the current signing key and it is different from // the previous signing key - List changedPubKeys = SigningKeys.getInstance(process.main).getDynamicKeys().stream() + List changedPubKeys = SigningKeys.getInstance(process.getProcess()).getDynamicKeys().stream() .map(key -> new io.supertokens.utils.Utils.PubPriKey(key.value).publicKey).collect(Collectors.toList()); JsonArray changedRespPubKeyList = changedResponse.get("jwtSigningPublicKeyList").getAsJsonArray(); @@ -213,7 +216,7 @@ private static void checkHandshakeAPIResponse(JsonObject response, TestingProces // check status assertEquals(response.get("status").getAsString(), "OK"); - List allKeys = SigningKeys.getInstance(process.main).getDynamicKeys(); + List allKeys = SigningKeys.getInstance(process.getProcess()).getDynamicKeys(); List pubKeys = allKeys.stream() .map(key -> new io.supertokens.utils.Utils.PubPriKey(key.value).publicKey).collect(Collectors.toList()); diff --git a/src/test/java/io/supertokens/test/session/api/JWTDataAPITest2_21.java b/src/test/java/io/supertokens/test/session/api/JWTDataAPITest2_21.java index dc37a864a..ffb45b711 100644 --- a/src/test/java/io/supertokens/test/session/api/JWTDataAPITest2_21.java +++ b/src/test/java/io/supertokens/test/session/api/JWTDataAPITest2_21.java @@ -38,6 +38,9 @@ public class JWTDataAPITest2_21 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/session/api/JWTDataAPITest2_7.java b/src/test/java/io/supertokens/test/session/api/JWTDataAPITest2_7.java index f97ae664b..28673021d 100644 --- a/src/test/java/io/supertokens/test/session/api/JWTDataAPITest2_7.java +++ b/src/test/java/io/supertokens/test/session/api/JWTDataAPITest2_7.java @@ -38,6 +38,9 @@ public class JWTDataAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest2_21.java b/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest2_21.java index a909961e5..7af48dbb5 100644 --- a/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest2_21.java +++ b/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest2_21.java @@ -35,6 +35,9 @@ public class RefreshSessionAPITest2_21 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest2_7.java b/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest2_7.java index 2dba29b86..5caa44fb3 100644 --- a/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest2_7.java +++ b/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest2_7.java @@ -43,6 +43,9 @@ public class RefreshSessionAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -58,7 +61,7 @@ public void refreshWithAntiCsrfOffOn() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; @@ -86,7 +89,7 @@ public void refreshWithAntiCsrfOffOn() throws Exception { return; } - process = TestingProcessManager.start(args); + process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); { @@ -113,7 +116,7 @@ public void refreshWithAntiCsrfOnOffOn() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; @@ -141,7 +144,7 @@ public void refreshWithAntiCsrfOnOffOn() throws Exception { return; } - process = TestingProcessManager.start(args); + process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); { @@ -161,7 +164,7 @@ public void refreshWithAntiCsrfOnOffOn() throws Exception { process.kill(false); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); - process = TestingProcessManager.start(args); + process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); { diff --git a/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest3_0.java b/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest3_0.java index 3d0c0c880..0fbf80ba2 100644 --- a/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest3_0.java +++ b/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest3_0.java @@ -38,6 +38,9 @@ public class RefreshSessionAPITest3_0 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest5_0.java b/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest5_0.java index 901605dd1..8a4ce76f9 100644 --- a/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest5_0.java +++ b/src/test/java/io/supertokens/test/session/api/RefreshSessionAPITest5_0.java @@ -39,6 +39,9 @@ public class RefreshSessionAPITest5_0 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/session/api/SessionAPITest2_21.java b/src/test/java/io/supertokens/test/session/api/SessionAPITest2_21.java index abfb4ed0e..026081680 100644 --- a/src/test/java/io/supertokens/test/session/api/SessionAPITest2_21.java +++ b/src/test/java/io/supertokens/test/session/api/SessionAPITest2_21.java @@ -43,6 +43,9 @@ public class SessionAPITest2_21 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/session/api/SessionAPITest2_7.java b/src/test/java/io/supertokens/test/session/api/SessionAPITest2_7.java index 93b65c4e6..ba669e3cd 100644 --- a/src/test/java/io/supertokens/test/session/api/SessionAPITest2_7.java +++ b/src/test/java/io/supertokens/test/session/api/SessionAPITest2_7.java @@ -40,6 +40,9 @@ public class SessionAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/session/api/SessionAPITest2_9.java b/src/test/java/io/supertokens/test/session/api/SessionAPITest2_9.java index a9615bbc1..1fb6194fb 100644 --- a/src/test/java/io/supertokens/test/session/api/SessionAPITest2_9.java +++ b/src/test/java/io/supertokens/test/session/api/SessionAPITest2_9.java @@ -47,6 +47,9 @@ public class SessionAPITest2_9 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/session/api/SessionAPITest4_0.java b/src/test/java/io/supertokens/test/session/api/SessionAPITest4_0.java index 442f887c1..f44a3f63d 100644 --- a/src/test/java/io/supertokens/test/session/api/SessionAPITest4_0.java +++ b/src/test/java/io/supertokens/test/session/api/SessionAPITest4_0.java @@ -45,6 +45,9 @@ public class SessionAPITest4_0 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/session/api/SessionDataAPITest2_7.java b/src/test/java/io/supertokens/test/session/api/SessionDataAPITest2_7.java index edcad5c7d..d92ef0da2 100644 --- a/src/test/java/io/supertokens/test/session/api/SessionDataAPITest2_7.java +++ b/src/test/java/io/supertokens/test/session/api/SessionDataAPITest2_7.java @@ -39,6 +39,9 @@ public class SessionDataAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/session/api/SessionGetAPIJWTTest2_8.java b/src/test/java/io/supertokens/test/session/api/SessionGetAPIJWTTest2_8.java index 8c067969a..3839c9211 100644 --- a/src/test/java/io/supertokens/test/session/api/SessionGetAPIJWTTest2_8.java +++ b/src/test/java/io/supertokens/test/session/api/SessionGetAPIJWTTest2_8.java @@ -39,6 +39,9 @@ public class SessionGetAPIJWTTest2_8 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/session/api/SessionRegenerateAPITest2_21.java b/src/test/java/io/supertokens/test/session/api/SessionRegenerateAPITest2_21.java index 488c3f8f0..62e5455f3 100644 --- a/src/test/java/io/supertokens/test/session/api/SessionRegenerateAPITest2_21.java +++ b/src/test/java/io/supertokens/test/session/api/SessionRegenerateAPITest2_21.java @@ -41,6 +41,9 @@ public class SessionRegenerateAPITest2_21 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -126,7 +129,7 @@ public void testCallRegenerateSessionWithv1AccessTokenFromReallyOldAndItSucceeds assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); // createSession with JWT payload - SessionInformationHolder session = Session.createNewSession(process.main, "user1", new JsonObject(), + SessionInformationHolder session = Session.createNewSession(process.getProcess(), "user1", new JsonObject(), new JsonObject()); AccessToken.AccessTokenInfo info = AccessToken.getInfoFromAccessToken(process.getProcess(), diff --git a/src/test/java/io/supertokens/test/session/api/SessionRegenerateAPITest2_7.java b/src/test/java/io/supertokens/test/session/api/SessionRegenerateAPITest2_7.java index 9eddd6c88..be35205b5 100644 --- a/src/test/java/io/supertokens/test/session/api/SessionRegenerateAPITest2_7.java +++ b/src/test/java/io/supertokens/test/session/api/SessionRegenerateAPITest2_7.java @@ -36,6 +36,9 @@ public class SessionRegenerateAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -113,7 +116,7 @@ public void testWaitForAccessTokenToExpireCallRegenerateWithNewJWTPayloadAndChec String[] args = {"../"}; Utils.setValueInConfig("access_token_validity", "1"); - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); // createSession with JWT payload diff --git a/src/test/java/io/supertokens/test/session/api/SessionRemoveAPITest2_7.java b/src/test/java/io/supertokens/test/session/api/SessionRemoveAPITest2_7.java index 04daf5538..74d96c856 100644 --- a/src/test/java/io/supertokens/test/session/api/SessionRemoveAPITest2_7.java +++ b/src/test/java/io/supertokens/test/session/api/SessionRemoveAPITest2_7.java @@ -45,6 +45,9 @@ public class SessionRemoveAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/session/api/SessionUserAPITest2_7.java b/src/test/java/io/supertokens/test/session/api/SessionUserAPITest2_7.java index 3aaa6d72f..12498a60e 100644 --- a/src/test/java/io/supertokens/test/session/api/SessionUserAPITest2_7.java +++ b/src/test/java/io/supertokens/test/session/api/SessionUserAPITest2_7.java @@ -38,6 +38,9 @@ public class SessionUserAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_21.java b/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_21.java index 9bddccfdc..bba38da7d 100644 --- a/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_21.java +++ b/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_21.java @@ -37,6 +37,9 @@ public class VerifySessionAPITest2_21 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_7.java b/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_7.java index addff469b..4da5eadda 100644 --- a/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_7.java +++ b/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_7.java @@ -36,6 +36,9 @@ public class VerifySessionAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -218,7 +221,7 @@ public void unauthorisedOutputCheck() throws Exception { Utils.setValueInConfig("access_token_blacklisting", "true"); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; diff --git a/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_9.java b/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_9.java index 2c5926437..2343a5dc6 100644 --- a/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_9.java +++ b/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest2_9.java @@ -38,6 +38,9 @@ public class VerifySessionAPITest2_9 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -247,7 +250,7 @@ public void unauthorisedOutputCheck() throws Exception { Utils.setValueInConfig("access_token_blacklisting", "true"); String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = TestingProcessManager.startIsolatedProcess(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); String userId = "userId"; diff --git a/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest3_0.java b/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest3_0.java index 188822c26..04e308272 100644 --- a/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest3_0.java +++ b/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest3_0.java @@ -42,6 +42,9 @@ public class VerifySessionAPITest3_0 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -278,7 +281,7 @@ public void testAccessTokenInfoOnV3AccessTokenPointsToPublicTenant() throws Exce "http://localhost:3567/recipe/session", sessionRequest, 1000, 1000, null, SemVer.v2_21.get(), "session"); - AccessToken.AccessTokenInfo accessTokenInfo = AccessToken.getInfoFromAccessToken(new AppIdentifier(null, null), + AccessToken.AccessTokenInfo accessTokenInfo = AccessToken.getInfoFromAccessToken(process.getAppForTesting().toAppIdentifier(), process.getProcess(), sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString(), false); @@ -355,7 +358,7 @@ public void testV3AccessTokenWithCustomtIdPayload() throws Exception { "http://localhost:3567/recipe/session", sessionRequest, 1000, 1000, null, SemVer.v2_21.get(), "session"); - AccessToken.AccessTokenInfo accessTokenInfo = AccessToken.getInfoFromAccessToken(new AppIdentifier(null, null), + AccessToken.AccessTokenInfo accessTokenInfo = AccessToken.getInfoFromAccessToken(process.getAppForTesting().toAppIdentifier(), process.getProcess(), sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString(), false); @@ -411,7 +414,7 @@ public void testV3AccessTokenWithCustomtIdPayloadAfterRefreshInV4() throws Excep "http://localhost:3567/recipe/session", sessionRequest, 1000, 1000, null, SemVer.v2_21.get(), "session"); - AccessToken.AccessTokenInfo accessTokenInfo = AccessToken.getInfoFromAccessToken(new AppIdentifier(null, null), + AccessToken.AccessTokenInfo accessTokenInfo = AccessToken.getInfoFromAccessToken(process.getAppForTesting().toAppIdentifier(), process.getProcess(), sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString(), false); diff --git a/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest4_0.java b/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest4_0.java index a6770005f..6301fc798 100644 --- a/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest4_0.java +++ b/src/test/java/io/supertokens/test/session/api/VerifySessionAPITest4_0.java @@ -41,6 +41,9 @@ public class VerifySessionAPITest4_0 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -328,7 +331,7 @@ public void testV4AccessTokenWithCustomtIdPayload() throws Exception { "http://localhost:3567/recipe/session", sessionRequest, 1000, 1000, null, SemVer.v3_0.get(), "session"); - AccessToken.AccessTokenInfo accessTokenInfo = AccessToken.getInfoFromAccessToken(new AppIdentifier(null, null), + AccessToken.AccessTokenInfo accessTokenInfo = AccessToken.getInfoFromAccessToken(process.getAppForTesting().toAppIdentifier(), process.getProcess(), sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString(), false); @@ -384,7 +387,7 @@ public void testV4AccessTokenWithCustomtIdPayloadAfterRefreshInV5() throws Excep "http://localhost:3567/recipe/session", sessionRequest, 1000, 1000, null, SemVer.v3_0.get(), "session"); - AccessToken.AccessTokenInfo accessTokenInfo = AccessToken.getInfoFromAccessToken(new AppIdentifier(null, null), + AccessToken.AccessTokenInfo accessTokenInfo = AccessToken.getInfoFromAccessToken(process.getAppForTesting().toAppIdentifier(), process.getProcess(), sessionInfo.get("accessToken").getAsJsonObject().get("token").getAsString(), false); diff --git a/src/test/java/io/supertokens/test/session/api/VersionTest.java b/src/test/java/io/supertokens/test/session/api/VersionTest.java index f97e6df29..9945c7e75 100644 --- a/src/test/java/io/supertokens/test/session/api/VersionTest.java +++ b/src/test/java/io/supertokens/test/session/api/VersionTest.java @@ -43,6 +43,9 @@ public class VersionTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/thirdparty/ThirdPartyTest.java b/src/test/java/io/supertokens/test/thirdparty/ThirdPartyTest.java index b9f7f114a..e97f439a4 100644 --- a/src/test/java/io/supertokens/test/thirdparty/ThirdPartyTest.java +++ b/src/test/java/io/supertokens/test/thirdparty/ThirdPartyTest.java @@ -42,6 +42,9 @@ public class ThirdPartyTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -291,7 +294,7 @@ public void testSignUpWithSameThirdPartyThirdPartyUserIdException() throws Excep checkSignInUpResponse(signUpResponse, thirdPartyUserId, thirdPartyId, email, true); try { ((ThirdPartySQLStorage) StorageLayer.getStorage(process.getProcess())) - .signUp(new TenantIdentifier(null, null, null), io.supertokens.utils.Utils.getUUID(), email, + .signUp(process.getAppForTesting(), io.supertokens.utils.Utils.getUUID(), email, new LoginMethod.ThirdParty(thirdPartyId, thirdPartyUserId), System.currentTimeMillis()); throw new Exception("Should not come here"); } catch (DuplicateThirdPartyUserException ignored) { @@ -324,7 +327,7 @@ public void testSignUpWithSameUserIdAndCheckDuplicateUserIdException() throws Ex checkSignInUpResponse(signUpResponse, thirdPartyUserId, thirdPartyId, email, true); try { ((ThirdPartySQLStorage) StorageLayer.getStorage(process.getProcess())) - .signUp(new TenantIdentifier(null, null, null), signUpResponse.user.getSupertokensUserId(), email, + .signUp(process.getAppForTesting(), signUpResponse.user.getSupertokensUserId(), email, new LoginMethod.ThirdParty("newThirdParty", "newThirdPartyUserId"), System.currentTimeMillis()); throw new Exception("Should not come here"); diff --git a/src/test/java/io/supertokens/test/thirdparty/ThirdPartyTest2_7.java b/src/test/java/io/supertokens/test/thirdparty/ThirdPartyTest2_7.java index fa0e467d0..0de916b56 100644 --- a/src/test/java/io/supertokens/test/thirdparty/ThirdPartyTest2_7.java +++ b/src/test/java/io/supertokens/test/thirdparty/ThirdPartyTest2_7.java @@ -42,6 +42,9 @@ public class ThirdPartyTest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -299,7 +302,7 @@ public void testSignUpWithSameThirdPartyThirdPartyUserIdException() throws Excep checkSignInUpResponse(signUpResponse, thirdPartyUserId, thirdPartyId, email, true); try { ((ThirdPartySQLStorage) StorageLayer.getStorage(process.getProcess())) - .signUp(new TenantIdentifier(null, null, null), io.supertokens.utils.Utils.getUUID(), email, + .signUp(process.getAppForTesting(), io.supertokens.utils.Utils.getUUID(), email, new LoginMethod.ThirdParty(thirdPartyId, thirdPartyUserId), System.currentTimeMillis()); throw new Exception("Should not come here"); } catch (DuplicateThirdPartyUserException ignored) { @@ -332,7 +335,7 @@ public void testSignUpWithSameUserIdAndCheckDuplicateUserIdException() throws Ex checkSignInUpResponse(signUpResponse, thirdPartyUserId, thirdPartyId, email, true); try { ((ThirdPartySQLStorage) StorageLayer.getStorage(process.getProcess())) - .signUp(new TenantIdentifier(null, null, null), signUpResponse.user.getSupertokensUserId(), email, + .signUp(process.getAppForTesting(), signUpResponse.user.getSupertokensUserId(), email, new LoginMethod.ThirdParty("newThirdParty", "newThirdPartyUserId"), System.currentTimeMillis()); throw new Exception("Should not come here"); diff --git a/src/test/java/io/supertokens/test/thirdparty/api/EmailVerificationTest.java b/src/test/java/io/supertokens/test/thirdparty/api/EmailVerificationTest.java index d0bf0a10e..d542360f5 100644 --- a/src/test/java/io/supertokens/test/thirdparty/api/EmailVerificationTest.java +++ b/src/test/java/io/supertokens/test/thirdparty/api/EmailVerificationTest.java @@ -48,6 +48,9 @@ public class EmailVerificationTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -226,11 +229,10 @@ public void testEmailVerificationStateDoesNotChangeWhenFalseIsPassed() throws Ex @Test public void testWithAccountLinking() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartyGetUserAPITest2_7.java b/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartyGetUserAPITest2_7.java index 55ed44bac..b91d6bf6b 100644 --- a/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartyGetUserAPITest2_7.java +++ b/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartyGetUserAPITest2_7.java @@ -50,6 +50,9 @@ public class ThirdPartyGetUserAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartyGetUsersByEmailAPITest2_7.java b/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartyGetUsersByEmailAPITest2_7.java index 3f43bc986..48efd6541 100644 --- a/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartyGetUsersByEmailAPITest2_7.java +++ b/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartyGetUsersByEmailAPITest2_7.java @@ -40,6 +40,9 @@ public class ThirdPartyGetUsersByEmailAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartySignInUpAPITest2_7.java b/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartySignInUpAPITest2_7.java index f0dd90e90..267d8b1c5 100644 --- a/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartySignInUpAPITest2_7.java +++ b/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartySignInUpAPITest2_7.java @@ -49,6 +49,9 @@ public class ThirdPartySignInUpAPITest2_7 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartySignInUpAPITest2_8.java b/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartySignInUpAPITest2_8.java index 462d1dd7f..98da786a0 100644 --- a/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartySignInUpAPITest2_8.java +++ b/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartySignInUpAPITest2_8.java @@ -49,6 +49,9 @@ public class ThirdPartySignInUpAPITest2_8 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartySignInUpAPITest4_0.java b/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartySignInUpAPITest4_0.java index 290224130..f9722abea 100644 --- a/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartySignInUpAPITest4_0.java +++ b/src/test/java/io/supertokens/test/thirdparty/api/ThirdPartySignInUpAPITest4_0.java @@ -45,6 +45,9 @@ public class ThirdPartySignInUpAPITest4_0 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -123,11 +126,10 @@ public void testGoodInput() throws Exception { public void testNotAllowedUpdateOfEmail() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -135,11 +137,11 @@ public void testNotAllowedUpdateOfEmail() throws Exception { } AuthRecipeUserInfo user0 = EmailPassword.signUp(process.getProcess(), "someemail1@gmail.com", "somePass"); - AuthRecipe.createPrimaryUser(process.main, user0.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), user0.getSupertokensUserId()); ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), "google", "user", "someemail@gmail.com"); - AuthRecipe.createPrimaryUser(process.main, signInUpResponse.user.getSupertokensUserId()); + AuthRecipe.createPrimaryUser(process.getProcess(), signInUpResponse.user.getSupertokensUserId()); JsonObject emailObject = new JsonObject(); emailObject.addProperty("id", "someemail1@gmail.com"); diff --git a/src/test/java/io/supertokens/test/totp/TOTPRecipeTest.java b/src/test/java/io/supertokens/test/totp/TOTPRecipeTest.java index d7d0539dd..e5de8b020 100644 --- a/src/test/java/io/supertokens/test/totp/TOTPRecipeTest.java +++ b/src/test/java/io/supertokens/test/totp/TOTPRecipeTest.java @@ -64,6 +64,9 @@ public class TOTPRecipeTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -84,7 +87,11 @@ public TestSetupResult(TOTPStorage storage, TestingProcessManager.TestingProcess } } - public TestSetupResult defaultInit() + public TestSetupResult defaultInit() throws InterruptedException { + return defaultInit(false); + } + + public TestSetupResult defaultInit(boolean restart) throws InterruptedException { String[] args = {"../"}; @@ -96,7 +103,7 @@ public TestSetupResult defaultInit() } TOTPStorage storage = (TOTPStorage) StorageLayer.getStorage(process.getProcess()); - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); return new TestSetupResult(storage, process); @@ -121,14 +128,14 @@ public static String generateTotpCode(Main main, TOTPDevice device, int step) return totp.generateOneTimePasswordString(key, Instant.now().plusSeconds(step * device.period)); } - private static TOTPUsedCode[] getAllUsedCodesUtil(TOTPStorage storage, String userId) + private static TOTPUsedCode[] getAllUsedCodesUtil(TestingProcessManager.TestingProcess process, TOTPStorage storage, String userId) throws StorageQueryException, StorageTransactionLogicException { assert storage instanceof TOTPSQLStorage; TOTPSQLStorage sqlStorage = (TOTPSQLStorage) storage; return (TOTPUsedCode[]) sqlStorage.startTransaction(con -> { TOTPUsedCode[] usedCodes = sqlStorage.getAllUsedCodesDescOrder_Transaction(con, - new TenantIdentifier(null, null, null), userId); + process.getAppForTesting(), userId); sqlStorage.commitTransaction(con); return usedCodes; }); @@ -250,7 +257,7 @@ public void createDeviceAndVerifyCodeTest() throws Exception { assertThrows(InvalidTotpException.class, () -> Totp.verifyCode(main, "user", "invalid")); - TOTPUsedCode[] usedCodes = getAllUsedCodesUtil(result.storage, "user"); + TOTPUsedCode[] usedCodes = getAllUsedCodesUtil(result.process, result.storage, "user"); TOTPUsedCode latestCode = usedCodes[0]; assert !latestCode.isValid; assert latestCode.expiryTime - latestCode.createdTime == @@ -338,7 +345,7 @@ public void rateLimitCooldownTest() throws Throwable { } try { - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); Main main = process.getProcess(); @@ -526,7 +533,7 @@ public void removeDeviceTest() throws Throwable { Totp.removeDevice(main, "user", "device1"); // 1 device still remain so all codes should still be there: - TOTPUsedCode[] usedCodes = getAllUsedCodesUtil(storage, "user"); + TOTPUsedCode[] usedCodes = getAllUsedCodesUtil(result.process, storage, "user"); assert (usedCodes.length == 5); // 2 for device verification and 3 for code verification devices = Totp.getDevices(main, "user"); @@ -551,10 +558,10 @@ public void removeDeviceTest() throws Throwable { assert (Totp.getDevices(main, "user").length == 0); // No device left so all codes of the user should be deleted: - TOTPUsedCode[] usedCodes = getAllUsedCodesUtil(storage, "user"); + TOTPUsedCode[] usedCodes = getAllUsedCodesUtil(result.process, storage, "user"); assert (usedCodes.length == 0); - usedCodes = getAllUsedCodesUtil(storage, "other-user"); + usedCodes = getAllUsedCodesUtil(result.process, storage, "other-user"); System.out.println("Point2 " + usedCodes.length); assert (usedCodes.length == 3); // 1 for device verification and 2 for code verification @@ -668,7 +675,7 @@ public void testCurrentAndMaxAttemptsInExceptions() throws Exception { TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/totp/TOTPStorageTest.java b/src/test/java/io/supertokens/test/totp/TOTPStorageTest.java index 5f590347a..d754b3405 100644 --- a/src/test/java/io/supertokens/test/totp/TOTPStorageTest.java +++ b/src/test/java/io/supertokens/test/totp/TOTPStorageTest.java @@ -1,6 +1,7 @@ package io.supertokens.test.totp; import io.supertokens.ProcessState; +import io.supertokens.ResourceDistributor; import io.supertokens.cronjobs.deleteExpiredTotpTokens.DeleteExpiredTotpTokens; import io.supertokens.featureflag.EE_FEATURES; import io.supertokens.featureflag.FeatureFlagTestContent; @@ -45,6 +46,9 @@ public TestSetupResult(TOTPSQLStorage storage, TestingProcessManager.TestingProc @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -60,6 +64,8 @@ public TestSetupResult initSteps() String[] args = {"../"}; TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + FeatureFlagTestContent.getInstance(process.getProcess()) + .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -67,9 +73,6 @@ public TestSetupResult initSteps() } TOTPSQLStorage storage = (TOTPSQLStorage) StorageLayer.getStorage(process.getProcess()); - FeatureFlagTestContent.getInstance(process.main) - .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); - return new TestSetupResult(storage, process); } @@ -80,7 +83,7 @@ private static TOTPUsedCode[] getAllUsedCodesUtil(TOTPStorage storage, String us return sqlStorage.startTransaction(con -> { TOTPUsedCode[] usedCodes = sqlStorage.getAllUsedCodesDescOrder_Transaction(con, - new TenantIdentifier(null, null, null), userId); + ResourceDistributor.getAppForTesting(), userId); sqlStorage.commitTransaction(con); return usedCodes; }); @@ -93,7 +96,7 @@ public static void insertUsedCodesUtil(TOTPSQLStorage storage, TOTPUsedCode[] us storage.startTransaction(con -> { try { for (TOTPUsedCode usedCode : usedCodes) { - storage.insertUsedCode_Transaction(con, new TenantIdentifier(null, null, null), usedCode); + storage.insertUsedCode_Transaction(con, ResourceDistributor.getAppForTesting(), usedCode); } } catch (UnknownTotpUserIdException | UsedCodeAlreadyExistsException e) { throw new StorageTransactionLogicException(e); @@ -128,21 +131,21 @@ public void createDeviceTests() throws Exception { TOTPDevice device2Duplicate = new TOTPDevice("user", "d2", "new-secret", 30, 1, false, System.currentTimeMillis()); - storage.createDevice(new AppIdentifier(null, null), device1); + storage.createDevice(result.process.getAppForTesting().toAppIdentifier(), device1); - TOTPDevice[] storedDevices = storage.getDevices(new AppIdentifier(null, null), "user"); + TOTPDevice[] storedDevices = storage.getDevices(result.process.getAppForTesting().toAppIdentifier(), "user"); assert (storedDevices.length == 1); assert storedDevices[0].equals(device1); - storage.createDevice(new AppIdentifier(null, null), device2); - storedDevices = storage.getDevices(new AppIdentifier(null, null), "user"); + storage.createDevice(result.process.getAppForTesting().toAppIdentifier(), device2); + storedDevices = storage.getDevices(result.process.getAppForTesting().toAppIdentifier(), "user"); assert (storedDevices.length == 2); assert (storedDevices[0].equals(device1) && storedDevices[1].equals(device2)) || (storedDevices[0].equals(device2) && storedDevices[1].equals(device1)); assertThrows(DeviceAlreadyExistsException.class, - () -> storage.createDevice(new AppIdentifier(null, null), device2Duplicate)); + () -> storage.createDevice(result.process.getAppForTesting().toAppIdentifier(), device2Duplicate)); result.process.kill(); assertNotNull(result.process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -155,27 +158,30 @@ public void verifyDeviceTests() throws Exception { return; } TOTPSQLStorage storage = result.storage; - + TOTPDevice device = new TOTPDevice("user", "device", "secretKey", 30, 1, false, System.currentTimeMillis()); - storage.createDevice(new AppIdentifier(null, null), device); + storage.createDevice(result.process.getAppForTesting().toAppIdentifier(), device); - TOTPDevice[] storedDevices = storage.getDevices(new AppIdentifier(null, null), "user"); + TOTPDevice[] storedDevices = storage.getDevices(result.process.getAppForTesting().toAppIdentifier(), "user"); assert (storedDevices.length == 1); assert (!storedDevices[0].verified); // Verify the device: - storage.markDeviceAsVerified(new AppIdentifier(null, null), "user", "device"); + storage.markDeviceAsVerified(result.process.getAppForTesting().toAppIdentifier(), "user", "device"); - storedDevices = storage.getDevices(new AppIdentifier(null, null), "user"); + storedDevices = storage.getDevices(result.process.getAppForTesting().toAppIdentifier(), "user"); assert (storedDevices.length == 1); assert (storedDevices[0].verified); // Try to verify the device again: - storage.markDeviceAsVerified(new AppIdentifier(null, null), "user", "device"); + storage.markDeviceAsVerified(result.process.getAppForTesting().toAppIdentifier(), "user", "device"); // Try to verify a device that doesn't exist: assertThrows(UnknownDeviceException.class, - () -> storage.markDeviceAsVerified(new AppIdentifier(null, null), "user", "non-existent-device")); + () -> storage.markDeviceAsVerified(result.process.getAppForTesting().toAppIdentifier(), "user", "non-existent-device")); + + result.process.kill(); + assertNotNull(result.process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } @Test @@ -189,7 +195,7 @@ public void getDevicesCount_TransactionTests() throws Exception { // Try to get the count for a user that doesn't exist (Should pass because // this is DB level txn that doesn't throw TotpNotEnabledException): int devicesCount = storage.startTransaction(con -> { - TOTPDevice[] devices = storage.getDevices_Transaction(con, new AppIdentifier(null, null), + TOTPDevice[] devices = storage.getDevices_Transaction(con, result.process.getAppForTesting().toAppIdentifier(), "non-existent-user"); storage.commitTransaction(con); return devices.length; @@ -199,15 +205,18 @@ public void getDevicesCount_TransactionTests() throws Exception { TOTPDevice device1 = new TOTPDevice("user", "device1", "sk1", 30, 1, false, System.currentTimeMillis()); TOTPDevice device2 = new TOTPDevice("user", "device2", "sk2", 30, 1, false, System.currentTimeMillis()); - storage.createDevice(new AppIdentifier(null, null), device1); - storage.createDevice(new AppIdentifier(null, null), device2); + storage.createDevice(result.process.getAppForTesting().toAppIdentifier(), device1); + storage.createDevice(result.process.getAppForTesting().toAppIdentifier(), device2); devicesCount = storage.startTransaction(con -> { - TOTPDevice[] devices = storage.getDevices_Transaction(con, new AppIdentifier(null, null), "user"); + TOTPDevice[] devices = storage.getDevices_Transaction(con, result.process.getAppForTesting().toAppIdentifier(), "user"); storage.commitTransaction(con); return devices.length; }); assert devicesCount == 2; + + result.process.kill(); + assertNotNull(result.process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } @Test @@ -221,7 +230,7 @@ public void removeUser_TransactionTests() throws Exception { // Try to remove a user that doesn't exist (Should pass because // this is DB level txn that doesn't throw TotpNotEnabledException): storage.startTransaction(con -> { - storage.removeUser_Transaction(con, new AppIdentifier(null, null), "non-existent-user"); + storage.removeUser_Transaction(con, result.process.getAppForTesting().toAppIdentifier(), "non-existent-user"); storage.commitTransaction(con); return null; }); @@ -229,8 +238,8 @@ public void removeUser_TransactionTests() throws Exception { TOTPDevice device1 = new TOTPDevice("user", "device1", "sk1", 30, 1, false, System.currentTimeMillis()); TOTPDevice device2 = new TOTPDevice("user", "device2", "sk2", 30, 1, false, System.currentTimeMillis()); - storage.createDevice(new AppIdentifier(null, null), device1); - storage.createDevice(new AppIdentifier(null, null), device2); + storage.createDevice(result.process.getAppForTesting().toAppIdentifier(), device1); + storage.createDevice(result.process.getAppForTesting().toAppIdentifier(), device2); long now = System.currentTimeMillis(); long expiryAfter10mins = now + 10 * 60 * 1000; @@ -240,23 +249,26 @@ public void removeUser_TransactionTests() throws Exception { insertUsedCodesUtil(storage, new TOTPUsedCode[]{usedCode1, usedCode2}); - TOTPDevice[] storedDevices = storage.getDevices(new AppIdentifier(null, null), "user"); + TOTPDevice[] storedDevices = storage.getDevices(result.process.getAppForTesting().toAppIdentifier(), "user"); assert (storedDevices.length == 2); TOTPUsedCode[] storedUsedCodes = getAllUsedCodesUtil(storage, "user"); assert (storedUsedCodes.length == 2); storage.startTransaction(con -> { - storage.removeUser_Transaction(con, new AppIdentifier(null, null), "user"); + storage.removeUser_Transaction(con, result.process.getAppForTesting().toAppIdentifier(), "user"); storage.commitTransaction(con); return null; }); - storedDevices = storage.getDevices(new AppIdentifier(null, null), "user"); + storedDevices = storage.getDevices(result.process.getAppForTesting().toAppIdentifier(), "user"); assert (storedDevices.length == 0); storedUsedCodes = getAllUsedCodesUtil(storage, "user"); assert (storedUsedCodes.length == 0); + + result.process.kill(); + assertNotNull(result.process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } @Test @@ -270,16 +282,16 @@ public void deleteDevice_TransactionTests() throws Exception { TOTPDevice device1 = new TOTPDevice("user", "device1", "sk1", 30, 1, false, System.currentTimeMillis()); TOTPDevice device2 = new TOTPDevice("user", "device2", "sk2", 30, 1, false, System.currentTimeMillis()); - storage.createDevice(new AppIdentifier(null, null), device1); - storage.createDevice(new AppIdentifier(null, null), device2); + storage.createDevice(result.process.getAppForTesting().toAppIdentifier(), device1); + storage.createDevice(result.process.getAppForTesting().toAppIdentifier(), device2); - TOTPDevice[] storedDevices = storage.getDevices(new AppIdentifier(null, null), "user"); + TOTPDevice[] storedDevices = storage.getDevices(result.process.getAppForTesting().toAppIdentifier(), "user"); assert (storedDevices.length == 2); // Try to delete a device for a user that doesn't exist (Should pass because // this is DB level txn that doesn't throw TotpNotEnabledException): storage.startTransaction(con -> { - int deletedCount = storage.deleteDevice_Transaction(con, new AppIdentifier(null, null), "non-existent-user", + int deletedCount = storage.deleteDevice_Transaction(con, result.process.getAppForTesting().toAppIdentifier(), "non-existent-user", "device1"); assert deletedCount == 0; storage.commitTransaction(con); @@ -288,7 +300,7 @@ public void deleteDevice_TransactionTests() throws Exception { // Try to delete a device that doesn't exist: storage.startTransaction(con -> { - int deletedCount = storage.deleteDevice_Transaction(con, new AppIdentifier(null, null), "user", + int deletedCount = storage.deleteDevice_Transaction(con, result.process.getAppForTesting().toAppIdentifier(), "user", "non-existent-device"); assert deletedCount == 0; storage.commitTransaction(con); @@ -297,14 +309,17 @@ public void deleteDevice_TransactionTests() throws Exception { // Successfully delete device1: storage.startTransaction(con -> { - int deletedCount = storage.deleteDevice_Transaction(con, new AppIdentifier(null, null), "user", "device1"); + int deletedCount = storage.deleteDevice_Transaction(con, result.process.getAppForTesting().toAppIdentifier(), "user", "device1"); assert deletedCount == 1; storage.commitTransaction(con); return null; }); - storedDevices = storage.getDevices(new AppIdentifier(null, null), "user"); + storedDevices = storage.getDevices(result.process.getAppForTesting().toAppIdentifier(), "user"); assert (storedDevices.length == 1); // device2 should still be there + + result.process.kill(); + assertNotNull(result.process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } @Test @@ -316,21 +331,21 @@ public void updateDeviceNameTests() throws Exception { TOTPSQLStorage storage = result.storage; TOTPDevice device = new TOTPDevice("user", "device", "secretKey", 30, 1, false, System.currentTimeMillis()); - storage.createDevice(new AppIdentifier(null, null), device); + storage.createDevice(result.process.getAppForTesting().toAppIdentifier(), device); - TOTPDevice[] storedDevices = storage.getDevices(new AppIdentifier(null, null), "user"); + TOTPDevice[] storedDevices = storage.getDevices(result.process.getAppForTesting().toAppIdentifier(), "user"); assert (storedDevices.length == 1); assert (storedDevices[0].deviceName.equals("device")); // Try to update a device that doesn't exist: assertThrows(UnknownDeviceException.class, - () -> storage.updateDeviceName(new AppIdentifier(null, null), "user", "non-existent-device", + () -> storage.updateDeviceName(result.process.getAppForTesting().toAppIdentifier(), "user", "non-existent-device", "new-device-name")); // Update the device name: - storage.updateDeviceName(new AppIdentifier(null, null), "user", "device", "updated-device-name"); + storage.updateDeviceName(result.process.getAppForTesting().toAppIdentifier(), "user", "device", "updated-device-name"); - storedDevices = storage.getDevices(new AppIdentifier(null, null), "user"); + storedDevices = storage.getDevices(result.process.getAppForTesting().toAppIdentifier(), "user"); assert (storedDevices.length == 1); assert (storedDevices[0].deviceName.equals("updated-device-name")); @@ -338,14 +353,17 @@ public void updateDeviceNameTests() throws Exception { // device: TOTPDevice newDevice = new TOTPDevice("user", "new-device", "secretKey", 30, 1, false, System.currentTimeMillis()); - storage.createDevice(new AppIdentifier(null, null), newDevice); + storage.createDevice(result.process.getAppForTesting().toAppIdentifier(), newDevice); assertThrows(DeviceAlreadyExistsException.class, - () -> storage.updateDeviceName(new AppIdentifier(null, null), "user", "new-device", + () -> storage.updateDeviceName(result.process.getAppForTesting().toAppIdentifier(), "user", "new-device", "updated-device-name")); // Try to rename the device the same name (Should work at database level): - storage.updateDeviceName(new AppIdentifier(null, null), "user", "updated-device-name", "updated-device-name"); + storage.updateDeviceName(result.process.getAppForTesting().toAppIdentifier(), "user", "updated-device-name", "updated-device-name"); + + result.process.kill(); + assertNotNull(result.process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } @Test @@ -359,17 +377,20 @@ public void getDevicesTest() throws Exception { TOTPDevice device1 = new TOTPDevice("user", "d1", "secretKey", 30, 1, false, System.currentTimeMillis()); TOTPDevice device2 = new TOTPDevice("user", "d2", "secretKey", 30, 1, false, System.currentTimeMillis()); - storage.createDevice(new AppIdentifier(null, null), device1); - storage.createDevice(new AppIdentifier(null, null), device2); + storage.createDevice(result.process.getAppForTesting().toAppIdentifier(), device1); + storage.createDevice(result.process.getAppForTesting().toAppIdentifier(), device2); - TOTPDevice[] storedDevices = storage.getDevices(new AppIdentifier(null, null), "user"); + TOTPDevice[] storedDevices = storage.getDevices(result.process.getAppForTesting().toAppIdentifier(), "user"); assert (storedDevices.length == 2); assert (storedDevices[0].deviceName.equals("d1") || storedDevices[1].deviceName.equals("d2")) || (storedDevices[0].deviceName.equals("d2") || storedDevices[1].deviceName.equals("d1")); - storedDevices = storage.getDevices(new AppIdentifier(null, null), "non-existent-user"); + storedDevices = storage.getDevices(result.process.getAppForTesting().toAppIdentifier(), "non-existent-user"); assert (storedDevices.length == 0); + + result.process.kill(); + assertNotNull(result.process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } @Test @@ -387,7 +408,7 @@ public void insertUsedCodeTest() throws Exception { TOTPDevice device = new TOTPDevice("user", "device", "secretKey", 30, 1, false, System.currentTimeMillis()); TOTPUsedCode code = new TOTPUsedCode("user", "1234", true, nextDay, now); - storage.createDevice(new AppIdentifier(null, null), device); + storage.createDevice(result.process.getAppForTesting().toAppIdentifier(), device); insertUsedCodesUtil(storage, new TOTPUsedCode[]{code}); TOTPUsedCode[] usedCodes = getAllUsedCodesUtil(storage, "user"); @@ -417,7 +438,7 @@ public void insertUsedCodeTest() throws Exception { { TOTPDevice newDevice = new TOTPDevice("user", "new-device", "secretKey", 30, 1, false, System.currentTimeMillis()); - storage.createDevice(new AppIdentifier(null, null), newDevice); + storage.createDevice(result.process.getAppForTesting().toAppIdentifier(), newDevice); insertUsedCodesUtil( storage, new TOTPUsedCode[]{ @@ -433,6 +454,9 @@ public void insertUsedCodeTest() throws Exception { })); // assert e.actualException instanceof UnknownDeviceException; + + result.process.kill(); + assertNotNull(result.process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } @Test @@ -458,7 +482,7 @@ public void getAllUsedCodesTest() throws Exception { TOTPUsedCode validCode2 = new TOTPUsedCode("user", "valid2", true, nextDay, now + 5); TOTPUsedCode validCode3 = new TOTPUsedCode("user", "valid3", true, nextDay, now + 6); - storage.createDevice(new AppIdentifier(null, null), device); + storage.createDevice(result.process.getAppForTesting().toAppIdentifier(), device); insertUsedCodesUtil(storage, new TOTPUsedCode[]{ validCode1, invalidCode, expiredCode, expiredInvalidCode, @@ -482,6 +506,9 @@ public void getAllUsedCodesTest() throws Exception { assert (usedCodes[1].equals(validCode2)); assert (usedCodes[2].equals(invalidCode)); assert (usedCodes[3].equals(validCode1)); + + result.process.kill(); + assertNotNull(result.process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } @Test @@ -502,7 +529,7 @@ public void removeExpiredCodesTest() throws Exception { TOTPUsedCode validCodeToExpire = new TOTPUsedCode("user", "valid", true, hundredMs, now + 2); TOTPUsedCode invalidCodeToExpire = new TOTPUsedCode("user", "invalid", false, hundredMs, now + 3); - storage.createDevice(new AppIdentifier(null, null), device); + storage.createDevice(result.process.getAppForTesting().toAppIdentifier(), device); insertUsedCodesUtil(storage, new TOTPUsedCode[]{ validCodeToLive, invalidCodeToLive, validCodeToExpire, invalidCodeToExpire @@ -515,11 +542,14 @@ public void removeExpiredCodesTest() throws Exception { Thread.sleep(250); now = System.currentTimeMillis(); - storage.removeExpiredCodes(new TenantIdentifier(null, null, null), now); + storage.removeExpiredCodes(ResourceDistributor.getAppForTesting(), now); usedCodes = getAllUsedCodesUtil(storage, "user"); assert (usedCodes.length == 2); assert (usedCodes[0].equals(invalidCodeToLive)); assert (usedCodes[1].equals(validCodeToLive)); + + result.process.kill(); + assertNotNull(result.process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } } diff --git a/src/test/java/io/supertokens/test/totp/TotpLicenseTest.java b/src/test/java/io/supertokens/test/totp/TotpLicenseTest.java index 77b36c51c..ac3a8deb2 100644 --- a/src/test/java/io/supertokens/test/totp/TotpLicenseTest.java +++ b/src/test/java/io/supertokens/test/totp/TotpLicenseTest.java @@ -49,6 +49,9 @@ public class TotpLicenseTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -70,9 +73,13 @@ public TestSetupResult(TOTPStorage storage, TestingProcessManager.TestingProcess } public TestSetupResult defaultInit() throws InterruptedException { + return defaultInit(false); + } + + public TestSetupResult defaultInit(boolean useIsolatedProcess) throws InterruptedException { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); + TestingProcessManager.TestingProcess process = useIsolatedProcess ? TestingProcessManager.startIsolatedProcess(args) : TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -85,7 +92,7 @@ public TestSetupResult defaultInit() throws InterruptedException { @Test public void testTotpWithoutLicense() throws Exception { - TestSetupResult result = defaultInit(); + TestSetupResult result = defaultInit(true); if (result == null) { return; } @@ -153,16 +160,19 @@ public void testTotpWithoutLicense() throws Exception { ); assert e2.statusCode == 402; assert e2.getMessage().contains("MFA feature is not enabled"); + + result.process.kill(); + assertNotNull(result.process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); } @Test public void testTotpWithLicense() throws Exception { - TestSetupResult result = defaultInit(); + TestSetupResult result = defaultInit(true); if (result == null) { return; } - FeatureFlagTestContent.getInstance(result.process.main) + FeatureFlagTestContent.getInstance(result.process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); Main main = result.process.getProcess(); @@ -176,7 +186,8 @@ public void testTotpWithLicense() throws Exception { Thread.sleep(1); String nextCode = generateTotpCode(main, device, 1); Totp.verifyCode(main, "user", nextCode); - } - + result.process.kill(); + assertNotNull(result.process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); + } } diff --git a/src/test/java/io/supertokens/test/totp/api/CreateTotpDeviceAPITest.java b/src/test/java/io/supertokens/test/totp/api/CreateTotpDeviceAPITest.java index 6ec6b482a..c2e5ef5e3 100644 --- a/src/test/java/io/supertokens/test/totp/api/CreateTotpDeviceAPITest.java +++ b/src/test/java/io/supertokens/test/totp/api/CreateTotpDeviceAPITest.java @@ -28,6 +28,9 @@ public class CreateTotpDeviceAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -80,9 +83,9 @@ public void testApi() throws Exception { return; } - FeatureFlag.getInstance(process.main) + FeatureFlag.getInstance(process.getProcess()) .setLicenseKeyAndSyncFeatures(TotpLicenseTest.OPAQUE_KEY_WITH_MFA_FEATURE); - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/totp/api/GetTotpDevicesAPITest.java b/src/test/java/io/supertokens/test/totp/api/GetTotpDevicesAPITest.java index f193a4445..5fc3f280b 100644 --- a/src/test/java/io/supertokens/test/totp/api/GetTotpDevicesAPITest.java +++ b/src/test/java/io/supertokens/test/totp/api/GetTotpDevicesAPITest.java @@ -28,6 +28,9 @@ public class GetTotpDevicesAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -77,7 +80,7 @@ public void testApi() throws Exception { TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/totp/api/ImportTotpDeviceAPITest.java b/src/test/java/io/supertokens/test/totp/api/ImportTotpDeviceAPITest.java index a5d263d9a..43bc0fac0 100644 --- a/src/test/java/io/supertokens/test/totp/api/ImportTotpDeviceAPITest.java +++ b/src/test/java/io/supertokens/test/totp/api/ImportTotpDeviceAPITest.java @@ -29,6 +29,9 @@ public class ImportTotpDeviceAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -80,9 +83,9 @@ public void testApi() throws Exception { return; } - FeatureFlag.getInstance(process.main) + FeatureFlag.getInstance(process.getProcess()) .setLicenseKeyAndSyncFeatures(TotpLicenseTest.OPAQUE_KEY_WITH_MFA_FEATURE); - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -201,9 +204,9 @@ public void testApiWithoutDeviceName() throws Exception { return; } - FeatureFlag.getInstance(process.main) + FeatureFlag.getInstance(process.getProcess()) .setLicenseKeyAndSyncFeatures(TotpLicenseTest.OPAQUE_KEY_WITH_MFA_FEATURE); - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/totp/api/RemoveTotpDeviceAPITest.java b/src/test/java/io/supertokens/test/totp/api/RemoveTotpDeviceAPITest.java index aa92e4ad0..5716e08dd 100644 --- a/src/test/java/io/supertokens/test/totp/api/RemoveTotpDeviceAPITest.java +++ b/src/test/java/io/supertokens/test/totp/api/RemoveTotpDeviceAPITest.java @@ -26,6 +26,9 @@ public class RemoveTotpDeviceAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -77,7 +80,7 @@ public void testApi() throws Exception { return; } - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); // Setup user and devices: diff --git a/src/test/java/io/supertokens/test/totp/api/TotpUserIdMappingTest.java b/src/test/java/io/supertokens/test/totp/api/TotpUserIdMappingTest.java index 95afebb9d..8352faf74 100644 --- a/src/test/java/io/supertokens/test/totp/api/TotpUserIdMappingTest.java +++ b/src/test/java/io/supertokens/test/totp/api/TotpUserIdMappingTest.java @@ -27,6 +27,9 @@ public class TotpUserIdMappingTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -48,17 +51,17 @@ public void testExternalUserIdTranslation() throws Exception { return; } - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); JsonObject body = new JsonObject(); - AuthRecipeUserInfo user = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); String superTokensUserId = user.getSupertokensUserId(); String externalUserId = "external-user-id"; // Create user id mapping first: - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, null, false); body.addProperty("userId", externalUserId); body.addProperty("deviceName", "d1"); diff --git a/src/test/java/io/supertokens/test/totp/api/UpdateTotpDeviceAPITest.java b/src/test/java/io/supertokens/test/totp/api/UpdateTotpDeviceAPITest.java index 3c6e0beb0..101682a0a 100644 --- a/src/test/java/io/supertokens/test/totp/api/UpdateTotpDeviceAPITest.java +++ b/src/test/java/io/supertokens/test/totp/api/UpdateTotpDeviceAPITest.java @@ -25,6 +25,9 @@ public class UpdateTotpDeviceAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -76,7 +79,7 @@ public void testApi() throws Exception { return; } - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); // Setup user and devices: diff --git a/src/test/java/io/supertokens/test/totp/api/VerifyTotpAPITest.java b/src/test/java/io/supertokens/test/totp/api/VerifyTotpAPITest.java index 8c5fdcb22..bb34121f4 100644 --- a/src/test/java/io/supertokens/test/totp/api/VerifyTotpAPITest.java +++ b/src/test/java/io/supertokens/test/totp/api/VerifyTotpAPITest.java @@ -33,6 +33,9 @@ public class VerifyTotpAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -104,7 +107,7 @@ public void testApi() throws Exception { return; } - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); // Setup user and devices: diff --git a/src/test/java/io/supertokens/test/totp/api/VerifyTotpDeviceAPITest.java b/src/test/java/io/supertokens/test/totp/api/VerifyTotpDeviceAPITest.java index 067d847b4..8be82e878 100644 --- a/src/test/java/io/supertokens/test/totp/api/VerifyTotpDeviceAPITest.java +++ b/src/test/java/io/supertokens/test/totp/api/VerifyTotpDeviceAPITest.java @@ -30,6 +30,9 @@ public class VerifyTotpDeviceAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -101,7 +104,7 @@ public void testApi() throws Exception { return; } - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); // Setup user and devices: diff --git a/src/test/java/io/supertokens/test/userIdMapping/UserIdMappingStorageTest.java b/src/test/java/io/supertokens/test/userIdMapping/UserIdMappingStorageTest.java index a02126822..6ffcbdba6 100644 --- a/src/test/java/io/supertokens/test/userIdMapping/UserIdMappingStorageTest.java +++ b/src/test/java/io/supertokens/test/userIdMapping/UserIdMappingStorageTest.java @@ -44,6 +44,9 @@ public class UserIdMappingStorageTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -64,12 +67,12 @@ public void testCreatingAUserWithAnUnknownSuperTokensUserId() throws Exception { return; } - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); Exception error = null; try { - storage.createUserIdMapping(new AppIdentifier(null, null), "unknownSuperTokensUserId", + storage.createUserIdMapping(process.getAppForTesting().toAppIdentifier(), "unknownSuperTokensUserId", "externalUserId", null); } catch (Exception e) { @@ -93,20 +96,20 @@ public void testCreatingUserIdMapping() throws Exception { return; } - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); // create a user - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPassword"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPassword"); String externalUserId = "external-test"; String externalUserIdInfo = "external-info"; // create a userId mapping - storage.createUserIdMapping(new AppIdentifier(null, null), userInfo.getSupertokensUserId(), externalUserId, + storage.createUserIdMapping(process.getAppForTesting().toAppIdentifier(), userInfo.getSupertokensUserId(), externalUserId, externalUserIdInfo); // check that the mapping exists - UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), + UserIdMapping userIdMapping = storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), userInfo.getSupertokensUserId(), true); assertEquals(userInfo.getSupertokensUserId(), userIdMapping.superTokensUserId); @@ -127,20 +130,20 @@ public void testDuplicateUserIdMapping() throws Exception { return; } - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); // create a user - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPassword"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPassword"); String externalUserId = "external-test"; - storage.createUserIdMapping(new AppIdentifier(null, null), userInfo.getSupertokensUserId(), externalUserId, + storage.createUserIdMapping(process.getAppForTesting().toAppIdentifier(), userInfo.getSupertokensUserId(), externalUserId, null); { // duplicate exception with both supertokensUserId and externalUserId Exception error = null; try { - storage.createUserIdMapping(new AppIdentifier(null, null), userInfo.getSupertokensUserId(), + storage.createUserIdMapping(process.getAppForTesting().toAppIdentifier(), userInfo.getSupertokensUserId(), externalUserId, null); } catch (Exception e) { error = e; @@ -158,7 +161,7 @@ public void testDuplicateUserIdMapping() throws Exception { // duplicate exception with superTokensUserId Exception error = null; try { - storage.createUserIdMapping(new AppIdentifier(null, null), userInfo.getSupertokensUserId(), + storage.createUserIdMapping(process.getAppForTesting().toAppIdentifier(), userInfo.getSupertokensUserId(), "newExternalId", null); } catch (Exception e) { error = e; @@ -176,10 +179,10 @@ public void testDuplicateUserIdMapping() throws Exception { { // duplicate exception with externalUserId - AuthRecipeUserInfo newUser = EmailPassword.signUp(process.main, "test2@example.com", "testPass123"); + AuthRecipeUserInfo newUser = EmailPassword.signUp(process.getProcess(), "test2@example.com", "testPass123"); Exception error = null; try { - storage.createUserIdMapping(new AppIdentifier(null, null), newUser.getSupertokensUserId(), + storage.createUserIdMapping(process.getAppForTesting().toAppIdentifier(), newUser.getSupertokensUserId(), externalUserId, null); } catch (Exception e) { error = e; @@ -208,20 +211,20 @@ public void testCreatingAMappingWithAnUnknownStUserIdAndAPreexistingExternalUser return; } - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); // create a User - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); String externalUserId = "externalUserId"; // create a userId mapping - storage.createUserIdMapping(new AppIdentifier(null, null), userInfo.getSupertokensUserId(), externalUserId, + storage.createUserIdMapping(process.getAppForTesting().toAppIdentifier(), userInfo.getSupertokensUserId(), externalUserId, null); // create a new mapping with unknown superTokensUserId and existing externalUserId Exception error = null; try { - storage.createUserIdMapping(new AppIdentifier(null, null), "unknownUserId", externalUserId, null); + storage.createUserIdMapping(process.getAppForTesting().toAppIdentifier(), "unknownUserId", externalUserId, null); } catch (Exception e) { error = e; } @@ -248,22 +251,22 @@ public void testRetrievingUserIdMappingWithUnknownSuperTokensUserId() throws Exc return; } - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); { - UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), "unknownId", + UserIdMapping userIdMapping = storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), "unknownId", true); assertNull(userIdMapping); } { - UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), "unknownId", + UserIdMapping userIdMapping = storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), "unknownId", false); assertNull(userIdMapping); } { - UserIdMapping[] userIdMappings = storage.getUserIdMapping(new AppIdentifier(null, null), + UserIdMapping[] userIdMappings = storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), "unknownUd"); assertEquals(0, userIdMappings.length); } @@ -282,21 +285,21 @@ public void testRetrievingUserIdMapping() throws Exception { return; } - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); // create a user - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); String externalUserId = "externalUserId"; String externalUserIdInfo = "externalUserIdInfo"; // create the mapping - storage.createUserIdMapping(new AppIdentifier(null, null), userInfo.getSupertokensUserId(), externalUserId, + storage.createUserIdMapping(process.getAppForTesting().toAppIdentifier(), userInfo.getSupertokensUserId(), externalUserId, externalUserIdInfo); // check that the mapping exists with supertokensUserId { - UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), + UserIdMapping userIdMapping = storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), userInfo.getSupertokensUserId(), true); @@ -308,7 +311,7 @@ public void testRetrievingUserIdMapping() throws Exception { // check that the mapping exists with externalUserId { - UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), + UserIdMapping userIdMapping = storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), externalUserId, false); assertNotNull(userIdMapping); @@ -319,7 +322,7 @@ public void testRetrievingUserIdMapping() throws Exception { // check that the mapping exists with either { - UserIdMapping[] userIdMappings = storage.getUserIdMapping(new AppIdentifier(null, null), + UserIdMapping[] userIdMappings = storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), userInfo.getSupertokensUserId()); assertEquals(1, userIdMappings.length); assertEquals(userInfo.getSupertokensUserId(), userIdMappings[0].superTokensUserId); @@ -327,7 +330,7 @@ public void testRetrievingUserIdMapping() throws Exception { assertEquals(externalUserIdInfo, userIdMappings[0].externalUserIdInfo); } { - UserIdMapping[] userIdMappings = storage.getUserIdMapping(new AppIdentifier(null, null), + UserIdMapping[] userIdMappings = storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), externalUserId); assertEquals(1, userIdMappings.length); assertEquals(userInfo.getSupertokensUserId(), userIdMappings[0].superTokensUserId); @@ -340,13 +343,13 @@ public void testRetrievingUserIdMapping() throws Exception { // superTokensUserId { - AuthRecipeUserInfo newUserInfo = EmailPassword.signUp(process.main, "test2@example.com", "testPass123"); + AuthRecipeUserInfo newUserInfo = EmailPassword.signUp(process.getProcess(), "test2@example.com", "testPass123"); String externalUserId2 = userInfo.getSupertokensUserId(); - storage.createUserIdMapping(new AppIdentifier(null, null), newUserInfo.getSupertokensUserId(), + storage.createUserIdMapping(process.getAppForTesting().toAppIdentifier(), newUserInfo.getSupertokensUserId(), externalUserId2, null); - UserIdMapping[] userIdMappings = storage.getUserIdMapping(new AppIdentifier(null, null), + UserIdMapping[] userIdMappings = storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), externalUserId2); assertEquals(2, userIdMappings.length); @@ -383,11 +386,11 @@ public void testDeletingUserIdMappingWithAnUnknownId() throws Exception { return; } - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); - assertFalse(storage.deleteUserIdMapping(new AppIdentifier(null, null), "unknownUserId", true)); + assertFalse(storage.deleteUserIdMapping(process.getAppForTesting().toAppIdentifier(), "unknownUserId", true)); - assertFalse(storage.deleteUserIdMapping(new AppIdentifier(null, null), "unknownUserId", false)); + assertFalse(storage.deleteUserIdMapping(process.getAppForTesting().toAppIdentifier(), "unknownUserId", false)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -403,19 +406,19 @@ public void testDeletingAUserIdMapping() throws Exception { return; } - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); // create a user - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); String superTokensUserId = userInfo.getSupertokensUserId(); String externalUserId = "externalUserId"; { // create a new userId mapping - storage.createUserIdMapping(new AppIdentifier(null, null), superTokensUserId, externalUserId, + storage.createUserIdMapping(process.getAppForTesting().toAppIdentifier(), superTokensUserId, externalUserId, null); // retrieve mapping and check that it exists - UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), + UserIdMapping userIdMapping = storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), superTokensUserId, true); assertNotNull(userIdMapping); assertEquals(superTokensUserId, userIdMapping.superTokensUserId); @@ -423,20 +426,20 @@ public void testDeletingAUserIdMapping() throws Exception { assertNull(userIdMapping.externalUserIdInfo); // delete mapping with a supertokensUserId - assertTrue(storage.deleteUserIdMapping(new AppIdentifier(null, null), superTokensUserId, true)); + assertTrue(storage.deleteUserIdMapping(process.getAppForTesting().toAppIdentifier(), superTokensUserId, true)); // check that the mapping does not exist - assertNull(storage.getUserIdMapping(new AppIdentifier(null, null), superTokensUserId, true)); + assertNull(storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), superTokensUserId, true)); } { // create a new userId mapping String newExternalUserId = "externalUserIdNew"; - storage.createUserIdMapping(new AppIdentifier(null, null), superTokensUserId, newExternalUserId, + storage.createUserIdMapping(process.getAppForTesting().toAppIdentifier(), superTokensUserId, newExternalUserId, null); // retrieve mapping and check that it exists - UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), + UserIdMapping userIdMapping = storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), newExternalUserId, false); assertNotNull(userIdMapping); assertEquals(superTokensUserId, userIdMapping.superTokensUserId); @@ -444,10 +447,10 @@ public void testDeletingAUserIdMapping() throws Exception { assertNull(userIdMapping.externalUserIdInfo); // delete mapping with externalUserId - assertTrue(storage.deleteUserIdMapping(new AppIdentifier(null, null), newExternalUserId, false)); + assertTrue(storage.deleteUserIdMapping(process.getAppForTesting().toAppIdentifier(), newExternalUserId, false)); // check that the mapping does not exist - assertNull(storage.getUserIdMapping(new AppIdentifier(null, null), newExternalUserId, false)); + assertNull(storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), newExternalUserId, false)); } @@ -465,21 +468,21 @@ public void testUpdatingExternalUserIdInfoWithUnknownUserId() throws Exception { return; } - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); String userId = "unknownId"; // update with unknown supertokensUserId assertFalse( - storage.updateOrDeleteExternalUserIdInfo(new AppIdentifier(null, null), userId, true, null)); + storage.updateOrDeleteExternalUserIdInfo(process.getAppForTesting().toAppIdentifier(), userId, true, null)); // update with unknown externalUserId assertFalse( - storage.updateOrDeleteExternalUserIdInfo(new AppIdentifier(null, null), userId, false, null)); + storage.updateOrDeleteExternalUserIdInfo(process.getAppForTesting().toAppIdentifier(), userId, false, null)); // check that there are no mappings with the userId - UserIdMapping[] userIdMappings = storage.getUserIdMapping(new AppIdentifier(null, null), userId); + UserIdMapping[] userIdMappings = storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), userId); assertEquals(0, userIdMappings.length); @@ -497,19 +500,19 @@ public void testUpdatingExternalUserIdInfo() throws Exception { return; } - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); // create User - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); String superTokensUserId = userInfo.getSupertokensUserId(); String externalUserId = "externalId"; String externalUserIdInfo = "externalUserIdInfo"; // create a userId mapping - storage.createUserIdMapping(new AppIdentifier(null, null), superTokensUserId, externalUserId, null); + storage.createUserIdMapping(process.getAppForTesting().toAppIdentifier(), superTokensUserId, externalUserId, null); { - UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), + UserIdMapping userIdMapping = storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), superTokensUserId, true); assertNotNull(userIdMapping); assertEquals(superTokensUserId, userIdMapping.superTokensUserId); @@ -518,12 +521,12 @@ public void testUpdatingExternalUserIdInfo() throws Exception { } // update from null to externalUserIdInfo - assertTrue(storage.updateOrDeleteExternalUserIdInfo(new AppIdentifier(null, null), superTokensUserId, + assertTrue(storage.updateOrDeleteExternalUserIdInfo(process.getAppForTesting().toAppIdentifier(), superTokensUserId, true, externalUserIdInfo)); // retrieve mapping and validate { - UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), + UserIdMapping userIdMapping = storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), superTokensUserId, true); assertNotNull(userIdMapping); assertEquals(superTokensUserId, userIdMapping.superTokensUserId); @@ -533,12 +536,12 @@ public void testUpdatingExternalUserIdInfo() throws Exception { // update externalUserIdInfo String newExternalUserIdInfo = "newExternalUserIdInfo"; - assertTrue(storage.updateOrDeleteExternalUserIdInfo(new AppIdentifier(null, null), superTokensUserId, + assertTrue(storage.updateOrDeleteExternalUserIdInfo(process.getAppForTesting().toAppIdentifier(), superTokensUserId, true, newExternalUserIdInfo)); // retrieve mapping and validate with the new externalUserIdInfo { - UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), + UserIdMapping userIdMapping = storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), superTokensUserId, true); assertNotNull(userIdMapping); assertEquals(superTokensUserId, userIdMapping.superTokensUserId); @@ -548,12 +551,12 @@ public void testUpdatingExternalUserIdInfo() throws Exception { // delete externalUserIdInfo by passing null assertTrue( - storage.updateOrDeleteExternalUserIdInfo(new AppIdentifier(null, null), externalUserId, false, + storage.updateOrDeleteExternalUserIdInfo(process.getAppForTesting().toAppIdentifier(), externalUserId, false, null)); // retrieve mapping and check that externalUserIdInfo is null { - UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), + UserIdMapping userIdMapping = storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), externalUserId, false); assertNotNull(userIdMapping); assertEquals(superTokensUserId, userIdMapping.superTokensUserId); @@ -575,13 +578,13 @@ public void createUsersMapTheirIdsCheckRetrieveUseIdMappingsWithListOfUserIds() return; } - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); ArrayList superTokensUserIdList = new ArrayList<>(); ArrayList externalUserIdList = new ArrayList<>(); // create users equal to the User Pagination limit for (int i = 1; i <= AuthRecipe.USER_PAGINATION_LIMIT; i++) { - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test" + i + "@example.com", + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test" + i + "@example.com", "testPass123"); superTokensUserIdList.add(userInfo.getSupertokensUserId()); String superTokensUserId = userInfo.getSupertokensUserId(); @@ -589,11 +592,11 @@ public void createUsersMapTheirIdsCheckRetrieveUseIdMappingsWithListOfUserIds() externalUserIdList.add(externalUserId); // create a userId mapping - storage.createUserIdMapping(new AppIdentifier(null, null), superTokensUserId, externalUserId, + storage.createUserIdMapping(process.getAppForTesting().toAppIdentifier(), superTokensUserId, externalUserId, null); } HashMap response = storage.getUserIdMappingForSuperTokensIds( - new AppIdentifier(null, null), superTokensUserIdList); + process.getAppForTesting().toAppIdentifier(), superTokensUserIdList); assertEquals(AuthRecipe.USER_PAGINATION_LIMIT, response.size()); for (int i = 0; i < response.size(); i++) { assertEquals(externalUserIdList.get(i), response.get(superTokensUserIdList.get(i))); @@ -613,11 +616,11 @@ public void testCallingGetUserIdMappingForSuperTokensIdsWithEmptyList() throws E return; } - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); ArrayList emptyList = new ArrayList<>(); HashMap response = storage.getUserIdMappingForSuperTokensIds( - new AppIdentifier(null, null), emptyList); + process.getAppForTesting().toAppIdentifier(), emptyList); assertEquals(0, response.size()); process.kill(); @@ -634,17 +637,17 @@ public void testCallingGetUserIdMappingForSuperTokensIdsWhenNoMappingExists() th return; } - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); ArrayList superTokensUserIdList = new ArrayList<>(); for (int i = 1; i <= 10; i++) { - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test" + i + "@example.com", + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test" + i + "@example.com", "testPass123"); superTokensUserIdList.add(userInfo.getSupertokensUserId()); } HashMap userIdMapping = storage.getUserIdMappingForSuperTokensIds( - new AppIdentifier(null, null), superTokensUserIdList); + process.getAppForTesting().toAppIdentifier(), superTokensUserIdList); assertEquals(0, userIdMapping.size()); process.kill(); @@ -661,13 +664,13 @@ public void create10UsersAndMap5UsersIds() throws Exception { return; } - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); ArrayList superTokensUserIdList = new ArrayList<>(); ArrayList userIdList = new ArrayList<>(); // create users equal to the User Pagination limit for (int i = 1; i <= 10; i++) { - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test" + i + "@example.com", + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test" + i + "@example.com", "testPass123"); superTokensUserIdList.add(userInfo.getSupertokensUserId()); @@ -677,14 +680,14 @@ public void create10UsersAndMap5UsersIds() throws Exception { // create userIdMapping for the last 5 users String externalUserId = "externalId" + i; userIdList.add(externalUserId); - storage.createUserIdMapping(new AppIdentifier(null, null), userInfo.getSupertokensUserId(), + storage.createUserIdMapping(process.getAppForTesting().toAppIdentifier(), userInfo.getSupertokensUserId(), externalUserId, null); } } // retrieve UserIDMapping HashMap response = storage.getUserIdMappingForSuperTokensIds( - new AppIdentifier(null, null), superTokensUserIdList); + process.getAppForTesting().toAppIdentifier(), superTokensUserIdList); assertEquals(5, response.size()); // check that the last 5 users have their ids mapped diff --git a/src/test/java/io/supertokens/test/userIdMapping/UserIdMappingTest.java b/src/test/java/io/supertokens/test/userIdMapping/UserIdMappingTest.java index 1af8acb90..f596f37d3 100644 --- a/src/test/java/io/supertokens/test/userIdMapping/UserIdMappingTest.java +++ b/src/test/java/io/supertokens/test/userIdMapping/UserIdMappingTest.java @@ -59,6 +59,9 @@ public class UserIdMappingTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -82,7 +85,7 @@ public void testCreatingUserIdMappingWithUnknownSuperTokensUserId() throws Excep // create a userId mapping with unknown SuperTokens UserId Exception error = null; try { - UserIdMapping.createUserIdMapping(process.main, "unknownSuperTokensUserId", "externalUserId", "someInfi", + UserIdMapping.createUserIdMapping(process.getProcess(), "unknownSuperTokensUserId", "externalUserId", "someInfi", false); } catch (Exception e) { error = e; @@ -106,17 +109,17 @@ public void testDuplicateUserIdMapping() throws Exception { } // create a user - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPassword"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPassword"); String externalUserId = "external-test"; - UserIdMapping.createUserIdMapping(process.main, userInfo.getSupertokensUserId(), externalUserId, null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), userInfo.getSupertokensUserId(), externalUserId, null, false); { // duplicate exception with both supertokensUserId and externalUserId Exception error = null; try { - UserIdMapping.createUserIdMapping(process.main, userInfo.getSupertokensUserId(), externalUserId, null, + UserIdMapping.createUserIdMapping(process.getProcess(), userInfo.getSupertokensUserId(), externalUserId, null, false); } catch (Exception e) { error = e; @@ -134,7 +137,7 @@ public void testDuplicateUserIdMapping() throws Exception { // duplicate exception with superTokensUserId Exception error = null; try { - UserIdMapping.createUserIdMapping(process.main, userInfo.getSupertokensUserId(), "newExternalId", null, + UserIdMapping.createUserIdMapping(process.getProcess(), userInfo.getSupertokensUserId(), "newExternalId", null, false); } catch (Exception e) { error = e; @@ -152,10 +155,10 @@ public void testDuplicateUserIdMapping() throws Exception { { // duplicate exception with externalUserId - AuthRecipeUserInfo newUser = EmailPassword.signUp(process.main, "test2@example.com", "testPass123"); + AuthRecipeUserInfo newUser = EmailPassword.signUp(process.getProcess(), "test2@example.com", "testPass123"); Exception error = null; try { - UserIdMapping.createUserIdMapping(process.main, newUser.getSupertokensUserId(), externalUserId, null, + UserIdMapping.createUserIdMapping(process.getProcess(), newUser.getSupertokensUserId(), externalUserId, null, false); } catch (Exception e) { error = e; @@ -184,10 +187,10 @@ public void testCreatingUserIdMapping() throws Exception { return; } - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); // create a user - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPassword"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPassword"); String externalUserId = "external-test"; String externalUserIdInfo = "external-info"; @@ -198,7 +201,7 @@ public void testCreatingUserIdMapping() throws Exception { // check that the mapping exists io.supertokens.pluginInterface.useridmapping.UserIdMapping userIdMapping = storage.getUserIdMapping( - new AppIdentifier(null, null), userInfo.getSupertokensUserId(), + process.getAppForTesting().toAppIdentifier(), userInfo.getSupertokensUserId(), true); assertEquals(userInfo.getSupertokensUserId(), userIdMapping.superTokensUserId); assertEquals(externalUserId, userIdMapping.externalUserId); @@ -219,13 +222,13 @@ public void testRetrievingUseridMappingWithUnknownId() throws Exception { } // get mapping with unknown userId with userIdType SUPERTOKENS - assertNull(UserIdMapping.getUserIdMapping(process.main, "unknownUserId", UserIdType.SUPERTOKENS)); + assertNull(UserIdMapping.getUserIdMapping(process.getProcess(), "unknownUserId", UserIdType.SUPERTOKENS)); // get mapping with unknown userId with userIdType EXTERNAL - assertNull(UserIdMapping.getUserIdMapping(process.main, "unknownUserId", UserIdType.EXTERNAL)); + assertNull(UserIdMapping.getUserIdMapping(process.getProcess(), "unknownUserId", UserIdType.EXTERNAL)); // get mapping with unknown userId with userIdTYPE ANY - assertNull(UserIdMapping.getUserIdMapping(process.main, "unknownUserId", UserIdType.ANY)); + assertNull(UserIdMapping.getUserIdMapping(process.getProcess(), "unknownUserId", UserIdType.ANY)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -242,18 +245,18 @@ public void testRetrievingUserIdMapping() throws Exception { } // create a User and then a UserId mapping - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); String superTokensUserId = userInfo.getSupertokensUserId(); String externalUserId = "externalId"; String externalUserIdInfo = "externalIdInfo"; - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, externalUserIdInfo, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, externalUserIdInfo, false); // retrieve mapping with supertokensUserId and validate response { io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS); assertNotNull(response); assertEquals(superTokensUserId, response.superTokensUserId); @@ -265,7 +268,7 @@ public void testRetrievingUserIdMapping() throws Exception { { io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, externalUserId, UserIdType.EXTERNAL); + .getUserIdMapping(process.getProcess(), externalUserId, UserIdType.EXTERNAL); assertNotNull(response); assertEquals(superTokensUserId, response.superTokensUserId); @@ -278,7 +281,7 @@ public void testRetrievingUserIdMapping() throws Exception { { // with supertokensUserId io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId, UserIdType.ANY); + .getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.ANY); assertNotNull(response); assertEquals(superTokensUserId, response.superTokensUserId); @@ -289,7 +292,7 @@ public void testRetrievingUserIdMapping() throws Exception { { // with externalUserId io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, externalUserId, UserIdType.ANY); + .getUserIdMapping(process.getProcess(), externalUserId, UserIdType.ANY); assertNotNull(response); assertEquals(superTokensUserId, response.superTokensUserId); @@ -299,23 +302,23 @@ public void testRetrievingUserIdMapping() throws Exception { } // create a new mapping where the superTokensUserId of Mapping1 = externalUserId of Mapping2 - AuthRecipeUserInfo userInfo2 = EmailPassword.signUp(process.main, "test2@example.com", "testPass123"); + AuthRecipeUserInfo userInfo2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "testPass123"); String newSuperTokensUserId = userInfo2.getSupertokensUserId(); String newExternalUserId = userInfo.getSupertokensUserId(); String newExternalUserIdInfo = "newExternalUserIdInfo"; - UserIdMapping.createUserIdMapping(process.main, newSuperTokensUserId, newExternalUserId, newExternalUserIdInfo, + UserIdMapping.createUserIdMapping(process.getProcess(), newSuperTokensUserId, newExternalUserId, newExternalUserIdInfo, true); // retrieve the mapping with newExternalUserId using ANY, it should return Mapping 1 { io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, newExternalUserId, UserIdType.ANY); + .getUserIdMapping(process.getProcess(), newExternalUserId, UserIdType.ANY); // query with the storage layer and check that the db returns two entries - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); io.supertokens.pluginInterface.useridmapping.UserIdMapping[] storageResponse = storage - .getUserIdMapping(new AppIdentifier(null, null), newExternalUserId); + .getUserIdMapping(process.getAppForTesting().toAppIdentifier(), newExternalUserId); assertEquals(2, storageResponse.length); assertNotNull(response); @@ -327,7 +330,7 @@ public void testRetrievingUserIdMapping() throws Exception { // retrieve the mapping with newExternalUserId using EXTERNAL, it should return Mapping 2 { io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, newExternalUserId, UserIdType.EXTERNAL); + .getUserIdMapping(process.getProcess(), newExternalUserId, UserIdType.EXTERNAL); assertNotNull(response); assertEquals(newSuperTokensUserId, response.superTokensUserId); @@ -351,15 +354,15 @@ public void testDeletingUserIdMappingWithUnknownId() throws Exception { // deleting a mapping with an unknown UserId with userIdType as SUPERTOKENS - assertFalse(UserIdMapping.deleteUserIdMapping(process.main, "unknownUserId", UserIdType.SUPERTOKENS, false)); + assertFalse(UserIdMapping.deleteUserIdMapping(process.getProcess(), "unknownUserId", UserIdType.SUPERTOKENS, false)); // deleting a mapping with an unknown UserId with userIdType as EXTERNAL - assertFalse(UserIdMapping.deleteUserIdMapping(process.main, "unknownUserId", UserIdType.EXTERNAL, false)); + assertFalse(UserIdMapping.deleteUserIdMapping(process.getProcess(), "unknownUserId", UserIdType.EXTERNAL, false)); // deleting a mapping with an unknown UserId with userIdType as ANY - assertFalse(UserIdMapping.deleteUserIdMapping(process.main, "unknownUserId", UserIdType.ANY, false)); + assertFalse(UserIdMapping.deleteUserIdMapping(process.getProcess(), "unknownUserId", UserIdType.ANY, false)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -376,7 +379,7 @@ public void testDeletingUserIdMapping() throws Exception { } // create mapping and check that it exists - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); String superTokensUserId = userInfo.getSupertokensUserId(); String externalUserId = "externalId"; String externalUserIdInfo = "externalIdInfo"; @@ -386,14 +389,14 @@ public void testDeletingUserIdMapping() throws Exception { superTokensUserId, externalUserId, externalUserIdInfo); { - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, externalUserIdInfo, + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, externalUserIdInfo, false); // retrieve mapping and validate response { io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS); assertNotNull(response); assertEquals(userIdMapping_1, response); @@ -401,66 +404,66 @@ public void testDeletingUserIdMapping() throws Exception { // Delete mapping with userIdType SUPERTOKENS and check that it is deleted assertTrue( - UserIdMapping.deleteUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS, false)); + UserIdMapping.deleteUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS, false)); // check that mapping does not exist - assertNull(UserIdMapping.getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS)); + assertNull(UserIdMapping.getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS)); } { // create mapping and check that it exists - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, externalUserIdInfo, + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, externalUserIdInfo, false); io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, externalUserId, UserIdType.EXTERNAL); + .getUserIdMapping(process.getProcess(), externalUserId, UserIdType.EXTERNAL); assertNotNull(response); assertEquals(userIdMapping_1, response); // delete mapping with userIdType EXTERNAL and check that it is deleted - assertTrue(UserIdMapping.deleteUserIdMapping(process.main, externalUserId, UserIdType.EXTERNAL, false)); + assertTrue(UserIdMapping.deleteUserIdMapping(process.getProcess(), externalUserId, UserIdType.EXTERNAL, false)); // check that mapping does not exist - assertNull(UserIdMapping.getUserIdMapping(process.main, externalUserId, UserIdType.EXTERNAL)); + assertNull(UserIdMapping.getUserIdMapping(process.getProcess(), externalUserId, UserIdType.EXTERNAL)); } { { // create mapping and check that it exists - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, externalUserIdInfo, + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, externalUserIdInfo, false); io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS); assertNotNull(response); assertEquals(userIdMapping_1, response); // delete mapping with superTokensUserId with userIdType ANY and check that it is deleted - assertTrue(UserIdMapping.deleteUserIdMapping(process.main, superTokensUserId, UserIdType.ANY, false)); + assertTrue(UserIdMapping.deleteUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.ANY, false)); // check that mapping does not exist - assertNull(UserIdMapping.getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS)); + assertNull(UserIdMapping.getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS)); } { // create mapping and check that it exists - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, externalUserIdInfo, + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, externalUserIdInfo, false); io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, externalUserId, UserIdType.ANY); + .getUserIdMapping(process.getProcess(), externalUserId, UserIdType.ANY); assertNotNull(response); assertEquals(userIdMapping_1, response); // delete mapping with externalUserId with userIdType ANY and check that it is deleted - assertTrue(UserIdMapping.deleteUserIdMapping(process.main, externalUserId, UserIdType.ANY, false)); + assertTrue(UserIdMapping.deleteUserIdMapping(process.getProcess(), externalUserId, UserIdType.ANY, false)); // check that mapping does not exist - assertNull(UserIdMapping.getUserIdMapping(process.main, externalUserId, UserIdType.ANY)); + assertNull(UserIdMapping.getUserIdMapping(process.getProcess(), externalUserId, UserIdType.ANY)); } } @@ -482,55 +485,55 @@ public void testDeletingUserIdMappingWithSharedId() throws Exception { // Create UserId mapping 1 - AuthRecipeUserInfo userInfo_1 = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo_1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); io.supertokens.pluginInterface.useridmapping.UserIdMapping userIdMapping_1 = new io.supertokens.pluginInterface.useridmapping.UserIdMapping( userInfo_1.getSupertokensUserId(), "externalUserId", "externalUserIdInfo"); // create the mapping and check that it exists { - UserIdMapping.createUserIdMapping(process.main, userIdMapping_1.superTokensUserId, + UserIdMapping.createUserIdMapping(process.getProcess(), userIdMapping_1.superTokensUserId, userIdMapping_1.externalUserId, userIdMapping_1.externalUserIdInfo, false); io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, userIdMapping_1.superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), userIdMapping_1.superTokensUserId, UserIdType.SUPERTOKENS); assertEquals(userIdMapping_1, response); } // Create UserId mapping 2 - AuthRecipeUserInfo userInfo_2 = EmailPassword.signUp(process.main, "test2@example.com", "testPass123"); + AuthRecipeUserInfo userInfo_2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "testPass123"); io.supertokens.pluginInterface.useridmapping.UserIdMapping userIdMapping_2 = new io.supertokens.pluginInterface.useridmapping.UserIdMapping( userInfo_2.getSupertokensUserId(), userIdMapping_1.superTokensUserId, "externalUserIdInfo2"); // create the mapping and check that it exists { - UserIdMapping.createUserIdMapping(process.main, userIdMapping_2.superTokensUserId, + UserIdMapping.createUserIdMapping(process.getProcess(), userIdMapping_2.superTokensUserId, userIdMapping_2.externalUserId, userIdMapping_2.externalUserIdInfo, true); io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, userIdMapping_2.superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), userIdMapping_2.superTokensUserId, UserIdType.SUPERTOKENS); assertEquals(userIdMapping_2, response); } // delete userIdMapping with userIdMapping_2.externalUserId with userIdType ANY, userIdMapping_1 should be // deleted assertTrue( - UserIdMapping.deleteUserIdMapping(process.main, userIdMapping_2.externalUserId, UserIdType.ANY, false)); + UserIdMapping.deleteUserIdMapping(process.getProcess(), userIdMapping_2.externalUserId, UserIdType.ANY, false)); - assertNull(UserIdMapping.getUserIdMapping(process.main, userIdMapping_1.superTokensUserId, + assertNull(UserIdMapping.getUserIdMapping(process.getProcess(), userIdMapping_1.superTokensUserId, UserIdType.SUPERTOKENS)); // check that userIdMapping_2 still exists { io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, userIdMapping_2.superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), userIdMapping_2.superTokensUserId, UserIdType.SUPERTOKENS); assertEquals(userIdMapping_2, response); } // delete userIdMapping with userIdMapping_2.externalUserId with EXTERNAL, userIdMapping_2 should be deleted - assertTrue(UserIdMapping.deleteUserIdMapping(process.main, userIdMapping_2.externalUserId, UserIdType.EXTERNAL, + assertTrue(UserIdMapping.deleteUserIdMapping(process.getProcess(), userIdMapping_2.externalUserId, UserIdType.EXTERNAL, false)); - assertNull(UserIdMapping.getUserIdMapping(process.main, userIdMapping_2.superTokensUserId, + assertNull(UserIdMapping.getUserIdMapping(process.getProcess(), userIdMapping_2.superTokensUserId, UserIdType.SUPERTOKENS)); process.kill(); @@ -550,17 +553,17 @@ public void testUpdatingExternalUserIdInfoWithUnknownUserId() throws Exception { String userId = "unknownId"; // update with unknown supertokensUserId - assertFalse(UserIdMapping.updateOrDeleteExternalUserIdInfo(process.main, userId, UserIdType.SUPERTOKENS, null)); + assertFalse(UserIdMapping.updateOrDeleteExternalUserIdInfo(process.getProcess(), userId, UserIdType.SUPERTOKENS, null)); // update with unknown externalUserId - assertFalse(UserIdMapping.updateOrDeleteExternalUserIdInfo(process.main, userId, UserIdType.EXTERNAL, null)); + assertFalse(UserIdMapping.updateOrDeleteExternalUserIdInfo(process.getProcess(), userId, UserIdType.EXTERNAL, null)); // update with unknown userId - assertFalse(UserIdMapping.updateOrDeleteExternalUserIdInfo(process.main, userId, UserIdType.ANY, null)); + assertFalse(UserIdMapping.updateOrDeleteExternalUserIdInfo(process.getProcess(), userId, UserIdType.ANY, null)); // check that there are no mappings with the userId - assertNull(UserIdMapping.getUserIdMapping(process.main, userId, UserIdType.ANY)); + assertNull(UserIdMapping.getUserIdMapping(process.getProcess(), userId, UserIdType.ANY)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -577,16 +580,16 @@ public void testUpdatingExternalUserIdInfo() throws Exception { } // create User - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); String superTokensUserId = userInfo.getSupertokensUserId(); String externalUserId = "externalId"; // create a userId mapping - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, null, false); { io.supertokens.pluginInterface.useridmapping.UserIdMapping userIdMapping = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS); assertNotNull(userIdMapping); assertEquals(superTokensUserId, userIdMapping.superTokensUserId); @@ -596,13 +599,13 @@ public void testUpdatingExternalUserIdInfo() throws Exception { // update from null to externalUserIdInfo using userIdType SUPERTOKENS String externalUserIdInfo = "externalUserIdInfo"; - assertTrue(UserIdMapping.updateOrDeleteExternalUserIdInfo(process.main, superTokensUserId, + assertTrue(UserIdMapping.updateOrDeleteExternalUserIdInfo(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS, externalUserIdInfo)); // retrieve mapping and validate { io.supertokens.pluginInterface.useridmapping.UserIdMapping userIdMapping = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS); assertNotNull(userIdMapping); assertEquals(superTokensUserId, userIdMapping.superTokensUserId); @@ -612,13 +615,13 @@ public void testUpdatingExternalUserIdInfo() throws Exception { // update externalUserIdInfo using userIdType EXTERNAL String newExternalUserIdInfo = "newExternalUserIdInfo"; - assertTrue(UserIdMapping.updateOrDeleteExternalUserIdInfo(process.main, externalUserId, UserIdType.EXTERNAL, + assertTrue(UserIdMapping.updateOrDeleteExternalUserIdInfo(process.getProcess(), externalUserId, UserIdType.EXTERNAL, newExternalUserIdInfo)); // retrieve mapping and validate with the new externalUserIdInfo { io.supertokens.pluginInterface.useridmapping.UserIdMapping userIdMapping = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS); assertNotNull(userIdMapping); assertEquals(superTokensUserId, userIdMapping.superTokensUserId); @@ -628,12 +631,12 @@ public void testUpdatingExternalUserIdInfo() throws Exception { // delete externalUserIdInfo by passing null with superTokensUserId with ANY assertTrue( - UserIdMapping.updateOrDeleteExternalUserIdInfo(process.main, superTokensUserId, UserIdType.ANY, null)); + UserIdMapping.updateOrDeleteExternalUserIdInfo(process.getProcess(), superTokensUserId, UserIdType.ANY, null)); // retrieve mapping and check that externalUserIdInfo is null { io.supertokens.pluginInterface.useridmapping.UserIdMapping userIdMapping = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS); assertNotNull(userIdMapping); assertEquals(superTokensUserId, userIdMapping.superTokensUserId); @@ -643,11 +646,11 @@ public void testUpdatingExternalUserIdInfo() throws Exception { // update the externalUserIdInfo with externalUserId with ANY { - assertTrue(UserIdMapping.updateOrDeleteExternalUserIdInfo(process.main, externalUserId, UserIdType.ANY, + assertTrue(UserIdMapping.updateOrDeleteExternalUserIdInfo(process.getProcess(), externalUserId, UserIdType.ANY, externalUserIdInfo)); io.supertokens.pluginInterface.useridmapping.UserIdMapping userIdMapping = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS); assertNotNull(userIdMapping); assertEquals(superTokensUserId, userIdMapping.superTokensUserId); @@ -672,18 +675,18 @@ public void testUpdatingExternalUserIdInfoWithSharedUserIds() throws Exception { // create two UserMappings where superTokensUserId in Mapping 1 = externalUserId in Mapping 2 // Create mapping 1 - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); String superTokensUserId = userInfo.getSupertokensUserId(); String externalUserId = "externalId"; String externalUserIdInfo = "externalUserIdInfo"; - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, externalUserIdInfo, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, externalUserIdInfo, false); // check that mapping exists { io.supertokens.pluginInterface.useridmapping.UserIdMapping userIdMapping = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS); assertNotNull(userIdMapping); assertEquals(superTokensUserId, userIdMapping.superTokensUserId); assertEquals(externalUserId, userIdMapping.externalUserId); @@ -691,17 +694,17 @@ public void testUpdatingExternalUserIdInfoWithSharedUserIds() throws Exception { } // Create mapping 2 - AuthRecipeUserInfo userInfo2 = EmailPassword.signUp(process.main, "test2@example.com", "testPass123"); + AuthRecipeUserInfo userInfo2 = EmailPassword.signUp(process.getProcess(), "test2@example.com", "testPass123"); String superTokensUserId2 = userInfo2.getSupertokensUserId(); String externalUserId2 = userInfo.getSupertokensUserId(); String externalUserIdInfo2 = "newExternalUserIdInfo"; - UserIdMapping.createUserIdMapping(process.main, superTokensUserId2, externalUserId2, externalUserIdInfo2, true); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId2, externalUserId2, externalUserIdInfo2, true); // check that the mapping exists { io.supertokens.pluginInterface.useridmapping.UserIdMapping userIdMapping = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId2, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId2, UserIdType.SUPERTOKENS); assertNotNull(userIdMapping); assertEquals(superTokensUserId2, userIdMapping.superTokensUserId); assertEquals(externalUserId2, userIdMapping.externalUserId); @@ -709,19 +712,19 @@ public void testUpdatingExternalUserIdInfoWithSharedUserIds() throws Exception { } // update the mapping with externalUserId2 with userIdType ANY, userId mapping 1 should be updated - assertTrue(UserIdMapping.updateOrDeleteExternalUserIdInfo(process.main, externalUserId2, UserIdType.ANY, null)); + assertTrue(UserIdMapping.updateOrDeleteExternalUserIdInfo(process.getProcess(), externalUserId2, UserIdType.ANY, null)); // check that userId mapping 1 got updated and userId mapping 2 is the same { io.supertokens.pluginInterface.useridmapping.UserIdMapping userIdMapping_1 = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS); assertNotNull(userIdMapping_1); assertEquals(superTokensUserId, userIdMapping_1.superTokensUserId); assertEquals(externalUserId, userIdMapping_1.externalUserId); assertNull(userIdMapping_1.externalUserIdInfo); io.supertokens.pluginInterface.useridmapping.UserIdMapping userIdMapping_2 = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId2, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId2, UserIdType.SUPERTOKENS); assertNotNull(userIdMapping_2); assertEquals(superTokensUserId2, userIdMapping_2.superTokensUserId); @@ -730,11 +733,11 @@ public void testUpdatingExternalUserIdInfoWithSharedUserIds() throws Exception { } // delete externalUserIdInfo with EXTERNAL from userIdMapping 2 and check that it gets updated - assertTrue(UserIdMapping.updateOrDeleteExternalUserIdInfo(process.main, externalUserId2, UserIdType.EXTERNAL, + assertTrue(UserIdMapping.updateOrDeleteExternalUserIdInfo(process.getProcess(), externalUserId2, UserIdType.EXTERNAL, null)); io.supertokens.pluginInterface.useridmapping.UserIdMapping userIdMapping = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId2, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId2, UserIdType.SUPERTOKENS); assertNotNull(userIdMapping); assertEquals(superTokensUserId2, userIdMapping.superTokensUserId); @@ -757,30 +760,30 @@ public void testUpdatingTheExternalUserIdInfoOfAMappingWithTheSameValue() throws // create a userIdMapping with externalUserIdInfo as null and update it to null { - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); String superTokensUserId = userInfo.getSupertokensUserId(); String externalUserId = "externalUserId"; // create mapping - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, null, false); // update the externalUserIdInfo to the same value - assertTrue(UserIdMapping.updateOrDeleteExternalUserIdInfo(process.main, superTokensUserId, + assertTrue(UserIdMapping.updateOrDeleteExternalUserIdInfo(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS, null)); } { - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test2@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test2@example.com", "testPass123"); String superTokensUserId = userInfo.getSupertokensUserId(); String externalUserId = "newExternalUserIdInfo"; String externalUserIdInfo = "externalUserIdInfo"; // create mapping - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, externalUserIdInfo, + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, externalUserIdInfo, false); // update the externalUserIdInfo to the same value - assertTrue(UserIdMapping.updateOrDeleteExternalUserIdInfo(process.main, superTokensUserId, + assertTrue(UserIdMapping.updateOrDeleteExternalUserIdInfo(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS, externalUserIdInfo)); } @@ -798,7 +801,7 @@ public void checkThatCreateUserIdMappingHasAllNonAuthRecipeChecks() throws Excep return; } - FeatureFlagTestContent.getInstance(process.main) + FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{EE_FEATURES.MFA}); // this list contains the package names for recipes which dont use UserIdMapping @@ -820,16 +823,16 @@ public void checkThatCreateUserIdMappingHasAllNonAuthRecipeChecks() throws Excep } for (String className : classNames) { - AuthRecipeUserInfo user = EmailPassword.signUp(process.main, "test@example.com", "password"); + AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "password"); String userId = user.getSupertokensUserId(); // create entry in nonAuth table - StorageLayer.getStorage(process.main) - .addInfoToNonAuthRecipesBasedOnUserId(TenantIdentifier.BASE_TENANT, className, userId); + StorageLayer.getStorage(process.getProcess()) + .addInfoToNonAuthRecipesBasedOnUserId(process.getAppForTesting(), className, userId); // try to create the mapping with superTokensId String errorMessage = null; try { - UserIdMapping.createUserIdMapping(process.main, userId, "externalId", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), userId, "externalId", null, false); } catch (ServletException e) { errorMessage = e.getRootCause().getMessage(); } catch (UnknownSuperTokensUserIdException e) { @@ -846,7 +849,7 @@ public void checkThatCreateUserIdMappingHasAllNonAuthRecipeChecks() throws Excep } // delete user data - AuthRecipe.deleteUser(process.main, userId); + AuthRecipe.deleteUser(process.getProcess(), userId); } process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -864,8 +867,8 @@ public void checkThatAddInfoToNonAuthRecipesBasedOnUserIdThrowsAnErrorWithUnknow Exception error = null; try { - StorageLayer.getStorage(process.main) - .addInfoToNonAuthRecipesBasedOnUserId(TenantIdentifier.BASE_TENANT, "unknownRecipe", "testUserId"); + StorageLayer.getStorage(process.getProcess()) + .addInfoToNonAuthRecipesBasedOnUserId(process.getAppForTesting(), "unknownRecipe", "testUserId"); } catch (IllegalStateException e) { error = e; } @@ -905,19 +908,19 @@ public void checkThatDeleteUserIdMappingHasAllNonAuthRecipeChecks() throws Excep String externalId = "externalId"; for (String className : classNames) { // Create a User - AuthRecipeUserInfo user = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); // create a mapping with the user - UserIdMapping.createUserIdMapping(process.main, user.getSupertokensUserId(), externalId, null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), user.getSupertokensUserId(), externalId, null, false); // create entry in nonAuth table with externalId - StorageLayer.getStorage(process.main) - .addInfoToNonAuthRecipesBasedOnUserId(TenantIdentifier.BASE_TENANT, className, externalId); + StorageLayer.getStorage(process.getProcess()) + .addInfoToNonAuthRecipesBasedOnUserId(process.getAppForTesting(), className, externalId); // try to delete UserIdMapping String errorMessage = null; try { - UserIdMapping.deleteUserIdMapping(process.main, user.getSupertokensUserId(), UserIdType.SUPERTOKENS, + UserIdMapping.deleteUserIdMapping(process.getProcess(), user.getSupertokensUserId(), UserIdType.SUPERTOKENS, false); } catch (ServletException e) { errorMessage = e.getRootCause().getMessage(); @@ -927,7 +930,7 @@ public void checkThatDeleteUserIdMappingHasAllNonAuthRecipeChecks() throws Excep assertTrue(errorMessage.contains("UserId is already in use")); } // delete user data - AuthRecipe.deleteUser(process.main, user.getSupertokensUserId()); + AuthRecipe.deleteUser(process.getProcess(), user.getSupertokensUserId()); } process.kill(); @@ -947,22 +950,22 @@ public void checkThatWeDontAllowDBStateA5FromBeingCreatedWhenForceIsFalse() thro } // create an EmailPassword User - AuthRecipeUserInfo user_1 = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo user_1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); // create a mapping for the EmailPassword User - UserIdMapping.createUserIdMapping(process.main, user_1.getSupertokensUserId(), "externalId", null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), user_1.getSupertokensUserId(), "externalId", null, false); // create some metadata for the user JsonObject data = new JsonObject(); data.addProperty("test", "testData"); - UserMetadata.updateUserMetadata(process.main, "externalId", data); + UserMetadata.updateUserMetadata(process.getProcess(), "externalId", data); // Create another User - AuthRecipeUserInfo user_2 = EmailPassword.signUp(process.main, "test123@example.com", "testPass123"); + AuthRecipeUserInfo user_2 = EmailPassword.signUp(process.getProcess(), "test123@example.com", "testPass123"); // try and map user_2 to user_1s superTokensUserId String errorMessage = null; try { - UserIdMapping.createUserIdMapping(process.main, user_2.getSupertokensUserId(), + UserIdMapping.createUserIdMapping(process.getProcess(), user_2.getSupertokensUserId(), user_1.getSupertokensUserId(), null, false); } catch (ServletException e) { errorMessage = e.getRootCause().getMessage(); @@ -985,19 +988,19 @@ public void testThatWeDontAllowDBStateA6WithoutForce() throws Exception { } // create user 1 - AuthRecipeUserInfo user_1 = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo user_1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); // create user 2 - AuthRecipeUserInfo user_2 = EmailPassword.signUp(process.main, "test123@example.com", "testPass123"); + AuthRecipeUserInfo user_2 = EmailPassword.signUp(process.getProcess(), "test123@example.com", "testPass123"); // create a mapping between User_1 and User_2 with force - UserIdMapping.createUserIdMapping(process.main, user_1.getSupertokensUserId(), user_2.getSupertokensUserId(), + UserIdMapping.createUserIdMapping(process.getProcess(), user_1.getSupertokensUserId(), user_2.getSupertokensUserId(), null, true); // try and create a mapping between User_2 and User_1 without force String errorMessage = null; try { - UserIdMapping.createUserIdMapping(process.main, user_2.getSupertokensUserId(), + UserIdMapping.createUserIdMapping(process.getProcess(), user_2.getSupertokensUserId(), user_1.getSupertokensUserId(), null, false); } catch (ServletException e) { errorMessage = e.getRootCause().getMessage(); @@ -1025,17 +1028,17 @@ public void testDeleteMappingWithUser_1AndUserIdTypeAsAny() throws Exception { } // create User_1 and User_2 - AuthRecipeUserInfo user_1 = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); - AuthRecipeUserInfo user_2 = EmailPassword.signUp(process.main, "test123@exmaple.com", "testPass123"); + AuthRecipeUserInfo user_1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); + AuthRecipeUserInfo user_2 = EmailPassword.signUp(process.getProcess(), "test123@exmaple.com", "testPass123"); // create a mapping between User_2 and User_1 with force - UserIdMapping.createUserIdMapping(process.main, user_2.getSupertokensUserId(), user_1.getSupertokensUserId(), + UserIdMapping.createUserIdMapping(process.getProcess(), user_2.getSupertokensUserId(), user_1.getSupertokensUserId(), null, true); // check that mapping exists { io.supertokens.pluginInterface.useridmapping.UserIdMapping mapping = UserIdMapping - .getUserIdMapping(process.main, user_2.getSupertokensUserId(), UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), user_2.getSupertokensUserId(), UserIdType.SUPERTOKENS); assertNotNull(mapping); assertEquals(mapping.superTokensUserId, user_2.getSupertokensUserId()); assertEquals(mapping.externalUserId, user_1.getSupertokensUserId()); @@ -1043,12 +1046,12 @@ public void testDeleteMappingWithUser_1AndUserIdTypeAsAny() throws Exception { // delete mapping with User_1s Id and UserIdType set to ANY, it should delete the mapping assertTrue( - UserIdMapping.deleteUserIdMapping(process.main, user_1.getSupertokensUserId(), UserIdType.ANY, false)); + UserIdMapping.deleteUserIdMapping(process.getProcess(), user_1.getSupertokensUserId(), UserIdType.ANY, false)); // check that mapping is deleted { io.supertokens.pluginInterface.useridmapping.UserIdMapping mapping = UserIdMapping - .getUserIdMapping(process.main, user_2.getSupertokensUserId(), UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), user_2.getSupertokensUserId(), UserIdType.SUPERTOKENS); assertNull(mapping); } @@ -1071,17 +1074,17 @@ public void testDeleteMappingWithUser_1AndUserIdTypeAsSUPERTOKENS() throws Excep } // create User_1 and User_2 - AuthRecipeUserInfo user_1 = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); - AuthRecipeUserInfo user_2 = EmailPassword.signUp(process.main, "test123@exmaple.com", "testPass123"); + AuthRecipeUserInfo user_1 = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); + AuthRecipeUserInfo user_2 = EmailPassword.signUp(process.getProcess(), "test123@exmaple.com", "testPass123"); // create a mapping between User_2 and User_1 with force - UserIdMapping.createUserIdMapping(process.main, user_2.getSupertokensUserId(), user_1.getSupertokensUserId(), + UserIdMapping.createUserIdMapping(process.getProcess(), user_2.getSupertokensUserId(), user_1.getSupertokensUserId(), null, true); // check that mapping exists { io.supertokens.pluginInterface.useridmapping.UserIdMapping mapping = UserIdMapping - .getUserIdMapping(process.main, user_2.getSupertokensUserId(), UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), user_2.getSupertokensUserId(), UserIdType.SUPERTOKENS); assertNotNull(mapping); assertEquals(mapping.superTokensUserId, user_2.getSupertokensUserId()); assertEquals(mapping.externalUserId, user_1.getSupertokensUserId()); @@ -1089,13 +1092,13 @@ public void testDeleteMappingWithUser_1AndUserIdTypeAsSUPERTOKENS() throws Excep // delete mapping with User_1s Id and UserIdType set to ANY, it should delete the mapping assertTrue( - UserIdMapping.deleteUserIdMapping(process.main, user_1.getSupertokensUserId(), UserIdType.SUPERTOKENS, + UserIdMapping.deleteUserIdMapping(process.getProcess(), user_1.getSupertokensUserId(), UserIdType.SUPERTOKENS, false)); // check that mapping is deleted { io.supertokens.pluginInterface.useridmapping.UserIdMapping mapping = UserIdMapping - .getUserIdMapping(process.main, user_2.getSupertokensUserId(), UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), user_2.getSupertokensUserId(), UserIdType.SUPERTOKENS); assertNull(mapping); } diff --git a/src/test/java/io/supertokens/test/userIdMapping/api/CreateUserIdMappingAPITest.java b/src/test/java/io/supertokens/test/userIdMapping/api/CreateUserIdMappingAPITest.java index cc268b7f6..52096946a 100644 --- a/src/test/java/io/supertokens/test/userIdMapping/api/CreateUserIdMappingAPITest.java +++ b/src/test/java/io/supertokens/test/userIdMapping/api/CreateUserIdMappingAPITest.java @@ -44,6 +44,9 @@ public class CreateUserIdMappingAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -224,12 +227,12 @@ public void testCreatingAUserIdMappingWithAndWithoutForce() throws Exception { } // create a User and add some non auth recipe info - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); // add some metadata to the user JsonObject userMetadata = new JsonObject(); userMetadata.addProperty("test", "testExample"); - UserMetadata.updateUserMetadata(process.main, userInfo.getSupertokensUserId(), userMetadata); + UserMetadata.updateUserMetadata(process.getProcess(), userInfo.getSupertokensUserId(), userMetadata); String superTokensUserId = userInfo.getSupertokensUserId(); String externalUserId = "externalId"; @@ -278,10 +281,10 @@ public void testCreatingAUserIdMapping() throws Exception { return; } - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); // create a User - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); String superTokensUserId = userInfo.getSupertokensUserId(); String externalUserId = "userId"; String externalUserIdInfo = "externUserIdInfo"; @@ -301,7 +304,7 @@ public void testCreatingAUserIdMapping() throws Exception { // check that userIdMapping was created - UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), + UserIdMapping userIdMapping = storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), superTokensUserId, true); assertEquals(superTokensUserId, userIdMapping.superTokensUserId); @@ -353,7 +356,7 @@ public void testCreatingUserIdMappingWithExternalUserIdInfoAsNull() throws Excep return; } - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); String externalUserId = "externalUserId"; JsonObject requestBody = new JsonObject(); requestBody.addProperty("superTokensUserId", userInfo.getSupertokensUserId()); @@ -364,9 +367,9 @@ public void testCreatingUserIdMappingWithExternalUserIdInfoAsNull() throws Excep "http://localhost:3567/recipe/userid/map", requestBody, 1000, 1000, null, SemVer.v2_15.get(), "useridmapping"); - UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.main); + UserIdMappingStorage storage = (UserIdMappingStorage) StorageLayer.getStorage(process.getProcess()); - UserIdMapping userIdMapping = storage.getUserIdMapping(new AppIdentifier(null, null), + UserIdMapping userIdMapping = storage.getUserIdMapping(process.getAppForTesting().toAppIdentifier(), userInfo.getSupertokensUserId(), true); @@ -391,13 +394,13 @@ public void testCreatingDuplicateUserIdMapping() throws Exception { return; } - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); String superTokensUserId = userInfo.getSupertokensUserId(); String externalUserId = "externalUserId"; // create UserId mapping - io.supertokens.useridmapping.UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, + io.supertokens.useridmapping.UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, null, false); { @@ -437,7 +440,7 @@ public void testCreatingDuplicateUserIdMapping() throws Exception { { // create a duplicate mapping with externalUserId - AuthRecipeUserInfo newUserInfo = EmailPassword.signUp(process.main, "test2@example.com", "testPass123"); + AuthRecipeUserInfo newUserInfo = EmailPassword.signUp(process.getProcess(), "test2@example.com", "testPass123"); JsonObject requestBody = new JsonObject(); diff --git a/src/test/java/io/supertokens/test/userIdMapping/api/GetUserIdMappingAPITest.java b/src/test/java/io/supertokens/test/userIdMapping/api/GetUserIdMappingAPITest.java index 8ec16e875..414c068f4 100644 --- a/src/test/java/io/supertokens/test/userIdMapping/api/GetUserIdMappingAPITest.java +++ b/src/test/java/io/supertokens/test/userIdMapping/api/GetUserIdMappingAPITest.java @@ -42,6 +42,9 @@ public class GetUserIdMappingAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -196,12 +199,12 @@ public void testRetrieveUserIdMapping() throws Exception { } // create a user and map their userId to an external userId - AuthRecipeUserInfo user = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); String superTokensUserId = user.getSupertokensUserId(); String externalUserId = "externalUserId"; String externalUserIdInfo = "externalUserIdInfo"; - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, externalUserIdInfo, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, externalUserIdInfo, false); // retrieve the userId mapping using the superTokensUserId with SUPERTOKENS as the userIdType { @@ -290,12 +293,12 @@ public void testRetrievingUserIdMappingWithoutSendingUserIdType() throws Excepti } // create a user and map their userId to an external userId - AuthRecipeUserInfo user = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); String superTokensUserId = user.getSupertokensUserId(); String externalUserId = "externalUserId"; String externalUserIdInfo = "externalUserIdInfo"; - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, externalUserIdInfo, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, externalUserIdInfo, false); { // retrieving with superTokensUserId @@ -345,11 +348,11 @@ public void testRetrieveUserIdMappingWithExternalUserIdInfoAsNull() throws Excep } // create a user and map their userId to an external userId - AuthRecipeUserInfo user = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); String superTokensUserId = user.getSupertokensUserId(); String externalUserId = "externalUserId"; - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, null, false); HashMap QUERY_PARAM = new HashMap<>(); QUERY_PARAM.put("userId", superTokensUserId); diff --git a/src/test/java/io/supertokens/test/userIdMapping/api/MultitenantAPITest.java b/src/test/java/io/supertokens/test/userIdMapping/api/MultitenantAPITest.java index a399d1227..b46fa97e9 100644 --- a/src/test/java/io/supertokens/test/userIdMapping/api/MultitenantAPITest.java +++ b/src/test/java/io/supertokens/test/userIdMapping/api/MultitenantAPITest.java @@ -37,10 +37,8 @@ import io.supertokens.test.httpRequest.HttpResponseException; import io.supertokens.thirdparty.InvalidProviderConfigException; import io.supertokens.utils.SemVer; -import org.junit.After; -import org.junit.AfterClass; -import org.junit.Before; -import org.junit.Test; +import org.junit.*; +import org.junit.rules.TestRule; import java.io.IOException; import java.util.HashMap; @@ -51,6 +49,9 @@ public class MultitenantAPITest { TestingProcessManager.TestingProcess process; TenantIdentifier t1, t2, t3, t4; + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -93,7 +94,7 @@ private void createTenants() { // tenant 1 JsonObject config = new JsonObject(); - TenantIdentifier tenantIdentifier = new TenantIdentifier(null, "a1", null); + TenantIdentifier tenantIdentifier = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", null); StorageLayer.getStorage(new TenantIdentifier(null, null, null), process.getProcess()) .modifyConfigToAddANewUserPoolForTesting(config, 1); @@ -113,14 +114,14 @@ private void createTenants() { // tenant 2 JsonObject config = new JsonObject(); - TenantIdentifier tenantIdentifier = new TenantIdentifier(null, "a1", "t1"); + TenantIdentifier tenantIdentifier = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", "t1"); StorageLayer.getStorage(new TenantIdentifier(null, null, null), process.getProcess()) .modifyConfigToAddANewUserPoolForTesting(config, 2); Multitenancy.addNewOrUpdateAppOrTenant( process.getProcess(), - new TenantIdentifier(null, "a1", null), + new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", null), new TenantConfig( tenantIdentifier, new EmailPasswordConfig(true), @@ -133,14 +134,14 @@ private void createTenants() { // tenant 3 JsonObject config = new JsonObject(); - TenantIdentifier tenantIdentifier = new TenantIdentifier(null, "a1", "t2"); + TenantIdentifier tenantIdentifier = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", "t2"); StorageLayer.getStorage(new TenantIdentifier(null, null, null), process.getProcess()) .modifyConfigToAddANewUserPoolForTesting(config, 2); Multitenancy.addNewOrUpdateAppOrTenant( process.getProcess(), - new TenantIdentifier(null, "a1", null), + new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", null), new TenantConfig( tenantIdentifier, new EmailPasswordConfig(true), @@ -153,7 +154,7 @@ private void createTenants() { // tenant 4 JsonObject config = new JsonObject(); - TenantIdentifier tenantIdentifier = new TenantIdentifier(null, "a2", null); + TenantIdentifier tenantIdentifier = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a2", null); StorageLayer.getStorage(new TenantIdentifier(null, null, null), process.getProcess()) .modifyConfigToAddANewUserPoolForTesting(config, 1); @@ -171,10 +172,10 @@ private void createTenants() ); } - t1 = new TenantIdentifier(null, "a1", null); - t2 = new TenantIdentifier(null, "a1", "t1"); - t3 = new TenantIdentifier(null, "a1", "t2"); - t4 = new TenantIdentifier(null, "a2", null); + t1 = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", null); + t2 = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", "t1"); + t3 = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a1", "t2"); + t4 = new TenantIdentifier(null, process.getAppForTesting().getAppId() + "a2", null); } private JsonObject emailPasswordSignUp(TenantIdentifier tenantIdentifier, String email, String password) diff --git a/src/test/java/io/supertokens/test/userIdMapping/api/RemoveUserIdMappingAPITest.java b/src/test/java/io/supertokens/test/userIdMapping/api/RemoveUserIdMappingAPITest.java index 0d71306b4..b696db0d7 100644 --- a/src/test/java/io/supertokens/test/userIdMapping/api/RemoveUserIdMappingAPITest.java +++ b/src/test/java/io/supertokens/test/userIdMapping/api/RemoveUserIdMappingAPITest.java @@ -43,6 +43,9 @@ public class RemoveUserIdMappingAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -230,10 +233,10 @@ public void testDeletingUserIdMapping() throws Exception { } // create a userId mapping - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); UserIdMapping userIdMapping = new UserIdMapping(userInfo.getSupertokensUserId(), "externalUserId", "externalUserIdInfo"); - createUserIdMappingAndCheckThatItExists(process.main, userIdMapping); + createUserIdMappingAndCheckThatItExists(process.getProcess(), userIdMapping); // delete userId mapping with userIdType as SUPERTOKENS { @@ -249,13 +252,13 @@ public void testDeletingUserIdMapping() throws Exception { assertTrue(response.get("didMappingExist").getAsBoolean()); // retrieve mapping and check that it does not exist - assertNull(io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.main, + assertNull(io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.getProcess(), userIdMapping.superTokensUserId, UserIdType.SUPERTOKENS)); } { // create userId mapping - createUserIdMappingAndCheckThatItExists(process.main, userIdMapping); + createUserIdMappingAndCheckThatItExists(process.getProcess(), userIdMapping); // delete userId mapping with userIdType as EXTERNAL @@ -271,13 +274,13 @@ public void testDeletingUserIdMapping() throws Exception { assertTrue(response.get("didMappingExist").getAsBoolean()); // retrieve mapping and check that it does not exist - assertNull(io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.main, + assertNull(io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.getProcess(), userIdMapping.externalUserId, UserIdType.EXTERNAL)); } { // create userId mapping - createUserIdMappingAndCheckThatItExists(process.main, userIdMapping); + createUserIdMappingAndCheckThatItExists(process.getProcess(), userIdMapping); // delete userId mapping with superTokensUserId with userIdType ANY { JsonObject request = new JsonObject(); @@ -292,12 +295,12 @@ public void testDeletingUserIdMapping() throws Exception { assertTrue(response.get("didMappingExist").getAsBoolean()); // retrieve mapping and check that it does not exist - assertNull(io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.main, + assertNull(io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.getProcess(), userIdMapping.superTokensUserId, UserIdType.ANY)); } // create userId mapping - createUserIdMappingAndCheckThatItExists(process.main, userIdMapping); + createUserIdMappingAndCheckThatItExists(process.getProcess(), userIdMapping); // delete userId mapping with externalUserId with userIdType ANY { JsonObject request = new JsonObject(); @@ -312,7 +315,7 @@ public void testDeletingUserIdMapping() throws Exception { assertTrue(response.get("didMappingExist").getAsBoolean()); // retrieve mapping and check that it does not exist - assertNull(io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.main, + assertNull(io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.getProcess(), userIdMapping.externalUserId, UserIdType.ANY)); } } @@ -333,10 +336,10 @@ public void testDeletingAUserIdMappingWithoutSendingUserIdType() throws Exceptio } // create a userId mapping - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); UserIdMapping userIdMapping = new UserIdMapping(userInfo.getSupertokensUserId(), "externalUserId", "externalUserIdInfo"); - createUserIdMappingAndCheckThatItExists(process.main, userIdMapping); + createUserIdMappingAndCheckThatItExists(process.getProcess(), userIdMapping); { // delete mapping with superTokensUserId @@ -351,13 +354,13 @@ public void testDeletingAUserIdMappingWithoutSendingUserIdType() throws Exceptio assertTrue(response.get("didMappingExist").getAsBoolean()); // retrieve mapping and check that it does not exist - assertNull(io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.main, + assertNull(io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.getProcess(), userIdMapping.superTokensUserId, UserIdType.ANY)); } // create mapping - createUserIdMappingAndCheckThatItExists(process.main, userIdMapping); + createUserIdMappingAndCheckThatItExists(process.getProcess(), userIdMapping); { // delete mapping with externalUserId @@ -372,7 +375,7 @@ public void testDeletingAUserIdMappingWithoutSendingUserIdType() throws Exceptio assertTrue(response.get("didMappingExist").getAsBoolean()); // retrieve mapping and check that it does not exist - assertNull(io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.main, + assertNull(io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.getProcess(), userIdMapping.superTokensUserId, UserIdType.ANY)); } @@ -391,16 +394,16 @@ public void deleteUserIdMappingWithAndWithoutForce() throws Exception { return; } - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); String superTokensUserId = userInfo.getSupertokensUserId(); String externalId = "externalId"; - io.supertokens.useridmapping.UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalId, + io.supertokens.useridmapping.UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalId, null, false); JsonObject data = new JsonObject(); data.addProperty("test", "testData"); - UserMetadata.updateUserMetadata(process.main, externalId, data); - UserMetadata.getUserMetadata(process.main, externalId); + UserMetadata.updateUserMetadata(process.getProcess(), externalId, data); + UserMetadata.getUserMetadata(process.getProcess(), externalId); // delete mapping without force { @@ -430,7 +433,7 @@ public void deleteUserIdMappingWithAndWithoutForce() throws Exception { } // check that mapping does not exist - UserIdMapping mapping = io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.main, + UserIdMapping mapping = io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS); assertNull(mapping); diff --git a/src/test/java/io/supertokens/test/userIdMapping/api/UpdateExternalUserIdInfoTest.java b/src/test/java/io/supertokens/test/userIdMapping/api/UpdateExternalUserIdInfoTest.java index eff927912..37f820398 100644 --- a/src/test/java/io/supertokens/test/userIdMapping/api/UpdateExternalUserIdInfoTest.java +++ b/src/test/java/io/supertokens/test/userIdMapping/api/UpdateExternalUserIdInfoTest.java @@ -41,6 +41,9 @@ public class UpdateExternalUserIdInfoTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -269,12 +272,12 @@ public void testUpdatingExternalUserIdInfoWithSuperTokensUserId() throws Excepti // create userId mapping with externalUserIdInfo String externalUserIdInfo = "externalUserIdInfo"; - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); UserIdMapping userIdMapping = new io.supertokens.pluginInterface.useridmapping.UserIdMapping( userInfo.getSupertokensUserId(), "externalUserIdInfo", externalUserIdInfo); - Utils.createUserIdMappingAndCheckThatItExists(process.main, userIdMapping); + Utils.createUserIdMappingAndCheckThatItExists(process.getProcess(), userIdMapping); { // update mapping with new externalUserIdInfo with userIdType SUPERTOKENS @@ -294,7 +297,7 @@ public void testUpdatingExternalUserIdInfoWithSuperTokensUserId() throws Excepti assertEquals("OK", response.get("status").getAsString()); // retrieve mapping and check that externalUserIdInfo got updated - UserIdMapping retrievedMapping = io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.main, + UserIdMapping retrievedMapping = io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.getProcess(), userIdMapping.superTokensUserId, UserIdType.SUPERTOKENS); assertNotNull(retrievedMapping); assertEquals(updatedUserIdMapping, retrievedMapping); @@ -318,7 +321,7 @@ public void testUpdatingExternalUserIdInfoWithSuperTokensUserId() throws Excepti assertEquals("OK", response.get("status").getAsString()); // retrieve mapping and check that externalUserIdInfo got updated - UserIdMapping retrievedMapping = io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.main, + UserIdMapping retrievedMapping = io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.getProcess(), userIdMapping.superTokensUserId, UserIdType.SUPERTOKENS); assertNotNull(retrievedMapping); assertEquals(updatedUserIdMapping, retrievedMapping); @@ -341,12 +344,12 @@ public void testUpdatingExternalUserIdInfoWithExternalUserId() throws Exception // create userId mapping with externalUserIdInfo String externalUserIdInfo = "externalUserIdInfo"; - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); UserIdMapping userIdMapping = new io.supertokens.pluginInterface.useridmapping.UserIdMapping( userInfo.getSupertokensUserId(), "externalUserIdInfo", externalUserIdInfo); - Utils.createUserIdMappingAndCheckThatItExists(process.main, userIdMapping); + Utils.createUserIdMappingAndCheckThatItExists(process.getProcess(), userIdMapping); { // update mapping with new externalUserIdInfo with userIdType External @@ -366,7 +369,7 @@ public void testUpdatingExternalUserIdInfoWithExternalUserId() throws Exception assertEquals("OK", response.get("status").getAsString()); // retrieve mapping and check that externalUserIdInfo got updated - UserIdMapping retrievedMapping = io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.main, + UserIdMapping retrievedMapping = io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.getProcess(), userIdMapping.superTokensUserId, UserIdType.SUPERTOKENS); assertNotNull(retrievedMapping); assertEquals(updatedUserIdMapping, retrievedMapping); @@ -390,7 +393,7 @@ public void testUpdatingExternalUserIdInfoWithExternalUserId() throws Exception assertEquals("OK", response.get("status").getAsString()); // retrieve mapping and check that externalUserIdInfo got updated - UserIdMapping retrievedMapping = io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.main, + UserIdMapping retrievedMapping = io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.getProcess(), userIdMapping.superTokensUserId, UserIdType.SUPERTOKENS); assertNotNull(retrievedMapping); assertEquals(updatedUserIdMapping, retrievedMapping); @@ -413,12 +416,12 @@ public void testDeletingExternalUserIdInfo() throws Exception { // create userId mapping with externalUserIdInfo String externalUserIdInfo = "externalUserIdInfo"; - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPass123"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPass123"); UserIdMapping userIdMapping = new io.supertokens.pluginInterface.useridmapping.UserIdMapping( userInfo.getSupertokensUserId(), "externalUserIdInfo", externalUserIdInfo); - Utils.createUserIdMappingAndCheckThatItExists(process.main, userIdMapping); + Utils.createUserIdMappingAndCheckThatItExists(process.getProcess(), userIdMapping); // delete mapping by passing externalUserIdInfo as JSON null JsonObject requestBody = new JsonObject(); @@ -432,7 +435,7 @@ public void testDeletingExternalUserIdInfo() throws Exception { assertEquals("OK", response.get("status").getAsString()); // retrieve mapping and check that externalUserIdInfo is null - UserIdMapping retrievedMapping = io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.main, + UserIdMapping retrievedMapping = io.supertokens.useridmapping.UserIdMapping.getUserIdMapping(process.getProcess(), userIdMapping.superTokensUserId, UserIdType.ANY); assertNotNull(retrievedMapping); assertEquals(userIdMapping.superTokensUserId, retrievedMapping.superTokensUserId); diff --git a/src/test/java/io/supertokens/test/userIdMapping/recipe/EmailPasswordAPITest.java b/src/test/java/io/supertokens/test/userIdMapping/recipe/EmailPasswordAPITest.java index 801d7bd6d..bc2a08ed2 100644 --- a/src/test/java/io/supertokens/test/userIdMapping/recipe/EmailPasswordAPITest.java +++ b/src/test/java/io/supertokens/test/userIdMapping/recipe/EmailPasswordAPITest.java @@ -43,6 +43,9 @@ public class EmailPasswordAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -67,17 +70,17 @@ public void testSignInAPI() throws Exception { // create a User String email = "test@example.com"; String password = "testPass123"; - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, email, password); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), email, password); String superTokensUserId = userInfo.getSupertokensUserId(); String externalUserId = "externalId"; // create the mapping - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, null, false); { // check that mapping exists io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS); assertNotNull(response); assertEquals(response.superTokensUserId, superTokensUserId); assertEquals(response.externalUserId, externalUserId); @@ -98,9 +101,9 @@ public void testSignInAPI() throws Exception { // delete User and check that the mapping no longer exists { - AuthRecipe.deleteUser(process.main, superTokensUserId); + AuthRecipe.deleteUser(process.getProcess(), superTokensUserId); io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS); assertNull(response); } @@ -122,12 +125,12 @@ public void testResetPasswordFlowWithUserIdMapping() throws Exception { // create a User String email = "test@example.com"; String password = "testPass123"; - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, email, password); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), email, password); String superTokensUserId = userInfo.getSupertokensUserId(); String externalUserId = "externalId"; // create the mapping - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, null, false); // call GeneratePasswordResetTokenAPI api with externalId String passwordResetToken = null; @@ -160,7 +163,7 @@ public void testResetPasswordFlowWithUserIdMapping() throws Exception { } // sign in with the new password and check that it works - AuthRecipeUserInfo userInfo1 = EmailPassword.signIn(process.main, email, newPassword); + AuthRecipeUserInfo userInfo1 = EmailPassword.signIn(process.getProcess(), email, newPassword); assertNotNull(userInfo1); process.kill(); @@ -181,12 +184,12 @@ public void testRetrievingUser() throws Exception { // create a User String email = "test@example.com"; String password = "testPass123"; - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, email, password); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), email, password); String superTokensUserId = userInfo.getSupertokensUserId(); String externalUserId = "externalId"; // create the mapping - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, null, false); // retrieving UserInfo with userId { @@ -227,12 +230,12 @@ public void testUpdatingUsersEmail() throws Exception { // create a User String email = "test@example.com"; String password = "testPass123"; - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, email, password); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), email, password); String superTokensUserId = userInfo.getSupertokensUserId(); String externalUserId = "externalId"; // create the mapping - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, null, false); // update the users email String newEmail = "testnew123@example.com"; @@ -248,7 +251,7 @@ public void testUpdatingUsersEmail() throws Exception { } // check that you can now sign in with the new email - AuthRecipeUserInfo userInfo1 = EmailPassword.signIn(process.main, newEmail, password); + AuthRecipeUserInfo userInfo1 = EmailPassword.signIn(process.getProcess(), newEmail, password); assertNotNull(userInfo1); process.kill(); diff --git a/src/test/java/io/supertokens/test/userIdMapping/recipe/PasswordlessAPITest.java b/src/test/java/io/supertokens/test/userIdMapping/recipe/PasswordlessAPITest.java index 96f70ec97..993294fc8 100644 --- a/src/test/java/io/supertokens/test/userIdMapping/recipe/PasswordlessAPITest.java +++ b/src/test/java/io/supertokens/test/userIdMapping/recipe/PasswordlessAPITest.java @@ -43,6 +43,9 @@ public class PasswordlessAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -68,20 +71,20 @@ public void testCreatingAPasswordlessUserMapTheirUserIdAndRetrieveUserId() throw String superTokensUserId; // create a passwordless User { - Passwordless.CreateCodeResponse createCodeResponse = Passwordless.createCode(process.main, + Passwordless.CreateCodeResponse createCodeResponse = Passwordless.createCode(process.getProcess(), "test@example.com", null, null, null); - Passwordless.ConsumeCodeResponse consumeCodeResponse = Passwordless.consumeCode(process.main, + Passwordless.ConsumeCodeResponse consumeCodeResponse = Passwordless.consumeCode(process.getProcess(), createCodeResponse.deviceId, createCodeResponse.deviceIdHash, createCodeResponse.userInputCode, null); assertTrue(consumeCodeResponse.createdNewUser); superTokensUserId = consumeCodeResponse.user.getSupertokensUserId(); // create mapping - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalId, null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalId, null, false); // check that mapping exists io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS); assertNotNull(response); assertEquals(response.superTokensUserId, superTokensUserId); assertEquals(response.externalUserId, externalId); @@ -107,11 +110,11 @@ public void testCreatingAPasswordlessUserMapTheirUserIdAndRetrieveUserId() throw { // delete User and check that the mapping is also deleted - AuthRecipe.deleteUser(process.main, superTokensUserId); + AuthRecipe.deleteUser(process.getProcess(), superTokensUserId); // check that mapping no longer exists io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS); assertNull(response); } @@ -135,20 +138,20 @@ public void testCreatingAPasswordlessUserAndRetrieveInfo() throws Exception { String email = "test@example.com"; // create a passwordless User { - Passwordless.CreateCodeResponse createCodeResponse = Passwordless.createCode(process.main, email, null, + Passwordless.CreateCodeResponse createCodeResponse = Passwordless.createCode(process.getProcess(), email, null, null, null); - Passwordless.ConsumeCodeResponse consumeCodeResponse = Passwordless.consumeCode(process.main, + Passwordless.ConsumeCodeResponse consumeCodeResponse = Passwordless.consumeCode(process.getProcess(), createCodeResponse.deviceId, createCodeResponse.deviceIdHash, createCodeResponse.userInputCode, null); assertTrue(consumeCodeResponse.createdNewUser); superTokensUserId = consumeCodeResponse.user.getSupertokensUserId(); // create mapping - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalId, null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalId, null, false); // check that mapping exists io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS); assertNotNull(response); assertEquals(response.superTokensUserId, superTokensUserId); assertEquals(response.externalUserId, externalId); @@ -213,20 +216,20 @@ public void testCreatingPasswordlessUserWithPhoneNumberAndRetrieveInfo() throws String phoneNumber = "+911234567890"; // create a passwordless User { - Passwordless.CreateCodeResponse createCodeResponse = Passwordless.createCode(process.main, null, + Passwordless.CreateCodeResponse createCodeResponse = Passwordless.createCode(process.getProcess(), null, phoneNumber, null, null); - Passwordless.ConsumeCodeResponse consumeCodeResponse = Passwordless.consumeCode(process.main, + Passwordless.ConsumeCodeResponse consumeCodeResponse = Passwordless.consumeCode(process.getProcess(), createCodeResponse.deviceId, createCodeResponse.deviceIdHash, createCodeResponse.userInputCode, null); assertTrue(consumeCodeResponse.createdNewUser); superTokensUserId = consumeCodeResponse.user.getSupertokensUserId(); // create mapping - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalId, null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalId, null, false); // check that mapping exists io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS); assertNotNull(response); assertEquals(response.superTokensUserId, superTokensUserId); assertEquals(response.externalUserId, externalId); @@ -263,14 +266,14 @@ public void testUpdatingPasswordlessUserWithTheirExternalId() throws Exception { String superTokensUserId; // create a passwordless user - Passwordless.CreateCodeResponse response = Passwordless.createCode(process.main, "test@example.com", null, null, + Passwordless.CreateCodeResponse response = Passwordless.createCode(process.getProcess(), "test@example.com", null, null, null); - Passwordless.ConsumeCodeResponse consumeCodeResponse = Passwordless.consumeCode(process.main, response.deviceId, + Passwordless.ConsumeCodeResponse consumeCodeResponse = Passwordless.consumeCode(process.getProcess(), response.deviceId, response.deviceIdHash, response.userInputCode, null); superTokensUserId = consumeCodeResponse.user.getSupertokensUserId(); // map their userId - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalId, null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalId, null, false); // call the update API and update email String newEmail = "testnew@example.com"; @@ -285,7 +288,7 @@ public void testUpdatingPasswordlessUserWithTheirExternalId() throws Exception { assertEquals(updateUserResponse.get("status").getAsString(), "OK"); // check that user got updated - AuthRecipeUserInfo userInfo = Passwordless.getUserByEmail(process.main, newEmail); + AuthRecipeUserInfo userInfo = Passwordless.getUserByEmail(process.getProcess(), newEmail); assertNotNull(userInfo); assertEquals(userInfo.getSupertokensUserId(), superTokensUserId); } diff --git a/src/test/java/io/supertokens/test/userIdMapping/recipe/ThirdPartyAPITest.java b/src/test/java/io/supertokens/test/userIdMapping/recipe/ThirdPartyAPITest.java index e566c10b6..41bb475b9 100644 --- a/src/test/java/io/supertokens/test/userIdMapping/recipe/ThirdPartyAPITest.java +++ b/src/test/java/io/supertokens/test/userIdMapping/recipe/ThirdPartyAPITest.java @@ -43,6 +43,9 @@ public class ThirdPartyAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -68,18 +71,18 @@ public void testSignInAPI() throws Exception { String thirdPartyId = "google"; String thirdPartyUserId = "test-google"; String email = "test@example.com"; - ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, thirdPartyId, thirdPartyUserId, + ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), thirdPartyId, thirdPartyUserId, email); String superTokensUserId = signInUpResponse.user.getSupertokensUserId(); String externalUserId = "externalId"; // create the mapping - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, null, false); // check that mapping exists { io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS); assertNotNull(response); assertEquals(response.superTokensUserId, superTokensUserId); assertEquals(response.externalUserId, externalUserId); @@ -103,9 +106,9 @@ public void testSignInAPI() throws Exception { // delete User and check that the mapping no longer exists { - AuthRecipe.deleteUser(process.main, superTokensUserId); + AuthRecipe.deleteUser(process.getProcess(), superTokensUserId); io.supertokens.pluginInterface.useridmapping.UserIdMapping response = UserIdMapping - .getUserIdMapping(process.main, superTokensUserId, UserIdType.SUPERTOKENS); + .getUserIdMapping(process.getProcess(), superTokensUserId, UserIdType.SUPERTOKENS); assertNull(response); } @@ -128,13 +131,13 @@ public void testGetUsersByEmailAPI() throws Exception { String thirdPartyId = "google"; String thirdPartyUserId = "test-google"; String email = "test@example.com"; - ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, thirdPartyId, thirdPartyUserId, + ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), thirdPartyId, thirdPartyUserId, email); String superTokensUserId = signInUpResponse.user.getSupertokensUserId(); String externalUserId = "externalId"; // create the mapping - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, null, false); // call getUsersByEmail { @@ -170,13 +173,13 @@ public void testGetUserById() throws Exception { String thirdPartyId = "google"; String thirdPartyUserId = "test-google"; String email = "test@example.com"; - ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, thirdPartyId, thirdPartyUserId, + ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), thirdPartyId, thirdPartyUserId, email); String superTokensUserId = signInUpResponse.user.getSupertokensUserId(); String externalUserId = "externalId"; // create the mapping - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, null, false); // get User with Id { @@ -211,13 +214,13 @@ public void testGetUserByThirdPartyId() throws Exception { String thirdPartyId = "google"; String thirdPartyUserId = "test-google"; String email = "test@example.com"; - ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.main, thirdPartyId, thirdPartyUserId, + ThirdParty.SignInUpResponse signInUpResponse = ThirdParty.signInUp(process.getProcess(), thirdPartyId, thirdPartyUserId, email); String superTokensUserId = signInUpResponse.user.getSupertokensUserId(); String externalUserId = "externalId"; // create the mapping - UserIdMapping.createUserIdMapping(process.main, superTokensUserId, externalUserId, null, false); + UserIdMapping.createUserIdMapping(process.getProcess(), superTokensUserId, externalUserId, null, false); // get User with Id { diff --git a/src/test/java/io/supertokens/test/userMetadata/UserMetadataTest.java b/src/test/java/io/supertokens/test/userMetadata/UserMetadataTest.java index b19cec6eb..9eb5c0b30 100644 --- a/src/test/java/io/supertokens/test/userMetadata/UserMetadataTest.java +++ b/src/test/java/io/supertokens/test/userMetadata/UserMetadataTest.java @@ -50,6 +50,9 @@ public class UserMetadataTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -212,12 +215,13 @@ public void testUserMetadataEmptyRowLocking() throws Exception { AtomicBoolean success1 = new AtomicBoolean(false); AtomicBoolean success2 = new AtomicBoolean(false); + AppIdentifier appIdentifier = process.getAppForTesting().toAppIdentifier(); + Runnable r1 = () -> { try { sqlStorage.startTransaction(con -> { tryCount1.incrementAndGet(); - JsonObject originalMetadata = sqlStorage.getUserMetadata_Transaction(new AppIdentifier(null, null), - con, userId); + JsonObject originalMetadata = sqlStorage.getUserMetadata_Transaction(appIdentifier, con, userId); synchronized (syncObject) { t1State.set("read"); @@ -237,7 +241,7 @@ public void testUserMetadataEmptyRowLocking() throws Exception { MetadataUtils.shallowMergeMetadataUpdate(updatedMetadata, update1); try { - sqlStorage.setUserMetadata_Transaction(new AppIdentifier(null, null), con, userId, + sqlStorage.setUserMetadata_Transaction(appIdentifier, con, userId, updatedMetadata); } catch (TenantOrAppNotFoundException e) { throw new StorageTransactionLogicException(e); @@ -259,8 +263,7 @@ public void testUserMetadataEmptyRowLocking() throws Exception { sqlStorage.startTransaction(con -> { tryCount2.incrementAndGet(); - JsonObject originalMetadata = sqlStorage.getUserMetadata_Transaction(new AppIdentifier(null, null), - con, userId); + JsonObject originalMetadata = sqlStorage.getUserMetadata_Transaction(appIdentifier, con, userId); synchronized (syncObject) { t2State.set("read"); @@ -280,7 +283,7 @@ public void testUserMetadataEmptyRowLocking() throws Exception { MetadataUtils.shallowMergeMetadataUpdate(updatedMetadata, update2); try { - sqlStorage.setUserMetadata_Transaction(new AppIdentifier(null, null), con, userId, + sqlStorage.setUserMetadata_Transaction(appIdentifier, con, userId, updatedMetadata); } catch (TenantOrAppNotFoundException e) { throw new StorageTransactionLogicException(e); @@ -317,7 +320,7 @@ public void testUserMetadataEmptyRowLocking() throws Exception { // assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.DEADLOCK_FOUND)); // The end result is as expected - assertEquals(expected, sqlStorage.getUserMetadata(new AppIdentifier(null, null), userId)); + assertEquals(expected, sqlStorage.getUserMetadata(appIdentifier, userId)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); diff --git a/src/test/java/io/supertokens/test/userMetadata/api/GetUserMetadataAPITest2_13.java b/src/test/java/io/supertokens/test/userMetadata/api/GetUserMetadataAPITest2_13.java index 1166e95ab..ea2027428 100644 --- a/src/test/java/io/supertokens/test/userMetadata/api/GetUserMetadataAPITest2_13.java +++ b/src/test/java/io/supertokens/test/userMetadata/api/GetUserMetadataAPITest2_13.java @@ -42,6 +42,9 @@ public class GetUserMetadataAPITest2_13 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/userMetadata/api/RemoveUserMetadataAPITest2_13.java b/src/test/java/io/supertokens/test/userMetadata/api/RemoveUserMetadataAPITest2_13.java index f8a041f44..83a26ca86 100644 --- a/src/test/java/io/supertokens/test/userMetadata/api/RemoveUserMetadataAPITest2_13.java +++ b/src/test/java/io/supertokens/test/userMetadata/api/RemoveUserMetadataAPITest2_13.java @@ -40,6 +40,9 @@ public class RemoveUserMetadataAPITest2_13 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/userMetadata/api/SetUserMetadataAPITest2_13.java b/src/test/java/io/supertokens/test/userMetadata/api/SetUserMetadataAPITest2_13.java index 5254ee87e..a96d072ad 100644 --- a/src/test/java/io/supertokens/test/userMetadata/api/SetUserMetadataAPITest2_13.java +++ b/src/test/java/io/supertokens/test/userMetadata/api/SetUserMetadataAPITest2_13.java @@ -42,6 +42,9 @@ public class SetUserMetadataAPITest2_13 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/userRoles/UserRolesStorageTest.java b/src/test/java/io/supertokens/test/userRoles/UserRolesStorageTest.java index ff35f5060..999228270 100644 --- a/src/test/java/io/supertokens/test/userRoles/UserRolesStorageTest.java +++ b/src/test/java/io/supertokens/test/userRoles/UserRolesStorageTest.java @@ -18,11 +18,8 @@ import io.supertokens.ProcessState; import io.supertokens.pluginInterface.STORAGE_TYPE; -import io.supertokens.pluginInterface.StorageUtils; import io.supertokens.pluginInterface.exceptions.StorageQueryException; import io.supertokens.pluginInterface.exceptions.StorageTransactionLogicException; -import io.supertokens.pluginInterface.multitenancy.AppIdentifier; -import io.supertokens.pluginInterface.multitenancy.TenantIdentifier; import io.supertokens.pluginInterface.multitenancy.exceptions.TenantOrAppNotFoundException; import io.supertokens.pluginInterface.userroles.exception.DuplicateUserRoleMappingException; import io.supertokens.pluginInterface.userroles.exception.UnknownRoleException; @@ -48,6 +45,9 @@ public class UserRolesStorageTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -73,14 +73,14 @@ public void testDeletingARoleWhileItIsBeingRemovedFromAUser() throws Exception { String role = "role"; String userId = "userId"; // create a role - boolean newRoleCreated = UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); + boolean newRoleCreated = UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, null); assertTrue(newRoleCreated); // assign role to user - boolean didUserAlreadyHaveRole = UserRoles.addRoleToUser(process.main, userId, role); + boolean didUserAlreadyHaveRole = UserRoles.addRoleToUser(process.getProcess(), userId, role); assertTrue(didUserAlreadyHaveRole); - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); AtomicBoolean r1_success = new AtomicBoolean(false); AtomicBoolean r2_success = new AtomicBoolean(false); @@ -89,7 +89,7 @@ public void testDeletingARoleWhileItIsBeingRemovedFromAUser() throws Exception { try { storage.startTransaction(con -> { // wait for some time - storage.doesRoleExist_Transaction(new AppIdentifier(null, null), con, role); + storage.doesRoleExist_Transaction(process.getAppForTesting().toAppIdentifier(), con, role); try { Thread.sleep(1000); @@ -99,7 +99,7 @@ public void testDeletingARoleWhileItIsBeingRemovedFromAUser() throws Exception { // add permissions boolean wasRoleRemovedFromUser = storage.deleteRoleForUser_Transaction( - new TenantIdentifier(null, null, null), con, userId, role); + process.getAppForTesting(), con, userId, role); storage.commitTransaction(con); r1_success.set(wasRoleRemovedFromUser); @@ -119,7 +119,7 @@ public void testDeletingARoleWhileItIsBeingRemovedFromAUser() throws Exception { } // delete the role try { - boolean wasRoleDeleted = storage.deleteRole(new AppIdentifier(null, null), role); + boolean wasRoleDeleted = storage.deleteRole(process.getAppForTesting().toAppIdentifier(), role); r2_success.set(wasRoleDeleted); } catch (StorageQueryException e) { // should not come here @@ -141,10 +141,10 @@ public void testDeletingARoleWhileItIsBeingRemovedFromAUser() throws Exception { assertTrue(r2_success.get()); // check that role was actuall removed from user - assertEquals(0, storage.getRolesForUser(new TenantIdentifier(null, null, null), userId).length); + assertEquals(0, storage.getRolesForUser(process.getAppForTesting(), userId).length); // check that role was actually deleted - assertFalse(storage.doesRoleExist(new AppIdentifier(null, null), role)); + assertFalse(storage.doesRoleExist(process.getAppForTesting().toAppIdentifier(), role)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -172,7 +172,7 @@ public void testCreatingAndAddingAPermissionToARoleInTransactionAndDeletingRole( return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // thread 1: start transaction -> call createNewRole_Transaction -> wait... -> // call addPermissionToRole_Transaction -> commit @@ -188,7 +188,7 @@ public void testCreatingAndAddingAPermissionToARoleInTransactionAndDeletingRole( numberOfIterations.incrementAndGet(); // create a new Role try { - storage.createNewRoleOrDoNothingIfExists_Transaction(new AppIdentifier(null, null), con, + storage.createNewRoleOrDoNothingIfExists_Transaction(process.getAppForTesting().toAppIdentifier(), con, role); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -203,7 +203,7 @@ public void testCreatingAndAddingAPermissionToARoleInTransactionAndDeletingRole( // add permissions try { - storage.addPermissionToRoleOrDoNothingIfExists_Transaction(new AppIdentifier(null, null), con, + storage.addPermissionToRoleOrDoNothingIfExists_Transaction(process.getAppForTesting().toAppIdentifier(), con, role, permissions[0]); } catch (UnknownRoleException e) { throw new StorageQueryException(e); @@ -226,9 +226,9 @@ public void testCreatingAndAddingAPermissionToARoleInTransactionAndDeletingRole( } // delete the newly created role try { - boolean wasRoleDeleted = storage.deleteAllUserRoleAssociationsForRole(new AppIdentifier(null, null), + boolean wasRoleDeleted = storage.deleteAllUserRoleAssociationsForRole(process.getAppForTesting().toAppIdentifier(), role); - wasRoleDeleted = storage.deleteRole(new AppIdentifier(null, null), role) || wasRoleDeleted; + wasRoleDeleted = storage.deleteRole(process.getAppForTesting().toAppIdentifier(), role) || wasRoleDeleted; r2_success.set(true); } catch (StorageQueryException e) { // should not come here @@ -260,16 +260,16 @@ public void testCreatingAndAddingAPermissionToARoleInTransactionAndDeletingRole( { // 1: The role and permissions still exist // check that the role is created and the permission still exists - String[] retrievedPermissions = storage.getPermissionsForRole(new AppIdentifier(null, null), role); - useCase1 = (storage.doesRoleExist(new AppIdentifier(null, null), role) && + String[] retrievedPermissions = storage.getPermissionsForRole(process.getAppForTesting().toAppIdentifier(), role); + useCase1 = (storage.doesRoleExist(process.getAppForTesting().toAppIdentifier(), role) && retrievedPermissions[0].equals(permissions[0]) && retrievedPermissions.length == 1); } { // 2. The role and permissions have been deleted, no mappings for the role-permission exist - String[] retrievedPermissions = storage.getPermissionsForRole(new AppIdentifier(null, null), role); - useCase2 = (!storage.doesRoleExist(new AppIdentifier(null, null), role) && + String[] retrievedPermissions = storage.getPermissionsForRole(process.getAppForTesting().toAppIdentifier(), role); + useCase2 = (!storage.doesRoleExist(process.getAppForTesting().toAppIdentifier(), role) && retrievedPermissions.length == 0); } @@ -292,18 +292,18 @@ public void testCreateNewRoleOrDoNothingIfExists_TransactionResponses() throws E if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // create a new role String role = "testRole"; { - boolean wasRoleCreated = UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); + boolean wasRoleCreated = UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, null); // check that a role was created assertTrue(wasRoleCreated); } // check that the role exists - assertTrue(UserRoles.doesRoleExist(process.main, role)); + assertTrue(UserRoles.doesRoleExist(process.getProcess(), role)); // check that createNewRole_transaction doesn't throw error, and no role was created { @@ -311,7 +311,7 @@ public void testCreateNewRoleOrDoNothingIfExists_TransactionResponses() throws E .startTransaction(con -> { try { return storage.createNewRoleOrDoNothingIfExists_Transaction( - new AppIdentifier(null, null), con, role); + process.getAppForTesting().toAppIdentifier(), con, role); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); } @@ -333,7 +333,7 @@ public void testAddPermissionToRole_TransactionResponses() throws Exception { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); { // add permissions to a role that does not exist @@ -341,7 +341,7 @@ public void testAddPermissionToRole_TransactionResponses() throws Exception { try { storage.startTransaction(con -> { try { - storage.addPermissionToRoleOrDoNothingIfExists_Transaction(new AppIdentifier(null, null), con, + storage.addPermissionToRoleOrDoNothingIfExists_Transaction(process.getAppForTesting().toAppIdentifier(), con, "unknown_role", "testPermission"); } catch (UnknownRoleException e) { @@ -361,7 +361,7 @@ public void testAddPermissionToRole_TransactionResponses() throws Exception { // crate a role with permissions String role = "role"; String permission = "permission"; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, new String[]{permission}); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, new String[]{permission}); // add duplicate permissions @@ -369,7 +369,7 @@ public void testAddPermissionToRole_TransactionResponses() throws Exception { try { storage.startTransaction(con -> { try { - storage.addPermissionToRoleOrDoNothingIfExists_Transaction(new AppIdentifier(null, null), con, + storage.addPermissionToRoleOrDoNothingIfExists_Transaction(process.getAppForTesting().toAppIdentifier(), con, role, permission); } catch (UnknownRoleException e) { throw new StorageTransactionLogicException(e); @@ -395,11 +395,11 @@ public void testDoesRoleExistResponses() throws Exception { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // call doesRoleExist on a role which doesn't exist String role = "role"; - assertFalse(storage.doesRoleExist(new AppIdentifier(null, null), role)); + assertFalse(storage.doesRoleExist(process.getAppForTesting().toAppIdentifier(), role)); // create a role and call doesRoleExist { @@ -407,7 +407,7 @@ public void testDoesRoleExistResponses() throws Exception { .startTransaction(con -> { try { return storage.createNewRoleOrDoNothingIfExists_Transaction( - new AppIdentifier(null, null), con, role); + process.getAppForTesting().toAppIdentifier(), con, role); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); } @@ -415,7 +415,7 @@ public void testDoesRoleExistResponses() throws Exception { // check that the role is created assertTrue(wasRoleCreated); - assertTrue(storage.doesRoleExist(new AppIdentifier(null, null), role)); + assertTrue(storage.doesRoleExist(process.getAppForTesting().toAppIdentifier(), role)); } process.kill(); @@ -431,10 +431,10 @@ public void testGetRolesResponses() throws Exception { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // call getRoles when no roles exist - String[] emptyRoles = storage.getRoles(new AppIdentifier(null, null)); + String[] emptyRoles = storage.getRoles(process.getAppForTesting().toAppIdentifier()); assertEquals(0, emptyRoles.length); @@ -443,7 +443,7 @@ public void testGetRolesResponses() throws Exception { storage.startTransaction(con -> { for (int i = 0; i < createdRoles.length; i++) { try { - storage.createNewRoleOrDoNothingIfExists_Transaction(new AppIdentifier(null, null), con, + storage.createNewRoleOrDoNothingIfExists_Transaction(process.getAppForTesting().toAppIdentifier(), con, createdRoles[i]); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); @@ -453,7 +453,7 @@ public void testGetRolesResponses() throws Exception { }); // check that the getRoles retrieved the correct roles - String[] retrievedRoles = storage.getRoles(new AppIdentifier(null, null)); + String[] retrievedRoles = storage.getRoles(process.getAppForTesting().toAppIdentifier()); Utils.checkThatArraysAreEqual(createdRoles, retrievedRoles); process.kill(); @@ -469,12 +469,12 @@ public void testAssociatingAnUnknownRoleWithUser() throws Exception { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); Exception error = null; try { UserRoles.addRoleToUser( - process.getProcess(), new TenantIdentifier(null, null, null), + process.getProcess(), process.getAppForTesting(), StorageLayer.getBaseStorage(process.getProcess()), "userId", "unknownRole"); } catch (Exception e) { error = e; @@ -496,7 +496,7 @@ public void testAssociatingRolesWithUser() throws Exception { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // associate multiple roles with a user and check that the user actually has those roles @@ -506,7 +506,7 @@ public void testAssociatingRolesWithUser() throws Exception { storage.startTransaction(con -> { for (String role : roles) { try { - storage.createNewRoleOrDoNothingIfExists_Transaction(new AppIdentifier(null, null), con, role); + storage.createNewRoleOrDoNothingIfExists_Transaction(process.getAppForTesting().toAppIdentifier(), con, role); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); } @@ -517,11 +517,11 @@ public void testAssociatingRolesWithUser() throws Exception { // associate user with roles for (String role : roles) { - storage.addRoleToUser(new TenantIdentifier(null, null, null), userId, role); + storage.addRoleToUser(process.getAppForTesting(), userId, role); } // check if user actually has the roles - String[] userRoles = storage.getRolesForUser(new TenantIdentifier(null, null, null), userId); + String[] userRoles = storage.getRolesForUser(process.getAppForTesting(), userId); Utils.checkThatArraysAreEqual(roles, userRoles); process.kill(); @@ -537,7 +537,7 @@ public void testAssociatingTheSameRoleWithUserTwice() throws Exception { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // associate multiple roles with a user and check that the user actually has those roles @@ -546,7 +546,7 @@ public void testAssociatingTheSameRoleWithUserTwice() throws Exception { String userId = "userId"; storage.startTransaction(con -> { try { - storage.createNewRoleOrDoNothingIfExists_Transaction(new AppIdentifier(null, null), con, role); + storage.createNewRoleOrDoNothingIfExists_Transaction(process.getAppForTesting().toAppIdentifier(), con, role); } catch (TenantOrAppNotFoundException e) { throw new IllegalStateException(e); } @@ -555,17 +555,17 @@ public void testAssociatingTheSameRoleWithUserTwice() throws Exception { }); // associate user with roles - storage.addRoleToUser(new TenantIdentifier(null, null, null), userId, role); + storage.addRoleToUser(process.getAppForTesting(), userId, role); // check if user actually has the role - String[] userRoles = storage.getRolesForUser(new TenantIdentifier(null, null, null), userId); + String[] userRoles = storage.getRolesForUser(process.getAppForTesting(), userId); assertEquals(1, userRoles.length); assertEquals(role, userRoles[0]); // associate the role with the user again, should throw DuplicateUserRoleMappingException Exception error = null; try { - storage.addRoleToUser(new TenantIdentifier(null, null, null), userId, role); + storage.addRoleToUser(process.getAppForTesting(), userId, role); } catch (Exception e) { error = e; } @@ -574,7 +574,7 @@ public void testAssociatingTheSameRoleWithUserTwice() throws Exception { assertTrue(error instanceof DuplicateUserRoleMappingException); // check that the user still has only one role - String[] userRoles_2 = storage.getRolesForUser(new TenantIdentifier(null, null, null), userId); + String[] userRoles_2 = storage.getRolesForUser(process.getAppForTesting(), userId); assertEquals(1, userRoles_2.length); assertEquals(role, userRoles_2[0]); @@ -592,11 +592,11 @@ public void testRemovingAnUnUnknownRoleFromAUser() throws Exception { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); boolean response = storage .startTransaction( - con -> storage.deleteRoleForUser_Transaction(new TenantIdentifier(null, null, null), con, + con -> storage.deleteRoleForUser_Transaction(process.getAppForTesting(), con, "userId", "unknown_role")); assertFalse(response); @@ -614,20 +614,20 @@ public void testRemovingARoleFromAUser() throws Exception { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); String[] roles = new String[]{"role"}; String userId = "userId"; // create a role - UserRoles.createNewRoleOrModifyItsPermissions(process.main, roles[0], null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), roles[0], null); // add role to user - UserRoles.addRoleToUser(process.main, userId, roles[0]); + UserRoles.addRoleToUser(process.getProcess(), userId, roles[0]); { // check that user has the roles - String[] userRoles = storage.getRolesForUser(new TenantIdentifier(null, null, null), userId); + String[] userRoles = storage.getRolesForUser(process.getAppForTesting(), userId); Utils.checkThatArraysAreEqual(roles, userRoles); } @@ -635,12 +635,12 @@ public void testRemovingARoleFromAUser() throws Exception { // remove the role from the user boolean response = storage .startTransaction( - con -> storage.deleteRoleForUser_Transaction(new TenantIdentifier(null, null, null), con, + con -> storage.deleteRoleForUser_Transaction(process.getAppForTesting(), con, userId, roles[0])); assertTrue(response); // check that user does not have any roles - String[] userRoles = storage.getRolesForUser(new TenantIdentifier(null, null, null), userId); + String[] userRoles = storage.getRolesForUser(process.getAppForTesting(), userId); assertEquals(0, userRoles.length); } @@ -657,19 +657,19 @@ public void testRetrievingUsersForRoles() throws Exception { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // create a role String role = "role"; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, null); // add role to multiple users String[] userIds = new String[]{"user1", "user2", "user3"}; for (String userId : userIds) { - UserRoles.addRoleToUser(process.main, userId, role); + UserRoles.addRoleToUser(process.getProcess(), userId, role); } - String[] userIdsWithSameRole = storage.getUsersForRole(new TenantIdentifier(null, null, null), role); + String[] userIdsWithSameRole = storage.getUsersForRole(process.getAppForTesting(), role); // check that the users you have retrieved is correct Utils.checkThatArraysAreEqual(userIds, userIdsWithSameRole); @@ -687,15 +687,15 @@ public void testRetrievingPermissionsForARole() throws Exception { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // create a role with permissions String role = "role"; String[] permissions = new String[]{"permission1", "permission2", "permission3"}; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, permissions); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, permissions); // retrieve permissions and check that the permissions retrieved are the same as those set - String[] retrievedPermissions = storage.getPermissionsForRole(new AppIdentifier(null, null), role); + String[] retrievedPermissions = storage.getPermissionsForRole(process.getAppForTesting().toAppIdentifier(), role); Utils.checkThatArraysAreEqual(permissions, retrievedPermissions); process.kill(); @@ -711,18 +711,18 @@ public void testDeletingAPermissionFromARole() throws Exception { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // create a role with permissions String role = "role"; String[] permissions = new String[]{"permission1", "permission2", "permission3"}; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, permissions); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, permissions); // delete a permission from the role boolean wasPermissionDeleted = storage .startTransaction( - con -> storage.deletePermissionForRole_Transaction(new AppIdentifier(null, null), con, role, + con -> storage.deletePermissionForRole_Transaction(process.getAppForTesting().toAppIdentifier(), con, role, "permission2")); assertTrue(wasPermissionDeleted); @@ -730,7 +730,7 @@ public void testDeletingAPermissionFromARole() throws Exception { String[] newPermissions = new String[]{"permission1", "permission3"}; // retrieve permissions for a role and check that the correct permissions are retrieved - String[] retrievedPermissions = UserRoles.getPermissionsForRole(process.main, role); + String[] retrievedPermissions = UserRoles.getPermissionsForRole(process.getProcess(), role); Utils.checkThatArraysAreEqual(newPermissions, retrievedPermissions); process.kill(); @@ -746,24 +746,24 @@ public void testDeletingAllPermissionFromARole() throws Exception { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // create a role with permissions String role = "role"; String[] permissions = new String[]{"permission1", "permission2", "permission3"}; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, permissions); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, permissions); // delete all permissions from the role int numberOfPermissionsDeleted = storage .startTransaction( - con -> storage.deleteAllPermissionsForRole_Transaction(new AppIdentifier(null, null), con, + con -> storage.deleteAllPermissionsForRole_Transaction(process.getAppForTesting().toAppIdentifier(), con, role)); assertEquals(permissions.length, numberOfPermissionsDeleted); // retrieve permissions for a role and check that no permissions are returned - String[] retrievedPermissions = UserRoles.getPermissionsForRole(process.main, role); + String[] retrievedPermissions = UserRoles.getPermissionsForRole(process.getProcess(), role); assertEquals(0, retrievedPermissions.length); process.kill(); @@ -779,7 +779,7 @@ public void testRetrievingRolesForAPermission() throws Exception { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // create two roles, assign [permission1] to role1 and [permission1, permission2] to role2 String[] roles = new String[]{"role1", "role2"}; @@ -787,20 +787,20 @@ public void testRetrievingRolesForAPermission() throws Exception { String permission2 = "permission2"; // create role1 with permission [permission1] - UserRoles.createNewRoleOrModifyItsPermissions(process.main, roles[0], new String[]{permission1}); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), roles[0], new String[]{permission1}); // create role2 with permissions [permission1, permission2] - UserRoles.createNewRoleOrModifyItsPermissions(process.main, roles[1], + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), roles[1], new String[]{permission1, permission2}); { // check that role1 and role2 have permission1 - String[] retrievedRoles = storage.getRolesThatHavePermission(new AppIdentifier(null, null), permission1); + String[] retrievedRoles = storage.getRolesThatHavePermission(process.getAppForTesting().toAppIdentifier(), permission1); assertEquals(2, retrievedRoles.length); Utils.checkThatArraysAreEqual(roles, retrievedRoles); } { // check that role2 has permission2 - String[] retrievedRoles = storage.getRolesThatHavePermission(new AppIdentifier(null, null), permission2); + String[] retrievedRoles = storage.getRolesThatHavePermission(process.getAppForTesting().toAppIdentifier(), permission2); assertEquals(1, retrievedRoles.length); assertEquals(roles[1], retrievedRoles[0]); } @@ -818,7 +818,7 @@ public void testDeletingRoleResponses() throws Exception { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); String role = "role"; @@ -826,20 +826,20 @@ public void testDeletingRoleResponses() throws Exception { // delete a role which exists // create a role - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, null); // delete role - boolean didRoleExist = storage.deleteAllUserRoleAssociationsForRole(new AppIdentifier(null, null), role); - assertTrue(didRoleExist = storage.deleteRole(new AppIdentifier(null, null), role) || didRoleExist); + boolean didRoleExist = storage.deleteAllUserRoleAssociationsForRole(process.getAppForTesting().toAppIdentifier(), role); + assertTrue(didRoleExist = storage.deleteRole(process.getAppForTesting().toAppIdentifier(), role) || didRoleExist); assertTrue(didRoleExist); // check that role doesnt exist - assertFalse(UserRoles.doesRoleExist(process.main, role)); + assertFalse(UserRoles.doesRoleExist(process.getProcess(), role)); } { // delete a role which doesnt exist - boolean didRoleExist = storage.deleteAllUserRoleAssociationsForRole(new AppIdentifier(null, null), role); - didRoleExist = storage.deleteRole(new AppIdentifier(null, null), role) || didRoleExist; + boolean didRoleExist = storage.deleteAllUserRoleAssociationsForRole(process.getAppForTesting().toAppIdentifier(), role); + didRoleExist = storage.deleteRole(process.getAppForTesting().toAppIdentifier(), role) || didRoleExist; assertFalse(didRoleExist); } @@ -856,17 +856,17 @@ public void testGettingAllCreatedRoles() throws Exception { if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // create roles String[] roles = new String[]{"role1", "role2", "role3"}; for (String role : roles) { - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, null); } // retrieve all role and check for correct output { - String[] retrievedRoles = storage.getRoles(new AppIdentifier(null, null)); + String[] retrievedRoles = storage.getRoles(process.getAppForTesting().toAppIdentifier()); Utils.checkThatArraysAreEqual(roles, retrievedRoles); } @@ -884,7 +884,7 @@ public void testDeletingAllRolesForAUser() throws Exception { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // create multiple roles and assign them to a user String userId = "userId"; @@ -892,30 +892,30 @@ public void testDeletingAllRolesForAUser() throws Exception { for (String role : roles) { // create role - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, null); // assign role to user - UserRoles.addRoleToUser(process.main, userId, role); + UserRoles.addRoleToUser(process.getProcess(), userId, role); } { // check that user has the roles - String[] retrievedRoles = storage.getRolesForUser(new TenantIdentifier(null, null, null), userId); + String[] retrievedRoles = storage.getRolesForUser(process.getAppForTesting(), userId); Utils.checkThatArraysAreEqual(roles, retrievedRoles); } // delete all roles for the user - int numberOfRolesDeleted = storage.deleteAllRolesForUser(new TenantIdentifier(null, null, null), userId); + int numberOfRolesDeleted = storage.deleteAllRolesForUser(process.getAppForTesting(), userId); assertEquals(roles.length, numberOfRolesDeleted); // check that the user does not have any roles { - String[] retrievedRoles = UserRoles.getRolesForUser(process.main, userId); + String[] retrievedRoles = UserRoles.getRolesForUser(process.getProcess(), userId); assertEquals(0, retrievedRoles.length); } { // check that no roles have been deleted - String[] retrievedRoles = UserRoles.getRoles(process.main); + String[] retrievedRoles = UserRoles.getRoles(process.getProcess()); Utils.checkThatArraysAreEqual(roles, retrievedRoles); } diff --git a/src/test/java/io/supertokens/test/userRoles/UserRolesTest.java b/src/test/java/io/supertokens/test/userRoles/UserRolesTest.java index d5b8df41f..8d0bbade1 100644 --- a/src/test/java/io/supertokens/test/userRoles/UserRolesTest.java +++ b/src/test/java/io/supertokens/test/userRoles/UserRolesTest.java @@ -44,6 +44,9 @@ public class UserRolesTest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -67,30 +70,30 @@ public void testCreatingTheSameRoleTwice() throws Exception { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); String role = "role"; String[] permissions = new String[]{"permission"}; { // create a new role - boolean wasRoleCreated = UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, permissions); + boolean wasRoleCreated = UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, permissions); // check if role is created assertTrue(wasRoleCreated); - assertTrue(storage.doesRoleExist(new AppIdentifier(null, null), role)); + assertTrue(storage.doesRoleExist(process.getAppForTesting().toAppIdentifier(), role)); // check if permissions are created - assertArrayEquals(storage.getPermissionsForRole(new AppIdentifier(null, null), role), permissions); + assertArrayEquals(storage.getPermissionsForRole(process.getAppForTesting().toAppIdentifier(), role), permissions); } { // create the same role again, should not throw an exception and no new role should be created - boolean wasRoleCreated = UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, permissions); + boolean wasRoleCreated = UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, permissions); assertFalse(wasRoleCreated); // check that roles and permissions still exist - assertTrue(storage.doesRoleExist(new AppIdentifier(null, null), role)); - checkThatArraysAreEqual(permissions, storage.getPermissionsForRole(new AppIdentifier(null, null), role)); + assertTrue(storage.doesRoleExist(process.getAppForTesting().toAppIdentifier(), role)); + checkThatArraysAreEqual(permissions, storage.getPermissionsForRole(process.getAppForTesting().toAppIdentifier(), role)); } process.kill(); @@ -110,23 +113,23 @@ public void testAddingPermissionsToARoleWithExistingPermissions() throws Excepti return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); String[] oldPermissions = new String[]{"permission1", "permission2"}; String role = "role"; { // create a new role - boolean wasRoleCreated = UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, oldPermissions); + boolean wasRoleCreated = UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, oldPermissions); assertTrue(wasRoleCreated); // check that role and permissions were created // check if role is created - assertTrue(storage.doesRoleExist(new AppIdentifier(null, null), role)); + assertTrue(storage.doesRoleExist(process.getAppForTesting().toAppIdentifier(), role)); // check if permissions are created - String[] createdPermissions_1 = storage.getPermissionsForRole(new AppIdentifier(null, null), role); + String[] createdPermissions_1 = storage.getPermissionsForRole(process.getAppForTesting().toAppIdentifier(), role); checkThatArraysAreEqual(oldPermissions, createdPermissions_1); } @@ -134,11 +137,11 @@ public void testAddingPermissionsToARoleWithExistingPermissions() throws Excepti // modify role with a new permission String[] newPermissions = new String[]{"permission1", "permission2", "permission3"}; - boolean wasRoleCreated = UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, newPermissions); + boolean wasRoleCreated = UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, newPermissions); // since only permissions were modified and no role was created, this should be false assertFalse(wasRoleCreated); - String[] createdPermissions_2 = storage.getPermissionsForRole(new AppIdentifier(null, null), role); + String[] createdPermissions_2 = storage.getPermissionsForRole(process.getAppForTesting().toAppIdentifier(), role); Arrays.sort(newPermissions); Arrays.sort(createdPermissions_2); @@ -162,30 +165,30 @@ public void createRoleWithNullOrEmptyPermissions() throws Exception { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); { // create a role with null permissions String role = "role"; - boolean wasRoleCreated = UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); + boolean wasRoleCreated = UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, null); // check that role and permissions were created // check if role is created assertTrue(wasRoleCreated); - assertTrue(storage.doesRoleExist(new AppIdentifier(null, null), role)); + assertTrue(storage.doesRoleExist(process.getAppForTesting().toAppIdentifier(), role)); // check that no permissions exist for the role - assertEquals(0, storage.getPermissionsForRole(new AppIdentifier(null, null), role).length); + assertEquals(0, storage.getPermissionsForRole(process.getAppForTesting().toAppIdentifier(), role).length); } { // create role with empty array permissions String role = "role2"; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, new String[]{}); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, new String[]{}); // check if role is created - assertTrue(storage.doesRoleExist(new AppIdentifier(null, null), role)); + assertTrue(storage.doesRoleExist(process.getAppForTesting().toAppIdentifier(), role)); // check that no permissions exist for the role - assertEquals(0, storage.getPermissionsForRole(new AppIdentifier(null, null), role).length); + assertEquals(0, storage.getPermissionsForRole(process.getAppForTesting().toAppIdentifier(), role).length); } process.kill(); @@ -206,22 +209,22 @@ public void testCreatingARoleWithPermissionsAndAddingOneMorePermission() throws return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); String role = "role"; { // create a new role String[] oldPermissions = new String[]{"permission1", "permission2"}; - boolean wasRoleCreated = UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, oldPermissions); + boolean wasRoleCreated = UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, oldPermissions); // check that role and permissions were created // check if role is created assertTrue(wasRoleCreated); - assertTrue(storage.doesRoleExist(new AppIdentifier(null, null), role)); + assertTrue(storage.doesRoleExist(process.getAppForTesting().toAppIdentifier(), role)); // retrieve permissions for role - String[] createdPermissions = storage.getPermissionsForRole(new AppIdentifier(null, null), role); + String[] createdPermissions = storage.getPermissionsForRole(process.getAppForTesting().toAppIdentifier(), role); // check that permissions are the same checkThatArraysAreEqual(oldPermissions, createdPermissions); @@ -232,14 +235,14 @@ public void testCreatingARoleWithPermissionsAndAddingOneMorePermission() throws String[] newPermission = new String[]{"permission3"}; // add additional permission to role - boolean wasRoleCreated = UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, newPermission); + boolean wasRoleCreated = UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, newPermission); assertFalse(wasRoleCreated); // check that the role still exists - assertTrue(storage.doesRoleExist(new AppIdentifier(null, null), role)); + assertTrue(storage.doesRoleExist(process.getAppForTesting().toAppIdentifier(), role)); // retrieve permissions for role - String[] createdPermissions = storage.getPermissionsForRole(new AppIdentifier(null, null), role); + String[] createdPermissions = storage.getPermissionsForRole(process.getAppForTesting().toAppIdentifier(), role); // check that newly added permission is added String[] allPermissions = new String[]{"permission1", "permission2", "permission3"}; @@ -263,14 +266,14 @@ public void testAddRoleToUserResponses() throws Exception { } String[] roles = new String[]{"role"}; String userId = "userId"; - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // assign an unknown role to a user, it should throw UNKNOWN_ROLE_EXCEPTION { Exception error = null; try { - UserRoles.addRoleToUser(process.main, userId, "unknown_role"); + UserRoles.addRoleToUser(process.getProcess(), userId, "unknown_role"); } catch (Exception e) { error = e; } @@ -282,24 +285,24 @@ public void testAddRoleToUserResponses() throws Exception { // create a role and assign the role to a user, check that the user has the role { // create role - UserRoles.createNewRoleOrModifyItsPermissions(process.main, roles[0], null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), roles[0], null); // assign role to user - boolean wasRoleAddedToUser = UserRoles.addRoleToUser(process.main, userId, roles[0]); + boolean wasRoleAddedToUser = UserRoles.addRoleToUser(process.getProcess(), userId, roles[0]); assertTrue(wasRoleAddedToUser); // check that the user actually has the role - String[] userRoles = storage.getRolesForUser(new TenantIdentifier(null, null, null), userId); + String[] userRoles = storage.getRolesForUser(process.getAppForTesting(), userId); Utils.checkThatArraysAreEqual(roles, userRoles); } // assign the same role to the user again, it should not be added and not throw an exception { // assign the role to the user again - boolean wasRoleAddedToUser = UserRoles.addRoleToUser(process.main, userId, roles[0]); + boolean wasRoleAddedToUser = UserRoles.addRoleToUser(process.getProcess(), userId, roles[0]); assertFalse(wasRoleAddedToUser); // check that the user still has the same role/ no additional role has been added - String[] userRoles = storage.getRolesForUser(new TenantIdentifier(null, null, null), userId); + String[] userRoles = storage.getRolesForUser(process.getAppForTesting(), userId); Utils.checkThatArraysAreEqual(roles, userRoles); } @@ -309,13 +312,13 @@ public void testAddRoleToUserResponses() throws Exception { String[] newRoles = new String[]{"role", "role2"}; // create another role - UserRoles.createNewRoleOrModifyItsPermissions(process.main, newRoles[1], null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), newRoles[1], null); // assign role to user and check that the role was added - boolean wasRoleAddedToUser = UserRoles.addRoleToUser(process.main, userId, newRoles[1]); + boolean wasRoleAddedToUser = UserRoles.addRoleToUser(process.getProcess(), userId, newRoles[1]); assertTrue(wasRoleAddedToUser); // check that user has two roles - String[] userRoles = storage.getRolesForUser(new TenantIdentifier(null, null, null), userId); + String[] userRoles = storage.getRolesForUser(process.getAppForTesting(), userId); Utils.checkThatArraysAreEqual(newRoles, userRoles); } @@ -336,7 +339,7 @@ public void testRemovingAnUnknownRoleFromAUser() throws Exception { Exception error = null; try { - UserRoles.removeUserRole(process.main, "userId", "unknown_role"); + UserRoles.removeUserRole(process.getProcess(), "userId", "unknown_role"); } catch (Exception e) { error = e; } @@ -360,30 +363,30 @@ public void testRemovingARoleFromAUser() throws Exception { String userId = "userId"; String[] roles = new String[]{"role"}; - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // create a role and assign the role to a user - UserRoles.createNewRoleOrModifyItsPermissions(process.main, roles[0], null); - UserRoles.addRoleToUser(process.main, userId, roles[0]); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), roles[0], null); + UserRoles.addRoleToUser(process.getProcess(), userId, roles[0]); { // check that the user has roles - String[] userRoles = storage.getRolesForUser(new TenantIdentifier(null, null, null), userId); + String[] userRoles = storage.getRolesForUser(process.getAppForTesting(), userId); Utils.checkThatArraysAreEqual(roles, userRoles); } { // remove the roles from the user - boolean didUserHaveRole = UserRoles.removeUserRole(process.main, userId, roles[0]); + boolean didUserHaveRole = UserRoles.removeUserRole(process.getProcess(), userId, roles[0]); assertTrue(didUserHaveRole); // check that the user has no roles - String[] userRoles = storage.getRolesForUser(new TenantIdentifier(null, null, null), userId); + String[] userRoles = storage.getRolesForUser(process.getAppForTesting(), userId); assertEquals(0, userRoles.length); } { // remove a role from a user where the user does not have the role - boolean didUserHaveRole = UserRoles.removeUserRole(process.main, userId, roles[0]); + boolean didUserHaveRole = UserRoles.removeUserRole(process.getProcess(), userId, roles[0]); assertFalse(didUserHaveRole); } @@ -402,30 +405,30 @@ public void testRemovingARoleFromAUserWhoHasMultipleRoles() throws Exception { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); String[] roles = new String[]{"role1", "role2", "role3"}; String userId = "userId"; // create multiple roles and assign them to a user for (String role : roles) { - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); - UserRoles.addRoleToUser(process.main, userId, role); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, null); + UserRoles.addRoleToUser(process.getProcess(), userId, role); } { // check that the user actually has the roles - String[] userRoles = storage.getRolesForUser(new TenantIdentifier(null, null, null), userId); + String[] userRoles = storage.getRolesForUser(process.getAppForTesting(), userId); Utils.checkThatArraysAreEqual(roles, userRoles); } // remove a role from the user - boolean didUserHaveRole = UserRoles.removeUserRole(process.main, userId, "role1"); + boolean didUserHaveRole = UserRoles.removeUserRole(process.getProcess(), userId, "role1"); assertTrue(didUserHaveRole); { String[] currentUserRoles = new String[]{"role2", "role3"}; - String[] retrievedUserRoles = storage.getRolesForUser(new TenantIdentifier(null, null, null), userId); + String[] retrievedUserRoles = storage.getRolesForUser(process.getAppForTesting(), userId); // check that the user has the correct roles Utils.checkThatArraysAreEqual(currentUserRoles, retrievedUserRoles); @@ -447,7 +450,7 @@ public void testRetrievingRolesForUser() throws Exception { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // create multiple roles and add them to a user String[] roles = new String[]{"role1", "role2", "role3"}; @@ -455,13 +458,13 @@ public void testRetrievingRolesForUser() throws Exception { for (String role : roles) { // create role - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, null); // add role to user - UserRoles.addRoleToUser(process.main, userId, role); + UserRoles.addRoleToUser(process.getProcess(), userId, role); } // retrieve roles and check that user has roles - String[] userRoles = UserRoles.getRolesForUser(process.main, userId); + String[] userRoles = UserRoles.getRolesForUser(process.getProcess(), userId); Utils.checkThatArraysAreEqual(roles, userRoles); process.kill(); @@ -482,7 +485,7 @@ public void testRetrievingRolesForUserWithNoRoles() throws Exception { String userId = "userId"; // retrieve roles and check that user has no roles - String[] userRoles = UserRoles.getRolesForUser(process.main, userId); + String[] userRoles = UserRoles.getRolesForUser(process.getProcess(), userId); assertEquals(0, userRoles.length); process.kill(); @@ -502,16 +505,16 @@ public void testRetrievingUsersForRole() throws Exception { // create a role String role = "role"; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, null); // add role to users String[] userIds = new String[]{"user1", "user2", "user3"}; for (String userId : userIds) { - UserRoles.addRoleToUser(process.main, userId, role); + UserRoles.addRoleToUser(process.getProcess(), userId, role); } // retrieve users with the input role and check that it is correct - String[] usersWithTheSameRole = UserRoles.getUsersForRole(process.main, role); + String[] usersWithTheSameRole = UserRoles.getUsersForRole(process.getProcess(), role); Utils.checkThatArraysAreEqual(userIds, usersWithTheSameRole); process.kill(); @@ -532,7 +535,7 @@ public void testRetrievingUsersForAnUnknownRole() throws Exception { // retrieve users with an unknown role Exception error = null; try { - UserRoles.getUsersForRole(process.main, "unknownRole"); + UserRoles.getUsersForRole(process.getProcess(), "unknownRole"); } catch (Exception e) { error = e; } @@ -556,9 +559,9 @@ public void testRetrievingUserIdsForRoleWhichHasNoUsers() throws Exception { // create a role String role = "role"; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, null); - String[] userIdsWithRole = UserRoles.getUsersForRole(process.main, role); + String[] userIdsWithRole = UserRoles.getUsersForRole(process.getProcess(), role); assertEquals(0, userIdsWithRole.length); @@ -579,10 +582,10 @@ public void testRetrievingPermissionsForARole() throws Exception { // create a role String role = "role"; String[] permissions = new String[]{"permission1", "permission2", "permission3"}; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, permissions); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, permissions); // check that role has permissions - String[] retrievedPermissions = UserRoles.getPermissionsForRole(process.main, role); + String[] retrievedPermissions = UserRoles.getPermissionsForRole(process.getProcess(), role); Utils.checkThatArraysAreEqual(permissions, retrievedPermissions); process.kill(); @@ -601,9 +604,9 @@ public void testRetrievingPermissionsForARoleWithNoPermissions() throws Exceptio // create a role String role = "role"; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, null); - String[] retrievedPermissions = UserRoles.getPermissionsForRole(process.main, role); + String[] retrievedPermissions = UserRoles.getPermissionsForRole(process.getProcess(), role); assertEquals(0, retrievedPermissions.length); process.kill(); @@ -622,7 +625,7 @@ public void testRetrievingPermissionsWithUnknownRole() throws Exception { Exception error = null; try { - UserRoles.getPermissionsForRole(process.main, "unknownRole"); + UserRoles.getPermissionsForRole(process.getProcess(), "unknownRole"); } catch (Exception e) { error = e; } @@ -647,14 +650,14 @@ public void testDeletingPermissionsFromARole() throws Exception { // create a role with permissions String role = "role"; String[] permissions = new String[]{"permission1", "permission2", "permission3"}; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, permissions); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, permissions); // remove permissions from role String[] permissionsToRemove = new String[]{"permission1", "permission2"}; - UserRoles.deletePermissionsFromRole(process.main, role, permissionsToRemove); + UserRoles.deletePermissionsFromRole(process.getProcess(), role, permissionsToRemove); // check that permissions have been removed - String[] retrievedPermissions = UserRoles.getPermissionsForRole(process.main, role); + String[] retrievedPermissions = UserRoles.getPermissionsForRole(process.getProcess(), role); assertEquals(1, retrievedPermissions.length); assertEquals("permission3", retrievedPermissions[0]); @@ -675,13 +678,13 @@ public void testDeletingAllPermissionsFromARole() throws Exception { // create a role with permissions String role = "role"; String[] permissions = new String[]{"permission1", "permission2", "permission3"}; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, permissions); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, permissions); // remove all permissions from role - UserRoles.deletePermissionsFromRole(process.main, role, null); + UserRoles.deletePermissionsFromRole(process.getProcess(), role, null); // check that permissions have been removed - String[] retrievedPermissions = UserRoles.getPermissionsForRole(process.main, role); + String[] retrievedPermissions = UserRoles.getPermissionsForRole(process.getProcess(), role); assertEquals(0, retrievedPermissions.length); process.kill(); @@ -701,14 +704,14 @@ public void testDeletingAPermissionWhichDoesNotExistFromARole() throws Exception // create a role with permissions String role = "role"; String[] permissions = new String[]{"permission1", "permission2", "permission3"}; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, permissions); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, permissions); // remove all permissions from role String[] permissionToRemove = new String[]{"permission4"}; - UserRoles.deletePermissionsFromRole(process.main, role, permissionToRemove); + UserRoles.deletePermissionsFromRole(process.getProcess(), role, permissionToRemove); // check that no permissions have been removed - String[] retrievedPermissions = UserRoles.getPermissionsForRole(process.main, role); + String[] retrievedPermissions = UserRoles.getPermissionsForRole(process.getProcess(), role); Utils.checkThatArraysAreEqual(permissions, retrievedPermissions); process.kill(); @@ -728,7 +731,7 @@ public void testDeletingPermissionsFromAnUnknownRole() throws Exception { // remove permissions from an unknown role Exception error = null; try { - UserRoles.deletePermissionsFromRole(process.main, "unknownRole", null); + UserRoles.deletePermissionsFromRole(process.getProcess(), "unknownRole", null); } catch (Exception e) { error = e; } @@ -752,13 +755,13 @@ public void testDeletingAPermissionsFromARoleWithAnEmptyArray() throws Exception // create a role with permissions String role = "role"; String[] permissions = new String[]{"permission1", "permission2", "permission3"}; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, permissions); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, permissions); // remove all permissions from role - UserRoles.deletePermissionsFromRole(process.main, role, new String[]{}); + UserRoles.deletePermissionsFromRole(process.getProcess(), role, new String[]{}); // check that no permissions have been removed - String[] retrievedPermissions = UserRoles.getPermissionsForRole(process.main, role); + String[] retrievedPermissions = UserRoles.getPermissionsForRole(process.getProcess(), role); Utils.checkThatArraysAreEqual(permissions, retrievedPermissions); process.kill(); @@ -781,18 +784,18 @@ public void testRetrievingRolesForPermissions() throws Exception { String permission2 = "permission2"; // create role1 with permission [permission1] - UserRoles.createNewRoleOrModifyItsPermissions(process.main, roles[0], new String[]{permission1}); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), roles[0], new String[]{permission1}); // create role2 with permissions [permission1, permission2] - UserRoles.createNewRoleOrModifyItsPermissions(process.main, roles[1], + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), roles[1], new String[]{permission1, permission2}); { - String[] retrievedRoles = UserRoles.getRolesThatHavePermission(process.main, permission1); + String[] retrievedRoles = UserRoles.getRolesThatHavePermission(process.getProcess(), permission1); Utils.checkThatArraysAreEqual(roles, retrievedRoles); } { - String[] retrievedRoles = UserRoles.getRolesThatHavePermission(process.main, permission2); + String[] retrievedRoles = UserRoles.getRolesThatHavePermission(process.getProcess(), permission2); assertEquals(1, retrievedRoles.length); assertEquals(roles[1], retrievedRoles[0]); } @@ -812,7 +815,7 @@ public void testRetrievingRolesForAnUnknownPermission() throws Exception { } // check that no roles are returned - String[] retrievedRoles = UserRoles.getRolesThatHavePermission(process.main, "unknownPermission"); + String[] retrievedRoles = UserRoles.getRolesThatHavePermission(process.getProcess(), "unknownPermission"); assertEquals(0, retrievedRoles.length); process.kill(); @@ -829,25 +832,25 @@ public void testDeletingARole() throws Exception { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // create a role with permissions and assign it to a user String role = "role"; String userId = "userId"; String[] permissions = new String[]{"permission1", "permission2", "permission3"}; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, permissions); - UserRoles.addRoleToUser(process.main, userId, role); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, permissions); + UserRoles.addRoleToUser(process.getProcess(), userId, role); // delete role - boolean didRoleExist = UserRoles.deleteRole(process.main, role); + boolean didRoleExist = UserRoles.deleteRole(process.getProcess(), role); assertTrue(didRoleExist); // retrieving permission should throw unknownRoleException Exception error = null; try { - UserRoles.getPermissionsForRole(process.main, role); + UserRoles.getPermissionsForRole(process.getProcess(), role); } catch (Exception e) { error = e; } @@ -855,19 +858,19 @@ public void testDeletingARole() throws Exception { assertTrue(error instanceof UnknownRoleException); // check that the role-permission mapping doesnt exist in the db - String[] retrievedPermissions = storage.getPermissionsForRole(new AppIdentifier(null, null), role); + String[] retrievedPermissions = storage.getPermissionsForRole(process.getAppForTesting().toAppIdentifier(), role); assertEquals(0, retrievedPermissions.length); // check that user has no roles - String[] retrievedRoles = UserRoles.getRolesForUser(process.main, userId); + String[] retrievedRoles = UserRoles.getRolesForUser(process.getProcess(), userId); assertEquals(0, retrievedRoles.length); // check that the user-role mapping doesnt exist in the db - String[] retrievedRolesFromDb = storage.getRolesForUser(new TenantIdentifier(null, null, null), userId); + String[] retrievedRolesFromDb = storage.getRolesForUser(process.getAppForTesting(), userId); assertEquals(0, retrievedRolesFromDb.length); // check that role doesnt exist - assertFalse(UserRoles.doesRoleExist(process.main, role)); + assertFalse(UserRoles.doesRoleExist(process.getProcess(), role)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); @@ -883,7 +886,7 @@ public void testDeletingAnUnknownRole() throws Exception { return; } - boolean didRoleExist = UserRoles.deleteRole(process.main, "unknownRole"); + boolean didRoleExist = UserRoles.deleteRole(process.getProcess(), "unknownRole"); assertFalse(didRoleExist); process.kill(); @@ -902,19 +905,19 @@ public void testGettingAllCreatedRoles() throws Exception { { // call getRoles when no roles exist - String[] retrievedRoles = UserRoles.getRoles(process.main); + String[] retrievedRoles = UserRoles.getRoles(process.getProcess()); assertEquals(0, retrievedRoles.length); } // create roles String[] roles = new String[]{"role1", "role2", "role3"}; for (String role : roles) { - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, null); } // retrieve all role and check for correct output { - String[] retrievedRoles = UserRoles.getRoles(process.main); + String[] retrievedRoles = UserRoles.getRoles(process.getProcess()); Utils.checkThatArraysAreEqual(roles, retrievedRoles); } @@ -935,15 +938,15 @@ public void testDeletingRolesFromAUserWhenMappingDoesExist() throws Exception { // create roles String[] roles = new String[]{"role1", "role2", "role3"}; for (String role : roles) { - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, null); } // delete all roles for a user - int numberOfRolesDeleted = UserRoles.deleteAllRolesForUser(process.main, "userId"); + int numberOfRolesDeleted = UserRoles.deleteAllRolesForUser(process.getProcess(), "userId"); assertEquals(0, numberOfRolesDeleted); // check that no roles have been deleted - String[] retrievedRoles = UserRoles.getRoles(process.main); + String[] retrievedRoles = UserRoles.getRoles(process.getProcess()); Utils.checkThatArraysAreEqual(roles, retrievedRoles); process.kill(); @@ -964,23 +967,23 @@ public void testDeletingAllRolesForAUser() throws Exception { String[] roles = new String[]{"role1", "role2", "role3"}; String userId = "user"; for (String role : roles) { - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); - UserRoles.addRoleToUser(process.main, userId, role); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, null); + UserRoles.addRoleToUser(process.getProcess(), userId, role); } // delete all roles for the user - int numberOfRolesDeleted = UserRoles.deleteAllRolesForUser(process.main, userId); + int numberOfRolesDeleted = UserRoles.deleteAllRolesForUser(process.getProcess(), userId); assertEquals(roles.length, numberOfRolesDeleted); // check that roles were removed from the user { - String[] retrievedRoles = UserRoles.getRolesForUser(process.main, userId); + String[] retrievedRoles = UserRoles.getRolesForUser(process.getProcess(), userId); assertEquals(0, retrievedRoles.length); } // check that no roles were removed { - String[] retrievedRoles = UserRoles.getRoles(process.main); + String[] retrievedRoles = UserRoles.getRoles(process.getProcess()); Utils.checkThatArraysAreEqual(roles, retrievedRoles); } @@ -998,42 +1001,42 @@ public void createAnAuthUserAssignRolesAndDeleteUser() throws Exception { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // create a role String role = "role"; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, null); // Create an Auth User - AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.main, "test@example.com", "testPassword"); + AuthRecipeUserInfo userInfo = EmailPassword.signUp(process.getProcess(), "test@example.com", "testPassword"); // assign role to user - UserRoles.addRoleToUser(process.main, userInfo.getSupertokensUserId(), role); + UserRoles.addRoleToUser(process.getProcess(), userInfo.getSupertokensUserId(), role); { // check that user has role - String[] retrievedRoles = UserRoles.getRolesForUser(process.main, userInfo.getSupertokensUserId()); + String[] retrievedRoles = UserRoles.getRolesForUser(process.getProcess(), userInfo.getSupertokensUserId()); assertEquals(1, retrievedRoles.length); assertEquals(role, retrievedRoles[0]); } // delete User - AuthRecipe.deleteUser(process.main, userInfo.getSupertokensUserId()); + AuthRecipe.deleteUser(process.getProcess(), userInfo.getSupertokensUserId()); { // check that user has no roles - String[] retrievedRoles = UserRoles.getRolesForUser(process.main, userInfo.getSupertokensUserId()); + String[] retrievedRoles = UserRoles.getRolesForUser(process.getProcess(), userInfo.getSupertokensUserId()); assertEquals(0, retrievedRoles.length); // check that the mapping for user role doesnt exist - String[] roleUserMapping = storage.getRolesForUser(new TenantIdentifier(null, null, null), + String[] roleUserMapping = storage.getRolesForUser(process.getAppForTesting(), userInfo.getSupertokensUserId()); assertEquals(0, roleUserMapping.length); } { // check that role still exists - String[] retrievedRoles = UserRoles.getRoles(process.main); + String[] retrievedRoles = UserRoles.getRoles(process.getProcess()); assertEquals(1, retrievedRoles.length); assertEquals(role, retrievedRoles[0]); } diff --git a/src/test/java/io/supertokens/test/userRoles/api/AddUserRoleAPITest.java b/src/test/java/io/supertokens/test/userRoles/api/AddUserRoleAPITest.java index 10f40d611..2ce0e7058 100644 --- a/src/test/java/io/supertokens/test/userRoles/api/AddUserRoleAPITest.java +++ b/src/test/java/io/supertokens/test/userRoles/api/AddUserRoleAPITest.java @@ -40,6 +40,9 @@ public class AddUserRoleAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -165,12 +168,12 @@ public void testAddingARoleToAUserTwice() throws Exception { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // create a role String[] role = new String[]{"role"}; String userId = "userId"; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role[0], null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role[0], null); { // add the role to a user @@ -187,7 +190,7 @@ public void testAddingARoleToAUserTwice() throws Exception { assertFalse(response.get("didUserAlreadyHaveRole").getAsBoolean()); // check that the user actually has only that role - String[] userRoles = storage.getRolesForUser(new TenantIdentifier(null, null, null), userId); + String[] userRoles = storage.getRolesForUser(process.getAppForTesting(), userId); Utils.checkThatArraysAreEqual(role, userRoles); } @@ -207,7 +210,7 @@ public void testAddingARoleToAUserTwice() throws Exception { assertTrue(response.get("didUserAlreadyHaveRole").getAsBoolean()); // check the users roles havent changed - String[] userRoles = storage.getRolesForUser(new TenantIdentifier(null, null, null), userId); + String[] userRoles = storage.getRolesForUser(process.getAppForTesting(), userId); Utils.checkThatArraysAreEqual(role, userRoles); } @@ -226,12 +229,12 @@ public void testAddingARoleToAUserByCallingAddUserRoleAPI() throws Exception { return; } - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // create a role String[] role = new String[]{"role"}; String userId = "userId"; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role[0], null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role[0], null); // add the role to a user JsonObject requestBody = new JsonObject(); @@ -247,7 +250,7 @@ public void testAddingARoleToAUserByCallingAddUserRoleAPI() throws Exception { assertFalse(response.get("didUserAlreadyHaveRole").getAsBoolean()); // check that the user actually has only that role - String[] userRoles = storage.getRolesForUser(new TenantIdentifier(null, null, null), userId); + String[] userRoles = storage.getRolesForUser(process.getAppForTesting(), userId); Utils.checkThatArraysAreEqual(role, userRoles); process.kill(); @@ -279,8 +282,8 @@ public void testAddingAnUnknownRoleToAUser() throws Exception { assertEquals(1, response.entrySet().size()); // check that user has no role associated with them - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); - String[] userRoles = storage.getRolesForUser(new TenantIdentifier(null, null, null), userId); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); + String[] userRoles = storage.getRolesForUser(process.getAppForTesting(), userId); assertEquals(0, userRoles.length); process.kill(); diff --git a/src/test/java/io/supertokens/test/userRoles/api/CreateRoleAPITest.java b/src/test/java/io/supertokens/test/userRoles/api/CreateRoleAPITest.java index c56309a17..325fee77a 100644 --- a/src/test/java/io/supertokens/test/userRoles/api/CreateRoleAPITest.java +++ b/src/test/java/io/supertokens/test/userRoles/api/CreateRoleAPITest.java @@ -42,6 +42,9 @@ public class CreateRoleAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -170,8 +173,8 @@ public void createTheSameRoleTwiceTest() throws Exception { assertTrue(response.get("createdNewRole").getAsBoolean()); // retrieve all roles and check that the newly created role is returned - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); - String[] roles = storage.getRoles(new AppIdentifier(null, null)); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); + String[] roles = storage.getRoles(process.getAppForTesting().toAppIdentifier()); assertEquals(1, roles.length); assertEquals(roles[0], role); } @@ -190,8 +193,8 @@ public void createTheSameRoleTwiceTest() throws Exception { assertFalse(response.get("createdNewRole").getAsBoolean()); // retrieve all roles and check that no new role has been created - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); - String[] roles = storage.getRoles(new AppIdentifier(null, null)); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); + String[] roles = storage.getRoles(process.getAppForTesting().toAppIdentifier()); assertEquals(1, roles.length); assertEquals(roles[0], role); } @@ -224,8 +227,8 @@ public void createANewRoleWithoutPermissionsTest() throws Exception { assertTrue(response.get("createdNewRole").getAsBoolean()); // retrieve all roles and check that the newly created role is returned - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); - String[] roles = storage.getRoles(new AppIdentifier(null, null)); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); + String[] roles = storage.getRoles(process.getAppForTesting().toAppIdentifier()); assertEquals(1, roles.length); assertEquals(roles[0], role); @@ -260,13 +263,13 @@ public void createANewRoleWithPermissionsTest() throws Exception { assertTrue(response.get("createdNewRole").getAsBoolean()); // check if role is created - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); - String[] roles = storage.getRoles(new AppIdentifier(null, null)); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); + String[] roles = storage.getRoles(process.getAppForTesting().toAppIdentifier()); assertEquals(1, roles.length); assertEquals(roles[0], role); // check if permissions have been added - String[] rolePermissions = storage.getPermissionsForRole(new AppIdentifier(null, null), role); + String[] rolePermissions = storage.getPermissionsForRole(process.getAppForTesting().toAppIdentifier(), role); Utils.checkThatArraysAreEqual(permissions, rolePermissions); diff --git a/src/test/java/io/supertokens/test/userRoles/api/GetPermissionsForRoleAPITest.java b/src/test/java/io/supertokens/test/userRoles/api/GetPermissionsForRoleAPITest.java index 341e0c7b7..32c538a2a 100644 --- a/src/test/java/io/supertokens/test/userRoles/api/GetPermissionsForRoleAPITest.java +++ b/src/test/java/io/supertokens/test/userRoles/api/GetPermissionsForRoleAPITest.java @@ -41,6 +41,9 @@ public class GetPermissionsForRoleAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -124,7 +127,7 @@ public void testRetrievingThePermissionsForARole() throws Exception { // create a role with permissions String role = "role"; String[] permissions = new String[]{"permission1", "permission2", "permission3"}; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, permissions); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, permissions); HashMap QUERY_PARAM = new HashMap<>(); QUERY_PARAM.put("role", role); diff --git a/src/test/java/io/supertokens/test/userRoles/api/GetRolesAPITest.java b/src/test/java/io/supertokens/test/userRoles/api/GetRolesAPITest.java index 3d94b6fea..818387310 100644 --- a/src/test/java/io/supertokens/test/userRoles/api/GetRolesAPITest.java +++ b/src/test/java/io/supertokens/test/userRoles/api/GetRolesAPITest.java @@ -38,6 +38,9 @@ public class GetRolesAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -62,7 +65,7 @@ public void testGettingRoles() throws Exception { // create multiple roles String[] roles = new String[]{"role1", "role2", "role3"}; for (String role : roles) { - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, null); } // retrieve all created roles diff --git a/src/test/java/io/supertokens/test/userRoles/api/GetRolesForPermissionAPITest.java b/src/test/java/io/supertokens/test/userRoles/api/GetRolesForPermissionAPITest.java index b1cf21624..a15c043e2 100644 --- a/src/test/java/io/supertokens/test/userRoles/api/GetRolesForPermissionAPITest.java +++ b/src/test/java/io/supertokens/test/userRoles/api/GetRolesForPermissionAPITest.java @@ -42,6 +42,9 @@ public class GetRolesForPermissionAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -127,9 +130,9 @@ public void testRetrievingRolesForAPermission() throws Exception { String permission2 = "permission2"; // create role1 with permission [permission1] - UserRoles.createNewRoleOrModifyItsPermissions(process.main, roles[0], new String[]{permission1}); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), roles[0], new String[]{permission1}); // create role2 with permissions [permission1, permission2] - UserRoles.createNewRoleOrModifyItsPermissions(process.main, roles[1], + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), roles[1], new String[]{permission1, permission2}); { diff --git a/src/test/java/io/supertokens/test/userRoles/api/GetUserRolesAPITest.java b/src/test/java/io/supertokens/test/userRoles/api/GetUserRolesAPITest.java index 73d9cf17f..f550757be 100644 --- a/src/test/java/io/supertokens/test/userRoles/api/GetUserRolesAPITest.java +++ b/src/test/java/io/supertokens/test/userRoles/api/GetUserRolesAPITest.java @@ -44,6 +44,9 @@ public class GetUserRolesAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -116,9 +119,9 @@ public void testGettingRolesForAUser() throws Exception { for (String role : roles) { // create role - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, null); // add role to User - UserRoles.addRoleToUser(process.main, userId, role); + UserRoles.addRoleToUser(process.getProcess(), userId, role); } HashMap QUERY_PARAMS = new HashMap<>(); diff --git a/src/test/java/io/supertokens/test/userRoles/api/GetUsersForRoleAPITest.java b/src/test/java/io/supertokens/test/userRoles/api/GetUsersForRoleAPITest.java index cd5837c99..c5182e04f 100644 --- a/src/test/java/io/supertokens/test/userRoles/api/GetUsersForRoleAPITest.java +++ b/src/test/java/io/supertokens/test/userRoles/api/GetUsersForRoleAPITest.java @@ -42,6 +42,9 @@ public class GetUsersForRoleAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -107,12 +110,12 @@ public void testRetrievingUsersWhoHaveRole() throws Exception { } String role = "role"; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, null); // add role to users String[] userIds = new String[]{"user1", "user2", "user3"}; for (String userId : userIds) { - UserRoles.addRoleToUser(process.main, userId, role); + UserRoles.addRoleToUser(process.getProcess(), userId, role); } // retrieve users for role diff --git a/src/test/java/io/supertokens/test/userRoles/api/RemovePermissionsForRoleAPITest.java b/src/test/java/io/supertokens/test/userRoles/api/RemovePermissionsForRoleAPITest.java index 816b9a841..fb8a5996c 100644 --- a/src/test/java/io/supertokens/test/userRoles/api/RemovePermissionsForRoleAPITest.java +++ b/src/test/java/io/supertokens/test/userRoles/api/RemovePermissionsForRoleAPITest.java @@ -43,6 +43,9 @@ public class RemovePermissionsForRoleAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -178,7 +181,7 @@ public void deletePermissionsFromRoleTest() throws Exception { String[] permissions = new String[]{"permission1", "permission2", "permission3"}; String role = "role"; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, permissions); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, permissions); // call api to remove some permissions String[] permissionsToRemove = new String[]{"permission1", "permission2"}; @@ -195,7 +198,7 @@ public void deletePermissionsFromRoleTest() throws Exception { assertEquals("OK", response.get("status").getAsString()); // check that only 1 permission exists for role - String[] retrievedPermissions = UserRoles.getPermissionsForRole(process.main, role); + String[] retrievedPermissions = UserRoles.getPermissionsForRole(process.getProcess(), role); assertEquals(1, retrievedPermissions.length); assertEquals("permission3", retrievedPermissions[0]); @@ -218,7 +221,7 @@ public void deleteAllPermissionsFromRoleTest() throws Exception { String[] permissions = new String[]{"permission1", "permission2", "permission3"}; String role = "role"; - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, permissions); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, permissions); // call api to remove all permissions JsonObject requestBody = new JsonObject(); @@ -233,7 +236,7 @@ public void deleteAllPermissionsFromRoleTest() throws Exception { assertEquals("OK", response.get("status").getAsString()); // check that there are no permissions for the role - String[] retrievedPermissions = UserRoles.getPermissionsForRole(process.main, role); + String[] retrievedPermissions = UserRoles.getPermissionsForRole(process.getProcess(), role); assertEquals(0, retrievedPermissions.length); process.kill(); diff --git a/src/test/java/io/supertokens/test/userRoles/api/RemoveRoleAPITest.java b/src/test/java/io/supertokens/test/userRoles/api/RemoveRoleAPITest.java index 6e6ee4d70..926499951 100644 --- a/src/test/java/io/supertokens/test/userRoles/api/RemoveRoleAPITest.java +++ b/src/test/java/io/supertokens/test/userRoles/api/RemoveRoleAPITest.java @@ -42,6 +42,9 @@ public class RemoveRoleAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -140,13 +143,13 @@ public void testRemovingARole() throws Exception { String role = "role"; String userId = "userId"; - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // create a role - UserRoles.createNewRoleOrModifyItsPermissions(process.main, role, new String[]{"permission"}); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), role, new String[]{"permission"}); // assign the role to a user - UserRoles.addRoleToUser(process.main, userId, role); + UserRoles.addRoleToUser(process.getProcess(), userId, role); // remove the role JsonObject request = new JsonObject(); @@ -166,7 +169,7 @@ public void testRemovingARole() throws Exception { // check that unknownRoleException is thrown when retrieving the permissions Exception error = null; try { - UserRoles.getPermissionsForRole(process.main, role); + UserRoles.getPermissionsForRole(process.getProcess(), role); } catch (Exception e) { error = e; } @@ -177,7 +180,7 @@ public void testRemovingARole() throws Exception { assertEquals(0, retrievedPermissions.length); // check that role doesnt exist - assertFalse(UserRoles.doesRoleExist(process.main, role)); + assertFalse(UserRoles.doesRoleExist(process.getProcess(), role)); process.kill(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STOPPED)); diff --git a/src/test/java/io/supertokens/test/userRoles/api/RemoveUserRoleAPITest.java b/src/test/java/io/supertokens/test/userRoles/api/RemoveUserRoleAPITest.java index fa9a0ef13..5658bc8e9 100644 --- a/src/test/java/io/supertokens/test/userRoles/api/RemoveUserRoleAPITest.java +++ b/src/test/java/io/supertokens/test/userRoles/api/RemoveUserRoleAPITest.java @@ -40,6 +40,9 @@ public class RemoveUserRoleAPITest { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -170,17 +173,17 @@ public void testRemovingARoleFromAUser() throws Exception { String[] roles = new String[]{"role1"}; String userId = "userId"; - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // create a role - UserRoles.createNewRoleOrModifyItsPermissions(process.main, roles[0], null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), roles[0], null); // assign the role to a user - UserRoles.addRoleToUser(process.main, userId, roles[0]); + UserRoles.addRoleToUser(process.getProcess(), userId, roles[0]); { // check that the user has the role - String[] userRoles = storage.getRolesForUser(new TenantIdentifier(null, null, null), userId); + String[] userRoles = storage.getRolesForUser(process.getAppForTesting(), userId); Utils.checkThatArraysAreEqual(roles, userRoles); } @@ -197,7 +200,7 @@ public void testRemovingARoleFromAUser() throws Exception { assertTrue(response.get("didUserHaveRole").getAsBoolean()); // check that user doesnt have any role - String[] userRoles = storage.getRolesForUser(new TenantIdentifier(null, null, null), userId); + String[] userRoles = storage.getRolesForUser(process.getAppForTesting(), userId); assertEquals(0, userRoles.length); process.kill(); @@ -217,10 +220,10 @@ public void testRemovingARoleFromAUserWhereTheUserDoesNotHaveTheRole() throws Ex String[] roles = new String[]{"role1"}; String userId = "userId"; - UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.main); + UserRolesSQLStorage storage = (UserRolesSQLStorage) StorageLayer.getStorage(process.getProcess()); // create a role - UserRoles.createNewRoleOrModifyItsPermissions(process.main, roles[0], null); + UserRoles.createNewRoleOrModifyItsPermissions(process.getProcess(), roles[0], null); // remove the role from the user JsonObject request = new JsonObject(); diff --git a/src/test/java/io/supertokens/test/webauthn/CredentialRegisterFlowTest.java b/src/test/java/io/supertokens/test/webauthn/CredentialRegisterFlowTest.java index d15dcde08..b09fd7937 100644 --- a/src/test/java/io/supertokens/test/webauthn/CredentialRegisterFlowTest.java +++ b/src/test/java/io/supertokens/test/webauthn/CredentialRegisterFlowTest.java @@ -53,11 +53,10 @@ public void beforeEach() { @Test public void registerCredential() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -81,11 +80,10 @@ public void registerCredential() throws Exception { @Test public void registerCredentialWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -117,11 +115,10 @@ public void registerCredentialWithUserIdMapping() throws Exception { @Test public void registerCredentialWithAccountLinking() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -139,7 +136,7 @@ public void registerCredentialWithAccountLinking() throws Exception { assertEquals("external_id", signInResponse.getAsJsonObject("user").get("id").getAsString()); assertEquals("external_id", signInResponse.get("recipeUserId").getAsString()); - List epUsers = Utils.createEmailPasswordUsers(process.getProcess(), 1, true); + List epUsers = Utils.createEmailPasswordUsers(process, 1, true); Utils.linkAccounts(process.getProcess(), epUsers.stream().map(AuthRecipeUserInfo::getSupertokensUserId).collect( Collectors.toList()), users.stream().map(user -> user.getAsJsonObject("user").get("id").getAsString()).collect(Collectors.toList())); diff --git a/src/test/java/io/supertokens/test/webauthn/GetCredentialFlowTest.java b/src/test/java/io/supertokens/test/webauthn/GetCredentialFlowTest.java index f4f70a4c1..0118bfaab 100644 --- a/src/test/java/io/supertokens/test/webauthn/GetCredentialFlowTest.java +++ b/src/test/java/io/supertokens/test/webauthn/GetCredentialFlowTest.java @@ -52,11 +52,10 @@ public void beforeEach() { @Test public void getCredential() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -82,11 +81,10 @@ public void getCredential() throws Exception { @Test public void getCredentialWithNotExistingId() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -106,11 +104,10 @@ public void getCredentialWithNotExistingId() throws Exception { @Test public void getCredentialWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -147,11 +144,10 @@ public void getCredentialWithUserIdMapping() throws Exception { @Test public void getCredentialWithAccountLinking() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -165,7 +161,7 @@ public void getCredentialWithAccountLinking() throws Exception { Utils.createUserIdMapping(process.getProcess(), users.get(0).getAsJsonObject("user").get("id").getAsString(), "external_id"); String userId = "external_id"; - List epUsers = Utils.createEmailPasswordUsers(process.getProcess(), 1, true); + List epUsers = Utils.createEmailPasswordUsers(process, 1, true); Utils.linkAccounts(process.getProcess(), epUsers.stream().map(AuthRecipeUserInfo::getSupertokensUserId).collect( Collectors.toList()), users.stream().map(user -> user.getAsJsonObject("user").get("id").getAsString()).collect(Collectors.toList())); diff --git a/src/test/java/io/supertokens/test/webauthn/ListCredentialsFlowTest.java b/src/test/java/io/supertokens/test/webauthn/ListCredentialsFlowTest.java index 933e5bfde..b073eef2a 100644 --- a/src/test/java/io/supertokens/test/webauthn/ListCredentialsFlowTest.java +++ b/src/test/java/io/supertokens/test/webauthn/ListCredentialsFlowTest.java @@ -53,11 +53,10 @@ public void beforeEach() { @Test public void listCredential() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -87,11 +86,10 @@ public void listCredential() throws Exception { @Test public void listCredentialWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -124,11 +122,10 @@ public void listCredentialWithUserIdMapping() throws Exception { @Test public void listCredentialWithAccountLinking() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -142,7 +139,7 @@ public void listCredentialWithAccountLinking() throws Exception { Utils.createUserIdMapping(process.getProcess(), users.get(0).getAsJsonObject("user").get("id").getAsString(), "external_id"); String userId = "external_id"; - List epUsers = Utils.createEmailPasswordUsers(process.getProcess(), 1, true); + List epUsers = Utils.createEmailPasswordUsers(process, 1, true); Utils.linkAccounts(process.getProcess(), epUsers.stream().map(AuthRecipeUserInfo::getSupertokensUserId).collect( Collectors.toList()), users.stream().map(user -> user.getAsJsonObject("user").get("id").getAsString()).collect(Collectors.toList())); diff --git a/src/test/java/io/supertokens/test/webauthn/RecoverAccountFlowTest.java b/src/test/java/io/supertokens/test/webauthn/RecoverAccountFlowTest.java index 284d992f7..7257f6d2f 100644 --- a/src/test/java/io/supertokens/test/webauthn/RecoverAccountFlowTest.java +++ b/src/test/java/io/supertokens/test/webauthn/RecoverAccountFlowTest.java @@ -53,11 +53,10 @@ public void beforeEach() { @Test public void recoverAccountTest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -93,11 +92,10 @@ public void recoverAccountTest() throws Exception { @Test public void recoverAccountFailsWithNonExistingUserTest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -116,11 +114,10 @@ public void recoverAccountFailsWithNonExistingUserTest() throws Exception { @Test public void recoverAccountWithLinkedPrimaryUserTest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -130,7 +127,7 @@ public void recoverAccountWithLinkedPrimaryUserTest() throws Exception { List users = Utils.registerUsers(process.getProcess(), 1); assertEquals(1, users.size()); - List emailPasswordUsers = Utils.createEmailPasswordUsers(process.getProcess(), 1, true); + List emailPasswordUsers = Utils.createEmailPasswordUsers(process, 1, true); assertEquals(1, emailPasswordUsers.size()); Utils.linkAccounts(process.getProcess(), emailPasswordUsers.stream().map(AuthRecipeUserInfo::getSupertokensUserId).collect( @@ -163,18 +160,17 @@ public void recoverAccountWithLinkedPrimaryUserTest() throws Exception { @Test public void recoverAccountTokenWithoutWANUserButWithExistingEmailPrimaryUserTest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { return; } - List emailPasswordUsers = Utils.createEmailPasswordUsers(process.getProcess(), 1, true); + List emailPasswordUsers = Utils.createEmailPasswordUsers(process, 1, true); assertEquals(1, emailPasswordUsers.size()); JsonObject recoverAccountToken = Utils.generateRecoverAccountTokenForEmail(process.getProcess(), "user0@example.com", emailPasswordUsers.get(0).getSupertokensUserId()); diff --git a/src/test/java/io/supertokens/test/webauthn/RemoveCredentialFlowTest.java b/src/test/java/io/supertokens/test/webauthn/RemoveCredentialFlowTest.java index 6ee66973d..44b60ffbb 100644 --- a/src/test/java/io/supertokens/test/webauthn/RemoveCredentialFlowTest.java +++ b/src/test/java/io/supertokens/test/webauthn/RemoveCredentialFlowTest.java @@ -52,11 +52,10 @@ public void beforeEach() { @Test public void removeCredential() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -89,11 +88,10 @@ public void removeCredential() throws Exception { @Test public void removeCredentialWithUserIdMapping() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -127,11 +125,10 @@ public void removeCredentialWithUserIdMapping() throws Exception { @Test public void removeCredentialWithAccountLinking() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -145,7 +142,7 @@ public void removeCredentialWithAccountLinking() throws Exception { Utils.createUserIdMapping(process.getProcess(), users.get(0).getAsJsonObject("user").get("id").getAsString(), "external_id"); String userId = "external_id"; - List epUsers = Utils.createEmailPasswordUsers(process.getProcess(), 1, true); + List epUsers = Utils.createEmailPasswordUsers(process, 1, true); Utils.linkAccounts(process.getProcess(), epUsers.stream().map(AuthRecipeUserInfo::getSupertokensUserId).collect( Collectors.toList()), users.stream().map(user -> user.getAsJsonObject("user").get("id").getAsString()).collect(Collectors.toList())); diff --git a/src/test/java/io/supertokens/test/webauthn/UpdateEmailFlowTest.java b/src/test/java/io/supertokens/test/webauthn/UpdateEmailFlowTest.java index 497f32cda..7fcc689db 100644 --- a/src/test/java/io/supertokens/test/webauthn/UpdateEmailFlowTest.java +++ b/src/test/java/io/supertokens/test/webauthn/UpdateEmailFlowTest.java @@ -52,11 +52,10 @@ public void beforeEach() { @Test public void updateEmailForUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -79,11 +78,10 @@ public void updateEmailForUser() throws Exception { @Test public void updateEmailForUserWithExternalId() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -109,11 +107,10 @@ public void updateEmailForUserWithExternalId() throws Exception { @Test public void updateEmailForNotExistingUser() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -132,11 +129,10 @@ public void updateEmailForNotExistingUser() throws Exception { @Test public void updateEmailForUserForAlreadyExistingEmailInWebauthn() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -156,11 +152,10 @@ public void updateEmailForUserForAlreadyExistingEmailInWebauthn() throws Excepti @Test public void updateEmailForUserForAlreadyExistingEmailInEmailPassword() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -172,7 +167,7 @@ public void updateEmailForUserForAlreadyExistingEmailInEmailPassword() throws Ex assertEquals("user0@example.com", users.get(0).getAsJsonObject("user").get("emails").getAsJsonArray().get(0).getAsString()); - List epUsers = Utils.createEmailPasswordUsers(process.getProcess(), 2, true); + List epUsers = Utils.createEmailPasswordUsers(process, 2, true); assertEquals(2, epUsers.size()); assertEquals("user1@example.com", epUsers.get(1).loginMethods[0].email); @@ -186,11 +181,10 @@ public void updateEmailForUserForAlreadyExistingEmailInEmailPassword() throws Ex @Test public void updateEmailForUserForAlreadyExistingEmailInEmailPasswordWithBothPrimary() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -201,12 +195,12 @@ public void updateEmailForUserForAlreadyExistingEmailInEmailPasswordWithBothPrim assertEquals(1, users.size()); assertEquals("user0@example.com", users.get(0).getAsJsonObject("user").get("emails").getAsJsonArray().get(0).getAsString()); - Utils.makePrimaryUserFrom(process.getProcess(), users.get(0).getAsJsonObject("user").get("id").getAsString()); + Utils.makePrimaryUserFrom(process, users.get(0).getAsJsonObject("user").get("id").getAsString()); - List epUsers = Utils.createEmailPasswordUsers(process.getProcess(), 2, false); + List epUsers = Utils.createEmailPasswordUsers(process, 2, false); assertEquals(2, epUsers.size()); assertEquals("user1@example.com", epUsers.get(1).loginMethods[0].email); - Utils.makePrimaryUserFrom(process.getProcess(), epUsers.get(1).getSupertokensUserId()); // make the target user email's account primary + Utils.makePrimaryUserFrom(process, epUsers.get(1).getSupertokensUserId()); // make the target user email's account primary JsonObject updateEmailResponse = Utils.updateEmail(process.getProcess(), users.get(0).getAsJsonObject("user").get("id").getAsString(), @@ -218,11 +212,10 @@ public void updateEmailForUserForAlreadyExistingEmailInEmailPasswordWithBothPrim @Test public void updateEmailForUserForAlreadyExistingEmailInEmailPasswordWithNoAccountLinking() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -235,7 +228,7 @@ public void updateEmailForUserForAlreadyExistingEmailInEmailPasswordWithNoAccoun Utils.verifyEmailFor(process.getProcess(), users.get(0).getAsJsonObject("user").get("id").getAsString(), "user0@example.com"); - List epUsers = Utils.createEmailPasswordUsers(process.getProcess(), 1, false, 1); + List epUsers = Utils.createEmailPasswordUsers(process, 1, false, 1); assertEquals(1, epUsers.size()); assertEquals("user1@example.com", epUsers.get(0).loginMethods[0].email); @@ -252,11 +245,10 @@ public void updateEmailForUserForAlreadyExistingEmailInEmailPasswordWithNoAccoun @Test public void updateEmailForUserForAlreadyExistingWithNoAccountLinking() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -278,11 +270,10 @@ public void updateEmailForUserForAlreadyExistingWithNoAccountLinking() throws Ex @Test public void updateEmailForUserForNewEmailBecomesUnverifiedWithNoAccountLinking() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/webauthn/Utils.java b/src/test/java/io/supertokens/test/webauthn/Utils.java index 4a6fe3913..66f2a2a6d 100644 --- a/src/test/java/io/supertokens/test/webauthn/Utils.java +++ b/src/test/java/io/supertokens/test/webauthn/Utils.java @@ -43,10 +43,10 @@ import io.supertokens.pluginInterface.emailpassword.exceptions.UnknownUserIdException; import io.supertokens.pluginInterface.exceptions.StorageQueryException; import io.supertokens.pluginInterface.exceptions.StorageTransactionLogicException; -import io.supertokens.pluginInterface.multitenancy.AppIdentifier; import io.supertokens.pluginInterface.multitenancy.exceptions.TenantOrAppNotFoundException; import io.supertokens.pluginInterface.useridmapping.UserIdMapping; import io.supertokens.storageLayer.StorageLayer; +import io.supertokens.test.TestingProcessManager; import io.supertokens.test.httpRequest.HttpRequestForTesting; import io.supertokens.test.httpRequest.HttpResponseException; import io.supertokens.useridmapping.UserIdType; @@ -345,15 +345,15 @@ private static void createUserIdMappingAndCheckThatItExists(Main main, UserIdMap assertEquals(userIdMapping, retrievedMapping); } - public static List createEmailPasswordUsers(Main main, int noUsers, boolean makePrimary) + public static List createEmailPasswordUsers(TestingProcessManager.TestingProcess process, int noUsers, boolean makePrimary) throws DuplicateEmailException, StorageQueryException, AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException, RecipeUserIdAlreadyLinkedWithPrimaryUserIdException, FeatureNotEnabledException, TenantOrAppNotFoundException, UnknownUserIdException { - return createEmailPasswordUsers(main, noUsers, makePrimary, 0); + return createEmailPasswordUsers(process, noUsers, makePrimary, 0); } - public static List createEmailPasswordUsers(Main main, int noUsers, boolean makePrimary, int emailIndexStart) + public static List createEmailPasswordUsers(TestingProcessManager.TestingProcess process, int noUsers, boolean makePrimary, int emailIndexStart) throws DuplicateEmailException, StorageQueryException, AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException, RecipeUserIdAlreadyLinkedWithPrimaryUserIdException, FeatureNotEnabledException, @@ -361,21 +361,21 @@ public static List createEmailPasswordUsers(Main main, int n List epUsers = new ArrayList<>(); for(int i = 0; i < noUsers; i++){ - AuthRecipeUserInfo user = EmailPassword.signUp(main, "user" + (emailIndexStart + i) + "@example.com", "password"); + AuthRecipeUserInfo user = EmailPassword.signUp(process.getProcess(), "user" + (emailIndexStart + i) + "@example.com", "password"); if(makePrimary) { - makePrimaryUserFrom(main, user.getSupertokensUserId()); + makePrimaryUserFrom(process, user.getSupertokensUserId()); } epUsers.add(user); } return epUsers; } - public static void makePrimaryUserFrom(Main main, String supertokensUserId) + public static void makePrimaryUserFrom(TestingProcessManager.TestingProcess process, String supertokensUserId) throws StorageQueryException, AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException, RecipeUserIdAlreadyLinkedWithPrimaryUserIdException, UnknownUserIdException, TenantOrAppNotFoundException, FeatureNotEnabledException { - AuthRecipe.createPrimaryUser(main, - new AppIdentifier(null, null), StorageLayer.getStorage(main), supertokensUserId); + AuthRecipe.createPrimaryUser(process.getProcess(), + process.getAppForTesting().toAppIdentifier(), StorageLayer.getStorage(process.getProcess()), supertokensUserId); } public static void verifyEmailFor(Main main, String userId, String emailAddress) diff --git a/src/test/java/io/supertokens/test/webauthn/WebAuthNFlowTest.java b/src/test/java/io/supertokens/test/webauthn/WebAuthNFlowTest.java index 5a4719635..c02de9db1 100644 --- a/src/test/java/io/supertokens/test/webauthn/WebAuthNFlowTest.java +++ b/src/test/java/io/supertokens/test/webauthn/WebAuthNFlowTest.java @@ -56,11 +56,10 @@ public void beforeEach() { @Test public void registerWebAuthNAndEmailPasswordUsersWithUIDMappingAndAccountLinkingAndSignInTest() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -70,7 +69,7 @@ public void registerWebAuthNAndEmailPasswordUsersWithUIDMappingAndAccountLinking int numberOfUsers = 1; //10k users List users = io.supertokens.test.webauthn.Utils.registerUsers(process.getProcess(), numberOfUsers); - List epUsers = Utils.createEmailPasswordUsers(process.getProcess(), numberOfUsers, true); + List epUsers = Utils.createEmailPasswordUsers(process, numberOfUsers, true); int w = 0; for (JsonObject user : users) { diff --git a/src/test/java/io/supertokens/test/webauthn/WebauthNAccountLinkingFlowTest.java b/src/test/java/io/supertokens/test/webauthn/WebauthNAccountLinkingFlowTest.java index c568e3421..d329116d0 100644 --- a/src/test/java/io/supertokens/test/webauthn/WebauthNAccountLinkingFlowTest.java +++ b/src/test/java/io/supertokens/test/webauthn/WebauthNAccountLinkingFlowTest.java @@ -59,11 +59,10 @@ public void beforeEach() { @Test public void linkAccountsWithBothEmailsVerifiedEPPrimary() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -74,7 +73,7 @@ public void linkAccountsWithBothEmailsVerifiedEPPrimary() throws Exception { //create users - webauthn and emailpassword List users = Utils.registerUsers(process.getProcess(), numberOfUsers); - List epUsers = Utils.createEmailPasswordUsers(process.getProcess(), numberOfUsers, true); + List epUsers = Utils.createEmailPasswordUsers(process, numberOfUsers, true); //create userid mapping and verify email for all wa users int w = 0; @@ -119,11 +118,10 @@ public void linkAccountsWithBothEmailsVerifiedEPPrimary() throws Exception { @Test public void linkAccountsWithEPEmailVerifiedEPPrimary() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -134,7 +132,7 @@ public void linkAccountsWithEPEmailVerifiedEPPrimary() throws Exception { //create users - webauthn and emailpassword List users = Utils.registerUsers(process.getProcess(), numberOfUsers); - List epUsers = Utils.createEmailPasswordUsers(process.getProcess(), numberOfUsers, true); + List epUsers = Utils.createEmailPasswordUsers(process, numberOfUsers, true); //create userid mapping and verify email for all wa users int w = 0; @@ -177,11 +175,10 @@ public void linkAccountsWithEPEmailVerifiedEPPrimary() throws Exception { @Test public void linkAccountsWithWANEmailVerifiedEPPrimary() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -192,7 +189,7 @@ public void linkAccountsWithWANEmailVerifiedEPPrimary() throws Exception { //create users - webauthn and emailpassword List users = Utils.registerUsers(process.getProcess(), numberOfUsers); - List epUsers = Utils.createEmailPasswordUsers(process.getProcess(), numberOfUsers, true); + List epUsers = Utils.createEmailPasswordUsers(process, numberOfUsers, true); //create userid mapping and verify email for all wa users int w = 0; @@ -236,11 +233,10 @@ public void linkAccountsWithWANEmailVerifiedEPPrimary() throws Exception { @Test public void linkAccountsWithEPEmailVerifiedWANPrimary() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -249,12 +245,12 @@ public void linkAccountsWithEPEmailVerifiedWANPrimary() throws Exception { //create users - webauthn and emailpassword List users = Utils.registerUsers(process.getProcess(), 1); - List epUsers = Utils.createEmailPasswordUsers(process.getProcess(), 1, false); + List epUsers = Utils.createEmailPasswordUsers(process, 1, false); JsonObject user = users.get(0); String userId = user.getAsJsonObject("user").get("id").getAsString(); Utils.createUserIdMapping(process.getProcess(), userId, "waexternal_" + userId); - Utils.makePrimaryUserFrom(process.getProcess(), userId); + Utils.makePrimaryUserFrom(process, userId); AuthRecipeUserInfo auser = epUsers.get(0); Utils.createUserIdMapping(process.getProcess(), auser.getSupertokensUserId(), "external_" + auser.getSupertokensUserId()); @@ -299,11 +295,10 @@ public void linkAccountsWithEPEmailVerifiedWANPrimary() throws Exception { @Test public void linkAccountsWithWANEmailVerifiedWAPrimary() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -312,14 +307,14 @@ public void linkAccountsWithWANEmailVerifiedWAPrimary() throws Exception { //create users - webauthn and emailpassword List users = Utils.registerUsers(process.getProcess(), 1); - List epUsers = Utils.createEmailPasswordUsers(process.getProcess(), 1, false); + List epUsers = Utils.createEmailPasswordUsers(process, 1, false); //create userid mapping and verify email for all wa users String userId = users.get(0).getAsJsonObject("user").get("id").getAsString(); Utils.createUserIdMapping(process.getProcess(), userId, "waexternal_" + userId); Utils.verifyEmailFor(process.getProcess(), userId, "user0@example.com"); - Utils.makePrimaryUserFrom(process.getProcess(), userId); + Utils.makePrimaryUserFrom(process, userId); //create userid mapping @@ -359,11 +354,10 @@ public void linkAccountsWithWANEmailVerifiedWAPrimary() throws Exception { @Test public void linkAccountsWithWANEmailVerifiedBothrimary() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -372,7 +366,7 @@ public void linkAccountsWithWANEmailVerifiedBothrimary() throws Exception { //create users - webauthn and emailpassword List users = Utils.registerUsers(process.getProcess(), 1); - List epUsers = Utils.createEmailPasswordUsers(process.getProcess(), 1, true); + List epUsers = Utils.createEmailPasswordUsers(process, 1, true); //create userid mapping and verify email for all wa users @@ -380,7 +374,7 @@ public void linkAccountsWithWANEmailVerifiedBothrimary() throws Exception { Utils.createUserIdMapping(process.getProcess(), userId, "waexternal_" + userId); Utils.verifyEmailFor(process.getProcess(), userId, "user0@example.com"); try { - Utils.makePrimaryUserFrom(process.getProcess(), userId); + Utils.makePrimaryUserFrom(process, userId); fail(); } catch (AccountInfoAlreadyAssociatedWithAnotherPrimaryUserIdException ignored) { //expected @@ -391,11 +385,10 @@ public void linkAccountsWithWANEmailVerifiedBothrimary() throws Exception { @Test public void linkAccountsWithNoEmailsVerifiedEPPrimary() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -404,7 +397,7 @@ public void linkAccountsWithNoEmailsVerifiedEPPrimary() throws Exception { //create users - webauthn and emailpassword List users = Utils.registerUsers(process.getProcess(), 1); - List epUsers = Utils.createEmailPasswordUsers(process.getProcess(), 1, true); + List epUsers = Utils.createEmailPasswordUsers(process, 1, true); String userId = users.get(0).getAsJsonObject("user").get("id").getAsString(); Utils.createUserIdMapping(process.getProcess(), userId, "waexternal_" + userId); @@ -433,11 +426,10 @@ public void linkAccountsWithNoEmailsVerifiedEPPrimary() throws Exception { @Test public void linkAccountsWithNoEmailsVerifiedNoPrimary() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { @@ -446,7 +438,7 @@ public void linkAccountsWithNoEmailsVerifiedNoPrimary() throws Exception { //create users - webauthn and emailpassword List users = Utils.registerUsers(process.getProcess(), 1); - List epUsers = Utils.createEmailPasswordUsers(process.getProcess(), 1, false); + List epUsers = Utils.createEmailPasswordUsers(process, 1, false); String userId = users.get(0).getAsJsonObject("user").get("id").getAsString(); Utils.createUserIdMapping(process.getProcess(), userId, "waexternal_" + userId); diff --git a/src/test/java/io/supertokens/test/webauthn/api/TestConsumeRecoverAccountTokenAPI_5_3.java b/src/test/java/io/supertokens/test/webauthn/api/TestConsumeRecoverAccountTokenAPI_5_3.java index 37e535cd3..9d4d981fa 100644 --- a/src/test/java/io/supertokens/test/webauthn/api/TestConsumeRecoverAccountTokenAPI_5_3.java +++ b/src/test/java/io/supertokens/test/webauthn/api/TestConsumeRecoverAccountTokenAPI_5_3.java @@ -42,6 +42,9 @@ public class TestConsumeRecoverAccountTokenAPI_5_3 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -118,11 +121,10 @@ public void testInvalidToken() throws Exception { public void testValidInput() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/webauthn/api/TestCredentialsRegisterAPI_5_3.java b/src/test/java/io/supertokens/test/webauthn/api/TestCredentialsRegisterAPI_5_3.java index 6f64dcd41..e98578a8e 100644 --- a/src/test/java/io/supertokens/test/webauthn/api/TestCredentialsRegisterAPI_5_3.java +++ b/src/test/java/io/supertokens/test/webauthn/api/TestCredentialsRegisterAPI_5_3.java @@ -31,6 +31,9 @@ public class TestCredentialsRegisterAPI_5_3 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/webauthn/api/TestGenerateRecoverAccountTokenAPI_5_3.java b/src/test/java/io/supertokens/test/webauthn/api/TestGenerateRecoverAccountTokenAPI_5_3.java index e01d9343b..50f18d637 100644 --- a/src/test/java/io/supertokens/test/webauthn/api/TestGenerateRecoverAccountTokenAPI_5_3.java +++ b/src/test/java/io/supertokens/test/webauthn/api/TestGenerateRecoverAccountTokenAPI_5_3.java @@ -40,6 +40,9 @@ public class TestGenerateRecoverAccountTokenAPI_5_3 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/webauthn/api/TestGetCredentialAPI_5_3.java b/src/test/java/io/supertokens/test/webauthn/api/TestGetCredentialAPI_5_3.java index 7c7bcf6f2..6e859fc78 100644 --- a/src/test/java/io/supertokens/test/webauthn/api/TestGetCredentialAPI_5_3.java +++ b/src/test/java/io/supertokens/test/webauthn/api/TestGetCredentialAPI_5_3.java @@ -32,6 +32,9 @@ public class TestGetCredentialAPI_5_3 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/webauthn/api/TestGetGeneratedOptionsAPI_5_3.java b/src/test/java/io/supertokens/test/webauthn/api/TestGetGeneratedOptionsAPI_5_3.java index b2cf9e7fd..4a7f48feb 100644 --- a/src/test/java/io/supertokens/test/webauthn/api/TestGetGeneratedOptionsAPI_5_3.java +++ b/src/test/java/io/supertokens/test/webauthn/api/TestGetGeneratedOptionsAPI_5_3.java @@ -24,6 +24,9 @@ public class TestGetGeneratedOptionsAPI_5_3 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/webauthn/api/TestGetUserFromRecoverAccountTokenAPI_5_3.java b/src/test/java/io/supertokens/test/webauthn/api/TestGetUserFromRecoverAccountTokenAPI_5_3.java index 8fdb3d25b..727f9c264 100644 --- a/src/test/java/io/supertokens/test/webauthn/api/TestGetUserFromRecoverAccountTokenAPI_5_3.java +++ b/src/test/java/io/supertokens/test/webauthn/api/TestGetUserFromRecoverAccountTokenAPI_5_3.java @@ -44,6 +44,9 @@ public class TestGetUserFromRecoverAccountTokenAPI_5_3 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); @@ -119,11 +122,10 @@ public void testInvalidToken() throws Exception { public void testValidInput() throws Exception { String[] args = {"../"}; - TestingProcessManager.TestingProcess process = TestingProcessManager.start(args, false); + TestingProcessManager.TestingProcess process = TestingProcessManager.start(args); FeatureFlagTestContent.getInstance(process.getProcess()) .setKeyValue(FeatureFlagTestContent.ENABLED_FEATURES, new EE_FEATURES[]{ EE_FEATURES.ACCOUNT_LINKING, EE_FEATURES.MULTI_TENANCY}); - process.startProcess(); assertNotNull(process.checkOrWaitForEvent(ProcessState.PROCESS_STATE.STARTED)); if (StorageLayer.getStorage(process.getProcess()).getType() != STORAGE_TYPE.SQL) { diff --git a/src/test/java/io/supertokens/test/webauthn/api/TestListCredentialsAPI_5_3.java b/src/test/java/io/supertokens/test/webauthn/api/TestListCredentialsAPI_5_3.java index d849ebd86..6569fcaed 100644 --- a/src/test/java/io/supertokens/test/webauthn/api/TestListCredentialsAPI_5_3.java +++ b/src/test/java/io/supertokens/test/webauthn/api/TestListCredentialsAPI_5_3.java @@ -34,6 +34,9 @@ public class TestListCredentialsAPI_5_3 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/webauthn/api/TestOptionsRegisterAPI_5_3.java b/src/test/java/io/supertokens/test/webauthn/api/TestOptionsRegisterAPI_5_3.java index d91bf13e0..c2148d52a 100644 --- a/src/test/java/io/supertokens/test/webauthn/api/TestOptionsRegisterAPI_5_3.java +++ b/src/test/java/io/supertokens/test/webauthn/api/TestOptionsRegisterAPI_5_3.java @@ -21,6 +21,9 @@ public class TestOptionsRegisterAPI_5_3 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/webauthn/api/TestRemoveCredentialAPI_5_3.java b/src/test/java/io/supertokens/test/webauthn/api/TestRemoveCredentialAPI_5_3.java index 7a32c9b90..6d15c70f6 100644 --- a/src/test/java/io/supertokens/test/webauthn/api/TestRemoveCredentialAPI_5_3.java +++ b/src/test/java/io/supertokens/test/webauthn/api/TestRemoveCredentialAPI_5_3.java @@ -33,6 +33,9 @@ public class TestRemoveCredentialAPI_5_3 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/webauthn/api/TestRemoveOptionsAPI_5_3.java b/src/test/java/io/supertokens/test/webauthn/api/TestRemoveOptionsAPI_5_3.java index c58e0d19a..5373002f5 100644 --- a/src/test/java/io/supertokens/test/webauthn/api/TestRemoveOptionsAPI_5_3.java +++ b/src/test/java/io/supertokens/test/webauthn/api/TestRemoveOptionsAPI_5_3.java @@ -25,6 +25,9 @@ public class TestRemoveOptionsAPI_5_3 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/webauthn/api/TestSignInAPI_5_3.java b/src/test/java/io/supertokens/test/webauthn/api/TestSignInAPI_5_3.java index deeec9231..520146d70 100644 --- a/src/test/java/io/supertokens/test/webauthn/api/TestSignInAPI_5_3.java +++ b/src/test/java/io/supertokens/test/webauthn/api/TestSignInAPI_5_3.java @@ -34,6 +34,9 @@ public class TestSignInAPI_5_3 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/webauthn/api/TestSignInOptionsAPI_5_3.java b/src/test/java/io/supertokens/test/webauthn/api/TestSignInOptionsAPI_5_3.java index 4beb7191b..22df2c1e7 100644 --- a/src/test/java/io/supertokens/test/webauthn/api/TestSignInOptionsAPI_5_3.java +++ b/src/test/java/io/supertokens/test/webauthn/api/TestSignInOptionsAPI_5_3.java @@ -22,6 +22,9 @@ public class TestSignInOptionsAPI_5_3 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/webauthn/api/TestSignUpWithCredentialRegisterAPI_5_3.java b/src/test/java/io/supertokens/test/webauthn/api/TestSignUpWithCredentialRegisterAPI_5_3.java index 08ebf6a26..aae7d15ae 100644 --- a/src/test/java/io/supertokens/test/webauthn/api/TestSignUpWithCredentialRegisterAPI_5_3.java +++ b/src/test/java/io/supertokens/test/webauthn/api/TestSignUpWithCredentialRegisterAPI_5_3.java @@ -32,6 +32,9 @@ public class TestSignUpWithCredentialRegisterAPI_5_3 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/src/test/java/io/supertokens/test/webauthn/api/TestUpdateUserEmailAPI_5_3.java b/src/test/java/io/supertokens/test/webauthn/api/TestUpdateUserEmailAPI_5_3.java index 9525bf073..ef87e9cf4 100644 --- a/src/test/java/io/supertokens/test/webauthn/api/TestUpdateUserEmailAPI_5_3.java +++ b/src/test/java/io/supertokens/test/webauthn/api/TestUpdateUserEmailAPI_5_3.java @@ -34,6 +34,9 @@ public class TestUpdateUserEmailAPI_5_3 { @Rule public TestRule watchman = Utils.getOnFailure(); + @Rule + public TestRule retryFlaky = Utils.retryFlakyTest(); + @AfterClass public static void afterTesting() { Utils.afterTesting(); diff --git a/stress-tests/.gitignore b/stress-tests/.gitignore new file mode 100644 index 000000000..1ca95f511 --- /dev/null +++ b/stress-tests/.gitignore @@ -0,0 +1,55 @@ +# Dependencies +node_modules/ +npm-debug.log* +yarn-debug.log* +yarn-error.log* +package-lock.json +yarn.lock + +# Environment variables +.env +.env.local +.env.*.local + +# Build output +dist/ +build/ +out/ + +# Logs +logs/ +*.log + +# IDE and editor files +.idea/ +.vscode/ +*.swp +*.swo +.DS_Store +Thumbs.db + +# Testing +coverage/ +.nyc_output/ + +# Temporary files +*.tmp +*.temp +.cache/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +users/ \ No newline at end of file diff --git a/stress-tests/.prettierrc b/stress-tests/.prettierrc new file mode 100644 index 000000000..1ad3d517b --- /dev/null +++ b/stress-tests/.prettierrc @@ -0,0 +1,8 @@ +{ + "semi": true, + "trailingComma": "es5", + "singleQuote": true, + "printWidth": 100, + "tabWidth": 2, + "useTabs": false +} \ No newline at end of file diff --git a/stress-tests/docker-compose.yml b/stress-tests/docker-compose.yml new file mode 100644 index 000000000..7d8ccaecb --- /dev/null +++ b/stress-tests/docker-compose.yml @@ -0,0 +1,66 @@ +version: '3' + +services: + # Note: If you are assigning a custom name to your db service on the line below, make sure it does not contain underscores + db: + image: 'postgres:latest' + environment: + POSTGRES_USER: supertokens + POSTGRES_PASSWORD: supertokens + POSTGRES_DB: supertokens + command: postgres -c shared_preload_libraries='pg_stat_statements' -c pg_stat_statements.track=all -c max_connections=1000 -c shared_buffers=1GB -c synchronous_commit=off -c wal_buffers=16MB -c checkpoint_timeout=30min -c max_wal_size=4GB + ports: + - 5432:5432 + networks: + - app_network + restart: unless-stopped + healthcheck: + test: ['CMD', 'pg_isready', '-U', 'supertokens', '-d', 'supertokens'] + interval: 5s + timeout: 5s + retries: 5 + + supertokens: + image: supertokens/supertokens-postgresql + platform: linux/amd64 + depends_on: + db: + condition: service_healthy + ports: + - 3567:3567 + environment: + POSTGRESQL_CONNECTION_URI: "postgresql://supertokens:supertokens@db:5432/supertokens" + PASSWORD_HASHING_ALG: "ARGON2" + ARGON2_ITERATIONS: 1 + ARGON2_MEMORY_KB: 8 + ARGON2_PARALLELISM: 1 + ARGON2_HASHING_POOL_SIZE: 8 + API_KEYS: "qwertyuiopasdfghjklzxcvbnm" + BULK_MIGRATION_PARALLELISM: "4" + BULK_MIGRATION_BATCH_SIZE: "500" + + networks: + - app_network + restart: unless-stopped + healthcheck: + test: > + bash -c 'exec 3<>/dev/tcp/127.0.0.1/3567 && echo -e "GET /hello HTTP/1.1\r\nhost: 127.0.0.1:3567\r\nConnection: close\r\n\r\n" >&3 && cat <&3 | grep "Hello"' + interval: 10s + timeout: 5s + retries: 5 + + pghero: + image: ankane/pghero + environment: + DATABASE_URL: "postgres://supertokens:supertokens@db:5432/supertokens" + ports: + - 8080:8080 + networks: + - app_network + depends_on: + - db + restart: unless-stopped + +networks: + app_network: + driver: bridge \ No newline at end of file diff --git a/stress-tests/package.json b/stress-tests/package.json new file mode 100644 index 000000000..b4397c0a6 --- /dev/null +++ b/stress-tests/package.json @@ -0,0 +1,27 @@ +{ + "name": "stress-tests", + "version": "1.0.0", + "description": "Stress tests for SuperTokens", + "main": "dist/index.js", + "scripts": { + "build": "tsc", + "start": "node dist/index.js", + "generate-users": "rm -rf users && mkdir -p users && ts-node src/oneMillionUsers/generateUsers.ts", + "one-million-users": "ts-node src/oneMillionUsers/index.ts", + "format": "prettier --write \"**/*.{ts,js,json}\"" + }, + "keywords": [], + "author": "", + "license": "ISC", + "devDependencies": { + "@types/node": "^20.11.24", + "prettier": "^3.5.3", + "ts-node": "^10.9.2", + "typescript": "^5.3.3" + }, + "dependencies": { + "@types/uuid": "^10.0.0", + "supertokens-node": "latest", + "uuid": "^11.1.0" + } +} diff --git a/stress-tests/src/common/utils.ts b/stress-tests/src/common/utils.ts new file mode 100644 index 000000000..da2d666dd --- /dev/null +++ b/stress-tests/src/common/utils.ts @@ -0,0 +1,143 @@ +import * as fs from 'fs'; + +export const LICENSE_FOR_TEST = + 'E1yITHflaFS4BPm7n0bnfFCjP4sJoTERmP0J=kXQ5YONtALeGnfOOe2rf2QZ0mfOh0aO3pBqfF-S0jb0ABpat6pySluTpJO6jieD6tzUOR1HrGjJO=50Ob3mHi21tQH1'; + +export const createStInstanceForTest = async () => { + return { + deployment_id: '1234567890', + core_url: 'http://localhost:3567', + api_key: 'qwertyuiopasdfghjklzxcvbnm', + }; +}; + +export const deleteStInstance = async (deploymentId: string) => { + // noop +}; + +export const formatTime = (ms: number): string => { + const seconds = Math.floor(ms / 1000); + if (seconds < 60) { + return `${seconds}s`; + } + const minutes = Math.floor(seconds / 60); + const remainingSeconds = seconds % 60; + return `${minutes}m ${remainingSeconds}s`; +}; + +export const workInBatches = async ( + count: number, + numberOfBatches: number, + work: (idx: number) => Promise +): Promise => { + const batchSize = Math.ceil(count / numberOfBatches); + const batches = []; + let workCount = 0; + + const st = Date.now(); + let done = numberOfBatches; + + for (let b = 0; b < numberOfBatches; b++) { + batches.push( + (async () => { + const startIndex = b * batchSize; + const endIndex = Math.min(startIndex + batchSize, count); + const batchResults: T[] = []; + for (let i = startIndex; i < endIndex; i++) { + batchResults.push(await work(i)); + workCount++; + } + done--; + return batchResults; + })() + ); + } + + batches.push( + (async () => { + while (done > 0) { + await new Promise((resolve) => setTimeout(resolve, 5000)); + const en = Date.now(); + console.log( + ` Progress: Time=${formatTime(en - st)}, Completed=${workCount}, Throughput=${Math.round((workCount / (en - st)) * 10000) / 10}/s` + ); + } + return []; + })() + ); + + const results = await Promise.all(batches); + return results.flat(); +}; + +export const setupLicense = async (coreUrl: string, apiKey: string) => { + try { + const response = await fetch(`${coreUrl}/ee/license`, { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + 'api-key': apiKey, + }, + body: JSON.stringify({ + licenseKey: LICENSE_FOR_TEST, + }), + }); + + if (!response.ok) { + throw new Error(`Failed with status: ${response.status}`); + } + const responseText = await response.text(); + console.log('License response:', responseText); + + console.log('License key set successfully'); + } catch (error) { + console.error('Failed to set license key:', error); + throw error; + } +}; + +export class StatsCollector { + private static instance: StatsCollector; + private measurements: { title: string; timeMs: number }[] = []; + + private constructor() {} + + public static getInstance(): StatsCollector { + if (!StatsCollector.instance) { + StatsCollector.instance = new StatsCollector(); + } + return StatsCollector.instance; + } + + public addMeasurement(title: string, timeMs: number) { + this.measurements.push({ title, timeMs }); + } + + public getStats() { + return this.measurements; + } + + public writeToFile() { + const formattedMeasurements = this.measurements.map((measurement) => ({ + title: measurement.title, + ms: measurement.timeMs, + formatted: formatTime(measurement.timeMs), + })); + + const stats = { + measurements: formattedMeasurements, + timestamp: new Date().toISOString(), + }; + fs.writeFileSync('stats.json', JSON.stringify(stats, null, 2)); + } +} + +export const measureTime = async (title: string, fn: () => Promise): Promise => { + const st = Date.now(); + const result = await fn(); + const et = Date.now(); + const timeMs = et - st; + console.log(` ${title} took ${formatTime(timeMs)}`); + StatsCollector.getInstance().addMeasurement(title, timeMs); + return result; +}; diff --git a/stress-tests/src/oneMillionUsers/accountLinking.ts b/stress-tests/src/oneMillionUsers/accountLinking.ts new file mode 100644 index 000000000..704ea63a4 --- /dev/null +++ b/stress-tests/src/oneMillionUsers/accountLinking.ts @@ -0,0 +1,24 @@ +import SuperTokens from 'supertokens-node'; +import AccountLinking from 'supertokens-node/recipe/accountlinking'; +import { measureTime, workInBatches } from '../common/utils'; + +export const doAccountLinking = async ( + users: { recipeUserId: string; email?: string; phoneNumber?: string }[][] +) => { + console.log('\n\n2. Linking accounts'); + + await measureTime('Linking accounts', async () => { + await workInBatches(users.length, 8, async (idx) => { + const userSet = users[idx]!; + await AccountLinking.createPrimaryUser( + SuperTokens.convertToRecipeUserId(userSet[0].recipeUserId) + ); + for (const user of userSet.slice(1)) { + await AccountLinking.linkAccounts( + SuperTokens.convertToRecipeUserId(user.recipeUserId), + userSet[0].recipeUserId + ); + } + }); + }); +}; diff --git a/stress-tests/src/oneMillionUsers/addRoles.ts b/stress-tests/src/oneMillionUsers/addRoles.ts new file mode 100644 index 000000000..a0381727d --- /dev/null +++ b/stress-tests/src/oneMillionUsers/addRoles.ts @@ -0,0 +1,18 @@ +import SuperTokens from 'supertokens-node'; +import UserRoles from 'supertokens-node/recipe/userroles'; +import { measureTime, workInBatches } from '../common/utils'; + +export const addRoles = async ( + users: { recipeUserId: string; email?: string; phoneNumber?: string }[] +) => { + console.log('\n\n4. Adding roles'); + + await measureTime('Adding roles', async () => { + await UserRoles.createNewRoleOrAddPermissions('admin', ['p1', 'p2']); + + await workInBatches(users.length, 8, async (idx) => { + const user = users[idx]!; + await UserRoles.addRoleToUser('public', user.recipeUserId, 'admin'); + }); + }); +}; diff --git a/stress-tests/src/oneMillionUsers/createSessions.ts b/stress-tests/src/oneMillionUsers/createSessions.ts new file mode 100644 index 000000000..0b20c5df4 --- /dev/null +++ b/stress-tests/src/oneMillionUsers/createSessions.ts @@ -0,0 +1,19 @@ +import SuperTokens from 'supertokens-node'; +import Session from 'supertokens-node/recipe/session'; +import { measureTime, workInBatches } from '../common/utils'; + +export const createSessions = async ( + users: { recipeUserId: string; email?: string; phoneNumber?: string }[] +) => { + console.log('\n\n5. Creating sessions'); + + await measureTime('Creating sessions', async () => { + await workInBatches(users.length, 8, async (idx) => { + const user = users[idx]!; + await Session.createNewSessionWithoutRequestResponse( + 'public', + SuperTokens.convertToRecipeUserId(user.recipeUserId) + ); + }); + }); +}; diff --git a/stress-tests/src/oneMillionUsers/createUserIdMappings.ts b/stress-tests/src/oneMillionUsers/createUserIdMappings.ts new file mode 100644 index 000000000..9f0ae327c --- /dev/null +++ b/stress-tests/src/oneMillionUsers/createUserIdMappings.ts @@ -0,0 +1,25 @@ +import { measureTime, workInBatches } from '../common/utils'; +import SuperTokens from 'supertokens-node'; + +export const createUserIdMappings = async ( + users: { recipeUserId: string; email?: string; phoneNumber?: string }[] +) => { + console.log('\n\n3. Create user id mappings'); + + await measureTime('Create user id mappings', async () => { + await workInBatches(users.length, 8, async (idx) => { + const user = users[idx]!; + if (Math.random() < 0.5) { + const newUserId = Array(64) + .fill(0) + .map(() => String.fromCharCode(97 + Math.floor(Math.random() * 26))) + .join(''); + await SuperTokens.createUserIdMapping({ + superTokensUserId: user.recipeUserId, + externalUserId: newUserId, + }); + user.recipeUserId = newUserId; + } + }); + }); +}; diff --git a/stress-tests/src/oneMillionUsers/createUsers.ts b/stress-tests/src/oneMillionUsers/createUsers.ts new file mode 100644 index 000000000..6aeacdfde --- /dev/null +++ b/stress-tests/src/oneMillionUsers/createUsers.ts @@ -0,0 +1,128 @@ +import EmailPassword from 'supertokens-node/recipe/emailpassword'; +import Passwordless from 'supertokens-node/recipe/passwordless'; +import ThirdParty from 'supertokens-node/recipe/thirdparty'; + +import { workInBatches, measureTime } from '../common/utils'; + +const TOTAL_USERS = 10000; + +const createEmailPasswordUsers = async () => { + console.log(` Creating EmailPassword users...`); + + return await workInBatches(Math.floor(TOTAL_USERS / 5), 4, async (idx) => { + const email = + Array(64) + .fill(0) + .map(() => String.fromCharCode(97 + Math.floor(Math.random() * 26))) + .join('') + '@example.com'; + const createdUser = await EmailPassword.signUp('public', email, 'password'); + // expect(createdUser.status).toBe("OK"); + if (createdUser.status === 'OK') { + return { + recipeUserId: createdUser.recipeUserId.getAsString(), + email: email, + }; + } + }); +}; + +const createPasswordlessUsersWithEmail = async () => { + console.log(` Creating Passwordless users (with email)...`); + return await workInBatches(Math.floor(TOTAL_USERS / 5), 4, async (idx) => { + const email = + Array(64) + .fill(0) + .map(() => String.fromCharCode(97 + Math.floor(Math.random() * 26))) + .join('') + '@example.com'; + const createdUser = await Passwordless.signInUp({ + tenantId: 'public', + email, + }); + // expect(createdUser.status).toBe("OK"); + if (createdUser.status === 'OK') { + return { + recipeUserId: createdUser.recipeUserId.getAsString(), + email, + }; + } + }); +}; + +const createPasswordlessUsersWithPhone = async () => { + console.log(` Creating Passwordless users (with phone)...`); + return await workInBatches(Math.floor(TOTAL_USERS / 5), 4, async (idx) => { + const phoneNumber = `+1${Math.floor(Math.random() * 10000000000)}`; + const createdUser = await Passwordless.signInUp({ + tenantId: 'public', + phoneNumber, + }); + // expect(createdUser.status).toBe("OK"); + if (createdUser.status === 'OK') { + return { + recipeUserId: createdUser.recipeUserId.getAsString(), + phoneNumber, + }; + } + }); +}; + +const createThirdPartyUsers = async (thirdPartyId: string) => { + console.log(` Creating ThirdParty (${thirdPartyId}) users...`); + return await workInBatches(Math.floor(TOTAL_USERS / 5), 4, async (idx) => { + const email = + Array(64) + .fill(0) + .map(() => String.fromCharCode(97 + Math.floor(Math.random() * 26))) + .join('') + '@example.com'; + const tpUserId = Array(64) + .fill(0) + .map(() => String.fromCharCode(97 + Math.floor(Math.random() * 26))) + .join(''); + const createdUser = await ThirdParty.manuallyCreateOrUpdateUser( + 'public', + thirdPartyId, + tpUserId, + email, + true + ); + // expect(createdUser.status).toBe("OK"); + if (createdUser.status === 'OK') { + return { + recipeUserId: createdUser.recipeUserId.getAsString(), + email, + }; + } + }); +}; + +export const createUsers = async () => { + console.log('\n\n1. Create one million users'); + + const epUsers = await measureTime('Emailpassword users creation', createEmailPasswordUsers); + + const plessEmailUsers = await measureTime( + 'Passwordless users (with email) creation', + createPasswordlessUsersWithEmail + ); + + const plessPhoneUsers = await measureTime( + 'Passwordless users (with phone) creation', + createPasswordlessUsersWithPhone + ); + + const tpUsers1 = await measureTime('ThirdParty users (google) creation', () => + createThirdPartyUsers('google') + ); + + const tpUsers2 = await measureTime('ThirdParty users (facebook) creation', () => + createThirdPartyUsers('facebook') + ); + + return { + epUsers, + plessEmailUsers, + plessPhoneUsers, + tpUsers1, + tpUsers2, + }; +}; diff --git a/stress-tests/src/oneMillionUsers/generateUsers.ts b/stress-tests/src/oneMillionUsers/generateUsers.ts new file mode 100644 index 000000000..2153d25c9 --- /dev/null +++ b/stress-tests/src/oneMillionUsers/generateUsers.ts @@ -0,0 +1,193 @@ +import * as fs from 'fs'; +import { v4 as uuidv4 } from 'uuid'; + +const USERS_TO_GENERATE = 1000000; +const USERS_PER_JSON = 10000; + +const n = Math.floor(USERS_TO_GENERATE / USERS_PER_JSON); + +const generatedEmails = new Set(); +const generatedPhoneNumbers = new Set(); +const generatedUserIds = new Set(); + +interface LoginMethod { + tenantIds: string[]; + email: string; + recipeId: string; + passwordHash?: string; + hashingAlgorithm?: string; + thirdPartyId?: string; + thirdPartyUserId?: string; + phoneNumber?: string; + isVerified: boolean; + isPrimary: boolean; + timeJoinedInMSSinceEpoch: number; +} + +interface User { + externalUserId: string; + userRoles: Array<{ + role: string; + tenantIds: string[]; + }>; + loginMethods: LoginMethod[]; +} + +function createEmailLoginMethod(email: string, tenantIds: string[]): LoginMethod { + return { + tenantIds, + email, + recipeId: 'emailpassword', + passwordHash: '$argon2d$v=19$m=12,t=3,p=1$aGI4enNvMmd0Zm0wMDAwMA$r6p7qbr6HD+8CD7sBi4HVw', + hashingAlgorithm: 'argon2', + isVerified: true, + isPrimary: false, + timeJoinedInMSSinceEpoch: + Math.floor(Math.random() * (Date.now() - 3 * 365 * 24 * 60 * 60 * 1000)) + + 3 * 365 * 24 * 60 * 60 * 1000, + }; +} + +function createThirdPartyLoginMethod(email: string, tenantIds: string[]): LoginMethod { + return { + tenantIds, + recipeId: 'thirdparty', + email, + thirdPartyId: 'google', + thirdPartyUserId: String(hashCode(email)), + isVerified: true, + isPrimary: false, + timeJoinedInMSSinceEpoch: + Math.floor(Math.random() * (Date.now() - 3 * 365 * 24 * 60 * 60 * 1000)) + + 3 * 365 * 24 * 60 * 60 * 1000, + }; +} + +function createPasswordlessLoginMethod( + email: string, + tenantIds: string[], + phoneNumber: string +): LoginMethod { + return { + tenantIds, + email, + recipeId: 'passwordless', + phoneNumber, + isVerified: true, + isPrimary: false, + timeJoinedInMSSinceEpoch: + Math.floor(Math.random() * (Date.now() - 3 * 365 * 24 * 60 * 60 * 1000)) + + 3 * 365 * 24 * 60 * 60 * 1000, + }; +} + +function hashCode(str: string): number { + let hash = 0; + for (let i = 0; i < str.length; i++) { + const char = str.charCodeAt(i); + hash = (hash << 5) - hash + char; + hash = hash & hash; + } + return hash; +} + +function generateRandomString(length: number, chars: string): string { + let result = ''; + for (let i = 0; i < length; i++) { + result += chars.charAt(Math.floor(Math.random() * chars.length)); + } + return result; +} + +function generateRandomEmail(): string { + return `${generateRandomString(24, 'abcdefghijklmnopqrstuvwxyz')}@example.com`; +} + +function generateRandomPhoneNumber(): string { + return `+91${generateRandomString(10, '0123456789')}`; +} + +function genUser(): User { + const user: User = { + externalUserId: '', + userRoles: [ + { role: 'role1', tenantIds: ['public'] }, + { role: 'role2', tenantIds: ['public'] }, + ], + loginMethods: [], + }; + + let userId = `e-${uuidv4()}`; + while (generatedUserIds.has(userId)) { + userId = `e-${uuidv4()}`; + } + generatedUserIds.add(userId); + user.externalUserId = userId; + + const tenantIds = ['public']; + + let email = generateRandomEmail(); + while (generatedEmails.has(email)) { + email = generateRandomEmail(); + } + generatedEmails.add(email); + + const loginMethods: LoginMethod[] = []; + + // Always add email login method + loginMethods.push(createEmailLoginMethod(email, tenantIds)); + + // 50% chance to add third party login + if (Math.random() < 0.5) { + loginMethods.push(createThirdPartyLoginMethod(email, tenantIds)); + } + + // 50% chance to add passwordless login + if (Math.random() < 0.5) { + let phoneNumber = generateRandomPhoneNumber(); + while (generatedPhoneNumbers.has(phoneNumber)) { + phoneNumber = generateRandomPhoneNumber(); + } + generatedPhoneNumbers.add(phoneNumber); + loginMethods.push(createPasswordlessLoginMethod(email, tenantIds, phoneNumber)); + } + + // If no methods were added, randomly add one + if (loginMethods.length === 0) { + const methodNumber = Math.floor(Math.random() * 3); + if (methodNumber === 0) { + loginMethods.push(createEmailLoginMethod(email, tenantIds)); + } else if (methodNumber === 1) { + loginMethods.push(createThirdPartyLoginMethod(email, tenantIds)); + } else { + let phoneNumber = generateRandomPhoneNumber(); + while (generatedPhoneNumbers.has(phoneNumber)) { + phoneNumber = generateRandomPhoneNumber(); + } + generatedPhoneNumbers.add(phoneNumber); + loginMethods.push(createPasswordlessLoginMethod(email, tenantIds, phoneNumber)); + } + } + + loginMethods[Math.floor(Math.random() * loginMethods.length)].isPrimary = true; + + user.loginMethods = loginMethods; + return user; +} + +// Create users directory if it doesn't exist +if (!fs.existsSync('users')) { + fs.mkdirSync('users'); +} + +for (let i = 0; i < n; i++) { + console.log(`Generating ${USERS_PER_JSON} users for ${i}`); + const users: User[] = []; + for (let j = 0; j < USERS_PER_JSON; j++) { + users.push(genUser()); + } + fs.writeFileSync( + `users/users-${i.toString().padStart(4, '0')}.json`, + JSON.stringify({ users }, null, 2) + ); +} diff --git a/stress-tests/src/oneMillionUsers/importMillionUsers.ts b/stress-tests/src/oneMillionUsers/importMillionUsers.ts new file mode 100644 index 000000000..fe6abc631 --- /dev/null +++ b/stress-tests/src/oneMillionUsers/importMillionUsers.ts @@ -0,0 +1,98 @@ +import fs from 'fs'; +import { formatTime, measureTime } from '../common/utils'; + +export const importMillionUsers = async (deployment: any) => { + console.log('\n\n0. Importing one million users'); + + // Create roles + await fetch(`${deployment.core_url}/recipe/role`, { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + 'Api-Key': deployment.api_key, + }, + body: JSON.stringify({ + role: 'role1', + permissions: ['p1', 'p2'], + }), + }); + + await fetch(`${deployment.core_url}/recipe/role`, { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + 'Api-Key': deployment.api_key, + }, + body: JSON.stringify({ + role: 'role2', + permissions: ['p3', 'p2'], + }), + }); + + await measureTime('Loading users for bulk import', async () => { + const files = fs.readdirSync('users').filter((file) => file.endsWith('.json')); + for (const file of files) { + const fileData = fs.readFileSync(`users/${file}`, 'utf8'); + const data = JSON.parse(fileData); + + await fetch(`${deployment.core_url}/bulk-import/users`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Api-Key': deployment.api_key, + }, + body: JSON.stringify(data), + }); + } + }); + + await measureTime('Waiting for users to be imported', async () => { + let lastCount = 1000000; + let st = Date.now(); + let lastTime = st; + while (true) { + await new Promise((resolve) => setTimeout(resolve, 5000)); + let response; + try { + response = await fetch(`${deployment.core_url}/bulk-import/users/count`, { + headers: { + 'Api-Key': deployment.api_key, + }, + }); + } catch (error) { + // Ignoring any error from this fetch request + console.log(' Error fetching user count, continuing anyway...'); + response = { json: async () => ({ count: lastCount }) }; + } + + let failedCountResponse; + try { + failedCountResponse = await fetch( + `${deployment.core_url}/bulk-import/users/count?status=FAILED`, + { + headers: { + 'Api-Key': deployment.api_key, + }, + } + ); + } catch (error) { + // Ignoring any error from this fetch request + console.log(' Error fetching user count, continuing anyway...'); + failedCountResponse = { json: async () => ({ count: 0 }) }; + } + + const count: any = await response.json(); + const failedCount: any = await failedCountResponse.json(); + console.log( + ` Progress: Time=${formatTime(Date.now() - st)}, UsersLeft=${count.count}, Rate=${(((lastCount - count.count) * 1000) / (Date.now() - lastTime)).toFixed(1)}, Failed=${failedCount.count}` + ); + + if (count.count - failedCount.count === 0) { + break; + } + + lastCount = count.count; + lastTime = Date.now(); + } + }); +}; diff --git a/stress-tests/src/oneMillionUsers/index.ts b/stress-tests/src/oneMillionUsers/index.ts new file mode 100644 index 000000000..5ab7cbc10 --- /dev/null +++ b/stress-tests/src/oneMillionUsers/index.ts @@ -0,0 +1,158 @@ +import { + createStInstanceForTest, + deleteStInstance, + setupLicense, + StatsCollector, +} from '../common/utils'; + +import SuperTokens from 'supertokens-node'; +import EmailPassword from 'supertokens-node/recipe/emailpassword'; +import Passwordless from 'supertokens-node/recipe/passwordless'; +import ThirdParty from 'supertokens-node/recipe/thirdparty'; +import UserRoles from 'supertokens-node/recipe/userroles'; +import Session from 'supertokens-node/recipe/session'; + +import { createUsers } from './createUsers'; +import { doAccountLinking } from './accountLinking'; +import { createUserIdMappings } from './createUserIdMappings'; +import { addRoles } from './addRoles'; +import { createSessions } from './createSessions'; +import { importMillionUsers } from './importMillionUsers'; + +function stInit(connectionURI: string, apiKey: string) { + SuperTokens.init({ + appInfo: { + appName: 'SuperTokens', + apiDomain: 'http://localhost:3001', + websiteDomain: 'http://localhost:3000', + apiBasePath: '/auth', + websiteBasePath: '/auth', + }, + supertokens: { + connectionURI: connectionURI, + apiKey: apiKey, + networkInterceptor: (request) => { + return request; + }, + }, + recipeList: [ + EmailPassword.init(), + Passwordless.init({ + contactMethod: 'EMAIL_OR_PHONE', + flowType: 'USER_INPUT_CODE', + }), + ThirdParty.init({ + signInAndUpFeature: { + providers: [ + { + config: { thirdPartyId: 'google' }, + }, + { + config: { thirdPartyId: 'facebook' }, + }, + ], + }, + }), + UserRoles.init(), + Session.init(), + ], + }); +} + +async function main() { + const deployment = await createStInstanceForTest(); + console.log(`Deployment created: ${deployment.core_url}`); + try { + stInit(deployment.core_url, deployment.api_key); + await setupLicense(deployment.core_url, deployment.api_key); + // 0. Import one million users + await importMillionUsers(deployment); + + // 1. Create one million users + const users = await createUsers(); + + // Randomly create groups of users for linking + const allUsers: ({ recipeUserId: string; email?: string; phoneNumber?: string } | undefined)[] = + [ + ...users.epUsers, + ...users.plessEmailUsers, + ...users.plessPhoneUsers, + ...users.tpUsers1, + ...users.tpUsers2, + ]; + const usersToLink: { recipeUserId: string; email?: string; phoneNumber?: string }[][] = []; + + while (allUsers.length > 0) { + const userSet: { recipeUserId: string; email?: string; phoneNumber?: string }[] = []; + const numAccounts = Math.min(Math.floor(Math.random() * 5 + 1), allUsers.length); + for (let i = 0; i < numAccounts; i++) { + const randomIndex = Math.floor(Math.random() * allUsers.length); + userSet.push(allUsers[randomIndex]!); + allUsers.splice(randomIndex, 1); + } + usersToLink.push(userSet); + } + + // 2. Link accounts + await doAccountLinking(usersToLink); + + // 3. Create user id mappings + const allUsersForMapping = [ + ...users.epUsers, + ...users.plessEmailUsers, + ...users.plessPhoneUsers, + ...users.tpUsers1, + ...users.tpUsers2, + ].filter((user) => user !== undefined) as { + recipeUserId: string; + email?: string; + phoneNumber?: string; + }[]; + await createUserIdMappings(allUsersForMapping); + + // 4. Add roles + await addRoles(allUsersForMapping); + + // 5. Create sessions + await createSessions(allUsersForMapping); + + // 6. List all users + console.log('\n\n6. Listing all users'); + let lmCount = 0; + let userCount = 0; + let paginationToken: string | undefined; + while (true) { + const result = await SuperTokens.getUsersNewestFirst({ + tenantId: 'public', + paginationToken, + }); + + for (const user of result.users) { + userCount++; + lmCount += user.loginMethods.length; + } + + paginationToken = result.nextPaginationToken; + + if (result.nextPaginationToken === undefined) break; + } + console.log(`Login methods count: ${lmCount}`); + console.log(`Users count: ${userCount}`); + + // 7. Count users + console.log('\n\n7. Count users'); + const total = await SuperTokens.getUserCount(); + console.log(`Users count: ${total}`); + + // Write stats to file + StatsCollector.getInstance().writeToFile(); + console.log('\nStats written to stats.json'); + } catch (error) { + console.error('An error occurred during execution:', error); + throw error; + } finally { + await deleteStInstance(deployment.deployment_id); + } +} + +main(); diff --git a/stress-tests/tsconfig.json b/stress-tests/tsconfig.json new file mode 100644 index 000000000..856edcce0 --- /dev/null +++ b/stress-tests/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "es2016", + "module": "commonjs", + "lib": ["ES2020"], + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "outDir": "./dist", + "rootDir": "./src", + "types": ["node"] + }, + "include": ["src/**/*"], + "exclude": ["node_modules"] +}