diff --git a/.github/workflows/ci-script-tests.yml b/.github/workflows/ci-script-tests.yml new file mode 100644 index 00000000..16b9d226 --- /dev/null +++ b/.github/workflows/ci-script-tests.yml @@ -0,0 +1,67 @@ +name: CI script tests + +# Runs the Pester tests of the scripts in ci/, which choose what a pull request +# builds and what a publish releases, check that every key is read under its +# _51DEGREES_ name in every workflow (ci/key-names.Tests.ps1), and test how +# free-threaded-python.yml fetches the free data files. A change to any +# workflow runs them. common-ci's main is +# checked out beside +# this repository, where ci/dispatch.Tests.ps1 looks for it. +on: + pull_request: + paths: + - 'ci/**' + - '*/ci/**' + - '**/tox.ini' + - 'pipeline/fiftyone_pipeline_cloudrequestengine/**/tests/**' + - 'pipeline/fiftyone_pipeline_did/tests/**' + - '.github/workflows/**' + push: + branches: + - main + - rc + paths: + - 'ci/**' + - '*/ci/**' + - '**/tox.ini' + - 'pipeline/fiftyone_pipeline_cloudrequestengine/**/tests/**' + - 'pipeline/fiftyone_pipeline_did/tests/**' + - '.github/workflows/**' + workflow_dispatch: + +permissions: + contents: read + +jobs: + pester: + name: CI script tests on ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + runs-on: ${{ matrix.os }} + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + path: 51degrees-python + persist-credentials: false + + - name: Checkout common-ci + uses: actions/checkout@v4 + with: + repository: 51Degrees/common-ci + ref: main + path: common-ci + persist-credentials: false + + - name: Run the tests + shell: pwsh + working-directory: 51degrees-python + run: | + $configuration = New-PesterConfiguration + $configuration.Run.Path = @(Get-ChildItem ci -Filter *.Tests.ps1 | + ForEach-Object FullName) + $configuration.Run.Exit = $true + $configuration.Output.Verbosity = 'Detailed' + Invoke-Pester -Configuration $configuration diff --git a/.github/workflows/cloud-51did.yml b/.github/workflows/cloud-51did.yml index 5f258dc1..461d40ce 100644 --- a/.github/workflows/cloud-51did.yml +++ b/.github/workflows/cloud-51did.yml @@ -1,21 +1,23 @@ name: Cloud 51Did Tests # Runs the live cloud 51Did integration test -# (pipeline/fiftyone_pipeline_did/tests/test_did_client_live.py) once for -# every _51DEGREES_RESOURCE_KEY* key passed to its step below. Each run sets -# the single _51DEGREES_RESOURCE_KEY the test reads first. Those keys carry -# the FODid product and the CloudV5FODiD product the marketing usages need. +# (pipeline/fiftyone_pipeline_did/tests/test_did_client_live.py) with the +# keys it reads, _51DEGREES_RESOURCE_KEY_51DID and +# _51DEGREES_LICENSE_KEY_51DID. The resource key carries the FODid product +# and the CloudV5FODiD product the marketing usages need. # The Basic key carries FODid without CloudV5FODiD, so it runs only the # tests of what the Basic tier is entitled to (test_did_tier_live.py). # -# The secrets are named one by one rather than passed as toJSON(secrets). +# The keys are named one by one rather than passed as toJSON(secrets). # GitHub marks a workflow that hands every secret to a step as possibly # malicious and holds each run for manual approval, so the nightly never ran. -# A new resource key therefore needs a line here as well as the organisation -# secret. +# The resource keys and the license key are organization secrets. A new +# resource key or license key therefore needs a line here as well as its +# organization secret. # -# A run with no key fails, because a cloud test that passes without calling -# the cloud has proved nothing. A pull request from a fork gets no secrets, +# A run with no key fails, naming the variable, because a cloud test that +# passes without calling the cloud has proved nothing. The tests themselves +# skip without a key. A pull request from a fork gets no secrets, # so run this workflow from a branch in this repository. on: @@ -29,7 +31,7 @@ on: schedule: - cron: '30 5 * * *' pull_request: - branches: [main] + branches: [main, rc] paths: - 'pipeline/fiftyone_pipeline_did/**' - 'pipeline/owid-python/**' @@ -61,40 +63,42 @@ jobs: run: ./pipeline/ci/copy-owid-source.ps1 - name: Install tox run: python -m pip install --upgrade pip tox - - name: Cloud 51Did test for each resource key secret - shell: pwsh + - name: Cloud 51Did test env: - _51DEGREES_RESOURCE_KEY_BESPOKE: ${{ secrets._51DEGREES_RESOURCE_KEY_BESPOKE }} - _51DEGREES_RESOURCE_KEY_51DID: ${{ vars._51DEGREES_RESOURCE_KEY_51DID }} + # The 51Did live tests read their resource key from + # _51DEGREES_RESOURCE_KEY_51DID, the organization secret of the + # same name. It has + # to be a key of the same account as _51DEGREES_LICENSE_KEY_51DID. + # With the Bespoke key in its place, the licensed redeem came back + # unreadable. + _51DEGREES_RESOURCE_KEY_51DID: ${{ secrets._51DEGREES_RESOURCE_KEY_51DID }} # The redemption tests check a sealed result reads back only with a # license key, and the service only opens a sealed result for a - # license key of the account whose resource key sealed it. So each - # license key is passed only with the resource key of the same - # suffix, and a resource key without one checks that the result - # redeems as unreadable. + # license key of the account whose resource key sealed it. The tests + # read it from _51DEGREES_LICENSE_KEY_51DID. _51DEGREES_LICENSE_KEY_51DID: ${{ secrets._51DEGREES_LICENSE_KEY_51DID }} + # The cloud service the tests call. The DidClient uses the public + # one when this is empty. + _51DEGREES_CLOUD_ENDPOINT: ${{ vars._51DEGREES_CLOUD_ENDPOINT }} + # The tests skip without a key, so the run fails here instead, + # naming the variable. -rs lists any test that skipped, and none + # should. + shell: pwsh run: | - $keys = Get-ChildItem env: | - Where-Object { $_.Name -like '_51DEGREES_RESOURCE_KEY*' -and $_.Value } - if (-not $keys) { - Write-Host '::error::No _51DEGREES_RESOURCE_KEY* secret reached this job. The tests need a key that carries the FODid product, and the CloudV5FODiD product for the marketing usages.' + if (-not $env:_51DEGREES_RESOURCE_KEY_51DID) { + Write-Host '::error::_51DEGREES_RESOURCE_KEY_51DID is not set. It comes from the _51DEGREES_RESOURCE_KEY_51DID organization secret.' exit 1 } - $failed = $false - foreach ($k in $keys) { - Write-Host "::group::test_did_client_live with $($k.Name)" - $env:_51DEGREES_RESOURCE_KEY = $k.Value - $licenseName = $k.Name -replace '^_51DEGREES_RESOURCE_KEY', '_51DEGREES_LICENSE_KEY' - $env:_51DEGREES_LICENSE_KEY = [Environment]::GetEnvironmentVariable($licenseName) - Write-Host "License key: $(if ($env:_51DEGREES_LICENSE_KEY) { $licenseName } else { 'none' })" - # -rs lists any test that skipped, and none should. - tox -- tests/test_did_client_live.py -v -rs - if ($LASTEXITCODE -ne 0) { $failed = $true } - Write-Host '::endgroup::' - } - if ($failed) { exit 1 } + tox -- tests/test_did_client_live.py -v -rs - name: Cloud 51Did tier test with the Basic key if: ${{ !cancelled() }} env: - _51DEGREES_RESOURCE_KEY_BASIC: ${{ vars._51DEGREES_RESOURCE_KEY_BASIC }} - run: tox -- tests/test_did_tier_live.py -v -rs + _51DEGREES_RESOURCE_KEY_BASIC: ${{ secrets._51DEGREES_RESOURCE_KEY_BASIC }} + _51DEGREES_CLOUD_ENDPOINT: ${{ vars._51DEGREES_CLOUD_ENDPOINT }} + shell: pwsh + run: | + if (-not $env:_51DEGREES_RESOURCE_KEY_BASIC) { + Write-Host '::error::_51DEGREES_RESOURCE_KEY_BASIC is not set. It comes from the _51DEGREES_RESOURCE_KEY_BASIC organization secret.' + exit 1 + } + tox -- tests/test_did_tier_live.py -v -rs diff --git a/.github/workflows/cloud-human-confidence.yml b/.github/workflows/cloud-human-confidence.yml new file mode 100644 index 00000000..a525beb1 --- /dev/null +++ b/.github/workflows/cloud-human-confidence.yml @@ -0,0 +1,139 @@ +name: Cloud Human Confidence Tests + +# Runs the Human Confidence web example's tests marked staging +# (pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/ +# test_cloud_humanconfidence_web.py) against the staging cloud, because the +# production cloud does not serve HumanConfidenceSource yet. The Bespoke key +# must get the source Passive, and the Basic key no source. +# +# CLOUD_STAGING_ENDPOINT, the staging cloud's API base, is an organization +# variable, and RESOURCE_KEY_BESPOKE_STAGING, a Bespoke key the staging cloud +# knows, is an organization secret. Only this workflow uses them. common-ci +# passes on only _51DEGREES_ names and its own list of CI secrets, so in the +# shared integration tests the staging tests skip, and the other Human +# Confidence tests run there against the cloud _51DEGREES_CLOUD_ENDPOINT +# names. _51DEGREES_RESOURCE_KEY_BASIC is an organization secret that both +# clouds know. +# +# The run fails when a name is empty, and when a test skipped or none ran, +# because a cloud test that passes without calling the cloud has proved +# nothing. A pull request from a fork gets no secrets, so run this workflow +# from a branch in this repository. + +on: + workflow_dispatch: + # Nightly as well, so a change in what the staging cloud answers is found + # the next morning. + schedule: + - cron: '50 6 * * *' + pull_request: + branches: [main, rc] + # The example and its tests, the files they import, and the files the + # install step uses. + paths: + - 'pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/**' + - 'pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/example_utils.py' + - 'pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/conftest.py' + - 'pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/live_cloud.py' + - 'pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web.py' + - 'pipeline/fiftyone_pipeline_cloudrequestengine/examples/pyproject.toml' + - 'ci/write-package-versions.ps1' + - 'ci/packages.ps1' + - 'ci/packages.json' + - '.github/workflows/cloud-human-confidence.yml' + +permissions: + contents: read + +jobs: + cloud-human-confidence: + name: Cloud Human Confidence + runs-on: ubuntu-latest + defaults: + run: + shell: pwsh + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + # The package versions written below come from the release tags. + fetch-depth: 0 + + # ci/write-package-versions.ps1 works out the versions with common-ci's + # release plan. + - name: Checkout common-ci + uses: actions/checkout@v4 + with: + repository: 51Degrees/common-ci + ref: main + path: .common-ci + persist-credentials: false + + - uses: actions/setup-python@v5 + with: + python-version: '3.12' + + - name: Install the example and the packages it uses + env: + _51DEGREES_COMMON_CI_DIR: ${{ github.workspace }}/.common-ci + run: | + # A pip install that fails stops the step here, rather than + # leaving the tests to fail on a missing module. + $PSNativeCommandUseErrorActionPreference = $true + python -m pip install --upgrade pip pytest + # A package installed from this checkout is 0.0.0 without the + # version.txt this writes, which is below the versions the packages + # here require of each other, so pip would refuse them. + ./ci/write-package-versions.ps1 + python -m pip install ` + -e pipeline/fiftyone_pipeline_core ` + -e pipeline/fiftyone_pipeline_engines ` + -e pipeline/fiftyone_pipeline_cloudrequestengine ` + -e pipeline/fiftyone_pipeline_cloudrequestengine/examples + + - name: Human Confidence tests against the staging cloud + working-directory: pipeline/fiftyone_pipeline_cloudrequestengine/examples + env: + CLOUD_STAGING_ENDPOINT: ${{ vars.CLOUD_STAGING_ENDPOINT }} + RESOURCE_KEY_BESPOKE_STAGING: ${{ secrets.RESOURCE_KEY_BESPOKE_STAGING }} + _51DEGREES_RESOURCE_KEY_BASIC: ${{ secrets._51DEGREES_RESOURCE_KEY_BASIC }} + run: | + # Each name, with where it comes from. + $names = [ordered]@{ + CLOUD_STAGING_ENDPOINT = 'organization variable' + RESOURCE_KEY_BESPOKE_STAGING = 'organization secret' + _51DEGREES_RESOURCE_KEY_BASIC = 'organization secret' + } + $missing = $false + foreach ($name in $names.Keys) { + if (-not [Environment]::GetEnvironmentVariable($name)) { + Write-Host ("::error::$name is empty or missing. It comes " + + "from the $($names[$name]) of the same name.") + $missing = $true + } + } + if ($missing) { exit 1 } + + $report = 'cloud-human-confidence.xml' + Remove-Item $report -ErrorAction SilentlyContinue + python -m pytest -m staging -p no:cacheprovider -v -rs ` + "--junit-xml=$report" + # pytest exits 5 when it selects no test. + if ($LASTEXITCODE -eq 5) { + Write-Host '::error::No staging test ran.' + exit 1 + } + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + if (-not (Test-Path $report)) { + Write-Host '::error::The staging tests did not run.' + exit 1 + } + $suite = ([xml](Get-Content -Raw $report)).SelectSingleNode( + '//testsuite') + if ([int]$suite.skipped -gt 0) { + foreach ($skipped in $suite.SelectNodes('testcase[skipped]')) { + Write-Host ("::error::$($skipped.name) skipped, so it proved " + + "nothing. $($skipped.skipped.message)") + } + exit 1 + } diff --git a/.github/workflows/environment-variable-names.yml b/.github/workflows/environment-variable-names.yml index e6bcaf04..5a679ec5 100644 --- a/.github/workflows/environment-variable-names.yml +++ b/.github/workflows/environment-variable-names.yml @@ -13,7 +13,7 @@ permissions: jobs: environment-variable-names: - name: No tracked file names a variable starting with a digit or a fallback name + name: Every variable a tracked file reads or sets is a _51DEGREES_ or platform name runs-on: ubuntu-latest steps: - name: Checkout repository diff --git a/device-detection/.github/workflows/example-assets-update.yml b/.github/workflows/example-assets-update.yml similarity index 69% rename from device-detection/.github/workflows/example-assets-update.yml rename to .github/workflows/example-assets-update.yml index dfbd3e5d..1fcf37e1 100644 --- a/device-detection/.github/workflows/example-assets-update.yml +++ b/.github/workflows/example-assets-update.yml @@ -3,17 +3,18 @@ name: Example Assets Update # Refreshes the shared web-example CSS/JS (examples-main) committed in this repo # from the latest examples-assets release, via the common-ci reusable workflow. # The assets change rarely, so this runs weekly and only opens a PR if they -# changed. common-ci is not a submodule; it is referenced as a reusable workflow. +# changed. It calls common-ci as a reusable workflow, not a submodule. on: workflow_dispatch: + # Mondays at 03:45 UTC, so it starts apart from the other repositories' + # example asset updates. schedule: - - cron: '0 3 * * 1' + - cron: '45 3 * * 1' jobs: Example_Assets_Update: uses: 51Degrees/common-ci/.github/workflows/nightly-example-assets-update.yml@main with: repo-name: ${{ github.event.repository.name }} - secrets: - token: ${{ secrets.ACCESS_TOKEN }} + secrets: inherit diff --git a/.github/workflows/free-threaded-python.yml b/.github/workflows/free-threaded-python.yml new file mode 100644 index 00000000..be4a347e --- /dev/null +++ b/.github/workflows/free-threaded-python.yml @@ -0,0 +1,209 @@ +name: Free-threaded Python + +# Builds the Device Detection and IP Intelligence on-premise packages on the +# free-threaded builds of Python and runs their tests there, with the free +# Lite data files. The first job downloads those once for each commit of the +# data submodule, which links them, and puts them in the cache. The test jobs +# restore them from there and never download them. +# ci/free-threaded-python.Tests.ps1 checks this. The native modules do not declare that they run without +# the GIL, so Python turns the GIL back on when it loads them. +# tests/test_free_threaded.py in each package checks that it does, and is +# skipped on every other build of Python. +on: + pull_request: + paths: + - 'device-detection/fiftyone_devicedetection_onpremise/**' + - 'ip-intelligence/fiftyone_ipintelligence_onpremise/**' + - 'pipeline/fiftyone_pipeline_core/**' + - 'pipeline/fiftyone_pipeline_engines/**' + - 'pipeline/fiftyone_pipeline_engines_fiftyone/**' + - 'cxx' + - '.github/workflows/free-threaded-python.yml' + push: + branches: + - main + - rc + paths: + - 'device-detection/fiftyone_devicedetection_onpremise/**' + - 'ip-intelligence/fiftyone_ipintelligence_onpremise/**' + - 'pipeline/fiftyone_pipeline_core/**' + - 'pipeline/fiftyone_pipeline_engines/**' + - 'pipeline/fiftyone_pipeline_engines_fiftyone/**' + - 'cxx' + - '.github/workflows/free-threaded-python.yml' + workflow_dispatch: + +permissions: + contents: read + +jobs: + free-data-files: + name: Fetch the free Lite data files once + runs-on: ubuntu-latest + outputs: + key: ${{ steps.key.outputs.key }} + defaults: + run: + shell: pwsh + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + submodules: recursive + + - name: Name the cache after the data submodule + id: key + run: | + # The data submodule's .link files say which files are fetched and + # from where, so a new commit of it needs the files again. Change + # v2 when the list of files below changes. + $data = git -C cxx rev-parse HEAD:data + if ($LASTEXITCODE) { exit $LASTEXITCODE } + "key=free-lite-data-v2-$data" >> $env:GITHUB_OUTPUT + + - name: Look for the files in the cache + id: cache + uses: actions/cache@v4 + with: + path: | + cxx/data/**/51Degrees-LiteV4.1.hash + cxx/data/**/20000 Evidence Records.yml + cxx/data/**/51Degrees-LiteV41.ipi + cxx/data/**/51Degrees-IPIV4AsnIpiV41.ipi + key: ${{ steps.key.outputs.key }} + # The Windows job restores what this Linux job saves. + enableCrossOsArchive: true + lookup-only: true + + # Runs only when the cache has no copy, and the cache saves the files + # when the job ends. + - name: Fetch the free Lite data files + if: steps.cache.outputs.cache-hit != 'true' + run: ./cxx/data/get-data-files.ps1 51Degrees-LiteV4.1.hash '20000 Evidence Records.yml' 51Degrees-LiteV41.ipi 51Degrees-IPIV4AsnIpiV41.ipi + + free-threaded: + name: Python ${{ matrix.python }} on ${{ matrix.os }} + needs: free-data-files + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu-latest + python: '3.13t' + - os: ubuntu-latest + python: '3.14t' + - os: windows-latest + python: '3.14t' + runs-on: ${{ matrix.os }} + defaults: + run: + shell: pwsh + steps: + - name: Checkout repository + uses: actions/checkout@v4 + with: + persist-credentials: false + # The native source is the cxx submodule, and the data files are + # linked from its own data submodule. + submodules: recursive + # The package versions written below come from the release tags. + fetch-depth: 0 + + # ci/write-package-versions.ps1 works out the versions with common-ci's + # release plan. + - name: Checkout common-ci + uses: actions/checkout@v4 + with: + repository: 51Degrees/common-ci + ref: main + path: .common-ci + persist-credentials: false + + - name: Set up Python ${{ matrix.python }} + uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python }} + + - name: Check the build is free-threaded + run: | + python -c "import sys, sysconfig; print(sys.version); assert sysconfig.get_config_var('Py_GIL_DISABLED') == 1, 'not a free-threaded build'; assert not sys._is_gil_enabled(), 'the GIL is on at start'" + + - name: Install the packages the tests use + env: + _51DEGREES_COMMON_CI_DIR: ${{ github.workspace }}/.common-ci + run: | + # A pip install that fails stops the step here, rather than + # leaving the tests to fail on a missing module. + $PSNativeCommandUseErrorActionPreference = $true + python -m pip install --upgrade pip + python -m pip install pytest flask flask-unittest json5 ruamel.yaml Cython setuptools + # A package installed from this checkout is 0.0.0 without the + # version.txt this writes, which is below the versions the packages + # here require of each other, so pip would refuse them. + ./ci/write-package-versions.ps1 + # The pipeline packages come from this checkout, as the tests run + # with the pipeline code they are released with. + python -m pip install ` + -e pipeline/fiftyone_pipeline_core ` + -e pipeline/fiftyone_pipeline_engines ` + -e pipeline/fiftyone_pipeline_engines_fiftyone ` + -e pipeline/fiftyone_pipeline_cloudrequestengine ` + -e device-detection/fiftyone_devicedetection_shared ` + -e device-detection/fiftyone_devicedetection_cloud ` + -e ip-intelligence/fiftyone_ipintelligence_shared + # These two require the on-premise package by name, which the + # tests read from its source folder instead. + python -m pip install --no-deps ` + -e device-detection/fiftyone_devicedetection ` + -e device-detection/fiftyone_devicedetection_examples + + - name: Restore the free Lite data files + uses: actions/cache/restore@v4 + with: + path: | + cxx/data/**/51Degrees-LiteV4.1.hash + cxx/data/**/20000 Evidence Records.yml + cxx/data/**/51Degrees-LiteV41.ipi + cxx/data/**/51Degrees-IPIV4AsnIpiV41.ipi + key: ${{ needs.free-data-files.outputs.key }} + enableCrossOsArchive: true + # The first job fetched them, so a miss is a fault, never a reason + # to download them here. + fail-on-cache-miss: true + + - name: Put the IP Intelligence file where the tests look for it + run: | + New-Item -ItemType Directory -Force -Path ip-intelligence/assets | Out-Null + New-Item -ItemType HardLink ` + -Path ip-intelligence/assets/51Degrees-LiteIpiV41.ipi ` + -Target cxx/data/ip-intelligence/51Degrees-LiteV41.ipi | Out-Null + + - name: Build the native modules + run: | + if ($IsWindows) { + # A short temporary path, for the MSVC path length limit. + $env:TEMP = New-Item -ItemType Directory -Force -Path 'C:\tmp' + $env:TMP = $env:TEMP + } + foreach ($package in 'device-detection/fiftyone_devicedetection_onpremise', 'ip-intelligence/fiftyone_ipintelligence_onpremise') { + Push-Location $package + python setup.py build_clib build_ext --inplace + if ($LASTEXITCODE) { exit $LASTEXITCODE } + Pop-Location + } + + - name: Run the tests + run: | + $failed = $false + foreach ($package in 'device-detection/fiftyone_devicedetection_onpremise', 'ip-intelligence/fiftyone_ipintelligence_onpremise') { + Write-Host "::group::$package" + Push-Location $package + $env:PYTHONPATH = Join-Path $PWD 'src' + # -rs lists any test that skipped, and none should here. + python -m pytest -rs tests + if ($LASTEXITCODE) { $failed = $true } + Pop-Location + Write-Host '::endgroup::' + } + if ($failed) { exit 1 } diff --git a/.github/workflows/monthly-copyright-update.yml b/.github/workflows/monthly-copyright-update.yml index 7a344b62..68fe9fd6 100644 --- a/.github/workflows/monthly-copyright-update.yml +++ b/.github/workflows/monthly-copyright-update.yml @@ -11,5 +11,4 @@ jobs: uses: 51Degrees/common-ci/.github/workflows/monthly-copyright-update.yml@main with: repo-name: ${{ github.event.repository.name }} - secrets: - token: ${{ secrets.ACCESS_TOKEN }} + secrets: inherit diff --git a/.github/workflows/nightly-pipeline.yml b/.github/workflows/nightly-pipeline.yml index e44f9d29..3c05d8e2 100644 --- a/.github/workflows/nightly-pipeline.yml +++ b/.github/workflows/nightly-pipeline.yml @@ -15,10 +15,25 @@ on: default: '' schedule: # The 51degrees-cxx nightly starts at 00:35 and ends by about 02:35, so - # its release reaches this submodule update the same night. - - cron: '0 3 * * *' + # its release reaches this submodule update the same night. The Node.js + # nightly starts at 02:30 and the Java nightly at 03:00, and both want + # macOS runners too, so this one starts after them. + - cron: '0 5 * * *' jobs: + # The publish builds main, which the pull requests into rc do not change, so + # it runs first and has the runners before the pull request builds do. + Publish: + name: Nightly Publish + uses: 51Degrees/common-ci/.github/workflows/nightly-publish.yml@main + with: + repo-name: ${{ github.event.repository.name }} + org-name: ${{ github.event.repository.owner.login }} + dryrun: ${{ inputs.dryrun || false }} + common-ci-ref: ${{ inputs.common-ci-ref || '' }} + cache-assets: true + secrets: inherit + SubmoduleUpdate: name: Nightly Submodule Update uses: 51Degrees/common-ci/.github/workflows/nightly-submodule-update.yml@main @@ -27,12 +42,11 @@ jobs: org-name: ${{ github.event.repository.owner.login }} dryrun: ${{ inputs.dryrun || false }} common-ci-ref: ${{ inputs.common-ci-ref || '' }} - secrets: - token: ${{ secrets.ACCESS_TOKEN }} + secrets: inherit PullRequests: if: ${{ !cancelled() }} - needs: SubmoduleUpdate + needs: [Publish, SubmoduleUpdate] name: Nightly Pull Requests uses: 51Degrees/common-ci/.github/workflows/nightly-pull-requests.yml@main with: @@ -42,33 +56,6 @@ jobs: common-ci-ref: ${{ inputs.common-ci-ref || '' }} skip-lite-tests: ${{ inputs.skip-lite-tests || false }} cache-assets: true - secrets: - token: ${{ secrets.ACCESS_TOKEN }} - DeviceDetection: ${{ secrets.DEVICE_DETECTION_KEY }} - DeviceDetectionUrl: ${{ secrets.DEVICE_DETECTION_URL }} - CsvUrl: ${{ secrets.CSV_URL }} - IpIntelligence: ${{ secrets.IP_INTELLIGENCE_KEY }} - IpIntelligenceUrl: ${{ secrets.IPI_DATA_FILE_URL }} - TestResourceKey: ${{ secrets._51DEGREES_RESOURCE_KEY_BESPOKE }} - - Publish: - if: ${{ !cancelled() }} - needs: PullRequests - name: Nightly Publish - uses: 51Degrees/common-ci/.github/workflows/nightly-publish.yml@main - with: - repo-name: ${{ github.event.repository.name }} - org-name: ${{ github.event.repository.owner.login }} - dryrun: ${{ inputs.dryrun || false }} - common-ci-ref: ${{ inputs.common-ci-ref || '' }} - cache-assets: true - secrets: - token: ${{ secrets.ACCESS_TOKEN }} - DeviceDetection: ${{ secrets.DEVICE_DETECTION_KEY }} - DeviceDetectionUrl: ${{ secrets.DEVICE_DETECTION_URL }} - CsvUrl: ${{ secrets.CSV_URL }} - IpIntelligence: ${{ secrets.IP_INTELLIGENCE_KEY }} - IpIntelligenceUrl: ${{ secrets.IPI_DATA_FILE_URL }} - TestResourceKey: ${{ secrets._51DEGREES_RESOURCE_KEY_BESPOKE }} - PypiToken: ${{ secrets.PYPI_TOKEN }} - TestPypiToken: ${{ secrets.TEST_PYPI_TOKEN }} + # One configuration that fails does not cancel the others. + fail-fast: false + secrets: inherit diff --git a/.github/workflows/only-rc-into-main.yml b/.github/workflows/only-rc-into-main.yml index 69e19ca3..aac9de24 100644 --- a/.github/workflows/only-rc-into-main.yml +++ b/.github/workflows/only-rc-into-main.yml @@ -8,4 +8,8 @@ on: jobs: rc: name: Only rc into main + # The shared check reads the pull request and its labels. + permissions: + contents: read + pull-requests: read uses: 51Degrees/common-ci/.github/workflows/only-rc-into-main.yml@main diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 195969ae..81d37252 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -9,6 +9,12 @@ on: common-ci-ref: type: string default: '' + # common-ci refuses a release less than a week after the last unless + # this is set, which is only for a release agreed to go out early. + allow-early-release: + description: 'Publish even though a package was released less than a week ago' + type: boolean + default: false jobs: Publish: @@ -19,14 +25,6 @@ jobs: org-name: ${{ github.event.repository.owner.login }} dryrun: ${{ inputs.dryrun || false }} common-ci-ref: ${{ inputs.common-ci-ref || '' }} + allow-early-release: ${{ inputs.allow-early-release || false }} cache-assets: true - secrets: - token: ${{ secrets.ACCESS_TOKEN }} - DeviceDetection: ${{ secrets.DEVICE_DETECTION_KEY }} - DeviceDetectionUrl: ${{ secrets.DEVICE_DETECTION_URL }} - CsvUrl: ${{ secrets.CSV_URL }} - IpIntelligence: ${{ secrets.IP_INTELLIGENCE_KEY }} - IpIntelligenceUrl: ${{ secrets.IPI_DATA_FILE_URL }} - TestResourceKey: ${{ secrets._51DEGREES_RESOURCE_KEY_BESPOKE }} - PypiToken: ${{ secrets.PYPI_TOKEN }} - TestPypiToken: ${{ secrets.TEST_PYPI_TOKEN }} + secrets: inherit diff --git a/.github/workflows/pull-requests.yml b/.github/workflows/pull-requests.yml index 0d600a54..e072cfba 100644 --- a/.github/workflows/pull-requests.yml +++ b/.github/workflows/pull-requests.yml @@ -13,6 +13,10 @@ on: common-ci-ref: type: string default: '' + full-matrix: + description: 'Build every configuration, not only those the changes need' + type: boolean + default: false jobs: PullRequests: @@ -25,11 +29,10 @@ jobs: common-ci-ref: ${{ inputs.common-ci-ref || '' }} skip-lite-tests: ${{ inputs.skip-lite-tests || false }} cache-assets: true - secrets: - token: ${{ secrets.ACCESS_TOKEN }} - DeviceDetection: ${{ secrets.DEVICE_DETECTION_KEY }} - DeviceDetectionUrl: ${{ secrets.DEVICE_DETECTION_URL }} - CsvUrl: ${{ secrets.CSV_URL }} - IpIntelligence: ${{ secrets.IP_INTELLIGENCE_KEY }} - IpIntelligenceUrl: ${{ secrets.IPI_DATA_FILE_URL }} - TestResourceKey: ${{ secrets._51DEGREES_RESOURCE_KEY_BESPOKE }} + # Each pull request is built on the configurations its changes need, + # as ci/select-options.ps1 chooses, and one that fails does not cancel + # the others. With nothing eligible, the nightly builds rc instead. + full-matrix: ${{ inputs.full-matrix || false }} + fail-fast: false + build-without-pull-requests: false + secrets: inherit diff --git a/.github/workflows/release-pull-request.yml b/.github/workflows/release-pull-request.yml new file mode 100644 index 00000000..8e4af949 --- /dev/null +++ b/.github/workflows/release-pull-request.yml @@ -0,0 +1,25 @@ +name: Release Pull Request + +# Builds and tests the release pull request, rc into main, on every entry in +# ci/options.json, and never merges it. A pull request into rc is built only on +# the entries its changes need, so this is the full build of a release before +# it reaches main. See common-ci .github/workflows/release-pull-request.yml. +on: + pull_request: + branches: [main] + +# A push to rc while the release is open builds it again, in place of the +# build of the older rc. +concurrency: + group: release-pull-request-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + Release: + name: Release Pull Request + uses: 51Degrees/common-ci/.github/workflows/release-pull-request.yml@main + with: + repo-name: ${{ github.event.repository.name }} + org-name: ${{ github.event.repository.owner.login }} + cache-assets: true + secrets: inherit diff --git a/.github/workflows/submodule-update.yml b/.github/workflows/submodule-update.yml index 7bf3291c..d3b64cce 100644 --- a/.github/workflows/submodule-update.yml +++ b/.github/workflows/submodule-update.yml @@ -19,5 +19,4 @@ jobs: org-name: ${{ github.event.repository.owner.login }} dryrun: ${{ inputs.dryrun || false }} common-ci-ref: ${{ inputs.common-ci-ref || '' }} - secrets: - token: ${{ secrets.ACCESS_TOKEN }} + secrets: inherit diff --git a/.gitmodules b/.gitmodules index af600379..c031260b 100644 --- a/.gitmodules +++ b/.gitmodules @@ -7,3 +7,6 @@ [submodule "cxx"] path = cxx url = ../51degrees-cxx +[submodule "pipeline/fiftyone_pipeline_derivedproperty/src/fiftyone_pipeline_derivedproperty/derived-properties"] + path = pipeline/fiftyone_pipeline_derivedproperty/src/fiftyone_pipeline_derivedproperty/derived-properties + url = ../derived-properties diff --git a/AGENTS.md b/AGENTS.md index 1b697ff7..145ff519 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -10,10 +10,10 @@ layout and how to get the code are in the [README](README.md). Device Detection's on-premise `gettingstarted_console` is the quickest example to show, because its data file is about 35 MB. IP Intelligence's -on-premise `gettingstarted_console` runs on the free Asn data file, which is -about 6 MB, and shows registration values once it is given the Lite file, -which is a download of about 230 MB. Run each command from the repository root -unless the step says otherwise. +on-premise `gettingstarted_console` runs on the free Lite data file, which is a +download of about 230 MB and has the registration values. The free Asn data +file, about 6 MB, has only the network properties. Run each command from the +repository root unless the step says otherwise. The on-premise engines are C and C++ code that is compiled when the package is installed. PyPI has only source distributions of @@ -150,16 +150,19 @@ macOS (`find_file` in python -m fiftyone_devicedetection_examples.onpremise.gettingstarted_console ``` -The IP Intelligence example with no argument looks for the Asn file in the -folder it runs in and in its `assets` and `cxx/data/ip-intelligence` folders, -then does the same in each of the seven folders above it, and downloads the -file into `cxx/data/ip-intelligence` when it is missing. To see registration -values, download the Lite file first, as "Data files" says, and give its path -as the first argument. +The IP Intelligence example with no argument looks for the Lite file, +`51Degrees-LiteV41.ipi`, in the folder it runs in and in its `assets`, +`cxx/data/ip-intelligence` and `cxx/data/device-detection` folders, then does +the same in each of the seven folders above it. When none of them has the +file, it downloads the file into the `cxx/data/ip-intelligence` folder that +holds the file's `.link` (`find_file` in +`ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/example_utils.py`). +To run it on the smaller Asn file, download that file first, as "Data files" +says, and give its path as the first argument. ``` python -m fiftyone_ipintelligence_examples.onpremise.gettingstarted_console -python -m fiftyone_ipintelligence_examples.onpremise.gettingstarted_console cxx/data/ip-intelligence/51Degrees-LiteV41.ipi +python -m fiftyone_ipintelligence_examples.onpremise.gettingstarted_console cxx/data/ip-intelligence/51Degrees-IPIV4AsnIpiV41.ipi ``` Either example uses a path given as the first argument as it is, so a file @@ -187,11 +190,12 @@ The IP Intelligence example logs `Using a '' data file created ''`, then for each of four IP addresses, starting with `116.154.188.222`, prints `Input values:` with `query.client-ip`, then `Results:` with a line for each of 16 properties, starting with `RegisteredName`, `RegisteredOwner` and -`RegisteredCountry`. A property the data file lacks reads -`This property is not present in the data file.` With the Asn file that is -every registration and location property, as the examples' README says. The -Lite file has RegisteredName, RegisteredOwner and RegisteredCountry, so with it -those three lines are read from the file. +`RegisteredCountry`. The Lite file has RegisteredName, RegisteredOwner and +RegisteredCountry, so those three lines are read from the file. Each property +the data file lacks reads `needs the Enterprise data file`, and after the last +address the example prints `Some of these properties need the Enterprise data +file. Contact us for a copy at` followed by a link. With the Asn file the +registration properties need the Enterprise data file as well. The paid data files have many more properties, as the [pricing page](https://51degrees.com/pricing?utm_source=github&utm_medium=docs&utm_campaign=51degrees-python&utm_content=agents.md&utm_term=correct-output) @@ -202,10 +206,10 @@ describes. The cloud examples need a resource key, which a person creates in the configurator, so ask for one if none is set. A key with the properties the Device Detection cloud example uses can be made -[here](https://configure.51degrees.com/1QWJwHxl?utm_source=github&utm_medium=docs&utm_campaign=51degrees-python&utm_content=agents.md&utm_term=cloud-examples), +[here](https://51degrees.com/configure/1QWJwHxl?utm_source=github&utm_medium=docs&utm_campaign=51degrees-python&utm_content=agents.md&utm_term=cloud-examples), which is the configuration the example's own message names, and a key for IP Intelligence in the -[configurator](https://configure.51degrees.com/?utm_source=github&utm_medium=docs&utm_campaign=51degrees-python&utm_content=agents.md&utm_term=cloud-examples). +[configuration page](https://51degrees.com/configure/?utm_source=github&utm_medium=docs&utm_campaign=51degrees-python&utm_content=agents.md&utm_term=cloud-examples). The Device Detection and IP Intelligence cloud examples take the key as their first argument, or from `_51DEGREES_RESOURCE_KEY`. @@ -250,6 +254,38 @@ example logs an error that names the variable and the configurator. assets, and the IP Intelligence example tests use the Asn file and throw their output away. +## Environment variable names + +Every environment variable the packages, tests, examples and CI scripts +define is named `_51DEGREES_`, and each name holds one thing. A name +that GitHub, the operating system or a tool defines, such as `GITHUB_JOB` or +`PYTEST_ADDOPTS`, is used as it is. +[`ci/check-environment-variable-names.ps1`](ci/check-environment-variable-names.ps1) +reads every tracked file and fails on a variable read or set under any other +name. It lists the platform names it lets through, so a new one is added +there, and the names only CI uses, which have no prefix because no customer +sets them. + +Two names are CI only. `CLOUD_STAGING_ENDPOINT`, an organization variable, +is the staging cloud's API base, ending `/api/v4/`, and +`RESOURCE_KEY_BESPOKE_STAGING`, an organization secret, is a Bespoke key the +staging cloud knows. Only +[`.github/workflows/cloud-human-confidence.yml`](.github/workflows/cloud-human-confidence.yml) +sets them, for the Human Confidence tests marked `staging`, which check what +the production cloud does not serve yet. common-ci passes on only +`_51DEGREES_` names and its own list of CI secrets, so in the shared +integration tests those tests skip. A staging test never falls back to +`_51DEGREES_CLOUD_ENDPOINT` or a default address. + +`_51DEGREES_RESOURCE_KEY` is the name a person running a cloud example sets. +The tests that call the cloud service read `_51DEGREES_RESOURCE_KEY_BESPOKE`, +and a test of an example gives the example that key under +`_51DEGREES_RESOURCE_KEY`. The Basic Human Confidence test, which calls the +staging cloud, and the 51Did tier test read `_51DEGREES_RESOURCE_KEY_BASIC`, +an organization secret, and skip naming it when it is not set. Cloud tests +and examples call the service `_51DEGREES_CLOUD_ENDPOINT` names, or the +public one when it is not set. + ## Products keep their own CI scripts Each product folder still has the `ci/` scripts it had as its own repository, @@ -262,16 +298,33 @@ product is built or tested belongs in that product's `ci/`, not in the root. A change touches a product when it is in that product's folder, or in a package another product depends on; a change outside every product folder touches all of them ([ci/packages.ps1](ci/packages.ps1), -`Resolve-AffectedProducts`). +`Resolve-AffectedProducts`). A pull request's changes are measured from the +branch it merges into, `rc`. + +[ci/select-options.ps1](ci/select-options.ps1) chooses the entries a pull +request runs. The standard set is Python 3.14 and 3.10 on Linux, with the +Selenium contract on 3.14 alone. A native change adds Windows, a packaging +change adds the other Python versions on Linux, and a change outside the +product folders or to a `ci/` folder adds every entry but macOS. macOS and +performance run only when `rc` itself or the release pull request is built, +which `.github/workflows/release-pull-request.yml` does on every entry. ## Versions are per package Every package is versioned and tagged on its own, `/`. A -package is released when its folders changed since its last tag, or when a -package it depends on is released. The examples packages are tested but never -published. common-ci's publish carries one version; here it is only a label, -and the release plan in `ci/packages.ps1` decides what is built, published -and tagged. Never push a plain `4.5.x` tag: nothing here reads one. +package is released when a file that counts in its folders changed since its +last tag, or when a package it depends on is released. Documentation +(`*.md`, `docs/`), tests (`tests/`, `test/`), examples (`examples/`) and +`LICENSE` files do not count, nor do files a package's `Ignore` globs in +`ci/packages.json` match, unless it sets `IgnoreDefaults` to false. A +`setup.py`, `setup.cfg` or `pyproject.toml` whose change is only to the +description, keywords, urls, classifiers, readme, authors or maintainers does +not count either, which `ci/release-plan-filter.ps1` works out with Python. +The examples packages are tested but never published. common-ci's publish +carries one version, which here is only a label, and the release plan +decides what is built, published and tagged. The release plan is common-ci's +`steps/release-plan.ps1`, which `ci/packages.ps1` loads, and common-ci tests +it. Never push a plain `4.5.x` tag, because nothing here reads one. `ci/packages.json` is the list of packages and what each depends on. Add a package there, with a `FirstVersion` if it has never been released, or it is @@ -313,13 +366,17 @@ A package's `ExtraPaths` in `ci/packages.json` cannot be a folder inside cxx update therefore releases no package, even when it brings new translations in `cxx/data/ip-intelligence`. -## Releases - -Pull requests go to `rc`, not `main`, and stay drafts until they have been -reviewed, because the nightly merges any pull request into `rc` that is not a -draft and has no review requested. When a release is wanted, one pull request -merges `rc` into `main`, and the "Only rc into main" check fails a pull request -into `main` from any other branch. +`pipeline/fiftyone_pipeline_derivedproperty` runs the scripts of +[derived-properties](https://github.com/51Degrees/derived-properties), which is +its submodule `src/fiftyone_pipeline_derivedproperty/derived-properties`, inside +the package so that the wheel carries its `scripts` folder (`MANIFEST.in`) and +nothing else from it. Its tests run every case file in the submodule's `tests` +folder, so moving the submodule moves the cases the tests run. `parse.py`, +`validate.py`, `evaluate.py` and `canonical.py` follow the reference tools in +the submodule's `tools` folder function for function, with `jsvalues.py` +holding the JavaScript rules they rely on, so a change there is made here the +same way. The package is `"Publish": false` in `ci/packages.json`, so it is +tested in every build and not published. ## Releases @@ -334,3 +391,11 @@ into `main` from any other branch. The four repositories were brought in with `git subtree add`, so commit SHAs match the originals. Use `git log --follow` to trace a file back through the import. + +## Tests that fail on timing + +A test that fails on a time limit, a performance threshold or a timeout is +fixed, not run again until it passes. Either the limit is set to fit the +slowest runner the test runs on, with each runner's measurement behind it, or +the reason it takes too long is found and fixed. A failure that comes and goes +costs everyone who meets it the time to look into it. diff --git a/README.md b/README.md index 04fb4d05..23688d15 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ python -m pip install fiftyone-ipintelligence The table below lists the other packages. To build from source, see [Getting the code](#getting-the-code). -Try the [User-Agent tester](https://51degrees.com/developers/user-agent-tester?utm_source=github&utm_medium=readme&utm_campaign=51degrees-python&utm_content=readme.md&utm_term=install) and [IP tester](https://51degrees.com/developers/ip-tester?utm_source=github&utm_medium=readme&utm_campaign=51degrees-python&utm_content=readme.md&utm_term=install). For cloud use, [create a Resource Key](https://configure.51degrees.com/?utm_source=github&utm_medium=readme&utm_campaign=51degrees-python&utm_content=readme.md&utm_term=install). +Try the [User-Agent tester](https://51degrees.com/developers/user-agent-tester?utm_source=github&utm_medium=readme&utm_campaign=51degrees-python&utm_content=readme.md&utm_term=install) and [IP tester](https://51degrees.com/developers/ip-tester?utm_source=github&utm_medium=readme&utm_campaign=51degrees-python&utm_content=readme.md&utm_term=install). For cloud use, [create a Resource Key](https://51degrees.com/configure/?utm_source=github&utm_medium=readme&utm_campaign=51degrees-python&utm_content=readme.md&utm_term=install). Created from `pipeline-python`, `device-detection-python`, and `location-python`, this repository continues their work. @@ -31,7 +31,7 @@ own folder, which has its own README. | Product | Folder | PyPI packages | | --- | --- | --- | -| Pipeline API | [pipeline](pipeline/readme.md) | `fiftyone_pipeline_core`, `_engines`, `_engines_fiftyone`, `_cloudrequestengine`, `_translation`, `_did` | +| Pipeline API | [pipeline](pipeline/readme.md) | `fiftyone_pipeline_core`, `_engines`, `_engines_fiftyone`, `_cloudrequestengine`, `_translation`, `_did`, `_derivedproperty` (not yet published) | | Device Detection | [device-detection](device-detection/readme.md) | `fiftyone_devicedetection`, `_shared`, `_cloud`, `_onpremise` | | IP Intelligence | [ip-intelligence](ip-intelligence/readme.md) | `fiftyone_ipintelligence`, `_shared`, `_cloud`, `_onpremise`, `_translation` | | Location | [location](location/readme.md) | `fiftyone_location` | diff --git a/ci/build-project.ps1 b/ci/build-project.ps1 index 3461d091..639d7435 100644 --- a/ci/build-project.ps1 +++ b/ci/build-project.ps1 @@ -1,5 +1,8 @@ param ( - [Parameter(Mandatory)][string]$RepoName + [Parameter(Mandatory)][string]$RepoName, + # The branch a pull request merges into, which its changes are measured + # against. + [string]$Branch = 'main' ) $ErrorActionPreference = "Stop" . (Join-Path $PSScriptRoot 'dispatch.ps1') diff --git a/ci/check-environment-variable-names.Tests.ps1 b/ci/check-environment-variable-names.Tests.ps1 index f70f1f79..2274ab4f 100644 --- a/ci/check-environment-variable-names.Tests.ps1 +++ b/ci/check-environment-variable-names.Tests.ps1 @@ -1,165 +1,157 @@ # Tests for ci/check-environment-variable-names.ps1. # -# Each case is one line of text and what the check must make of it. Names are -# matched in any case, because Windows reads an environment variable name in -# any case, so a lower case old name is still the old name there. +# Each case is one line of text and what the check must make of it. The names +# that must fail are made up for these tests. BeforeAll { . (Join-Path $PSScriptRoot 'check-environment-variable-names.ps1') - - function Get-Kind([string]$Line) { - @(Find-EnvironmentNameProblem $Line | ForEach-Object { $_.Kind }) - } } Describe 'Find-EnvironmentNameProblem' { - It 'finds the digit-initial name ' -ForEach @( - @{ Line = '$env:51DEGREES_DD_PATH = "file.hash"' } - @{ Line = 'export 51DEGREES_IPI_PATH=file.ipi' } - @{ Line = 'os.environ.get("51degrees_dd_path")' } - @{ Line = '$env:51Degrees_Resource_Key = "key"' } + It 'finds read or set in ' -ForEach @( + @{ Line = 'os.environ.get("EXAMPLE_SETTING")'; Name = 'EXAMPLE_SETTING' } + @{ Line = "os.environ.get('example_setting', 'none')"; Name = 'example_setting' } + @{ Line = 'os.environ["EXAMPLE_SETTING"] = "value"'; Name = 'EXAMPLE_SETTING' } + @{ Line = 'saved = os.environ.pop("EXAMPLE_SETTING", None)'; Name = 'EXAMPLE_SETTING' } + @{ Line = 'os.environ.setdefault("EXAMPLE_SETTING", "value")'; Name = 'EXAMPLE_SETTING' } + @{ Line = 'value = os.getenv("EXAMPLE_SETTING")'; Name = 'EXAMPLE_SETTING' } + @{ Line = 'if "example_setting" in os.environ:'; Name = 'example_setting' } + @{ Line = 'if "EXAMPLE_SETTING" not in os.environ:'; Name = 'EXAMPLE_SETTING' } + @{ Line = 'monkeypatch.setenv("EXAMPLE_SETTING", "value")'; Name = 'EXAMPLE_SETTING' } + @{ Line = 'monkeypatch.delenv("EXAMPLE_SETTING", raising=False)'; Name = 'EXAMPLE_SETTING' } + @{ Line = '$env:EXAMPLE_SETTING = "value"'; Name = 'EXAMPLE_SETTING' } + @{ Line = 'if (!$Env:Example_Setting) {'; Name = 'Example_Setting' } + @{ Line = '${env:EXAMPLE_SETTING} = "value"'; Name = 'EXAMPLE_SETTING' } + @{ Line = 'Remove-Item Env:EXAMPLE_SETTING'; Name = 'EXAMPLE_SETTING' } + @{ Line = 'Remove-Item Env:\EXAMPLE_SETTING'; Name = 'EXAMPLE_SETTING' } + @{ Line = '[Environment]::SetEnvironmentVariable("EXAMPLE_SETTING", $value)'; Name = 'EXAMPLE_SETTING' } + @{ Line = '[Environment]::GetEnvironmentVariable("EXAMPLE_SETTING")'; Name = 'EXAMPLE_SETTING' } + @{ Line = ' url: ${{ env.EXAMPLE_SETTING }}'; Name = 'EXAMPLE_SETTING' } + @{ Line = 'export EXAMPLE_SETTING=value'; Name = 'EXAMPLE_SETTING' } + # A name has to start with the underscore and be in upper case. + @{ Line = 'os.environ.get("51DEGREES_EXAMPLE_SETTING")'; Name = '51DEGREES_EXAMPLE_SETTING' } + @{ Line = '$env:_51degrees_example_setting = "value"'; Name = '_51degrees_example_setting' } + @{ Line = 'os.environ.get("EXAMPLE_51DEGREES_SETTING")'; Name = 'EXAMPLE_51DEGREES_SETTING' } ) { - Get-Kind $Line | Should -Contain 'digit' + @(Find-EnvironmentNameProblem $Line) | Should -Be @($Name) } - It 'finds the fallback name ' -ForEach @( - @{ Line = 'os.environ.get("RESOURCE_KEY")' } - @{ Line = 'os.environ.get("resource_key")' } - @{ Line = 'os.environ["license_key"]' } - @{ Line = 'os.getenv(''License_Key'')' } - @{ Line = 'if "resource_key" in os.environ:' } - @{ Line = '$env:resource_key = "key"' } - @{ Line = '[Environment]::SetEnvironmentVariable("license_key", $k)' } - @{ Line = 'LEGACY_RESOURCE_KEY_ENV_VAR = "resource_key"' } - @{ Line = 'self.baseURL = os.environ.get("FOD_CLOUD_API_URL")' } - @{ Line = 'FOD_CLOUD_API_URL = "FOD_CLOUD_API_URL"' } - @{ Line = 'saved = os.environ.pop("FOD_CLOUD_API_URL", None)' } - @{ Line = '$env:FOD_CLOUD_API_URL = "https://cloud.51degrees.com/api/v4/"' } - @{ Line = 'key = env("_51DEGREES_RESOURCE_KEY", "resource_key") or os.environ.get("license_key")' } - @{ Line = 'RESOURCE_KEY_ENV_VAR = "resource_key"' } - @{ Line = 'ENDPOINT_ENV_VAR = "cloud_endpoint"' } - @{ Line = 'ORIGIN_ENV_VAR = "cloud_request_origin"' } - @{ Line = 'os.environ.get("cloud_request_origin")' } - @{ Line = '$env:cloud_endpoint = "https://cloud.51degrees.com/api/v4/"' } - @{ Line = '${env:cloud_endpoint} = "https://cloud.51degrees.com/api/v4/"' } - @{ Line = '${Env:RESOURCE_KEY}' } - @{ Line = 'Remove-Item Env:\license_key' } - @{ Line = ' url: ${{ env.cloud_endpoint }}' } - @{ Line = 'env = os.environ.get("IPINTELLIGENCEDATAFILE")' } - @{ Line = 'os.environ["ipintelligencetestkey"] = "value"' } - @{ Line = 'if "run_performance_tests" in os.environ:' } + It 'finds each name once in ' -ForEach @( + @{ Line = 'a = os.environ.get("_51DEGREES_EXAMPLE_SETTING") or os.environ.get("EXAMPLE_SETTING") or os.environ.get("OTHER_SETTING")' + Names = @('EXAMPLE_SETTING', 'OTHER_SETTING') } + @{ Line = '$env:EXAMPLE_SETTING = $env:EXAMPLE_SETTING + $env:TEMP' + Names = @('EXAMPLE_SETTING') } ) { - Get-Kind $Line | Should -Contain 'fallback' + @(Find-EnvironmentNameProblem $Line) | Should -Be $Names } - # cloud_endpoint is a pipeline setting as well as an old variable name, - # and only the variable moves, so a setting written by its key is left - # alone. - It 'leaves alone' -ForEach @( - @{ Line = 'os.environ.get("_51DEGREES_RESOURCE_KEY")' } + It 'leaves alone, as its name starts _51DEGREES_' -ForEach @( + @{ Line = 'os.environ.get("_51DEGREES_EXAMPLE_SETTING")' } + @{ Line = 'os.environ["_51DEGREES_EXAMPLE_SETTING"] = "value"' } + @{ Line = 'if "_51DEGREES_EXAMPLE_SETTING" in os.environ:' } + @{ Line = '$env:_51DEGREES_EXAMPLE_SETTING = "value"' } + @{ Line = '${env:_51DEGREES_EXAMPLE_SETTING} = $value' } + @{ Line = 'Remove-Item Env:_51DEGREES_EXAMPLE_SETTING' } + @{ Line = 'export _51DEGREES_EXAMPLE_SETTING=value' } + @{ Line = ' url: ${{ env._51DEGREES_EXAMPLE_SETTING }}' } + ) { + @(Find-EnvironmentNameProblem $Line) | Should -BeNullOrEmpty + } + + It 'leaves alone, as the platform defines its name' -ForEach @( + @{ Line = 'in_actions = os.environ.get("GITHUB_ACTIONS") == "true"' } + @{ Line = 'if ($env:GITHUB_JOB -eq "Test") {' } + @{ Line = '"key=value" >> $env:GITHUB_OUTPUT' } + @{ Line = '$env:TEMP = New-Item -ItemType Directory -Force -Path "C:\tmp"' } + @{ Line = '$env:TMP = $env:TEMP' } + @{ Line = '$env:PYTEST_ADDOPTS = "$addopts -m `"not live`"".Trim()' } + @{ Line = '$env:PYTHONPATH = Join-Path $PWD ''src''' } + @{ Line = 'export FLASK_APP=app.py' } + @{ Line = '$env:PATH = "$bin;$env:Path"' } + ) { + @(Find-EnvironmentNameProblem $Line) | Should -BeNullOrEmpty + } + + # A setting, a parameter and a request's own environ are not environment + # variables of the process. + It 'leaves alone, as it reads or sets no environment variable' -ForEach @( @{ Line = 'pipeline_settings["cloud_endpoint"] = cloud_endpoint' } - @{ Line = 'resourceKey = "resource_key"' } - @{ Line = 'class IpIntelligenceDataFile(DataFile):' } - @{ Line = 'if isinstance(datafile, IpIntelligenceDataFile):' } - @{ Line = 'RESOURCE_KEY = "resource_key"' } - @{ Line = 'testResourceKey = "resource_key"' } - @{ Line = 'def __init__(self, resource_key, cloud_request_origin=None):' } - @{ Line = '"cloud_request_origin": cloud_request_origin,' } - @{ Line = 'cloudRequestEngineSettings["cloud_endpoint"] = cloudEndPoint' } - @{ Line = 'def run(self, resource_key, logger, cloud_endpoint = None):' } - @{ Line = 'ENDPOINT_VARIABLE = "_51DEGREES_CLOUD_ENDPOINT"' } - @{ Line = '$env:_51DEGREES_DD_PATH = "file.hash"' } - @{ Line = '$env:_51DEGREES_LICENSE_KEY_51DID = $k' } - @{ Line = 'RESOURCE_KEY_ENV_VAR = "_51DEGREES_RESOURCE_KEY"' } @{ Line = 'builder = Builder({"resource_key": "YOUR_RESOURCE_KEY"})' } @{ Line = 'Builder(resource_key=key, license_key=licence)' } - @{ Line = '$env:PAID_RESOURCE_KEY = $Keys.TestResourceKey' } - @{ Line = '${env:_51DEGREES_RESOURCE_KEY} = $Keys.TestResourceKey' } - @{ Line = ' PAID_RESOURCE_KEY: ${{ env.PAID_RESOURCE_KEY }}' } + @{ Line = 'def run(self, resource_key, logger, cloud_endpoint = None):' } + @{ Line = 'EXAMPLE_SETTING = "example_setting"' } + @{ Line = 'raw = request.environ.get("RAW_URI")' } + @{ Line = 'env.pop("EXAMPLE_SETTING", None)' } + @{ Line = 'environment = dict(os.environ, EXAMPLE_SETTING=value)' } + @{ Line = 'pass_env = EXAMPLE_SETTING' } @{ Line = 'Set the 51D_ cookie for the 51Did example.' } + @{ Line = ' env:' } ) { - Get-Kind $Line | Should -BeNullOrEmpty - } - - # A variable whose name changed is still read under its old name when - # the new one is not set. That read gives the old name as the argument - # straight after the new one, and it is left alone. - It 'leaves the deprecated read alone' -ForEach @( - @{ Line = 'RESOURCE = env("_51DEGREES_RESOURCE_KEY", "RESOURCE_KEY")' } - @{ Line = 'LICENCE = env("_51DEGREES_LICENSE_KEY", "license_key")' } - @{ Line = 'API = env("_51DEGREES_CLOUD_ENDPOINT", "FOD_CLOUD_API_URL")' } - @{ Line = 'read_environment("_51DEGREES_IPI_PATH", "IPINTELLIGENCEDATAFILE")' } - @{ Line = ' "_51DEGREES_RUN_PERFORMANCE_TESTS", "run_performance_tests")' } - @{ Line = "read_environment('_51DEGREES_DD_PATH', '51DEGREES_DD_PATH')" } - ) { - Get-Kind $Line | Should -BeNullOrEmpty + @(Find-EnvironmentNameProblem $Line) | Should -BeNullOrEmpty } } -Describe 'Find-EnvironmentNameProblem with the old names a file may hold' { +Describe 'Find-EnvironmentNameProblem in a workflow' { - It 'leaves alone when the file may hold ' -ForEach @( - @{ Line = 'ENDPOINT_ENV_VAR = "cloud_endpoint"'; Allowed = @('cloud_endpoint') } - @{ Line = 'os.environ["resource_key"] = "old-key"'; Allowed = @('resource_key', 'license_key') } - @{ Line = 'DATA_FILE_ENV_VAR = "51DEGREES_DD_PATH"'; Allowed = @('51DEGREES_DD_PATH') } - @{ Line = ' FOD_CLOUD_API_URL'; Allowed = @('FOD_CLOUD_API_URL') } - @{ Line = 'os.environ["RESOURCE_KEY"] = "old-resource-key"'; Allowed = @('RESOURCE_KEY') } + It 'finds , a key of an env map, in ' -ForEach @( + @{ Line = ' EXAMPLE_SETTING: ${{ github.workspace }}/folder'; Name = 'EXAMPLE_SETTING' } + @{ Line = ' EXAMPLE_SETTING: value'; Name = 'EXAMPLE_SETTING' } ) { - @(Find-EnvironmentNameProblem $Line $Allowed) | Should -BeNullOrEmpty + @(Find-EnvironmentNameProblem $Line '.github/workflows/example.yml') | + Should -Be @($Name) } - It 'finds in when the file may hold only ' -ForEach @( - @{ Line = 'ENDPOINT_ENV_VAR = "cloud_endpoint"'; Allowed = @('resource_key'); Kind = 'fallback' } - @{ Line = 'os.environ["license_key"] = "old-key"'; Allowed = @('resource_key'); Kind = 'fallback' } - @{ Line = 'os.environ["RESOURCE_KEY"] = "old-key"'; Allowed = @('resource_key'); Kind = 'fallback' } - @{ Line = ' IPINTELLIGENCEDATAFILE'; Allowed = @('FOD_CLOUD_API_URL'); Kind = 'fallback' } - @{ Line = 'DATA_FILE_ENV_VAR = "51DEGREES_IPI_PATH"'; Allowed = @('51DEGREES_DD_PATH'); Kind = 'digit' } - @{ Line = ' 51DEGREES_DD_PATH_OTHER'; Allowed = @('51DEGREES_DD_PATH'); Kind = 'digit' } - @{ Line = 'DATA_FILE_ENV_VAR = "51DEGREES_DD_PATH"'; Allowed = @(); Kind = 'digit' } + It 'leaves alone' -ForEach @( + @{ Line = ' _51DEGREES_EXAMPLE_SETTING: ${{ secrets._51DEGREES_EXAMPLE_SETTING }}' } + @{ Line = ' CLOUD_STAGING_ENDPOINT: ${{ vars.CLOUD_STAGING_ENDPOINT }}' } + @{ Line = ' RESOURCE_KEY_BESPOKE_STAGING: ${{ secrets.RESOURCE_KEY_BESPOKE_STAGING }}' } + @{ Line = ' GITHUB_TOKEN: ${{ github.token }}' } + @{ Line = ' uses: actions/checkout@v4' } + @{ Line = ' runs-on: ubuntu-latest' } + @{ Line = ' shell: pwsh' } ) { - @(Find-EnvironmentNameProblem $Line $Allowed | ForEach-Object { $_.Kind }) | - Should -Contain $Kind + @(Find-EnvironmentNameProblem $Line '.github/workflows/example.yml') | + Should -BeNullOrEmpty } -} - -Describe 'Get-FallbackName' { - It 'lets hold ' -ForEach @( - @{ Path = 'pipeline/fiftyone_pipeline_did/tox.ini'; Name = 'FOD_CLOUD_API_URL' } - @{ Path = 'device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/example_utils.py'; Name = '51DEGREES_DD_PATH' } - @{ Path = 'device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/example_utils.py'; Name = 'cloud_endpoint' } - @{ Path = 'ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/example_utils.py'; Name = 'IPINTELLIGENCEDATAFILE' } - @{ Path = 'pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/constants.py'; Name = 'FOD_CLOUD_API_URL' } - @{ Path = 'pipeline/fiftyone_pipeline_cloudrequestengine/readme.md'; Name = 'FOD_CLOUD_API_URL' } - @{ Path = 'pipeline/fiftyone_pipeline_did/src/fiftyone_pipeline_did/did_client.py'; Name = 'FOD_CLOUD_API_URL' } - @{ Path = 'pipeline/fiftyone_pipeline_did/tests/test_live_cloud.py'; Name = 'resource_key' } + It 'reads a key of a map only in a workflow, so is left alone' -ForEach @( + @{ Path = 'ci/packages.json' } + @{ Path = 'device-detection/readme.md' } + @{ Path = '' } ) { - @(Get-FallbackName $Path) | Should -Contain $Name + @(Find-EnvironmentNameProblem ' EXAMPLE_SETTING: value' $Path) | + Should -BeNullOrEmpty } +} + +Describe 'Test-EnvironmentName' { - It 'does not let hold ' -ForEach @( - @{ Path = 'pipeline/fiftyone_pipeline_did/tox.ini'; Name = '51DEGREES_DD_PATH' } - @{ Path = 'pipeline/fiftyone_pipeline_did/src/fiftyone_pipeline_did/did_client.py'; Name = 'resource_key' } - @{ Path = 'pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/constants.py'; Name = '51DEGREES_DD_PATH' } - @{ Path = 'ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/example_utils.py'; Name = '51DEGREES_DD_PATH' } - @{ Path = 'device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/example_utils.py'; Name = 'IPINTELLIGENCEDATAFILE' } + It 'takes ' -ForEach @( + @{ Name = '_51DEGREES_EXAMPLE_SETTING' } + @{ Name = 'GITHUB_ENV' } + @{ Name = 'TEMP' } + @{ Name = 'PSModulePath' } + # Names only CI uses. + @{ Name = 'CLOUD_STAGING_ENDPOINT' } + @{ Name = 'RESOURCE_KEY_BESPOKE_STAGING' } ) { - @(Get-FallbackName $Path) | Should -Not -Contain $Name + Test-EnvironmentName $Name | Should -BeTrue } - It 'lets hold no old name' -ForEach @( - @{ Path = 'ci/run-unit-tests.ps1' } - @{ Path = 'readme.md' } - @{ Path = 'pipeline/fiftyone_pipeline_core/src/fiftyone_pipeline_core/pipeline.py' } - @{ Path = 'pipeline/fiftyone_pipeline_core/readme.md' } - @{ Path = 'device-detection/fiftyone_devicedetection_examples/tests/test_cloudexamples.py' } - @{ Path = 'device-detection/ci/run-integration-tests.ps1' } - @{ Path = 'pipeline/fiftyone_pipeline_did/tests/test_did_client_live.py' } - @{ Path = 'location/examples/cloud/gettingstarted.py' } - @{ Path = 'some/new/package/tox.ini' } - @{ Path = 'some/new/example_utils.py' } + It 'refuses ' -ForEach @( + @{ Name = 'EXAMPLE_SETTING' } + @{ Name = '_51degrees_example_setting' } + @{ Name = '51DEGREES_EXAMPLE_SETTING' } + @{ Name = 'TEMPORARY' } + @{ Name = 'MY_GITHUB_SETTING' } + # Look-alikes of the names only CI uses. + @{ Name = 'cloud_staging_endpoint' } + @{ Name = 'CLOUD_STAGING_ENDPOINT_URL' } + @{ Name = 'CLOUD_ENDPOINT' } + @{ Name = 'RESOURCE_KEY_BESPOKE' } + @{ Name = 'RESOURCE_KEY_BASIC_STAGING' } ) { - @(Get-FallbackName $Path) | Should -BeNullOrEmpty + Test-EnvironmentName $Name | Should -BeFalse } } diff --git a/ci/check-environment-variable-names.ps1 b/ci/check-environment-variable-names.ps1 index 5283cd81..e808fdd7 100644 --- a/ci/check-environment-variable-names.ps1 +++ b/ci/check-environment-variable-names.ps1 @@ -1,19 +1,15 @@ -# Every 51Degrees environment variable name in this repository starts with an -# underscore, because a POSIX shell cannot set a name that starts with a digit, -# and everything documents that one name. This reads every file git tracks, -# which leaves out build output and the submodules, and fails on any name -# that starts with the digit and on any old name. +# Every environment variable this repository defines is named _51DEGREES_, +# so wherever it appears it is clearly 51Degrees. This reads every file git +# tracks, which leaves out build output and the submodules, and fails on any +# line that reads or sets an environment variable under another name. # -# A variable whose name changed is still read under its old name when the new -# one is not set, which is deprecated. So an old name is left alone in the two -# places that read needs it. One is a line where the old name is the argument -# straight after its _51DEGREES_ name, which is how each deprecated read is -# written. The other is the files $FallbackNames lists, each of which may hold -# the old names it is listed with and no others. +# A name that GitHub, the operating system or a tool defines is used as it +# is. $PlatformNames lists the ones this repository uses. The few names only +# CI uses, which no customer sets, are in $CiNames. # -# Names are matched in any case, because Windows reads an environment -# variable name in any case, so a lower case old name is still the old name -# there. +# Only a name written out where a variable is read or set is checked. A +# pipeline setting, a builder parameter and a request's own environ are not +# environment variables of the process, so they are left alone. # # Dot-sourcing the script defines Find-EnvironmentNameProblem without reading # the repository, which is how its tests use it. @@ -28,181 +24,87 @@ param( Set-StrictMode -Version Latest $ErrorActionPreference = 'Stop' -# The start of a name a shell cannot set, split so this file does not match -# itself. -$digitInitial = '5' + '1DEGREES_' - -# A name is not matched when a name character comes before it, so a name with -# a leading underscore is left alone. -$script:DigitInitialPattern = [regex]::new( - "(?[A-Za-z0-9_]+)' +$quoted = "['`"]$name['`"]" + +# Each way a line reads or sets an environment variable by a name written out. +$script:ReadOrSetPatterns = @( + # Python: a name given to os.environ, to its get, pop and setdefault, to + # os.getenv and to pytest's setenv and delenv, and a name looked for in + # os.environ. + ('os\.environ(?:\.get|\.pop|\.setdefault)?\s*[\(\[]\s*' + $quoted) + ('os\.getenv\(\s*' + $quoted) + ($quoted + '\s+(?:not\s+)?in\s+os\.environ') + ('\.(?:setenv|delenv)\(\s*' + $quoted) + # PowerShell: a name after the env: prefix, with or without braces, a + # path on the Env: drive, and the [Environment] methods. + ('\$\{?env:' + $name) + ('(?[A-Z_][A-Z0-9_]*):(?:\s|$)') -# The old names each file may hold. The files are the ones that hold the -# deprecated constants, the documentation that says an old name is still -# read, the tests that set an old name to check it is read, and the lists of -# names tox passes to the tests. A file is given by its path from the root of -# the repository, and may hold only the names it is listed with, so any other -# old name still fails there, and so does any other name that starts with a -# digit. The names that are matched wherever they appear are built from -# pieces, so that this file does not name one itself. -$endpointOld = 'FOD_CLOUD' + '_API_URL' -$ipiFileOld = 'IPINTELLIGENCE' + 'DATAFILE' -$performanceOld = 'run_performance' + '_tests' -$ddPathOld = '5' + '1DEGREES_DD_PATH' -$script:FallbackNames = @( - @{ - Names = @($ddPathOld, 'LICENSE_KEY') - Paths = @( - 'device-detection/fiftyone_devicedetection_examples/tests/test_environment_names.py' - ) - } - @{ - Names = @($ddPathOld, 'cloud_endpoint', 'license_key', 'resource_key') - Paths = @( - 'device-detection/fiftyone_devicedetection_examples/src/fiftyone_devicedetection_examples/example_utils.py' - ) - } - @{ - Names = @($endpointOld) - Paths = @( - 'pipeline/fiftyone_pipeline_cloudrequestengine/examples/tox.ini' - 'pipeline/fiftyone_pipeline_cloudrequestengine/readme.md' - 'pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/cloudrequestengine.py' - 'pipeline/fiftyone_pipeline_cloudrequestengine/src/fiftyone_pipeline_cloudrequestengine/constants.py' - 'pipeline/fiftyone_pipeline_cloudrequestengine/tests/test_cloudrequestengine.py' - 'pipeline/fiftyone_pipeline_did/examples/creator_context_web/server.py' - 'pipeline/fiftyone_pipeline_did/readme.md' - 'pipeline/fiftyone_pipeline_did/src/fiftyone_pipeline_did/did_client.py' - 'pipeline/fiftyone_pipeline_did/tests/test_did_client.py' - 'pipeline/fiftyone_pipeline_did/tox.ini' - ) - } - @{ - Names = @($endpointOld, 'LICENSE_KEY', 'RESOURCE_KEY') - Paths = @( - 'pipeline/fiftyone_pipeline_did/tests/test_creator_context_server.py' - ) +# Whether a name may be read or set: one this repository defines, one only CI +# uses, or one the platform does. +function Test-EnvironmentName([string]$Name) { + if ($Name.StartsWith($script:Prefix, [StringComparison]::Ordinal)) { + return $true } - @{ - Names = @($ipiFileOld) - Paths = @( - 'ip-intelligence/fiftyone_ipintelligence_examples/tox.ini' - 'ip-intelligence/fiftyone_ipintelligence_onpremise/tests/test_environment_names.py' - 'ip-intelligence/fiftyone_ipintelligence_onpremise/tox.ini' - ) + if ($script:CiNames -ccontains $Name) { + return $true } - @{ - Names = @($ipiFileOld, 'LICENSE_KEY') - Paths = @( - 'ip-intelligence/fiftyone_ipintelligence_examples/tests/test_environment_names.py' - ) + if ($script:PlatformNames -contains $Name) { + return $true } - @{ - Names = @($ipiFileOld, 'cloud_endpoint', 'license_key', 'resource_key') - Paths = @( - 'ip-intelligence/fiftyone_ipintelligence_examples/src/fiftyone_ipintelligence_examples/example_utils.py' - ) - } - @{ - Names = @('cloud_endpoint', 'cloud_request_origin', 'license_key', 'resource_key') - Paths = @( - 'pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/example_utils.py' - ) - } - @{ - Names = @('license_key', 'resource_key') - Paths = @( - 'pipeline/fiftyone_pipeline_did/tests/test_live_cloud.py' - ) - } - @{ - Names = @($performanceOld) - Paths = @( - 'device-detection/fiftyone_devicedetection_examples/tox.ini' - ) - } -) - -# The old names a file may hold, given its path from the root of the -# repository written with forward slashes. Nothing for any other file. -function Get-FallbackName([string]$Relative) { - foreach ($entry in $script:FallbackNames) { - if ($entry.Paths -ccontains $Relative) { - $entry.Names + foreach ($prefix in $script:PlatformPrefixes) { + if ($Name.StartsWith($prefix, [StringComparison]::OrdinalIgnoreCase)) { + return $true } } + return $false } -# The problems on one line, each as its kind, 'digit' or 'fallback', and the -# text matched. Allowed holds the old names the line's file may hold, which -# are taken out of the line, in the case they are written in, before the -# line is checked. -function Find-EnvironmentNameProblem([string]$Line, [string[]]$Allowed = @()) { - $Line = $script:DeprecatedReadPattern.Replace($Line, '$1""') - if ($Allowed.Count -gt 0) { - $names = ($Allowed | ForEach-Object { [regex]::Escape($_) }) -join '|' - $Line = [regex]::Replace( - $Line, "(?' -ForEach $script:Scripts { + (Get-Command $Full).Parameters.ContainsKey('Keys') | Should -BeFalse + } + + It 'gives a common-ci script only the parameters it declares in ' -ForEach $script:Scripts { + $unknown = foreach ($call in (Get-CommonCiCalls $Full)) { + $target = Join-Path $script:CommonCiSource $call.Script + $target | Should -Exist -Because "line $($call.Line) calls it" + $declared = (Get-Command $target).Parameters + foreach ($parameter in $call.Parameters) { + if ($declared.ContainsKey($parameter) -eq $false) { + "line $($call.Line): -$parameter is not a parameter of $($call.Script)" + } + } + } + $unknown | Should -BeNullOrEmpty + } +} + +Describe 'The integration test step as common-ci runs it' { + + BeforeEach { + $script:Saved = @{} + foreach ($name in '_51DEGREES_RESOURCE_KEY', '_51DEGREES_RESOURCE_KEY_BESPOKE', + 'PYTEST_ADDOPTS', 'TEMP') { + $script:Saved[$name] = [Environment]::GetEnvironmentVariable($name) + } + $env:_51DEGREES_RESOURCE_KEY = $null + $env:_51DEGREES_RESOURCE_KEY_BESPOKE = $null + $env:PYTEST_ADDOPTS = $null + + # A folder laid out like a common-ci checkout, with this repository + # inside it under its own name. Its python/run-integration-tests.ps1 + # has the parameters of common-ci's own, runs no tests, and records + # the product of each call. + $script:CommonCi = Join-Path ([IO.Path]::GetTempPath()) ([Guid]::NewGuid().ToString()) + $null = New-Item -ItemType Directory -Force (Join-Path $script:CommonCi 'python') + Copy-Item -Recurse (Join-Path $script:CommonCiSource 'steps') ` + (Join-Path $script:CommonCi 'steps') + $real = Join-Path $script:CommonCiSource 'python' 'run-integration-tests.ps1' + $block = [Management.Automation.Language.Parser]::ParseFile( + $real, [ref]$null, [ref]$null).ParamBlock.Extent.Text + Set-Content (Join-Path $script:CommonCi 'python' 'run-integration-tests.ps1') @" +$block +Add-Content (Join-Path `$PWD 'calls.txt') (Split-Path `$RepoName -Leaf) +`$global:LASTEXITCODE = 0 +"@ + $script:RepoName = Split-Path -Leaf $script:Repo + $link = Join-Path $script:CommonCi $script:RepoName + $null = New-Item -ItemType Junction -Path $link -Target $script:Repo -ErrorAction SilentlyContinue + if ((Test-Path $link) -eq $false) { + $null = New-Item -ItemType SymbolicLink -Path $link -Target $script:Repo + } + Push-Location $script:CommonCi + } + + AfterEach { + Pop-Location + # The link is removed on its own first, so that removing the folder + # never follows it into this repository. + (Get-Item (Join-Path $script:CommonCi $script:RepoName)).Delete() + Remove-Item -Recurse -Force $script:CommonCi + foreach ($name in $script:Saved.Keys) { + [Environment]::SetEnvironmentVariable($name, $script:Saved[$name]) + } + } + + It 'runs every product''s tests from the options of a build, which hold no keys' { + # The options common-ci builds: an entry of ci/options.json, and the + # parameters of its build and test script. No branch has this name, + # so every product counts as changed. + $options = @{ + Name = 'Ubuntu_Python_3.12' + Image = 'ubuntu-latest' + Language = 'python' + LanguageVersion = '3.12' + RunPerformance = $true + PackageRequirement = $true + RepoName = $script:RepoName + OrgName = '51Degrees' + Branch = 'a-branch-that-does-not-exist' + PullRequestId = '1' + DryRun = $true + SkipLiteTests = $false + } + + ./steps/run-script.ps1 "./$($script:RepoName)/ci/run-integration-tests.ps1" $options *>&1 | + Out-Null + + $calls = @(Get-Content (Join-Path $script:CommonCi 'calls.txt')) + foreach ($product in 'device-detection', 'ip-intelligence', 'location', 'pipeline') { + $calls | Should -Contain $product + } + } +} diff --git a/ci/device-detection-performance.Tests.ps1 b/ci/device-detection-performance.Tests.ps1 new file mode 100644 index 00000000..d1208cb3 --- /dev/null +++ b/ci/device-detection-performance.Tests.ps1 @@ -0,0 +1,102 @@ +# Tests for device-detection/ci/run-performance-tests.ps1. +# +# common-ci runs the script from its own folder, which holds the assets, with +# the product folder as RepoName. Each test lays out such a folder with empty +# stand-ins for the data files, and mocks python, so that what is checked is +# which data file the script measures on, not the measurement itself. + +BeforeAll { + $script:Script = Join-Path $PSScriptRoot '..' 'device-detection' 'ci' ` + 'run-performance-tests.ps1' + + # The name of the file given to the console benchmark as an option. + function Get-FileArgument([object[]]$Arguments, [string]$Option) { + $index = [Array]::IndexOf($Arguments, $Option) + if ($index -lt 0) { + return $null + } + return Split-Path -Leaf $Arguments[$index + 1] + } + + # The name of the file given to the console benchmark as --data_file. + function Get-DataFileArgument([object[]]$Arguments) { + return Get-FileArgument $Arguments '--data_file' + } +} + +Describe 'device-detection run-performance-tests.ps1' { + +BeforeEach { + $script:CommonCi = Join-Path ([IO.Path]::GetTempPath()) ` + ([Guid]::NewGuid().ToString()) + $script:Assets = New-Item -ItemType Directory -Force ` + (Join-Path $script:CommonCi 'assets') + $script:Product = (New-Item -ItemType Directory -Force ` + (Join-Path $script:CommonCi 'device-detection')).FullName + foreach ($name in '51Degrees-LiteV4.1.hash', '20000 Evidence Records.yml') { + Set-Content (Join-Path $script:Assets $name) '' + } + + # The console benchmark writes its summary where --json_output says. + Mock python { + $index = [Array]::IndexOf($args, '--json_output') + if ($index -ge 0) { + '{ "DetectionsPerSecond": 1, "MsPerDetection": 1 }' | + Set-Content $args[$index + 1] + } + } + + Push-Location $script:CommonCi +} + +AfterEach { + Pop-Location + Remove-Item -Recurse -Force $script:CommonCi +} + +It 'measures on the free Lite file when the TAC file is absent' { + $output = & $script:Script -RepoName $script:Product -Name 'test' | + Out-String + + Should -Invoke python -Times 1 -Exactly -ParameterFilter { + (Get-DataFileArgument $args) -eq '51Degrees-LiteV4.1.hash' + } + $output | Should -Match 'on 51Degrees-LiteV4\.1\.hash' + Join-Path $script:Product 'test-results' 'performance-summary' ` + 'results_test.json' | Should -Exist +} + +It 'measures on the TAC file when it is there' { + Set-Content (Join-Path $script:Assets 'TAC-HashV41.hash') '' + + $output = & $script:Script -RepoName $script:Product -Name 'test' | + Out-String + + Should -Invoke python -Times 1 -Exactly -ParameterFilter { + (Get-DataFileArgument $args) -eq 'TAC-HashV41.hash' + } + $output | Should -Match 'on TAC-HashV41\.hash' +} + +It 'gives both benchmarks the YAML evidence' { + & $script:Script -RepoName $script:Product -Name 'test' | Out-Null + + # The console benchmark takes the evidence as an option. + Should -Invoke python -Times 1 -Exactly -ParameterFilter { + (Get-FileArgument $args '--evidence_file') -eq '20000 Evidence Records.yml' + } + # The web benchmark takes the data file and then the evidence. + Should -Invoke python -Times 1 -Exactly -ParameterFilter { + $args -contains '--output' -and + (Split-Path -Leaf $args[2]) -eq '20000 Evidence Records.yml' + } +} + +It 'runs nothing when performance is turned off' { + & $script:Script -RepoName $script:Product -Name 'test' ` + -RunPerformance $false + + Should -Invoke python -Times 0 -Exactly +} + +} diff --git a/ci/dispatch.Tests.ps1 b/ci/dispatch.Tests.ps1 index 3d75e0a2..b7cb49e6 100644 --- a/ci/dispatch.Tests.ps1 +++ b/ci/dispatch.Tests.ps1 @@ -2,21 +2,26 @@ # # Each test builds a throwaway repository with two products, 'alpha' and # 'beta', whose ci/ scripts are written by the test, and runs the dispatcher -# from a folder laid out like a common-ci checkout, with common-ci's real -# steps/run-script.ps1, because that is how common-ci calls it. +# from a folder laid out like a common-ci checkout, with a copy of common-ci's +# real steps folder, because that is how common-ci calls it. BeforeAll { . (Join-Path $PSScriptRoot 'dispatch.ps1') - # common-ci checked out beside this repository, or wherever COMMON_CI says. - $commonCi = $env:COMMON_CI + # common-ci checked out beside this repository, or wherever + # _51DEGREES_COMMON_CI_DIR says. + $commonCi = $env:_51DEGREES_COMMON_CI_DIR if ([string]::IsNullOrEmpty($commonCi) -eq $true) { $commonCi = Join-Path $PSScriptRoot '..' '..' 'common-ci' } $script:RunScript = Join-Path $commonCi 'steps' 'run-script.ps1' if ((Test-Path $script:RunScript) -eq $false) { - throw "common-ci not found at '$commonCi'; set COMMON_CI to a checkout of it" + throw "common-ci not found at '$commonCi'; set _51DEGREES_COMMON_CI_DIR to a checkout of it" } + # The whole steps folder is copied, because ci/packages.ps1 loads the + # release plan from the common-ci checkout that holds this repository's + # folder, and the release plan may load other steps beside it. + $script:Steps = Join-Path $commonCi 'steps' # A repository with packages.json naming one package in each product. function New-ProductRepo { @@ -42,11 +47,21 @@ BeforeAll { "param ([Parameter(Mandatory)][string]`$RepoName)`n$Body" } + # The body of a product's run-performance-tests step that writes the + # summary of the configuration 'test' with the given figures. + function Get-SummaryStep([hashtable]$Higher, [hashtable]$Lower) { + $json = @{ HigherIsBetter = $Higher; LowerIsBetter = $Lower } | + ConvertTo-Json -Compress + return '$dir = New-Item -ItemType Directory -Force ' + + '(Join-Path $RepoName "test-results" "performance-summary"); ' + + "Set-Content (Join-Path `$dir 'results_test.json') '$json'" + } + # A folder laid out like a common-ci checkout, which the dispatcher runs in. function New-CommonCi { $path = Join-Path ([IO.Path]::GetTempPath()) ([Guid]::NewGuid().ToString()) - $steps = New-Item -ItemType Directory -Force (Join-Path $path 'steps') - Copy-Item $script:RunScript $steps + $null = New-Item -ItemType Directory -Force $path + Copy-Item -Recurse $script:Steps (Join-Path $path 'steps') return $path } } @@ -114,6 +129,38 @@ Describe 'Invoke-ProductStep' { Test-Path (Join-Path $script:Repo 'alpha' 'test-results') | Should -BeFalse } + It 'keeps every product''s figures in the one summary of a configuration' { + # common-ci compares one results_.json for each configuration. + Set-ProductStep $script:Repo 'alpha' 'run-performance-tests' ` + (Get-SummaryStep @{ alpha_PerSecond = 1 } @{ alpha_Ms = 2 }) + Set-ProductStep $script:Repo 'beta' 'run-performance-tests' ` + (Get-SummaryStep @{ beta_PerSecond = 3 } @{ beta_Ms = 4 }) + + Invoke-ProductStep 'run-performance-tests' $script:Repo @{ + RepoName = $script:Repo } + + $results = Get-Content (Join-Path $script:Repo 'test-results' ` + 'performance-summary' 'results_test.json') | ConvertFrom-Json + $results.HigherIsBetter.alpha_PerSecond | Should -Be 1 + $results.HigherIsBetter.beta_PerSecond | Should -Be 3 + $results.LowerIsBetter.alpha_Ms | Should -Be 2 + $results.LowerIsBetter.beta_Ms | Should -Be 4 + } + + It 'fails the step when two products report the same figure' { + Set-ProductStep $script:Repo 'alpha' 'run-performance-tests' ` + (Get-SummaryStep @{ PerSecond = 1 } @{}) + Set-ProductStep $script:Repo 'beta' 'run-performance-tests' ` + (Get-SummaryStep @{ PerSecond = 3 } @{}) + + { Invoke-ProductStep 'run-performance-tests' $script:Repo @{ + RepoName = $script:Repo } } | Should -Throw '*failed for: beta' + + $results = Get-Content (Join-Path $script:Repo 'test-results' ` + 'performance-summary' 'results_test.json') | ConvertFrom-Json + $results.HigherIsBetter.PerSecond | Should -Be 1 + } + It 'fetches assets when called without a repository name' { # common-ci's prefetch_assets action runs ci/fetch-assets.ps1 directly # with only the keys, from the common-ci checkout that holds this @@ -139,7 +186,7 @@ Describe 'Invoke-ProductStep' { Set-ProductStep $script:Repo 'beta' 'run-integration-tests' 'Write-Output ok' { Invoke-ProductStep 'run-integration-tests' $script:Repo @{ - RepoName = $script:Repo; Keys = @{ TestResourceKey = 'x' } } } | + RepoName = $script:Repo; Keys = @{ AnySecret = 'x' } } } | Should -Not -Throw } } diff --git a/ci/dispatch.ps1 b/ci/dispatch.ps1 index 4249d40b..f06d2a35 100644 --- a/ci/dispatch.ps1 +++ b/ci/dispatch.ps1 @@ -10,12 +10,15 @@ # Runs $Step for each affected product, or for each of $Products when given. # Every product is run even when an earlier one fails, so one run reports -# every broken product, and the step fails at the end if any did. +# every broken product, and the step fails at the end if any did. A pull +# request's changes are measured from the Branch in $Options, the branch it +# merges into. function Invoke-ProductStep([string]$Step, [string]$RepoName, [Collections.IDictionary]$Options, [string[]]$Products) { $failed = [Collections.Generic.List[string]]::new() if (-not $Products) { - $Products = Get-AffectedProducts $RepoName + $branch = $Options.Branch ? $Options.Branch : 'main' + $Products = Get-AffectedProducts $RepoName $branch } foreach ($product in $Products) { $script = Join-Path $RepoName $product 'ci' "$Step.ps1" @@ -36,7 +39,14 @@ function Invoke-ProductStep([string]$Step, [string]$RepoName, Write-Output "::error title=$Step failed::$product`: $_" $failed.Add($product) } finally { - Move-ProductTestResults $RepoName $product + try { + Move-ProductTestResults $RepoName $product + } catch { + Write-Output "::error title=$Step failed::$product`: $_" + if ($failed.Contains($product) -eq $false) { + $failed.Add($product) + } + } Write-Output "::endgroup::" } } @@ -48,6 +58,8 @@ function Invoke-ProductStep([string]$Step, [string]$RepoName, # common-ci collects test results from /test-results, and a # product's own scripts write them under its folder, where they would not be # found. Move them up, keeping the unit/integration/performance folders. +# common-ci compares one performance summary for each configuration, so a +# summary another product already wrote gets this product's figures added. function Move-ProductTestResults([string]$RepoName, [string]$Product) { $results = Join-Path $RepoName $Product 'test-results' if ((Test-Path $results) -eq $false) { @@ -56,7 +68,39 @@ function Move-ProductTestResults([string]$RepoName, [string]$Product) { foreach ($kind in (Get-ChildItem -Directory $results)) { $target = New-Item -ItemType Directory -Force ` (Join-Path $RepoName 'test-results' $kind.Name) - Get-ChildItem $kind.FullName | Move-Item -Destination $target -Force + foreach ($file in (Get-ChildItem $kind.FullName)) { + $existing = Join-Path $target $file.Name + if ($kind.Name -eq 'performance-summary' -and + $file.Extension -eq '.json' -and + (Test-Path $existing -PathType Leaf) -eq $true) { + Add-PerformanceFigures $file.FullName $existing + } else { + Move-Item $file.FullName -Destination $target -Force + } + } } Remove-Item -Recurse -Force $results } + +# Adds the HigherIsBetter and LowerIsBetter figures of the summary at $Source +# to the one at $Destination. A figure already in $Destination fails, because +# one of the two would be lost. +function Add-PerformanceFigures([string]$Source, [string]$Destination) { + $from = Get-Content -Raw $Source | ConvertFrom-Json -AsHashtable + $into = Get-Content -Raw $Destination | ConvertFrom-Json -AsHashtable + foreach ($section in 'HigherIsBetter', 'LowerIsBetter') { + if ($null -eq $from[$section]) { + continue + } + if ($null -eq $into[$section]) { + $into[$section] = [ordered]@{} + } + foreach ($metric in $from[$section].Keys) { + if ($into[$section].Contains($metric) -eq $true) { + throw "$section.$metric is in both '$Source' and '$Destination'" + } + $into[$section][$metric] = $from[$section][$metric] + } + } + $into | ConvertTo-Json -Depth 10 | Set-Content $Destination +} diff --git a/ci/fetch-assets.ps1 b/ci/fetch-assets.ps1 index 802476f1..6ca6495c 100644 --- a/ci/fetch-assets.ps1 +++ b/ci/fetch-assets.ps1 @@ -4,11 +4,11 @@ param ( # this repository's folder is the default. It is relative to the # common-ci checkout, which is where both callers run it from. [string]$RepoName = (Split-Path -Leaf (Split-Path -Parent $PSScriptRoot)), - [string]$DeviceDetection, - [string]$DeviceDetectionUrl, - [string]$CsvUrl, - [string]$IpIntelligence, - [string]$IpIntelligenceUrl + # No key is taken: common-ci downloads the data files with the + # _51DEGREES_LICENSE_KEY it exports. + # The branch a pull request merges into, which its changes are measured + # against. + [string]$Branch = 'main' ) $ErrorActionPreference = "Stop" . (Join-Path $PSScriptRoot 'dispatch.ps1') diff --git a/ci/free-threaded-python.Tests.ps1 b/ci/free-threaded-python.Tests.ps1 new file mode 100644 index 00000000..8f95fe3f --- /dev/null +++ b/ci/free-threaded-python.Tests.ps1 @@ -0,0 +1,176 @@ +# Tests that .github/workflows/free-threaded-python.yml fetches the free Lite +# data files once, in one job, and that the jobs that test take them from the +# cache that job fills, rather than each downloading them again. +# The workflow is read as text, as the runners have no YAML module. + +BeforeAll { + $script:Workflow = Join-Path $PSScriptRoot '..' '.github' 'workflows' ` + 'free-threaded-python.yml' + $lines = @(Get-Content -LiteralPath $script:Workflow) + + # Each job's lines, by the job's name, from the two-space keys under jobs. + $script:Jobs = [ordered]@{} + $inJobs = $false + $name = $null + foreach ($line in $lines) { + if ($line -match '^\S') { + $inJobs = $line -match '^jobs:\s*$' + $name = $null + continue + } + if (-not $inJobs) { continue } + if ($line -match '^ ([\w-]+):\s*$') { + $name = $Matches[1] + $script:Jobs[$name] = [System.Collections.Generic.List[string]]::new() + continue + } + if ($name) { $script:Jobs[$name].Add($line) } + } + + # The text of the step that uses the action given, from its "- name:" or + # "- uses:" line to the next step. + function Get-Step([string]$Job, [string]$Uses) { + $steps = @() + $current = $null + foreach ($line in $script:Jobs[$Job]) { + if ($line -match '^ - ') { + if ($null -ne $current) { $steps += , $current } + $current = [System.Collections.Generic.List[string]]::new() + } + if ($null -ne $current) { $current.Add($line) } + } + if ($null -ne $current) { $steps += , $current } + return @($steps | Where-Object { + ($_ -join "`n") -match "uses:\s*$([regex]::Escape($Uses))@" }) + } + + # The lines of a "path: |" block in a step, trimmed. + function Get-Paths($Step) { + $paths = @() + $inPaths = $false + foreach ($line in $Step) { + if ($line -match '^\s+path:\s*\|\s*$') { $inPaths = $true; continue } + if ($inPaths -and $line -match '^\s{12,}\S') { + $paths += $line.Trim() + continue + } + $inPaths = $false + } + return $paths + } + + function Get-Value($Step, [string]$Key) { + foreach ($line in $Step) { + if ($line -match "^\s+$Key\:\s*(.+?)\s*$") { return $Matches[1] } + } + } + + $script:Fetching = @($script:Jobs.Keys | Where-Object { + ($script:Jobs[$_] -join "`n") -match 'get-data-files\.ps1' }) + $script:Testing = @($script:Jobs.Keys | Where-Object { + ($script:Jobs[$_] -join "`n") -match 'pytest' }) +} + +Describe 'free-threaded-python.yml' { + It 'downloads the free data files in one job only' { + $script:Fetching.Count | Should -Be 1 + } + + It 'downloads them in a job that is not a matrix' { + foreach ($job in $script:Fetching) { + ($script:Jobs[$job] -join "`n") | Should -Not -Match 'matrix:' + } + } + + It 'never downloads them in a job that runs the tests' { + $script:Testing.Count | Should -BeGreaterThan 0 + foreach ($job in $script:Testing) { + $script:Fetching | Should -Not -Contain $job + } + } + + It 'saves them in the cache, and downloads them only when it misses' { + $job = $script:Fetching[0] + $cache = @(Get-Step $job 'actions/cache') + $cache.Count | Should -Be 1 + Get-Value $cache[0] 'id' | Should -Not -BeNullOrEmpty + $id = Get-Value $cache[0] 'id' + $fetch = ($script:Jobs[$job] -join "`n") + $fetch | Should -Match ("if:\s*steps\.$id\.outputs\.cache-hit\s*!=\s*" + + "'true'\s*\n\s+run:\s*[|]?\s*\n?\s*\./cxx/data/get-data-files\.ps1") + } + + It 'restores them in each job that runs the tests, from the same key and paths' { + $job = $script:Fetching[0] + $save = @(Get-Step $job 'actions/cache')[0] + $keyStep = Get-Value $save 'key' + $keyStep | Should -Match '^\$\{\{\s*steps\.([\w-]+)\.outputs\.key\s*\}\}$' + ($script:Jobs[$job] -join "`n") | Should -Match ( + '\n outputs:\s*\n\s+key:\s*' + [regex]::Escape($keyStep)) + foreach ($testing in $script:Testing) { + $text = $script:Jobs[$testing] -join "`n" + $text | Should -Match "\n needs:\s*\[?\s*$([regex]::Escape($job))\b" + $restore = @(Get-Step $testing 'actions/cache/restore') + $restore.Count | Should -Be 1 + Get-Value $restore[0] 'key' | + Should -Be ('${{ needs.' + $job + '.outputs.key }}') + Get-Value $restore[0] 'fail-on-cache-miss' | Should -Be 'true' + Get-Paths $restore[0] | Should -Be (Get-Paths $save) + } + } + + It 'saves and restores across operating systems, for the Windows jobs' { + $job = $script:Fetching[0] + $steps = @(Get-Step $job 'actions/cache') + @($script:Testing | + ForEach-Object { Get-Step $_ 'actions/cache/restore' }) + $steps.Count | Should -BeGreaterThan 1 + foreach ($step in $steps) { + Get-Value $step 'enableCrossOsArchive' | Should -Be 'true' + } + } + + It 'writes the package versions before it installs the packages from this checkout' { + foreach ($testing in $script:Testing) { + $text = $script:Jobs[$testing] -join "`n" + $write = $text.IndexOf('./ci/write-package-versions.ps1') + $install = $text.IndexOf('-e pipeline/') + $write | Should -BeGreaterThan -1 + $install | Should -BeGreaterThan $write + } + } + + It 'checks out the release tags and common-ci, which the versions are worked out from' { + foreach ($testing in $script:Testing) { + $checkouts = @(Get-Step $testing 'actions/checkout') + $own = @($checkouts | Where-Object { + -not (Get-Value $_ 'repository') }) + $own.Count | Should -Be 1 + Get-Value $own[0] 'fetch-depth' | Should -Be '0' + $commonCi = @($checkouts | Where-Object { + (Get-Value $_ 'repository') -eq '51Degrees/common-ci' }) + $commonCi.Count | Should -Be 1 + $path = Get-Value $commonCi[0] 'path' + ($script:Jobs[$testing] -join "`n") | + Should -Match "(?m)^\s+_51DEGREES_COMMON_CI_DIR:.*$([regex]::Escape($path))" + } + } + + It 'fails the install step when pip fails' { + foreach ($testing in $script:Testing) { + $text = $script:Jobs[$testing] -join "`n" + $text | Should -Match ('- name: Install the packages the tests use' + + '\s*\n(\s+\S.*\n)*?\s+\$PSNativeCommandUseErrorActionPreference = \$true') + } + } + + It 'caches each of the free data files the tests use' { + $paths = Get-Paths (@(Get-Step $script:Fetching[0] 'actions/cache')[0]) + foreach ($file in '51Degrees-LiteV4.1.hash', '51Degrees-LiteV41.ipi', + '51Degrees-IPIV4AsnIpiV41.ipi', '20000 Evidence Records.yml') { + $paths | Should -Contain "cxx/data/**/$file" + } + # The evidence is the YAML file, and no other evidence file is cached. + @($paths | Where-Object { $_ -notmatch '\.(hash|ipi|yml)$' }) | + Should -BeNullOrEmpty + } +} diff --git a/ci/get-next-package-version.Tests.ps1 b/ci/get-next-package-version.Tests.ps1 new file mode 100644 index 00000000..706e6f0c --- /dev/null +++ b/ci/get-next-package-version.Tests.ps1 @@ -0,0 +1,46 @@ +# Tests for ci/get-next-package-version.ps1, which labels a publish with the +# highest version in the release plan. +# +# Each test copies the script to a throwaway folder beside a packages.ps1 +# whose release plan is the versions the test gives, so the test states the +# plan it labels. + +Describe 'get-next-package-version.ps1' { + BeforeAll { + $script:Label = Join-Path $PSScriptRoot 'get-next-package-version.ps1' + + function Get-Label([string[]]$Versions) { + $folder = Join-Path ([IO.Path]::GetTempPath()) ` + ([Guid]::NewGuid().ToString()) + $null = New-Item -ItemType Directory $folder + try { + Copy-Item $script:Label $folder + $list = ($Versions | ForEach-Object { "'$_'" }) -join ', ' + Set-Content (Join-Path $folder 'packages.ps1') @" +function Get-ReleasePlan(`$RepoPath) { + @(@($list) | ForEach-Object { + [pscustomobject]@{ Name = "package-`$_"; Version = `$_ } + }) +} +"@ + & (Join-Path $folder 'get-next-package-version.ps1') ` + -RepoName 'repository' -VariableName 'TestLabel' + return $global:TestLabel + } finally { + Remove-Item -Recurse -Force $folder + } + } + } + + It 'labels a plan of one package with its whole version' { + Get-Label @('4.5.3') | Should -Be '4.5.3' + } + + It 'labels a plan of several packages with the highest version' { + Get-Label @('4.5.3', '4.5.10', '4.5.9') | Should -Be '4.5.10' + } + + It 'gives a valid version when nothing is released' { + Get-Label @() | Should -Be '4.5.0' + } +} diff --git a/ci/get-next-package-version.ps1 b/ci/get-next-package-version.ps1 index d94aa4d7..0456e988 100644 --- a/ci/get-next-package-version.ps1 +++ b/ci/get-next-package-version.ps1 @@ -13,7 +13,7 @@ $ErrorActionPreference = "Stop" # build-package.ps1 and publish-package.ps1, all from the same release plan. $plan = @(Get-ReleasePlan $RepoName) if ($plan.Count -gt 0) { - $label = ($plan.Version | Sort-Object { [version]$_ })[-1] + $label = @($plan.Version | Sort-Object { [version]$_ })[-1] } else { # Nothing to release. Any valid version will do, because # package-update-required.ps1 stops the publish before it is used. diff --git a/ci/ip-intelligence-performance.Tests.ps1 b/ci/ip-intelligence-performance.Tests.ps1 new file mode 100644 index 00000000..161e7c2d --- /dev/null +++ b/ci/ip-intelligence-performance.Tests.ps1 @@ -0,0 +1,121 @@ +# Tests for ip-intelligence/ci/run-performance-tests.ps1. +# +# common-ci runs the script from its own folder, which holds the assets, with +# the product folder as RepoName. Each test lays out such a folder with empty +# stand-ins for the free Lite data file and the evidence, and mocks python, so +# that what is checked is what the script measures and on which file, not the +# measurement itself. + +BeforeAll { + $script:Script = Join-Path $PSScriptRoot '..' 'ip-intelligence' 'ci' ` + 'run-performance-tests.ps1' + + # The free data file and the evidence, as common-ci's assets name them. + $script:LiteFile = '51Degrees-LiteIpiV41.ipi' + $script:EvidenceFile = 'ip-intelligence-evidence.yml' + + # The web benchmark, in the same place as Device Detection's, and the + # console example, relative to the product folder. + $script:WebBenchmark = + 'fiftyone_ipintelligence_examples/performance-tests/test_performance.py' + $script:ConsoleBenchmark = 'fiftyone_ipintelligence_examples/src/' + + 'fiftyone_ipintelligence_examples/onpremise/performance_console.py' + + # The name of the file that follows $Option in the arguments, or null. + function Get-OptionFile([object[]]$Arguments, [string]$Option) { + $index = [Array]::IndexOf($Arguments, $Option) + if ($index -lt 0) { + return $null + } + return Split-Path -Leaf $Arguments[$index + 1] + } +} + +Describe 'ip-intelligence run-performance-tests.ps1' { + +BeforeEach { + $script:CommonCi = Join-Path ([IO.Path]::GetTempPath()) ` + ([Guid]::NewGuid().ToString()) + $script:Assets = New-Item -ItemType Directory -Force ` + (Join-Path $script:CommonCi 'assets') + $script:Product = (New-Item -ItemType Directory -Force ` + (Join-Path $script:CommonCi 'ip-intelligence')).FullName + foreach ($name in $script:LiteFile, $script:EvidenceFile) { + Set-Content (Join-Path $script:Assets $name) '' + } + + # The console benchmark writes its summary where --json_output says. + Mock python { + $index = [Array]::IndexOf($args, '--json_output') + if ($index -ge 0) { + '{ "DetectionsPerSecond": 1, "MsPerDetection": 1 }' | + Set-Content $args[$index + 1] + } + } + + Push-Location $script:CommonCi +} + +AfterEach { + Pop-Location + Remove-Item -Recurse -Force $script:CommonCi +} + +It 'has a web benchmark in the same form as Device Detection' { + Join-Path $PSScriptRoot '..' 'ip-intelligence' $script:WebBenchmark | + Should -Exist +} + +It 'runs the web benchmark on the free Lite file and the evidence' { + & $script:Script -RepoName $script:Product -Name 'test' | Out-Null + + Should -Invoke python -Times 1 -Exactly -ParameterFilter { + $args[0] -eq $script:WebBenchmark -and + (Split-Path -Leaf $args[1]) -eq $script:LiteFile -and + (Split-Path -Leaf $args[2]) -eq $script:EvidenceFile -and + $args -contains '--output' + } +} + +It 'runs the console benchmark on the free Lite file and the evidence' { + $output = & $script:Script -RepoName $script:Product -Name 'test' | + Out-String + + Should -Invoke python -Times 1 -Exactly -ParameterFilter { + $args[0] -eq $script:ConsoleBenchmark -and + (Get-OptionFile $args '--data_file') -eq $script:LiteFile -and + (Get-OptionFile $args '--evidence_file') -eq $script:EvidenceFile + } + $output | Should -Match 'on 51Degrees-LiteIpiV41\.ipi' +} + +It 'writes the summary the performance step reports' { + & $script:Script -RepoName $script:Product -Name 'test' | Out-Null + + # common-ci compares results_.json, one file for each configuration, + # which also holds Device Detection's figures, so these carry the product. + $folder = Join-Path $script:Product 'test-results' 'performance-summary' + Get-ChildItem $folder | ForEach-Object Name | Should -Be 'results_test.json' + $results = Get-Content (Join-Path $folder 'results_test.json') | + ConvertFrom-Json + $results.HigherIsBetter.IpIntelligence_DetectionsPerSecond | Should -Be 1 + $results.LowerIsBetter.IpIntelligence_AvgMillisecsPerDetection | + Should -Be 1 +} + +It 'fails rather than skipping when the free Lite file is absent' { + Remove-Item (Join-Path $script:Assets $script:LiteFile) + + { & $script:Script -RepoName $script:Product -Name 'test' } | + Should -Throw "*$($script:LiteFile)*" + Should -Invoke python -Times 0 -Exactly +} + +It 'runs nothing when performance is turned off' { + & $script:Script -RepoName $script:Product -Name 'test' ` + -RunPerformance $false + + Should -Invoke python -Times 0 -Exactly +} + +} diff --git a/ci/key-names.Tests.ps1 b/ci/key-names.Tests.ps1 new file mode 100644 index 00000000..8b5b8607 --- /dev/null +++ b/ci/key-names.Tests.ps1 @@ -0,0 +1,620 @@ +# Tests that the CI scripts, the tox configurations and the cloud tests read +# each key under its _51DEGREES_ name, and fill no name from another. +# +# common-ci exports every _51DEGREES_ secret and organization variable under +# its own name before any of this repository's scripts run. The resource +# keys and the license keys are organization secrets. +# The tests that need every property read _51DEGREES_RESOURCE_KEY_BESPOKE. +# _51DEGREES_RESOURCE_KEY is the name a person running an example sets, and +# only an example's own test sets it, for that example. The Cloud 51Did +# workflow takes _51DEGREES_RESOURCE_KEY_51DID and +# _51DEGREES_RESOURCE_KEY_BASIC from the organization secret of the same +# name. It +# downloads every data file with _51DEGREES_LICENSE_KEY, which is the data +# license and not a cloud license. No key reaches a script as an option. +# +# Two names only CI uses have no _51DEGREES_ prefix. CLOUD_STAGING_ENDPOINT, +# an organization variable, names the staging cloud, and +# RESOURCE_KEY_BESPOKE_STAGING, an organization secret, is a Bespoke key it +# knows. Only the Cloud Human Confidence workflow sets them, for the tests +# marked staging, which check what the production cloud does not serve yet. + +BeforeDiscovery { + $script:DiscoveryRoot = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path +} + +BeforeAll { + $script:Root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path + + # The variables the scripts read or write, saved before each test and put + # back after it. + $script:Saved = @( + '_51DEGREES_RESOURCE_KEY', '_51DEGREES_RESOURCE_KEY_BESPOKE', + '_51DEGREES_LICENSE_KEY', 'TEMP', 'GITHUB_ENV', + 'GITHUB_JOB', 'PYTEST_ADDOPTS') + + function New-TempFolder { + $path = Join-Path ([IO.Path]::GetTempPath()) ([Guid]::NewGuid().ToString()) + return [IO.Directory]::CreateDirectory($path).FullName + } + + # A folder laid out like a common-ci checkout, which the product scripts + # run in. Its python/run-integration-tests.ps1 writes the keys it was run + # with to seen.json, and its steps/fetch-assets.ps1 writes each call to + # fetch.json and leaves an empty file for each asset. + function New-CommonCi { + $path = New-TempFolder + $null = [IO.Directory]::CreateDirectory((Join-Path $path 'python')) + $null = [IO.Directory]::CreateDirectory((Join-Path $path 'steps')) + Set-Content (Join-Path $path 'python' 'run-integration-tests.ps1') @' +param ([string]$RepoName, [string[]]$Packages) +@{ + Resource = $env:_51DEGREES_RESOURCE_KEY_BESPOKE + Example = $env:_51DEGREES_RESOURCE_KEY + License = $env:_51DEGREES_LICENSE_KEY +} | ConvertTo-Json | Set-Content (Join-Path $PSScriptRoot '..' 'seen.json') +$global:LASTEXITCODE = 0 +'@ + Set-Content (Join-Path $path 'steps' 'fetch-assets.ps1') @' +param ( + [Parameter(Mandatory)][string[]]$Assets, + [Parameter(ValueFromRemainingArguments)][object[]]$Others +) +$log = Join-Path $PSScriptRoot '..' 'fetch.json' +$calls = @() +if (Test-Path $log) { $calls = @(Get-Content -Raw $log | ConvertFrom-Json) } +$calls += [pscustomobject]@{ + Assets = @($Assets) + Others = @($Others | ForEach-Object { "$_" }) +} +ConvertTo-Json -InputObject @($calls) -Depth 4 | Set-Content $log +$null = [IO.Directory]::CreateDirectory((Join-Path $PWD 'assets')) +foreach ($asset in $Assets) { Set-Content -LiteralPath "assets/$asset" '' } +'@ + return $path + } + + # A copy of one product's CI script in a repository of its own, with the + # scripts it calls replaced by ones that do nothing, and the folders it + # writes to. + function New-ProductRepo([string]$Product, [string]$Script) { + $repo = New-TempFolder + $ci = [IO.Directory]::CreateDirectory((Join-Path $repo $Product 'ci')).FullName + Copy-Item (Join-Path $script:Root $Product 'ci' $Script) $ci + Set-Content (Join-Path $ci 'report-key-products.ps1') 'param ([string]$ResourceKey)' + Set-Content (Join-Path $ci 'copy-owid-source.ps1') 'param ([string]$RepoRoot)' + $null = [IO.Directory]::CreateDirectory((Join-Path $repo 'cxx' 'data' 'device-detection')) + $null = [IO.Directory]::CreateDirectory((Join-Path $repo 'cxx' 'data' 'ip-intelligence')) + return Join-Path $repo $Product + } + + # The run script of the step called $Step in the workflow file $Workflow, + # without its indent. + function Get-StepScript([string]$Workflow, [string]$Step) { + $lines = @(Get-Content (Join-Path $script:Root '.github/workflows' $Workflow)) + $name = ($lines | Select-String -SimpleMatch "- name: $Step" | + Select-Object -First 1).LineNumber + $start = $lines | Select-Object -Skip $name | + Select-String -Pattern '^(\s*)run: \|\s*$' | Select-Object -First 1 + $indent = $start.Matches[0].Groups[1].Value.Length + foreach ($line in $lines[($name + $start.LineNumber)..($lines.Count - 1)]) { + if ($line.Trim() -and $line -notmatch "^\s{$($indent + 1),}") { break } + if ($line.Length -gt $indent + 2) { $line.Substring($indent + 2) } else { '' } + } + } + + # Runs the Cloud Human Confidence workflow's test step in its own process + # and folder, with the names given set and no others, and python replaced + # by a function that writes $Report as the junit report and exits with + # $PytestExitCode. Gives the step's exit code and the output. + function Invoke-StagingStep([hashtable]$Names, [string]$Report, + [int]$PytestExitCode = 0) { + $folder = Join-Path $TestDrive ([Guid]::NewGuid().ToString()) + $null = New-Item -ItemType Directory $folder + $stepFile = Join-Path $folder 'step.ps1' + $python = @( + 'function python {' + ' Write-Output "pytest ran"' + ' $path = "$($args | Where-Object { "$_" -like "--junit-xml=*" })" -replace "^--junit-xml=", ""' + " if (`$path) { Set-Content `$path '$Report' }" + " `$global:LASTEXITCODE = $PytestExitCode" + '}' + ) + @($python + @(Get-StepScript 'cloud-human-confidence.yml' 'Human Confidence tests against the staging cloud')) | + Set-Content $stepFile + $all = 'CLOUD_STAGING_ENDPOINT', 'RESOURCE_KEY_BESPOKE_STAGING', + '_51DEGREES_RESOURCE_KEY_BASIC' + $saved = @{} + foreach ($name in $all) { + $saved[$name] = [Environment]::GetEnvironmentVariable($name) + [Environment]::SetEnvironmentVariable($name, $Names[$name]) + } + Push-Location $folder + try { + $output = & (Get-Process -Id $PID).Path -NoProfile -File $stepFile 2>&1 | Out-String + return [pscustomobject]@{ ExitCode = $LASTEXITCODE; Output = $output } + } finally { + Pop-Location + foreach ($name in $all) { + [Environment]::SetEnvironmentVariable($name, $saved[$name]) + } + } + } + + # Every name the staging step needs, set to a stand-in. + $script:StagingNames = @{ + CLOUD_STAGING_ENDPOINT = 'https://cloud.example.test/api/v4/' + RESOURCE_KEY_BESPOKE_STAGING = 'staging-bespoke-key' + _51DEGREES_RESOURCE_KEY_BASIC = 'basic-key' + } + + # A junit report of the two staging tests, as pytest writes it. + function New-JunitReport([int]$Tests, [int]$Skipped) { + $cases = for ($i = 0; $i -lt $Tests; $i++) { + if ($i -lt $Skipped) { + "" + } else { + "" + } + } + return ('' + + "$($cases -join '')" + + '') + } +} + +Describe 'Keys under their _51DEGREES_ names' { + + BeforeEach { + $script:Before = @{} + foreach ($name in $script:Saved) { + $script:Before[$name] = [Environment]::GetEnvironmentVariable($name) + [Environment]::SetEnvironmentVariable($name, $null) + } + } + + AfterEach { + foreach ($name in $script:Saved) { + [Environment]::SetEnvironmentVariable($name, $script:Before[$name]) + } + } + + Describe 'Each product''s run-integration-tests.ps1' { + + BeforeEach { + $script:CommonCi = New-CommonCi + } + + AfterEach { + Remove-Item -Recurse -Force $script:CommonCi + } + + It 'leaves the resource key under _51DEGREES_RESOURCE_KEY_BESPOKE in , and gives the tests no other name for it' -ForEach @( + @{ Product = 'device-detection'; Extra = @{ SeleniumContract = $false } } + @{ Product = 'ip-intelligence'; Extra = @{} } + @{ Product = 'location'; Extra = @{} } + @{ Product = 'pipeline'; Extra = @{} } + ) { + $repoName = New-ProductRepo $Product 'run-integration-tests.ps1' + $env:_51DEGREES_RESOURCE_KEY_BESPOKE = 'bespoke-resource-key' + $env:_51DEGREES_LICENSE_KEY = 'data-license' + Push-Location $script:CommonCi + try { + & (Join-Path $repoName 'ci' 'run-integration-tests.ps1') ` + -RepoName $repoName @Extra + } finally { + Pop-Location + } + + $seen = Get-Content -Raw (Join-Path $script:CommonCi 'seen.json') | ConvertFrom-Json + $seen.Resource | Should -Be 'bespoke-resource-key' + $seen.Example | Should -BeNullOrEmpty + $env:_51DEGREES_RESOURCE_KEY | Should -BeNullOrEmpty + } + + It 'leaves the data license common-ci exported as it was in ' -ForEach @( + @{ Product = 'device-detection'; Extra = @{ SeleniumContract = $false } } + @{ Product = 'ip-intelligence'; Extra = @{} } + @{ Product = 'location'; Extra = @{} } + @{ Product = 'pipeline'; Extra = @{} } + ) { + $repoName = New-ProductRepo $Product 'run-integration-tests.ps1' + $env:_51DEGREES_RESOURCE_KEY_BESPOKE = 'bespoke-resource-key' + $env:_51DEGREES_LICENSE_KEY = 'data-license' + Push-Location $script:CommonCi + try { + & (Join-Path $repoName 'ci' 'run-integration-tests.ps1') ` + -RepoName $repoName @Extra + } finally { + Pop-Location + } + + $seen = Get-Content -Raw (Join-Path $script:CommonCi 'seen.json') | ConvertFrom-Json + $seen.License | Should -Be 'data-license' + $seen.Resource | Should -Be 'bespoke-resource-key' + } + + It 'runs the tests that need no key, naming _51DEGREES_RESOURCE_KEY_BESPOKE, when it is not set in ' -ForEach @( + @{ Product = 'device-detection'; Extra = @{ SeleniumContract = $false } } + @{ Product = 'ip-intelligence'; Extra = @{} } + @{ Product = 'location'; Extra = @{} } + @{ Product = 'pipeline'; Extra = @{} } + ) { + $repoName = New-ProductRepo $Product 'run-integration-tests.ps1' + Push-Location $script:CommonCi + try { + $output = & (Join-Path $repoName 'ci' 'run-integration-tests.ps1') ` + -RepoName $repoName @Extra *>&1 | Out-String + } finally { + Pop-Location + } + + $output | Should -Match '_51DEGREES_RESOURCE_KEY_BESPOKE is not set' + Join-Path $script:CommonCi 'seen.json' | Should -Exist + } + } + + Describe 'Each product''s fetch-assets.ps1' { + + BeforeEach { + $script:CommonCi = New-CommonCi + # The scripts make symbolic links, which need a privilege a test + # run may not have, and folders for them. Where they point is not + # what these tests check, so New-Item does nothing here, and the + # helpers above make their folders without it. + Mock New-Item { } + } + + AfterEach { + Remove-Item -Recurse -Force $script:CommonCi + } + + It 'takes no key or address option in " @@ -166,4 +197,7 @@ def server(): """ + # Where to go next. + output += find_out_more_html() + return output diff --git a/location/readme.md b/location/readme.md index dd21ab30..bbd04a36 100644 --- a/location/readme.md +++ b/location/readme.md @@ -23,7 +23,7 @@ The [tested versions](https://51degrees.com/documentation/_product_summaries__te You can confirm this is working with the following micro-example. -* Create a resource key for free with the 51Degrees [configurator](https://configure.51degrees.com/6CTsmbPx?utm_source=pypi&utm_medium=package&utm_campaign=51degrees-python&utm_content=fiftyone_location&utm_term=from-pypi). This defines the properties you want to access. +* Create a resource key for free with the 51Degrees [configuration page](https://51degrees.com/configure/6CTsmbPx?utm_source=pypi&utm_medium=package&utm_campaign=51degrees-python&utm_content=fiftyone_location&utm_term=from-pypi). This defines the properties you want to access. * On the 'implement' page of the configurator, copy the resource key and replace YOUR_RESOURCE_KEY in the example below. Save this as examplelocation.py * Run the example with `python examplelocation.py` * Feel free to try different locations and property values. @@ -54,11 +54,17 @@ To run the web example navigate into Examples folder: #### Linux -Execute `export FLASK_APP=web` where `web` is the example file, and start your application via `flask run`. +Execute `export FLASK_APP=web` where `web` is the example file, and start your application via `flask run --port 5151`. #### Windows -Execute `$env:FLASK_APP = "web"` where `web` is the example file, and start your application via `flask run`. +Execute `$env:FLASK_APP = "web"` where `web` is the example file, and start your application via `flask run --port 5151`. + +A Flow Data cannot be used by two threads at once, so the web example +creates a Flow Data for each request, uses it only in the code that handles +that request, and closes it before the request ends. To hand work to +another thread or task, read the values it needs from the Flow Data first +and pass those values, not the Flow Data. ## Find out more diff --git a/location/tests/conftest.py b/location/tests/conftest.py new file mode 100644 index 00000000..df687fc0 --- /dev/null +++ b/location/tests/conftest.py @@ -0,0 +1,76 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +# The tests that call the live cloud service are marked live here, so the +# released test files stay as they are. ci/run-integration-tests.ps1 leaves +# the live tests out when no resource key is passed, and the other tests run. + +from pathlib import Path + +import pytest +from _pytest.mark.expression import Expression + +HERE = Path(__file__).resolve().parent + +# Every test in these modules is live. test_web_example.py marks its own. +LIVE_MODULES = { + HERE / "test_examples.py", + HERE / "test_properties51D.py", +} + +BUILT_AT_IMPORT = {HERE / "test_properties51D.py"} + + +def _is_live(item): + return Path(item.path).resolve() in LIVE_MODULES + + +def pytest_configure(config): + config.addinivalue_line( + "markers", + "live: calls the live 51Degrees cloud service and needs a resource " + "key") + + +@pytest.hookimpl(tryfirst=True) +def pytest_collection_modifyitems(config, items): + # Runs before -m deselects, so the selection sees the marker. + for item in items: + if _is_live(item): + item.add_marker(pytest.mark.live) + + +def _leaves_out_live(config): + """Whether the -m expression leaves out a test marked live alone.""" + expression = config.getoption("markexpr") + return bool(expression) and not Expression.compile(expression).evaluate( + lambda name, **kwargs: name == "live") + + +# A module that builds a cloud Pipeline when imported raises with no resource +# key, so it is not collected when the live tests are left out. Every test in +# it is live, so the selection is the same. +def pytest_ignore_collect(collection_path, config): + if (Path(collection_path).resolve() in BUILT_AT_IMPORT and + _leaves_out_live(config)): + return True + return None diff --git a/location/tests/live_cloud.py b/location/tests/live_cloud.py index 36bc26ad..b86793bf 100644 --- a/location/tests/live_cloud.py +++ b/location/tests/live_cloud.py @@ -21,94 +21,57 @@ # ********************************************************************* """Where the tests that call the live 51Degrees cloud service find their -resource key, and what they fail with when there is none or when the -answer lacks what they asked for. Also how a test reads any setting from -an environment variable whose name has changed. +resource key, what they skip with when there is none, and what they +fail with when the answer lacks what they asked for. Also how a test reads a setting from an +environment variable. The same file is in each test folder whose tests read a setting from the -environment. There is no fallback to a skip, because a cloud test that -passes without calling the cloud has proved nothing. +environment. A test with no key skips, naming the variable it reads, +and never fails for want of one. CI checks that the key is set before +it runs them, so a run that called nothing is not taken for a pass. """ import os -import sys -# Tried in this order. _51DEGREES_RESOURCE_KEY is first because the Cloud -# 51Did workflow sets it to each key in turn, and each product's -# integration test script sets it too. -RESOURCE_KEY_NAMES = ( - "_51DEGREES_RESOURCE_KEY", - "_51DEGREES_RESOURCE_KEY_BESPOKE", -) +# The key that carries every property, which a test reads unless it names +# another. +RESOURCE_KEY_NAMES = ("_51DEGREES_RESOURCE_KEY_BESPOKE",) -# Deprecated. The name the resource key variable had before, read when -# none of RESOURCE_KEY_NAMES is set. -OLD_RESOURCE_KEY_NAME = "resource_key" - -# The old names already reported as deprecated, so each is reported once. -_reported_old_names = set() +# The name a person running an example sets. A test of an example gives the +# example its key under this name. +RESOURCE_KEY_VARIABLE = "_51DEGREES_RESOURCE_KEY" ACCESSIBLE_PROPERTIES_URL = ( "https://cloud.51degrees.com/api/v4/accessibleproperties?resource=") -CREATE_KEY_URL = "https://configure.51degrees.com?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=live_cloud.py&utm_term=resource-key-required" - - -def _report_old_name(name, old_name): - """Prints, once for each old name, that it is deprecated and which - name replaces it.""" - if old_name in _reported_old_names: - return - _reported_old_names.add(old_name) - print( - f"The {old_name} environment variable is deprecated and {name} " - f"replaces it. The value was read from {old_name} because {name} " - f"is not set, so set {name} to the same value.", - file=sys.stderr) +CREATE_KEY_URL = "https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=live_cloud.py&utm_term=resource-key-required" -def read_environment(name, old_name): +def read_environment(name): """The value of the environment variable name, or None when it has - none. When name is unset or empty the name the variable had before is - read, and using it prints once that the old name is deprecated.""" + none.""" value = os.environ.get(name, "").strip() - if value: - return value - value = os.environ.get(old_name, "").strip() - if not value: - return None - _report_old_name(name, old_name) - return value + return value or None -def is_set(name, old_name): +def is_set(name): """Whether the environment variable name is set, whatever it holds, - which is how a switch is read. When it is not set, the name the - variable had before counts, and using it prints once that the old name - is deprecated.""" - if name in os.environ: - return True - if old_name not in os.environ: - return False - _report_old_name(name, old_name) - return True + which is how a switch is read.""" + return name in os.environ def find_resource_key(names=RESOURCE_KEY_NAMES): - """The first resource key set under any of the names, or None. When - none of RESOURCE_KEY_NAMES is set, the deprecated old name is read.""" + """The resource key set under the names, or None.""" for name in names: value = os.environ.get(name, "").strip() if value: return value - if names is RESOURCE_KEY_NAMES: - return read_environment(names[0], OLD_RESOURCE_KEY_NAME) return None def no_resource_key(product, asks_for, several=False, names=RESOURCE_KEY_NAMES): - """What to fail with when no resource key is set. + """What to skip with when no resource key is set. product names the product the key has to carry, with its article, as in "the device product". asks_for says what the test asks the service for. @@ -123,8 +86,8 @@ def no_resource_key(product, asks_for, several=False, "it needs a resource key") asker = "the test asks" return ( - f"{opening} and there is nothing to fall back on. None of " - f"{', '.join(names)} is set, tried in that order. The key has to " + f"{opening} and there is nothing to fall back on. " + f"{', '.join(names)} is not set. The key has to " f"carry {product}, because {asker} the service for {asks_for}. To " f"see the products a key carries, open {ACCESSIBLE_PROPERTIES_URL}. " f"Create a key at {CREATE_KEY_URL}.") diff --git a/location/tests/test_builder_timeout.py b/location/tests/test_builder_timeout.py new file mode 100644 index 00000000..43280997 --- /dev/null +++ b/location/tests/test_builder_timeout.py @@ -0,0 +1,77 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +"""! +The Location Pipeline Builder passes timeout_seconds to the Cloud Request +Engine, as it does the other cloud settings. These tests need no network +connection and no resource key. +""" + +import unittest +import warnings + +import requests + +from fiftyone_pipeline_cloudrequestengine.requestclient import RequestClient + +from fiftyone_location.location_pipelinebuilder import LocationPipelineBuilder + +# A timeout other than the default, in seconds. +GIVEN_TIMEOUT_SECONDS = 7 + + +class TimeoutRecorder(RequestClient): + """! + Stands in for the cloud service as it is when it cannot be reached, and + keeps the timeout each request was given. + """ + + def __init__(self): + self.timeouts = [] + + def request(self, type, url, content, originHeader, timeout_seconds=None): + self.timeouts.append(timeout_seconds) + raise requests.exceptions.ConnectionError( + "The stand-in service cannot be reached.") + + +class BuilderTimeoutTests(unittest.TestCase): + + def test_the_builder_passes_the_timeout_to_the_engine(self): + recorder = TimeoutRecorder() + + # The service cannot be reached, which the engine gives as a + # warning and builds regardless. + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + LocationPipelineBuilder( + resource_key="a-resource-key", + settings={ + "timeout_seconds": GIVEN_TIMEOUT_SECONDS, + "http_client": recorder}) + + # The two discovery requests made when the engine is built. + self.assertEqual([GIVEN_TIMEOUT_SECONDS] * 2, recorder.timeouts) + + +if __name__ == "__main__": + unittest.main() diff --git a/location/tests/test_environment_names.py b/location/tests/test_environment_names.py deleted file mode 100644 index f3ad6f0a..00000000 --- a/location/tests/test_environment_names.py +++ /dev/null @@ -1,114 +0,0 @@ -# ********************************************************************* -# This Original Work is copyright of 51 Degrees Mobile Experts Limited. -# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, -# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. -# -# This Original Work is licensed under the European Union Public Licence -# (EUPL) v.1.2 and is subject to its terms as set out below. -# -# If a copy of the EUPL was not distributed with this file, You can obtain -# one at https://opensource.org/licenses/EUPL-1.2. -# -# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be -# amended by the European Commission) shall be deemed incompatible for -# the purposes of the Work and the provisions of the compatibility -# clause in Article 5 of the EUPL shall not apply. -# -# If using the Work as, or as part of, a network application, by -# including the attribution notice(s) required under Article 5 of the EUPL -# in the end user terms of the application under an appropriate heading, -# such notice(s) shall fulfill the requirements of that article. -# ********************************************************************* - -"""Checks that the two cloud examples still read the resource key under -the name its environment variable had before, when the new name is not set. - -Importing an example runs it, which calls the cloud service, so the -function each example reads its key with is taken out of the example's -source and run on its own. -""" - -import ast -import contextlib -import io -import os -import sys -import unittest -from pathlib import Path -from unittest import mock - -EXAMPLES = Path(__file__).resolve().parent.parent / "examples" / "cloud" - -NEW_NAME = "_51DEGREES_RESOURCE_KEY" -OLD_NAME = "resource_key" - - -def reader(example): - """The read_environment function of an example, or None when the - example has none.""" - source = (EXAMPLES / example).read_text(encoding="utf-8") - for node in ast.parse(source).body: - if isinstance(node, ast.FunctionDef) \ - and node.name == "read_environment": - module = ast.Module(body=[node], type_ignores=[]) - names = {"os": os, "sys": sys} - exec(compile(module, example, "exec"), names) - return names["read_environment"] - return None - - -class OldNameTests(unittest.TestCase): - - def setUp(self): - environment = mock.patch.dict(os.environ) - environment.start() - self.addCleanup(environment.stop) - os.environ.pop(NEW_NAME, None) - os.environ.pop(OLD_NAME, None) - - def read(self, example): - """What the example reads for its resource key, and what it prints - to the error stream.""" - read_environment = reader(example) - self.assertIsNotNone( - read_environment, - example + " has no read_environment function, so it does not " - "read the old name") - # The example has to read the key through the function. - self.assertIn( - 'read_environment("' + NEW_NAME + '", "' + OLD_NAME + '")', - (EXAMPLES / example).read_text(encoding="utf-8")) - errors = io.StringIO() - with contextlib.redirect_stderr(errors): - value = read_environment(NEW_NAME, OLD_NAME) - return value, errors.getvalue() - - def test_resource_key_is_read_from_the_old_name(self): - for example in ("gettingstarted.py", "web.py"): - with self.subTest(example=example): - os.environ[OLD_NAME] = "old-key" - value, errors = self.read(example) - self.assertEqual("old-key", value) - self.assertIn( - OLD_NAME + " environment variable is deprecated", errors) - self.assertIn(NEW_NAME, errors) - - def test_new_name_wins_and_nothing_is_printed(self): - for example in ("gettingstarted.py", "web.py"): - with self.subTest(example=example): - os.environ[NEW_NAME] = "new-key" - os.environ[OLD_NAME] = "old-key" - value, errors = self.read(example) - self.assertEqual("new-key", value) - self.assertEqual("", errors) - - def test_neither_name_gives_none(self): - for example in ("gettingstarted.py", "web.py"): - with self.subTest(example=example): - value, errors = self.read(example) - self.assertIsNone(value) - self.assertEqual("", errors) - - -if __name__ == "__main__": - unittest.main() diff --git a/location/tests/test_examples.py b/location/tests/test_examples.py index d01a5bee..121e5c2f 100644 --- a/location/tests/test_examples.py +++ b/location/tests/test_examples.py @@ -25,13 +25,23 @@ import unittest from pathlib import Path -from .live_cloud import read_environment +from unittest import mock + +from .live_cloud import ( + RESOURCE_KEY_VARIABLE, find_resource_key, no_resource_key) class LocationExampleTests(unittest.TestCase): def test_cloud_getting_started(self): - if read_environment("_51DEGREES_RESOURCE_KEY", "resource_key"): - # this is required to import the example code, - # since pytest sets sys.path to the test directory - sys.path.append(str(Path(__file__).parent.parent.absolute() / "examples")) + resource_key = find_resource_key() + if not resource_key: + self.skipTest(no_resource_key( + "the location product", + "the country at a latitude and longitude")) + # this is required to import the example code, + # since pytest sets sys.path to the test directory + sys.path.append(str(Path(__file__).parent.parent.absolute() / "examples")) + # The example reads its key when it is imported. + with mock.patch.dict( + os.environ, {RESOURCE_KEY_VARIABLE: resource_key}): import cloud.gettingstarted diff --git a/location/tests/test_examples_without_key.py b/location/tests/test_examples_without_key.py new file mode 100644 index 00000000..89b59a1e --- /dev/null +++ b/location/tests/test_examples_without_key.py @@ -0,0 +1,74 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +""" +Runs each cloud example as it runs from a fresh clone, with no resource key +set. Each must end without an error, name the environment variable to set +and give a tagged link to the page where a key is created. +""" + +import io +import os +import runpy +import unittest +from contextlib import redirect_stdout +from pathlib import Path +from unittest import mock + +EXAMPLES = Path(__file__).resolve().parent.parent / "examples" / "cloud" + +# Every name a key can be read from, which a fresh clone does not set. +KEY_SETTINGS = ["_51DEGREES_RESOURCE_KEY"] + +# A link to the page where a resource key is created, with the campaign +# tags every example's links carry. +CONFIGURE_LINK = ( + r"https://51degrees\.com/configure[^\s?]*\?utm_source=code" + r"&utm_medium=example&utm_campaign=51degrees-python&utm_content=") + + +def run_without_key(example): + """Runs an example file as a script with no key in the environment, and + returns what it printed.""" + printed = io.StringIO() + with mock.patch.dict(os.environ), redirect_stdout(printed): + for name in KEY_SETTINGS: + os.environ.pop(name, None) + runpy.run_path(str(EXAMPLES / example), run_name="__main__") + return printed.getvalue() + + +class LocationExamplesWithoutKeyTests(unittest.TestCase): + + def test_cloud_getting_started(self): + said = run_without_key("gettingstarted.py") + self.assertIn("_51DEGREES_RESOURCE_KEY", said) + self.assertRegex(said, CONFIGURE_LINK) + + def test_cloud_web(self): + said = run_without_key("web.py") + self.assertIn("_51DEGREES_RESOURCE_KEY", said) + self.assertRegex(said, CONFIGURE_LINK) + + +if __name__ == "__main__": + unittest.main() diff --git a/location/tests/test_find_out_more.py b/location/tests/test_find_out_more.py new file mode 100644 index 00000000..d250c4d9 --- /dev/null +++ b/location/tests/test_find_out_more.py @@ -0,0 +1,99 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +""" +Every example ends with a "Find out more" section, which gives the person +running it links to follow up, wherever the example ends. The first check +reads the examples' source. The other runs each example with no resource +key, so none of them needs a key or the network. +""" + +import io +import os +import re +import runpy +import unittest +from contextlib import redirect_stdout +from unittest import mock + +# The product folder. Each link's utm_content is the path of its file below +# this folder. +PRODUCT = os.path.abspath(os.path.join( + os.path.dirname(os.path.abspath(__file__)), "..")) +EXAMPLES = os.path.join(PRODUCT, "examples", "cloud") + +# Every example. The web example has one section for the console and the +# same links at the end of its page. +SOURCES = [ + os.path.join(EXAMPLES, "gettingstarted.py"), + os.path.join(EXAMPLES, "web.py"), +] + +# The name of the section, or of the list that holds its links. +SECTION_NAME = re.compile(r"(?i)find[ _]out[ _]more") + +# A 51degrees.com link in the section, which carries a utm_term that starts +# with "find-out-more". +SECTION_LINK = re.compile( + r"https://51degrees\.com/[^\s\"'<>)]*utm_term=find-out-more[^\s\"'<>)]*") + +# This product's folder in the repository, which every section links to. +REPOSITORY = "https://github.com/51Degrees/51degrees-python/tree/main/location" + +# The settings that let an example get past its early end. +SETTINGS = ["_51DEGREES_RESOURCE_KEY"] + + +def slug(path): + """The utm_content of a link in the file, which is the path below the + product folder with each separator a hyphen.""" + return os.path.relpath(path, PRODUCT).replace(os.sep, "-") + + +class FindOutMoreTests(unittest.TestCase): + + def test_every_example_has_a_find_out_more_section(self): + for path in SOURCES: + with self.subTest(example=slug(path)): + with open(path, encoding="utf-8") as source: + text = source.read() + self.assertRegex(text, SECTION_NAME) + links = SECTION_LINK.findall(text) + self.assertTrue( + links, "The section has no tagged 51degrees.com link") + for link in links: + self.assertIn(f"&utm_content={slug(path)}&", link) + self.assertIn(REPOSITORY, text) + + def test_every_example_without_a_resource_key(self): + for path in SOURCES: + with self.subTest(example=slug(path)): + printed = io.StringIO() + with mock.patch.dict(os.environ), redirect_stdout(printed): + for name in SETTINGS: + os.environ.pop(name, None) + runpy.run_path(path, run_name="__main__") + self.assertIn("Find out more:", printed.getvalue()) + + +if __name__ == "__main__": + unittest.main() diff --git a/location/tests/test_finished_writes.py b/location/tests/test_finished_writes.py new file mode 100644 index 00000000..e4f5111e --- /dev/null +++ b/location/tests/test_finished_writes.py @@ -0,0 +1,108 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +""" +Every FlowElement this package defines is processed, then a write to its +ElementData is expected to fail, as the thread safety page of the +specification requires. +""" + +import importlib +import inspect +import json +import pkgutil +import unittest + +import fiftyone_location +from fiftyone_pipeline_core.elementdata_dictionary import \ + ElementDataDictionary +from fiftyone_pipeline_core.flowelement import FlowElement +from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder +from fiftyone_location.location_cloud import LocationCloud + +FINISHED = "finished processing" + + +def item_store(data): + """The dictionary the data keeps its values in.""" + if isinstance(data, dict): + return data + return data.contents + + +# FlowElements that only other FlowElements build on. +BASES = set() + + +class StandInRequestEngine(FlowElement): + """Stands in for a Cloud Request Engine whose answer has an empty + section for each of the given data keys.""" + + def __init__(self, keys): + super(StandInRequestEngine, self).__init__() + self.datakey = "cloud" + self.flow_element_properties = {key: {} for key in keys} + self.answer = json.dumps({key: {} for key in keys}) + + def process_internal(self, flowdata): + flowdata.set_element_data( + ElementDataDictionary(self, {"cloud": self.answer})) + + +def defined_flow_elements(package): + """Every FlowElement class defined in the package's own modules.""" + found = set() + for module in pkgutil.walk_packages(package.__path__, + package.__name__ + "."): + loaded = importlib.import_module(module.name) + for _, cls in inspect.getmembers(loaded, inspect.isclass): + if (issubclass(cls, FlowElement) + and cls.__module__.startswith(package.__name__)): + found.add(cls) + return found + + +class FinishedWritesTests(unittest.TestCase): + + def test_every_flow_element_refuses_writes_once_finished(self): + processed = set() + for element in [LocationCloud()]: + builder = PipelineBuilder({"add_javascript_builder": False, + "use_setheader_properties": False}) + flowdata = builder \ + .add(StandInRequestEngine([element.datakey])) \ + .add(element).build().create_flowdata() + flowdata.process() + data = flowdata.get(element.datakey) + with self.assertRaises(Exception) as caught: + data.written_after_processing = True + self.assertIn(FINISHED, str(caught.exception)) + with self.assertRaises(Exception) as caught: + item_store(data)["written_after_processing"] = True + self.assertIn(FINISHED, str(caught.exception)) + processed.add(type(element)) + self.assertEqual( + defined_flow_elements(fiftyone_location) - BASES, processed) + + +if __name__ == "__main__": + unittest.main() \ No newline at end of file diff --git a/location/tests/test_properties51D.py b/location/tests/test_properties51D.py index a31468c2..01af048d 100644 --- a/location/tests/test_properties51D.py +++ b/location/tests/test_properties51D.py @@ -25,15 +25,15 @@ from fiftyone_location.location_pipelinebuilder import LocationPipelineBuilder from .test_helper import * -from .live_cloud import read_environment +from .live_cloud import find_resource_key, no_resource_key location_LAT = '51.4578261'; location_LON = '-0.975922996290084'; -resource_key = read_environment("_51DEGREES_RESOURCE_KEY", "resource_key") +resource_key = find_resource_key() if not resource_key: - raise Exception("To run the cloud tests, please set a valid 51Degrees " - "cloud resource key as the _51DEGREES_RESOURCE_KEY environment variable.") + raise unittest.SkipTest(no_resource_key( + "the location product", "the location properties", several=True)) # Create a simple pipeline to access the engine with and process it with flow data pipeline = LocationPipelineBuilder(resource_key = resource_key, location_provider = "fiftyonedegrees").build() diff --git a/location/tests/test_web_example.py b/location/tests/test_web_example.py new file mode 100644 index 00000000..8be3bfa6 --- /dev/null +++ b/location/tests/test_web_example.py @@ -0,0 +1,227 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +"""Runs the cloud web example, examples/cloud/web.py, against the live cloud +service. Its page is requested through Flask's test client, and so is the +JSON the page's script asks for once it has the browser's position. + +The cloud service's own location lookup sometimes takes too long, and then +answers without a country and with the reason "Timeout processing location +request". That passes on a later request, so the JSON is asked for again on +that reason alone, a few times, before the test fails.""" + +import importlib.util +import json +import os +import time +import unittest +from pathlib import Path +from unittest import mock + +import pytest + +from .live_cloud import ( + RESOURCE_KEY_VARIABLE, answered_without, find_resource_key, + no_resource_key) + +EXAMPLE = Path(__file__).resolve().parents[1] / "examples" / "cloud" / "web.py" + +NO_KEY = no_resource_key( + "the location product", + "the country at a latitude and longitude", several=True) + +# What the page's script posts once the browser gives it a position, which +# is in Reading, in the United Kingdom. +POSITION = { + "51D_Pos_latitude": "51.4578261", + "51D_Pos_longitude": "-0.975922996290084", +} + +# The Cache-Control of a client-side response whose processing failed. +AFTER_ERRORS = "private, no-cache" + +# The reason the cloud service gives when its location lookup took too long. +LOOKUP_TIMEOUT = "timeout processing location request" + +# The requests made before a lookup that took too long counts as a failure. +ATTEMPTS = 3 + +# Seconds between requests whose lookup took too long. +PAUSE_SECONDS = 2 + + +def post_position(client, sleep=time.sleep): + """Posts the position to the example's JSON route, asking again while + the cloud service's location lookup takes too long, and returns the last + response, its text and its location section.""" + for attempt in range(ATTEMPTS): + response = client.post("/json", data=POSITION) + text = response.get_data(as_text=True) + try: + location = json.loads(text).get("location", {}) + except ValueError: + return response, text, {} + reason = (location.get("countrynullreason") or "").lower() + if (location.get("country") or LOOKUP_TIMEOUT not in reason + or attempt == ATTEMPTS - 1): + return response, text, location + sleep(PAUSE_SECONDS) + + +def country_failure(location): + """What to fail with when the answer has no country. A lookup that took + too long on every request is said so, and any other reason points at the + key, as that is what a key without the location product gets.""" + reason = location.get("countrynullreason") + if LOOKUP_TIMEOUT in (reason or "").lower(): + return (f"The cloud service's location lookup took too long on all " + f"{ATTEMPTS} requests ({reason}).") + return answered_without("a country", reason, "the location product") + + +def load_example(resource_key): + """Runs the example's file as a module, with the resource key in its + environment, and returns the module.""" + spec = importlib.util.spec_from_file_location( + "location_cloud_web_example", EXAMPLE) + module = importlib.util.module_from_spec(spec) + with mock.patch.dict(os.environ, {RESOURCE_KEY_VARIABLE: resource_key}): + spec.loader.exec_module(module) + return module + + +@pytest.mark.live +class LocationWebExampleTests(unittest.TestCase): + + resource_key = find_resource_key() + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.example = load_example(cls.resource_key) \ + if cls.resource_key else None + + @classmethod + def tearDownClass(cls): + if cls.example is not None: + cls.example.pipeline.close() + super().tearDownClass() + + def setUp(self): + if not self.resource_key: + self.skipTest(NO_KEY) + self.client = self.example.app.test_client() + + def test_page_holds_the_script_that_asks_for_the_position(self): + response = self.client.get("/") + page = response.get_data(as_text=True) + + self.assertEqual(200, response.status_code, page) + self.assertIn("

Client side evidence

", page) + # The script posts to the example's JSON route. + self.assertIn("/json", page) + + def test_json_route_gives_the_country_at_the_position(self): + response, text, location = post_position(self.client) + + self.assertEqual(200, response.status_code, text) + self.assertEqual("application/json", response.headers["Content-Type"]) + self.assertNotEqual( + AFTER_ERRORS, response.headers.get("Cache-Control"), + "Processing the request failed.") + self.assertTrue(location.get("country"), country_failure(location)) + + +class StandInResponse: + + def __init__(self, location): + self.text = json.dumps({"location": location}) + + def get_data(self, as_text=False): + return self.text + + +class StandInClient: + """Answers each post with the next location section given.""" + + def __init__(self, *locations): + self.locations = list(locations) + self.posts = 0 + + def post(self, path, data=None): + self.posts += 1 + return StandInResponse(self.locations.pop(0)) + + +TIMED_OUT = {"country": None, + "countrynullreason": "Timeout processing location request"} +NOT_CARRIED = {"country": None, + "countrynullreason": "The key does not include location"} +ANSWERED = {"country": "United Kingdom"} + + +class PostPositionTests(unittest.TestCase): + """The asking again, against a stand-in for the example, so these run + with no resource key.""" + + def setUp(self): + self.pauses = [] + + def post(self, client): + return post_position(client, sleep=self.pauses.append)[2] + + def test_a_lookup_that_took_too_long_is_asked_again(self): + client = StandInClient(TIMED_OUT, ANSWERED) + + self.assertEqual(ANSWERED, self.post(client)) + self.assertEqual(2, client.posts) + self.assertEqual([PAUSE_SECONDS], self.pauses) + + def test_any_other_reason_is_not_asked_again(self): + client = StandInClient(NOT_CARRIED, ANSWERED) + + self.assertEqual(NOT_CARRIED, self.post(client)) + self.assertEqual(1, client.posts) + + def test_a_lookup_that_took_too_long_each_time_is_said_so(self): + message = country_failure(TIMED_OUT) + + self.assertIn("took too long", message) + self.assertIn(str(ATTEMPTS), message) + self.assertNotIn("key", message) + + def test_any_other_reason_points_at_the_key(self): + self.assertEqual( + answered_without("a country", NOT_CARRIED["countrynullreason"], + "the location product"), + country_failure(NOT_CARRIED)) + + def test_it_stops_after_the_attempts(self): + client = StandInClient(*[TIMED_OUT] * (ATTEMPTS + 1)) + + self.assertEqual(TIMED_OUT, self.post(client)) + self.assertEqual(ATTEMPTS, client.posts) + self.assertEqual([PAUSE_SECONDS] * (ATTEMPTS - 1), self.pauses) + + +if __name__ == "__main__": + unittest.main() diff --git a/location/tox.ini b/location/tox.ini index c625edbc..1a487fd9 100644 --- a/location/tox.ini +++ b/location/tox.ini @@ -5,6 +5,10 @@ minversion = 4.0 deps = pytest>=6 pytest-cov + # The web example is a Flask application, and the web integration in + # fiftyone_pipeline_core, which it uses, imports Flask without the + # package requiring it. + flask [testenv] description = run the tests with pytest @@ -20,10 +24,11 @@ deps = commands = pytest --cov={envsitepackagesdir}/fiftyone_location {tty:--color=yes} {posargs} pass_env = - _51DEGREES_RESOURCE_KEY - resource_key - _51DEGREES_LICENSE_KEY - license_key + # Every variable the tests read starts _51DEGREES_. + _51DEGREES_* + # The marker selection of ci/run-integration-tests.ps1, which leaves the + # live tests out when no resource key is passed. + PYTEST_ADDOPTS # Tests the packages just built, so it takes the test tools from [common] # and every package from the requirements file, never the editable copies diff --git a/pipeline/.github/workflows/examples.yml b/pipeline/.github/workflows/examples.yml deleted file mode 100644 index 2b0fcc41..00000000 --- a/pipeline/.github/workflows/examples.yml +++ /dev/null @@ -1,43 +0,0 @@ -name: Examples - -# Runs the tests of the examples in fiftyone_pipeline_cloudrequestengine/examples -# on demand. -# -# The examples are tested by common-ci on every Python version and operating -# system in ci/options.json, in the pull request and nightly workflows, because -# ci/run-integration-tests.ps1 lists them. This workflow is only for running -# them alone, on one Linux runner, without waiting for a full pipeline. -# -# The tests that call the cloud service read _51DEGREES_RESOURCE_KEY. It is -# set from the organisation's bespoke resource key, because that key carries -# the device detection, IP intelligence and translated country name -# properties the examples show. -# -# The secret is named rather than passed as toJSON(secrets), for the reason -# given in cloud-51did.yml. - -on: - workflow_dispatch: - -jobs: - examples: - name: Examples - runs-on: ubuntu-latest - defaults: - run: - working-directory: fiftyone_pipeline_cloudrequestengine/examples - steps: - - uses: actions/checkout@v4 - with: - # The client-side script is built from the JavaScript templates, - # which are a submodule of the core package. - submodules: recursive - - uses: actions/setup-python@v5 - with: - python-version: '3.11' - - name: Install tox - run: python -m pip install --upgrade pip tox - - name: Test the examples - env: - _51DEGREES_RESOURCE_KEY: ${{ secrets._51DEGREES_RESOURCE_KEY_BESPOKE }} - run: python -m tox -e py -- -v -rs diff --git a/pipeline/.github/workflows/monthly-copyright-update.yml b/pipeline/.github/workflows/monthly-copyright-update.yml deleted file mode 100644 index 8a8536f6..00000000 --- a/pipeline/.github/workflows/monthly-copyright-update.yml +++ /dev/null @@ -1,22 +0,0 @@ -name: Monthly Copyright Update - -on: - workflow_dispatch: - inputs: - dryrun: - default: false - type: boolean - description: Dry Run - schedule: - # The copyright year only changes once a year, so this runs on 1 January. - - cron: '0 0 1 1 *' - -jobs: - Monthly_Copyright_Update: - uses: 51Degrees/common-ci/.github/workflows/monthly-copyright-update.yml@main - with: - repo-name: ${{ github.event.repository.name }} - org-name: ${{ github.event.repository.owner.login }} - dryrun: ${{ inputs.dryrun || false }} - secrets: - token: ${{ secrets.ACCESS_TOKEN }} diff --git a/pipeline/.github/workflows/nightly-pipeline.yml b/pipeline/.github/workflows/nightly-pipeline.yml deleted file mode 100644 index 6bf37dc3..00000000 --- a/pipeline/.github/workflows/nightly-pipeline.yml +++ /dev/null @@ -1,49 +0,0 @@ -name: Nightly Pipeline - -on: - workflow_dispatch: - inputs: - dryrun: - type: boolean - default: false - schedule: - - cron: '0 1 * * *' - -jobs: - SubmoduleUpdate: - name: Nightly Submodule Update - uses: 51Degrees/common-ci/.github/workflows/nightly-submodule-update.yml@main - with: - repo-name: ${{ github.event.repository.name }} - org-name: ${{ github.event.repository.owner.login }} - dryrun: ${{ inputs.dryrun || false }} - secrets: - token: ${{ secrets.ACCESS_TOKEN }} - - PullRequests: - if: ${{ !cancelled() }} - needs: SubmoduleUpdate - name: Nightly Pull Requests - uses: 51Degrees/common-ci/.github/workflows/nightly-pull-requests.yml@main - with: - repo-name: ${{ github.event.repository.name }} - org-name: ${{ github.event.repository.owner.login }} - dryrun: ${{ inputs.dryrun || false }} - secrets: - token: ${{ secrets.ACCESS_TOKEN }} - TestResourceKey: ${{ secrets._51DEGREES_RESOURCE_KEY_BESPOKE }} - - Publish: - if: ${{ !cancelled() }} - needs: PullRequests - name: Nightly Publish - uses: 51Degrees/common-ci/.github/workflows/nightly-publish.yml@main - with: - repo-name: ${{ github.event.repository.name }} - org-name: ${{ github.event.repository.owner.login }} - dryrun: ${{ inputs.dryrun || false }} - secrets: - token: ${{ secrets.ACCESS_TOKEN }} - TestResourceKey: ${{ secrets._51DEGREES_RESOURCE_KEY_BESPOKE }} - PypiToken: ${{ secrets.PYPI_TOKEN }} - diff --git a/pipeline/.github/workflows/publish.yml b/pipeline/.github/workflows/publish.yml deleted file mode 100644 index adfa9188..00000000 --- a/pipeline/.github/workflows/publish.yml +++ /dev/null @@ -1,21 +0,0 @@ -name: Publish - -on: - workflow_dispatch: - inputs: - dryrun: - type: boolean - default: false - -jobs: - Publish: - name: Publish - uses: 51Degrees/common-ci/.github/workflows/nightly-publish.yml@main - with: - repo-name: ${{ github.event.repository.name }} - org-name: ${{ github.event.repository.owner.login }} - dryrun: ${{ inputs.dryrun || false }} - secrets: - token: ${{ secrets.ACCESS_TOKEN }} - TestResourceKey: ${{ secrets._51DEGREES_RESOURCE_KEY_BESPOKE }} - PypiToken: ${{ secrets.PYPI_TOKEN }} diff --git a/pipeline/.github/workflows/pull-requests.yml b/pipeline/.github/workflows/pull-requests.yml deleted file mode 100644 index 0a65b3e6..00000000 --- a/pipeline/.github/workflows/pull-requests.yml +++ /dev/null @@ -1,20 +0,0 @@ -name: Pull Requests - -on: - workflow_dispatch: - inputs: - dryrun: - type: boolean - default: false - -jobs: - PullRequests: - name: Pull Requests - uses: 51Degrees/common-ci/.github/workflows/nightly-pull-requests.yml@main - with: - repo-name: ${{ github.event.repository.name }} - org-name: ${{ github.event.repository.owner.login }} - dryrun: ${{ inputs.dryrun || false }} - secrets: - token: ${{ secrets.ACCESS_TOKEN }} - TestResourceKey: ${{ secrets._51DEGREES_RESOURCE_KEY_BESPOKE }} diff --git a/pipeline/.github/workflows/submodule-update.yml b/pipeline/.github/workflows/submodule-update.yml deleted file mode 100644 index 76c78c0f..00000000 --- a/pipeline/.github/workflows/submodule-update.yml +++ /dev/null @@ -1,19 +0,0 @@ -name: Submodule Update - -on: - workflow_dispatch: - inputs: - dryrun: - type: boolean - default: false - -jobs: - SubmoduleUpdate: - name: Submodule Update - uses: 51Degrees/common-ci/.github/workflows/nightly-submodule-update.yml@main - with: - repo-name: ${{ github.event.repository.name }} - org-name: ${{ github.event.repository.owner.login }} - dryrun: ${{ inputs.dryrun || false }} - secrets: - token: ${{ secrets.ACCESS_TOKEN }} diff --git a/pipeline/.github/workflows/utm-link-lint.yml b/pipeline/.github/workflows/utm-link-lint.yml deleted file mode 100644 index 2edc6722..00000000 --- a/pipeline/.github/workflows/utm-link-lint.yml +++ /dev/null @@ -1,25 +0,0 @@ -name: UTM link lint - -on: - pull_request: - push: - branches: - - main - workflow_dispatch: - -jobs: - utm-link-lint: - runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@v4 - - - name: Checkout common-ci - uses: actions/checkout@v4 - with: - repository: 51Degrees/common-ci - path: utm-lint-common-ci - - - name: Lint 51degrees.com links - shell: pwsh - run: ./utm-lint-common-ci/scripts/utm-lint.ps1 -RepoRoot . diff --git a/pipeline/ci/README.md b/pipeline/ci/README.md index 399dcd50..8b6a36ef 100644 --- a/pipeline/ci/README.md +++ b/pipeline/ci/README.md @@ -2,9 +2,16 @@ This API complies with the `common-ci` approach. The following secrets are required: -* `ACCESS_TOKEN` - GitHub [access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#about-personal-access-tokens) for cloning repos, creating PRs, etc. +* `_51DEGREES_ACCESS_TOKEN` - GitHub [access token](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens#about-personal-access-tokens) for cloning repos, creating PRs, etc. * Example: `github_pat_l0ng_r4nd0m_s7r1ng` -* `SUPER_RESOURCE_KEY` - [resource key](https://51degrees.com/documentation/_services__cloud__resource_keys.html?utm_source=github&utm_medium=readme&utm_campaign=51degrees-python&utm_content=ci-readme.md&utm_term=api-specific-ci-cd-approach) for integration tests +* `_51DEGREES_RESOURCE_KEY_BESPOKE` - [resource key](https://51degrees.com/documentation/_services__cloud__resource_keys.html?utm_source=github&utm_medium=readme&utm_campaign=51degrees-python&utm_content=ci-readme.md&utm_term=api-specific-ci-cd-approach) for the integration tests. It is an organization secret. common-ci exports it. * Example: `R4nd0m-S7r1ng` -* `PYPI_TOKEN` - [PyPI token](https://pypi.org/help/#apitoken) for publishing packages +* `_51DEGREES_RESOURCE_KEY_BASIC` - resource key of the Basic product, an organization secret. The Basic Human Confidence test, which calls the staging cloud, and the 51Did tier test read it, and skip naming it when it is not set. +* `_51DEGREES_LICENSE_KEY_BESPOKE` - cloud license key for the license-key tests, an organization secret, which skip naming it when it is not set. +* `_51DEGREES_RESOURCE_KEY_51DID` and `_51DEGREES_LICENSE_KEY_51DID` - the 51Did live tests' resource key and the license key of the same account. The resource key and the license key are both organization secrets. With a resource key of another account, such as `_51DEGREES_RESOURCE_KEY_BESPOKE`, the licensed redeem comes back unreadable. +* `_51DEGREES_PYPI_TOKEN` - [PyPI token](https://pypi.org/help/#apitoken) for publishing packages * Example: `pypi-sUp3r-l0nG_r4nd0m-s7r1Ng` + +The Human Confidence tests marked `staging` check what the production cloud does not serve yet, and the Cloud Human Confidence workflow (`.github/workflows/cloud-human-confidence.yml`) runs them against the staging cloud. Only CI uses these two names, which have no `_51DEGREES_` prefix. common-ci does not pass them on, so in the shared integration tests the staging tests skip. +* `CLOUD_STAGING_ENDPOINT` - the staging cloud's API base, ending `/api/v4/`, an organization variable. The staging tests have no default address and skip, naming it, when it is not set. +* `RESOURCE_KEY_BESPOKE_STAGING` - a Bespoke resource key the staging cloud knows, an organization secret. diff --git a/pipeline/ci/build-project.ps1 b/pipeline/ci/build-project.ps1 index a7ae240c..bbf0d7b9 100644 --- a/pipeline/ci/build-project.ps1 +++ b/pipeline/ci/build-project.ps1 @@ -8,7 +8,7 @@ param ( # anything builds. See ci/copy-owid-source.ps1 for the full reasoning. & "$PSScriptRoot/copy-owid-source.ps1" -RepoRoot $RepoName -$packages = "fiftyone_pipeline_core", "fiftyone_pipeline_engines", "fiftyone_pipeline_engines_fiftyone", "fiftyone_pipeline_cloudrequestengine", "fiftyone_pipeline_translation" +$packages = "fiftyone_pipeline_core", "fiftyone_pipeline_engines", "fiftyone_pipeline_engines_fiftyone", "fiftyone_pipeline_cloudrequestengine", "fiftyone_pipeline_translation", "fiftyone_pipeline_derivedproperty" ./python/build-project.ps1 -RepoName $RepoName -Packages $packages exit $LASTEXITCODE diff --git a/pipeline/ci/publish-package.ps1 b/pipeline/ci/publish-package.ps1 index cb74fe47..596db5cf 100644 --- a/pipeline/ci/publish-package.ps1 +++ b/pipeline/ci/publish-package.ps1 @@ -1,9 +1,7 @@ param ( - [Parameter(Mandatory=$true)] - [Hashtable]$Keys, [bool]$DryRun = $False ) -./python/publish-package-pypi.ps1 -Keys $Keys -DryRun $DryRun +./python/publish-package-pypi.ps1 -DryRun $DryRun exit $LASTEXITCODE diff --git a/pipeline/ci/run-integration-tests.ps1 b/pipeline/ci/run-integration-tests.ps1 index a4845edd..07aa7d45 100644 --- a/pipeline/ci/run-integration-tests.ps1 +++ b/pipeline/ci/run-integration-tests.ps1 @@ -1,48 +1,59 @@ param ( [Parameter(Mandatory=$true)] - [string]$RepoName, - [Parameter(Mandatory=$true)] - [Hashtable]$Keys + [string]$RepoName ) -if (!$Keys.TestResourceKey) { - throw "No TestResourceKey was passed, so the cloud tests cannot call " + - "the cloud service. The workflows set it from the " + - "_51DEGREES_RESOURCE_KEY_BESPOKE secret." -} - # The examples call the cloud service, so they are integration tests rather # than unit tests. Listing them here runs them on every Python version and # operating system in options.json, and in the nightly, which a standalone # workflow did not. # -# This script's common-ci counterpart sets resource_key from the -# TestResourceKey secret, and license_key from the DeviceDetection secret. -# The workflows pass DeviceDetection for Device Detection's data files. It is -# not a licence key for the cloud service, so the examples' licence-key tests -# failed with it. They are not given it, and skip themselves as they did when -# pipeline was its own repository, until a cloud licence key is passed. +# _51DEGREES_LICENSE_KEY is the data license, for Device Detection's data +# files, and not a license key for the cloud service. The license-key tests +# read _51DEGREES_LICENSE_KEY_BESPOKE instead, and skip naming it when it is +# not set. The 51Did tests read _51DEGREES_RESOURCE_KEY_51DID and +# _51DEGREES_LICENSE_KEY_51DID, which common-ci exports. # # The 51Did package runs only its tests marked live here, as its others ran # in the unit step. Its tier tests need a key for another tier, which only # the Cloud 51Did workflow has. Only a package whose tox.ini passes -# PYTEST_ADDOPTS sees the selection. Its build needs the OWID source, which -# build-project.ps1 copies, and the publish workflow's test job does not run -# that script, so it is copied here too. -& "$PSScriptRoot/copy-owid-source.ps1" -RepoRoot $RepoName -$packages = "fiftyone_pipeline_cloudrequestengine", "fiftyone_pipeline_cloudrequestengine/examples", "fiftyone_pipeline_did" -$pipelineKeys = $Keys.Clone() -$pipelineKeys.Remove('DeviceDetection') -# The tests read the resource key from _51DEGREES_RESOURCE_KEY, and common-ci -# sets only the older resource_key, so the key is set here. -$env:_51DEGREES_RESOURCE_KEY = $Keys.TestResourceKey +# PYTEST_ADDOPTS sees the selection, so the 51Did package is run on its own, +# after the others. Its build needs the OWID source, which build-project.ps1 +# copies, and the publish workflow's test job does not run that script, so +# it is copied here too. +# +# Without a resource key the tests that need one, which are marked live, are +# left out and every other test runs. That leaves nothing of the 51Did +# package, so it is not run. A live test still fails when it finds no key, so +# a key that is passed but does not reach it is not missed. The selection is +# added to any options a caller set in PYTEST_ADDOPTS. +$packages = "fiftyone_pipeline_cloudrequestengine", "fiftyone_pipeline_cloudrequestengine/examples" +$failed = $false $addopts = $env:PYTEST_ADDOPTS -$env:PYTEST_ADDOPTS = '-m "live and not tier"' try { - ./python/run-integration-tests.ps1 -RepoName $RepoName -Packages $packages -Keys $pipelineKeys + if (!$env:_51DEGREES_RESOURCE_KEY_BESPOKE) { + Write-Output "::warning title=No resource key::_51DEGREES_RESOURCE_KEY_BESPOKE is not set, so the tests that need a resource key are skipped. They are marked live, and the other integration tests run. fiftyone_pipeline_did runs only live tests here, so it is skipped. common-ci exports it from the organization secret of that name." + $env:PYTEST_ADDOPTS = "$addopts -m `"not live`"".Trim() + } + ./python/run-integration-tests.ps1 -RepoName $RepoName -Packages $packages + if ($LASTEXITCODE -ne 0) { $failed = $true } + + if ($env:_51DEGREES_RESOURCE_KEY_BESPOKE) { + # common-ci's script combines the coverage of the packages it ran + # into .coverage, and a second run replaces that file, so the first + # run's is kept under a name the second run's combine reads. + $coverage = Join-Path $RepoName '.coverage' + if (Test-Path $coverage) { + Move-Item -Force $coverage (Join-Path $RepoName '.coverage.cloudrequestengine') + } + & "$PSScriptRoot/copy-owid-source.ps1" -RepoRoot $RepoName + $env:PYTEST_ADDOPTS = '-m "live and not tier"' + ./python/run-integration-tests.ps1 -RepoName $RepoName -Packages "fiftyone_pipeline_did" + if ($LASTEXITCODE -ne 0) { $failed = $true } + } } finally { $env:PYTEST_ADDOPTS = $addopts } -exit $LASTEXITCODE +exit ($failed ? 1 : 0) diff --git a/pipeline/ci/run-unit-tests.ps1 b/pipeline/ci/run-unit-tests.ps1 index 441a2bcc..c379c287 100644 --- a/pipeline/ci/run-unit-tests.ps1 +++ b/pipeline/ci/run-unit-tests.ps1 @@ -9,7 +9,7 @@ param ( $addopts = $env:PYTEST_ADDOPTS $env:PYTEST_ADDOPTS = '-m "not live"' try { - $packages = "fiftyone_pipeline_core", "fiftyone_pipeline_engines", "fiftyone_pipeline_engines_fiftyone", "fiftyone_pipeline_translation", "fiftyone_pipeline_did" + $packages = "fiftyone_pipeline_core", "fiftyone_pipeline_engines", "fiftyone_pipeline_engines_fiftyone", "fiftyone_pipeline_translation", "fiftyone_pipeline_did", "fiftyone_pipeline_derivedproperty" ./python/run-unit-tests.ps1 -RepoName $RepoName -Packages $packages } finally { $env:PYTEST_ADDOPTS = $addopts diff --git a/pipeline/docs/Doxyfile b/pipeline/docs/Doxyfile index c62f0df0..68995958 100644 --- a/pipeline/docs/Doxyfile +++ b/pipeline/docs/Doxyfile @@ -897,6 +897,7 @@ EXCLUDE_SYMBOLS = # command). EXAMPLE_PATH = ../fiftyone_pipeline_core/examples \ + ../fiftyone_pipeline_engines/examples \ ../fiftyone_pipeline_engines_fiftyone/examples \ ../fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples \ ../../../documentation/src/snippets diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/readme.md b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/readme.md index c3457cd2..ca67efd2 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/readme.md +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/readme.md @@ -1,8 +1,9 @@ # Examples -Examples of the 51Degrees Pipeline API for Python that call the 51Degrees -cloud service through the cloud request engine, which is the package this -folder sits in. +Examples of the 51Degrees Pipeline API for Python that use the cloud request +engine, which is the package this folder sits in. The mixed examples call +the 51Degrees cloud service, and the cloud engine example calls a star sign +service of its own. ## Cloud, mixed @@ -25,13 +26,19 @@ answer. Those engines are in `src/fiftyone_pipeline_examples/cloud/engines.py`, and `src/fiftyone_pipeline_examples/cloud/mixed/pipeline.py` puts them together. +A Flow Data cannot be used by two threads at once, so the web example +creates a Flow Data for each request, uses it only in the code that handles +that request, and closes it when the request ends. To hand work to another +thread or task, read the values it needs from the Flow Data first and pass +those values, not the Flow Data. + ### Keys The examples call the cloud service with a resource key or a licence key. A resource key carries the list of properties it returns. Create one carrying device detection and IP intelligence properties for free with the -[configurator](https://configure.51degrees.com?utm_source=github&utm_medium=readme&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-readme.md&utm_term=resource-key), +[configuration page](https://51degrees.com/configure?utm_source=github&utm_medium=readme&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-readme.md&utm_term=resource-key), and set the `_51DEGREES_RESOURCE_KEY` environment variable to it. A resource key limited to particular domains only answers a request whose origin is one of them, so set @@ -82,7 +89,8 @@ and the web example with .venv/bin/python -m fiftyone_pipeline_examples.cloud.mixed.gettingstarted_web ``` -then open . Set `PORT` to listen on another port. +then open . Set `_51DEGREES_EXAMPLE_HTTP_PORTS` to +listen on another port. ### Tests @@ -90,18 +98,41 @@ then open . Set `PORT` to listen on another port. .venv/bin/python -m pytest ``` -The tests that call the cloud service with a resource key fail when none is -set, naming the variables they read, which are `_51DEGREES_RESOURCE_KEY` -and `_51DEGREES_RESOURCE_KEY_BESPOKE`, in that order. The +The tests that call the cloud service with a resource key skip when none is +set, naming the variable they read, which is +`_51DEGREES_RESOURCE_KEY_BESPOKE`. They are marked +`live`, so `python -m pytest -m "not live"` runs every other test. The tests that use a licence key skip themselves when none is set. In CI the examples are run by [ci/run-integration-tests.ps1](../../ci/run-integration-tests.ps1) through common-ci, on every Python version and operating system in [ci/options.json](../../ci/options.json), with the resource key the pipeline -holds. No licence key is passed to the pipeline, so the licence-key tests -skip themselves there. That uses the [tox.ini](tox.ini) in this folder, +holds. When no resource key is passed, the script leaves out the tests +marked `live`, says so, and runs the rest. No licence key is passed to the +pipeline, so the licence-key tests skip themselves there. That uses the [tox.ini](tox.ini) in this folder, which can also be run by hand with `python -m tox -e py` from here. +## Cloud engine + +`src/fiftyone_pipeline_examples/cloud/simple_cloud_engine.py` shows how to +write a cloud engine of your own. The engine gets the star sign for a date +of birth from a remote service, through a cloud request engine, and the +example prints the reason the service gives when it has no star sign. + +So that it runs with no key and no network, the example starts a small star +sign service of its own on this machine, which answers in the shapes the +51Degrees cloud service uses. It reads none of the environment variables +under Keys. + +Run it, once the requirements are installed as above, with + +```sh +.venv/bin/python -m fiftyone_pipeline_examples.cloud.simple_cloud_engine +``` + +Its test, `tests/test_simple_cloud_engine.py`, runs with the others and needs +no key. + ## Find out more - [Device detection](https://51degrees.com/device-detection?utm_source=github&utm_medium=readme&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-readme.md&utm_term=find-out-more-device-detection) diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/__init__.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/__main__.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/__main__.py new file mode 100644 index 00000000..33d18ae1 --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/__main__.py @@ -0,0 +1,29 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +import sys + +from .app import main + +# Lets the example run as the package, without ".app" on the module name. +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/app.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/app.py new file mode 100644 index 00000000..97f13c1d --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/app.py @@ -0,0 +1,309 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +## @example cloud/humanconfidence_web/app.py +# +# Human Confidence demo server. A Flask web application. Run: +# ``` +# python -m fiftyone_pipeline_examples.cloud.humanconfidence_web +# ``` +# then open http://localhost:5151/ +# +# Human Confidence says how likely it is that a person is looking at the +# page. It comes in two ways, and this demo shows both. +# +# 1. Passive. This server asks the cloud itself, sending the visitor's +# request headers and IP address. HumanConfidenceSource is Passive and +# HumanConfidence is a plain level. +# The server asks for it rather than reading it from the page, because +# a level a browser sends can be forged. +# 2. Active. The page loads the 51Degrees client script, which runs the +# browser tests and sends the answers to the cloud. When the script +# completes, HumanConfidenceSource is Active and HumanConfidence holds +# a sealed value the browser can't read or change. +# 3. Redeem. The page hands the sealed value to this server, which calls +# hc/redeem with it and the account's License Key, and gets the true +# level back. A sealed value redeems once, within ten seconds. This +# server is the only party holding the License Key, which the browser +# never sees. +# +# This example is available in full on [GitHub](https://github.com/51Degrees/51degrees-python/blob/main/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/app.py). +# +# Environment variables: +# - _51DEGREES_RESOURCE_KEY, the Resource Key, required +# - _51DEGREES_LICENSE_KEY, a License Key of the same account, required +# to redeem +# - _51DEGREES_CLOUD_ENDPOINT, the API base including the /api/v4/ +# segment, defaults to https://cloud.51degrees.com/api/v4/ +# - _51DEGREES_EXAMPLE_HTTP_PORTS, the port to listen on, defaults to 5151 +# +# See readme.md beside this file for the steps and what to expect. +# +# Required PyPI dependencies: +# - [flask](https://pypi.org/project/flask/) +# - [requests](https://pypi.org/project/requests/) + +import ipaddress +import os +import sys +import urllib.parse + +import requests +from flask import Flask, Response, jsonify, make_response, render_template +from flask import request + +from fiftyone_pipeline_examples.example_utils import ExampleUtils + +DEFAULT_API = "https://cloud.51degrees.com/api/v4/" + +# The property the Resource Key has to carry. +PROPERTY = "HumanConfidence" + +# A short limit, in seconds, so a slow cloud can't hang the demo. +TIMEOUT = 10 + +# Where to go next. The page ends with these links, and the example prints +# them when it stops before the page is served. +FIND_OUT_MORE = [ + ("Bots and humans", + "https://51degrees.com/bots-and-humans?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-humanconfidence_web-app.py&utm_term=find-out-more-bots-and-humans"), + ("Resource keys", + "https://51degrees.com/documentation/_services__cloud__resource_keys.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-humanconfidence_web-app.py&utm_term=find-out-more-resource-keys"), + ("Pricing", + "https://51degrees.com/pricing?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-humanconfidence_web-app.py&utm_term=find-out-more-pricing"), + ("Contact us", + "https://51degrees.com/contact-us?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-humanconfidence_web-app.py&utm_term=find-out-more-contact-us"), + ("Pipeline API for Python", + "https://github.com/51Degrees/51degrees-python/tree/main/pipeline"), +] + + +def print_find_out_more(): + + """! + Print the "Find out more" section, a line of "=" and then each label + with its link, to standard output. The example prints it when it stops + before the page is served, which ends with the same links. + """ + + message = ["=" * 79, "Find out more:"] + for label, url in FIND_OUT_MORE: + message.append(f"\t{label}: {url}") + print("\n".join(message) + "\n") + + +def api_base(endpoint): + + """! + The cloud API base ending in /api/v4/, being the endpoint named, or the + public cloud when none is named. + """ + + endpoint = (endpoint or "").strip() + return (endpoint or DEFAULT_API).rstrip("/") + "/" + + +def carries_human_confidence(api, resource_key): + + """! + Whether the Resource Key carries HumanConfidence, from the cloud's own + list of the properties the key carries. + """ + + answer = requests.request( + "GET", + api + "accessibleproperties?resource=" + + urllib.parse.quote(resource_key, safe=""), + timeout=TIMEOUT) + if answer.status_code != 200: + raise ValueError(f"HTTP {answer.status_code}: {trim(answer.text)}") + products = answer.json().get("Products") or {} + for product in products.values(): + for item in (product or {}).get("Properties") or []: + if str(item.get("Name", "")).lower() == PROPERTY.lower(): + return True + return False + + +def create_app(resource_key, license_key, api): + + """! + Create the Flask application that serves the page, asks the cloud for + the passive level, and redeems the sealed active level. + """ + + # Serve the files in the static folder from the root, so the stylesheet + # is at /css, as in the other web examples. + app = Flask(__name__, static_url_path="") + + # The request headers the cloud reads, from its own list, fetched once. + # Only these are passed on, so headers such as Authorization stay here. + fetched = [] + + def cloud_headers(): + if not fetched: + answer = requests.request( + "GET", api + "evidencekeys", timeout=TIMEOUT) + if answer.status_code != 200: + raise ValueError( + f"HTTP {answer.status_code}: {trim(answer.text)}") + fetched.append({ + key[len("header."):].lower() for key in answer.json() + if key.lower().startswith("header.")}) + return fetched[0] + + @app.route("/") + def index(): + + response = make_response(render_template( + "index.html", resource_key=resource_key, api=api)) + # The page must never come from a cache, as each load runs the + # tests. + response.headers["Cache-Control"] = "no-store" + return response + + # Passive: this server asks the cloud for the visitor, with the + # visitor's headers and IP address, and reads the plain level from the + # answer. + @app.route("/passive") + def passive(): + + try: + names = cloud_headers() + evidence = {} + for name, value in request.headers.items(): + if name.lower() in names: + evidence[name.lower()] = value + # Behind a load balancer or CDN, use the visitor's address it + # passes on. Set last, so no header can replace it. + if request.remote_addr: + evidence["client-ip"] = client_ip(request.remote_addr) + answer = requests.request( + "POST", api + resource_key + ".json", data=evidence, + timeout=TIMEOUT) + if answer.status_code >= 400: + return jsonify( + error=f"HTTP {answer.status_code}: {trim(answer.text)}") + derived = answer.json().get("derived") + return jsonify( + source=read(derived, "humanconfidencesource"), + humanConfidence=read(derived, "humanconfidence")) + except (requests.RequestException, ValueError) as error: + return jsonify(error=str(error)) + + # Redeem: the page sends the sealed value, and this server redeems it + # with the License Key. The answer goes back to the page as the cloud + # gave it. + @app.route("/redeem", methods=["POST"]) + def redeem(): + + fields = {"value": request.form.get("value", "")} + if license_key: + fields["license"] = license_key + try: + answer = requests.request( + "POST", api + "hc/redeem", data=fields, timeout=TIMEOUT) + except requests.RequestException as error: + return jsonify(error=str(error)), 502 + if answer.status_code == 404: + return jsonify( + error=f"The service at {api} doesn't redeem Human " + "Confidence.") + return Response( + answer.text, status=answer.status_code, + content_type="application/json") + + return app + + +def client_ip(address): + + """! + The address of the connection, as IPv4 when it is an IPv4 address + written as IPv6. + """ + + try: + mapped = getattr(ipaddress.ip_address(address), "ipv4_mapped", None) + except ValueError: + return address + return str(mapped) if mapped else address + + +def read(parent, name): + + """! + The text held under name, or None when there is none. + """ + + value = parent.get(name) if isinstance(parent, dict) else None + return value if isinstance(value, str) else None + + +def trim(text): + return text[:200] + + +def main(argv): + + # A Resource Key given on the command line is used as it is. Otherwise + # it comes from the environment. + resource_key = argv[0] if len(argv) > 0 else \ + ExampleUtils.get_resource_key() + if not resource_key.strip(): + print(f"Set {ExampleUtils.RESOURCE_KEY_ENV_VAR} to the Resource Key " + "of the page. Resource keys are created at " + "https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-humanconfidence_web-app.py&utm_term=resource-key-required") + print_find_out_more() + return + + license_key = ExampleUtils.get_license_key() + api = api_base(ExampleUtils.get_cloud_endpoint()) + + # Before the flow, ask the cloud whether the key carries + # HumanConfidence, so a key without it is told so here. + try: + carried = carries_human_confidence(api, resource_key) + except (requests.RequestException, ValueError) as error: + print(error) + print_find_out_more() + sys.exit(1) + if not carried: + print("Contact us: " + "https://51degrees.com/contact-us?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-humanconfidence_web-app.py&utm_term=human-confidence-required") + print_find_out_more() + sys.exit(1) + + if not license_key.strip(): + print(f"No {ExampleUtils.LICENSE_KEY_ENV_VAR} set. The page still " + "shows Passive and Active, but an account that holds License " + "Keys can't redeem without one, so the redeemed level will be " + "unreadable.") + + app = create_app(resource_key, license_key, api) + port = os.environ.get("_51DEGREES_EXAMPLE_HTTP_PORTS", 5151) + print(f"Human Confidence demo on http://localhost:{port}/, using {api}") + app.run(port=int(os.environ.get("_51DEGREES_EXAMPLE_HTTP_PORTS", 5151))) + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/static/css/examples-main.min.css b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/static/css/examples-main.min.css new file mode 100644 index 00000000..8007642a --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/static/css/examples-main.min.css @@ -0,0 +1 @@ +/*! normalize.css v8.0.1 | MIT License | github.com/necolas/normalize.css */html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}main{display:block}h1{font-size:2em;margin:.67em 0}hr{box-sizing:content-box;height:0;overflow:visible}pre{font-family:monospace,monospace;font-size:1em}a{background-color:transparent}abbr[title]{border-bottom:none;text-decoration:underline;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp{font-family:monospace,monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}img{border-style:none}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,input{overflow:visible}button,select{text-transform:none}button,[type=button],[type=reset],[type=submit]{-webkit-appearance:button}button::-moz-focus-inner,[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner{border-style:none;padding:0}button:-moz-focusring,[type=button]:-moz-focusring,[type=reset]:-moz-focusring,[type=submit]:-moz-focusring{outline:1px dotted ButtonText}fieldset{padding:.35em .75em .625em}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{vertical-align:baseline}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details{display:block}summary{display:list-item}template{display:none}[hidden]{display:none}.a-size--10{width:.1615055829rem;height:.1615055829rem}.a-size--9{width:.1938066995rem;height:.1938066995rem}.a-size--8{width:.2325680394rem;height:.2325680394rem}.a-size--7{width:.2790816472rem;height:.2790816472rem}.a-size--6{width:.3348979767rem;height:.3348979767rem}.a-size--5{width:.401877572rem;height:.401877572rem}.a-size--4{width:.4822530864rem;height:.4822530864rem}.a-size--3{width:.5787037037rem;height:.5787037037rem}.a-size--2{width:.6944444444rem;height:.6944444444rem}.a-size--1{width:.8333333333rem;height:.8333333333rem}.a-size-0{width:1rem;height:1rem}.a-size-1{width:1.2rem;height:1.2rem}.a-size-2{width:1.44rem;height:1.44rem}.a-size-3{width:1.728rem;height:1.728rem}.a-size-4{width:2.0736rem;height:2.0736rem}.a-size-5{width:2.48832rem;height:2.48832rem}.a-size-6{width:2.985984rem;height:2.985984rem}.a-size-7{width:3.5831808rem;height:3.5831808rem}.a-size-8{width:4.29981696rem;height:4.29981696rem}.a-size-9{width:5.159780352rem;height:5.159780352rem}.a-size-10{width:6.1917364224rem;height:6.1917364224rem}.a-size-11{width:7.4300837069rem;height:7.4300837069rem}.a-size-12{width:8.9161004483rem;height:8.9161004483rem}.a-size-13{width:10.6993205379rem;height:10.6993205379rem}.a-size-14{width:12.8391846455rem;height:12.8391846455rem}.a-size-15{width:15.4070215746rem;height:15.4070215746rem}.a-size-16{width:18.4884258895rem;height:18.4884258895rem}.a-size-17{width:22.1861110674rem;height:22.1861110674rem}.a-size-18{width:26.6233332809rem;height:26.6233332809rem}.a-size-19{width:31.9479999371rem;height:31.9479999371rem}.a-size-20{width:38.3375999245rem;height:38.3375999245rem}.a-font-size--10{font-size:.1615055829rem}.a-font-size--9{font-size:.1938066995rem}.a-font-size--8{font-size:.2325680394rem}.a-font-size--7{font-size:.2790816472rem}.a-font-size--6{font-size:.3348979767rem}.a-font-size--5{font-size:.401877572rem}.a-font-size--4{font-size:.4822530864rem}.a-font-size--3{font-size:.5787037037rem}.a-font-size--2{font-size:.6944444444rem}.a-font-size--1{font-size:.8333333333rem}.a-font-size-0{font-size:1rem}.a-font-size-1{font-size:1.2rem}.a-font-size-2{font-size:1.44rem}.a-font-size-3{font-size:1.728rem}.a-font-size-4{font-size:2.0736rem}.a-font-size-5{font-size:2.48832rem}.a-font-size-6{font-size:2.985984rem}.a-font-size-7{font-size:3.5831808rem}.a-font-size-8{font-size:4.29981696rem}.a-font-size-9{font-size:5.159780352rem}.a-font-size-10{font-size:6.1917364224rem}.a-font-size-11{font-size:7.4300837069rem}.a-font-size-12{font-size:8.9161004483rem}.a-font-size-13{font-size:10.6993205379rem}.a-font-size-14{font-size:12.8391846455rem}.a-font-size-15{font-size:15.4070215746rem}.a-font-size-16{font-size:18.4884258895rem}.a-font-size-17{font-size:22.1861110674rem}.a-font-size-18{font-size:26.6233332809rem}.a-font-size-19{font-size:31.9479999371rem}.a-font-size-20{font-size:38.3375999245rem}.a-font--default{font-family:Arial,sans-serif}.a-font--code{font-family:Consolas,monospace}.b-text--hidden{position:absolute;width:1px;height:1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.b-text--default{font-family:Arial,sans-serif;font-size:1rem;color:#252525}.b-text--count{font-family:Arial,sans-serif;font-size:.6944444444rem;color:#9b9b9b}.b-text--count-pill{font-family:Arial,sans-serif;font-size:.6944444444rem;color:#9b9b9b;border:1px solid #BAC82A;border-radius:28px;padding:.093463879rem .4822530864rem;color:#252525;background-color:#fff;display:inline}.b-text--property-pill{font-family:Arial,sans-serif;font-size:.8333333333rem;color:#646060}.b-text--heading-1{font-family:Arial,sans-serif;font-weight:700;font-size:1.44rem;color:#252525;margin:0 0 1.728rem}.b-text--heading-2{font-family:Arial,sans-serif;font-weight:700;font-size:1.2rem;color:#252525;margin:0 0 1.44rem}.b-text--heading-3{font-family:Arial,sans-serif;font-weight:700;font-size:1rem;color:#252525;margin:0 0 1.2rem}.b-text--code{font-family:Consolas,monospace;font-size:.8333333333rem;color:#646060}.b-text--code-snip{font-family:Consolas,monospace;font-size:.8333333333rem;color:#646060;background-color:#fff;border-radius:5px;border:1px solid #EAEAEA;padding:0 .2325680394rem}.b-text--heading-caps{font-family:Arial,sans-serif;font-size:.6944444444rem;color:#252525;font-weight:400;text-transform:uppercase;letter-spacing:.5px}.b-text--copyright{font-family:Arial,sans-serif;font-size:.6944444444rem;color:#252525}.b-text--progress{font-family:Arial,sans-serif;font-size:.8333333333rem}@media(min-width:769px){.b-text--progress{font-size:1rem}}.b-text--progress{color:#252525;letter-spacing:.7px;text-transform:uppercase;font-weight:700}.b-text--red{color:#cc2b27}body{font-family:Arial,sans-serif;font-size:1rem;color:#252525;margin:0;line-height:1.5}*{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;box-sizing:border-box}.b-link{transition:color .3s ease;color:#252525;text-decoration:underline}.b-link:active,.b-link:hover,.b-link:focus{color:#f5841f;text-decoration:underline}.b-link{display:inline-flex;align-items:center}.b-link img{margin:0 .5787037037rem}.b-link--property{font-family:Arial,sans-serif;font-size:.8333333333rem;color:#646060;color:#9b9b9b;border-bottom:2px dotted #EAEAEA;text-decoration:none}.b-link--property:active,.b-link--property:hover,.b-link--property:focus{color:#646060;border-bottom:2px dotted #646060;text-decoration:none}.b-link--dotted{color:#9b9b9b;border-bottom:2px dotted #EAEAEA;text-decoration:none}.b-link--dotted:active,.b-link--dotted:hover,.b-link--dotted:focus{color:#646060;border-bottom:2px dotted #646060;text-decoration:none}.b-link--unstyled{color:inherit;text-decoration:none}.b-link--unstyled:active,.b-link--unstyled:hover,.b-link--unstyled:focus{color:inherit;text-decoration:none}.b-link--docs{transition:color .3s ease;color:#00aeef;text-decoration:none;font-weight:700}.b-link--docs:active,.b-link--docs:hover,.b-link--docs:focus{text-decoration:underline}a.anchor{scroll-margin-top:128px}.b-btn{font-family:Arial,sans-serif;font-size:1rem;color:#252525;color:inherit;text-decoration:none}.b-btn:active,.b-btn:hover,.b-btn:focus{color:inherit;text-decoration:none}.b-btn{display:inline-flex;justify-content:center;align-items:center;padding:.8333333333rem 1.728rem;border:1px solid #BAC82A;background-color:#cbdb2a;cursor:pointer}.b-btn:active,.b-btn:hover,.b-btn:focus{background-color:#daed1a;border:1px solid #CBDB2A;text-decoration:none}.b-btn.b-btn--disabled,.b-btn:disabled{background-color:#f8f8f8;border:1px solid #EAEAEA;color:#646060;cursor:not-allowed;pointer-events:all!important}@media(min-width:769px){.b-btn--large{padding:1.2rem 2.48832rem}}.b-btn--secondary{background-color:#fff}.b-btn--secondary:active,.b-btn--secondary:hover,.b-btn--secondary:focus{background-color:#fff}.b-btn--block{width:100%}.b-btn__icon{margin-right:1rem}.b-btn__icon--after{margin-right:0;margin-left:1rem}input[type=text]{-webkit-appearance:none;-moz-appearance:none;appearance:none}.b-label{color:#646060;font-size:.8333333333rem;margin-bottom:.4822530864rem;width:100%}.b-input-group{display:flex;flex-direction:column}@media(min-width:769px){.b-input-group{flex-direction:row}}.b-input{font-family:Arial,sans-serif;font-size:1rem;color:#252525;border:solid 1px #646060;padding:.8333333333rem;line-height:1.2}.b-form-group--with-icon .b-input{padding-left:46px}.b-input::placeholder{color:#bfbfbf;opacity:1}.b-input,.b-input--block{width:100%}.b-form-group{display:flex;flex-direction:column}.b-form-group .b-btn{margin-top:1rem}@media(min-width:769px){.b-form-group .b-btn{margin-top:0;margin-left:.8333333333rem}}.b-form-group--with-icon{position:relative}.b-form-group--with-icon .b-icon{position:absolute;width:20px;height:20px;top:14px;left:10px}.c-eg-page{max-width:800px;margin:0 auto;padding:1.44rem 1.2rem}.c-eg-page__title{font-family:Arial,sans-serif;font-weight:700;font-size:1.2rem;color:#252525;margin:0 0 1.44rem}.c-eg-page__heading{font-family:Arial,sans-serif;font-weight:700;font-size:1rem;color:#252525;margin:1.728rem 0 1.2rem}.c-eg-page__lead{margin-bottom:1.44rem}.c-eg-section{margin-bottom:1.728rem}.c-eg-alert{font-family:Arial,sans-serif;font-size:1rem;color:#252525;border:1px solid #CC2B27;border-radius:5px;background-color:#fef1f9;padding:.8333333333rem 1rem;margin:1.2rem 0}.c-eg-alert a{color:#cc2b27;font-weight:700}.c-eg-table{font-family:Arial,sans-serif;font-size:1rem;color:#252525;width:100%;max-width:800px;font-size:.8333333333rem;background-color:#fff;border-collapse:collapse;margin-bottom:1.2rem}.c-eg-table__head .c-eg-table__cell{font-weight:700;border-bottom:3px solid #EAEAEA}.c-eg-table__cell{padding:.5787037037rem .6944444444rem;text-align:left;vertical-align:top;border-bottom:1px solid #EAEAEA}.c-eg-table__cell--key{font-weight:700;white-space:nowrap}.c-eg-table__cell ul{margin:0;padding-left:1rem}.c-eg-table__row--used{background-color:#f9fbe9}.c-eg-table__row--present,.c-eg-table__row--alt{background-color:#f8f8f8}.c-eg-table__action{padding:.4822530864rem .6944444444rem;font-size:.6944444444rem;white-space:nowrap;width:auto}.c-eg-legend{font-size:.6944444444rem;color:#646060;margin-bottom:.6944444444rem}.c-eg-legend__swatch{padding:0 .4822530864rem;border-radius:5px}.c-eg-legend__swatch--used{background-color:#f9fbe9}.c-eg-legend__swatch--present{background-color:#f8f8f8}.c-eg-form{margin-bottom:1.44rem}.c-eg-form__row{display:flex;flex-direction:column}@media(min-width:769px){.c-eg-form__row{flex-direction:row;align-items:flex-end}}.c-eg-form .b-btn{margin-top:.8333333333rem}@media(min-width:769px){.c-eg-form .b-btn{margin-top:0;margin-left:.8333333333rem}}.c-eg-map{margin:1.44rem 0}.c-eg-map__title{font-family:Arial,sans-serif;font-weight:700;font-size:1rem;color:#252525;margin:0 0 1.2rem}.c-eg-map__canvas{height:400px;width:100%;border:1px solid #EAEAEA;border-radius:5px}.c-eg-columns{display:grid;grid-template-columns:1fr;gap:1.44rem}@media(min-width:993px){.c-eg-columns{grid-template-columns:1fr 1fr}}.c-eg-details{margin:1.2rem 0 1.44rem;border:1px solid #EAEAEA;border-radius:5px;padding:0 1rem}.c-eg-details>summary{cursor:pointer;padding:.6944444444rem 0;font-weight:700}.c-eg-button-row{margin:1.2rem 0 1.44rem}.c-eg-message{display:flex;flex-direction:column;align-items:flex-start;gap:.8333333333rem;margin-top:2.0736rem;padding:1rem 1.2rem;background:#f8f8f8;border:1px solid #EAEAEA;border-radius:5px}@media(min-width:769px){.c-eg-message{flex-direction:row;align-items:center;justify-content:space-between;gap:1.2rem}}.c-eg-message__text{margin:0}.c-eg-message__cta{flex-shrink:0}.c-eg-status{font-family:Arial,sans-serif;font-size:1rem;color:#252525;font-weight:700}.c-eg-status--pass{color:#9ba90d}.c-eg-status--fail{color:#cc2b27}.c-eg-status--part{color:#f5841f}.c-eg-status--none{color:#646060;font-weight:400}.c-eg-value{font-family:Consolas,monospace;font-size:.8333333333rem;color:#646060;word-break:break-all} diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/templates/index.html b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/templates/index.html new file mode 100644 index 00000000..a847b084 --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/templates/index.html @@ -0,0 +1,207 @@ +{# + ********************************************************************* + * This Original Work is copyright of 51 Degrees Mobile Experts Limited. + * Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, + * Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. + * + * This Original Work is licensed under the European Union Public Licence + * (EUPL) v.1.2 and is subject to its terms as set out below. + * + * If a copy of the EUPL was not distributed with this file, You can obtain + * one at https://opensource.org/licenses/EUPL-1.2. + * + * The 'Compatible Licences' set out in the Appendix to the EUPL (as may be + * amended by the European Commission) shall be deemed incompatible for + * the purposes of the Work and the provisions of the compatibility + * clause in Article 5 of the EUPL shall not apply. + * + * If using the Work as, or as part of, a network application, by + * including the attribution notice(s) required under Article 5 of the EUPL + * in the end user terms of the application under an appropriate heading, + * such notice(s) shall fulfill the requirements of that article. + * ********************************************************************* #} + +{# Human Confidence demo page. + Served by app.py, which puts in the Resource Key and the cloud address, + and holds the License Key server side. Styling is the 51Degrees example + design system, vendored with this example as the 51Did demo vendors + it. #} + + + + +Human Confidence demo + + + +
+

Human Confidence demo

+

This page shows how likely it is that a + person is looking at it. The server asks the cloud first. Then your + browser runs the 51Degrees browser tests, and the server redeems the + sealed result. The License Key stays on the server.

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
StepSourceHuman Confidence
1. Passive, asked by the serverwaiting…waiting…
2. After the browser tests, in the pagerunning the tests…waiting…
3. Redeemed by the serverwaiting…waiting…
+ +

+ + +

+ +

+ +

Find out more

+ +
+ + + + diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_console.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_console.py index 42ef1f62..91b9c644 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_console.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_console.py @@ -39,7 +39,7 @@ # # A resource key carries the list of properties it returns. Create one # carrying device detection and IP intelligence properties for free at -# https://configure.51degrees.com?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_console.py&utm_term=header +# https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_console.py&utm_term=header # and set the _51DEGREES_RESOURCE_KEY environment variable to it, or pass it # as the first argument. # @@ -159,7 +159,7 @@ class GettingStartedConsole(): ("Time Zone Offset", "timezoneoffset"), ] - # Where to go next, printed after the results. + # Where to go next, printed when the example ends. FIND_OUT_MORE = [ ("Device detection", "https://51degrees.com/device-detection?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_console.py&utm_term=find-out-more-device-detection"), @@ -199,8 +199,19 @@ def run(self, pipeline, output): for evidence in self.EVIDENCE: self.analyse_evidence(evidence, pipeline, output) + self.print_find_out_more(output) + + @classmethod + def print_find_out_more(cls, output): + + """! + Write the "Find out more" section, a line of "=" and then each label + with its link. The example ends with it, whether it ran or stopped + early. + """ + message = ["=" * 79, "Find out more:"] - for label, url in self.FIND_OUT_MORE: + for label, url in cls.FIND_OUT_MORE: message.append(f"\t{label}: {url}") output("\n".join(message) + "\n") @@ -296,9 +307,10 @@ def main(argv): "A resource key carrying the device detection and IP " "intelligence properties this example uses can be created for " "free at " - "https://configure.51degrees.com?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_console.py&utm_term=resource-key-required. " + "https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_console.py&utm_term=resource-key-required. " "Once complete, set the first environment variable named at " "the start of this message to the key.") + GettingStartedConsole.print_find_out_more(print) return try: @@ -311,6 +323,7 @@ def main(argv): # refused it, for example because the key is limited to domains # that do not include the origin sent. logger.log("error", str(error)) + GettingStartedConsole.print_find_out_more(print) return GettingStartedConsole().run(pipeline, print) diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_web/app.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_web/app.py index f86331cf..e96ddb08 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_web/app.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/gettingstarted_web/app.py @@ -37,7 +37,7 @@ # # A resource key carries the list of properties it returns. Create one # carrying device detection and IP intelligence properties for free at -# https://configure.51degrees.com?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_web-app.py&utm_term=header +# https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_web-app.py&utm_term=header # and set the _51DEGREES_RESOURCE_KEY environment variable to it, or pass it # as the first argument. # @@ -58,8 +58,8 @@ # ``` # python -m fiftyone_pipeline_examples.cloud.mixed.gettingstarted_web # ``` -# and open http://localhost:5000, or the port named by the PORT environment -# variable. Use the form on the page, or add ?client-ip=8.8.8.8 to the +# and open http://localhost:5151, or the port named by the +# _51DEGREES_EXAMPLE_HTTP_PORTS environment variable. Use the form on the page, or add ?client-ip=8.8.8.8 to the # address, to look up an IP address other than your own. # # Results are also available to the page's own JavaScript through the `fod` @@ -73,6 +73,14 @@ # Required PyPI dependencies: # - [fiftyone_pipeline_cloudrequestengine](https://pypi.org/project/fiftyone-pipeline-cloudrequestengine/) # - [flask](https://pypi.org/project/flask/) +# +# ## Flow Data and threads +# +# A Flow Data cannot be used by two threads at once. This example creates one +# for each request, uses it only in the code that handles that request, and +# closes it when the request ends. To hand work to another thread or task, +# read the values it needs from the Flow Data first and pass those values, +# not the Flow Data. import os import sys @@ -146,6 +154,39 @@ # Evidence values longer than this are shortened on the page. EVIDENCE_DISPLAY_LENGTH = 100 +# Where to go next. The page ends with these links, and the example prints +# them when it stops before the page is served. +FIND_OUT_MORE = [ + ("Device detection", + "https://51degrees.com/device-detection?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_web-app.py&utm_term=find-out-more-device-detection"), + ("IP intelligence", + "https://51degrees.com/ip-intelligence?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_web-app.py&utm_term=find-out-more-ip-intelligence"), + ("Resource keys", + "https://51degrees.com/documentation/_services__cloud__resource_keys.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_web-app.py&utm_term=find-out-more-resource-keys"), + ("Pricing", + "https://51degrees.com/pricing?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_web-app.py&utm_term=find-out-more-pricing"), + ("Pipeline API for Python", + "https://github.com/51Degrees/51degrees-python/tree/main/pipeline"), + ("Device detection for Python", + "https://github.com/51Degrees/51degrees-python/tree/main/device-detection"), + ("IP intelligence engine", + "https://github.com/51Degrees/51degrees-cxx"), +] + + +def print_find_out_more(): + + """! + Print the "Find out more" section, a line of "=" and then each label + with its link, to standard output. The example prints it when it stops + before the page is served, which ends with the same links. + """ + + message = ["=" * 79, "Find out more:"] + for label, url in FIND_OUT_MORE: + message.append(f"\t{label}: {url}") + print("\n".join(message) + "\n") + def values(): @@ -232,35 +273,32 @@ def create_app(pipeline): # else can set the header to any address. app.wsgi_app = ProxyFix(app.wsgi_app, x_for=1, x_proto=1) - def process(): - - flowdata = pipeline.create_flowdata() - - # Add the evidence from the request, being its headers, cookies, - # query parameters and client address, along with any form fields - # the client-side script posts. - flowdata.evidence.add_from_dict(webevidence(request)) - - flowdata.process() - - return flowdata - @app.route("/") def index(): - flowdata = process() + # A Flow Data cannot be used by two threads at once, so this one is + # made for this request, used only here, and closed when the route + # returns. + with pipeline.create_flowdata() as flowdata: + + # Add the evidence from the request, being its headers, cookies, + # query parameters and client address, along with any form + # fields the client-side script posts. + flowdata.evidence.add_from_dict(webevidence(request)) - response = make_response() + flowdata.process() - # Some browsers only send User-Agent Client Hints that are asked for, - # so set the Accept-CH header the results call for. More about this - # at https://51degrees.com/blog/user-agent-client-hints?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_web-app.py&utm_term=index - set_response_header(flowdata, response) + response = make_response() - response.set_data(render_template( - "index.html", **page_model(flowdata))) + # Some browsers only send User-Agent Client Hints that are asked + # for, so set the Accept-CH header the results call for. More + # about this at https://51degrees.com/blog/user-agent-client-hints?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_web-app.py&utm_term=index + set_response_header(flowdata, response) - return response + response.set_data(render_template( + "index.html", **page_model(flowdata))) + + return response # The other Pipeline APIs ship web integrations that serve the # client-side script at '/51Degrees.core.js', so the page refers to it by @@ -434,10 +472,11 @@ def main(argv): "A resource key carrying the device detection and IP " "intelligence properties this example uses can be created for " "free at " - "https://configure.51degrees.com?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_web-app.py&utm_term=resource-key-required. " + "https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-gettingstarted_web-app.py&utm_term=resource-key-required. " "Once complete, set the first environment variable named at " "the start of this message to the key.") - sys.exit(1) + print_find_out_more() + return try: pipeline = create_pipeline( @@ -449,9 +488,11 @@ def main(argv): # refused it, for example because the key is limited to domains # that do not include the origin sent. logger.log("error", str(error)) + print_find_out_more() sys.exit(1) - create_app(pipeline).run(port=int(os.environ.get("PORT", 5000))) + create_app(pipeline).run(port=int(os.environ.get( + "_51DEGREES_EXAMPLE_HTTP_PORTS", 5151))) if __name__ == "__main__": diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/pipeline.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/pipeline.py index 41895b64..7ce672ee 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/pipeline.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/mixed/pipeline.py @@ -114,7 +114,7 @@ def can_fill(engine): "The key carries neither the device detection nor the IP " "intelligence properties this example shows. Create a resource " "key that carries them for free at " - "https://configure.51degrees.com?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-pipeline.py&utm_term=key-carries-nothing") + "https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-mixed-pipeline.py&utm_term=key-carries-nothing") builder = PipelineBuilder(pipeline_settings or {}).add(request_engine) diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/simple_cloud_engine.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/simple_cloud_engine.py new file mode 100644 index 00000000..a537962f --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/simple_cloud_engine.py @@ -0,0 +1,352 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +## @example cloud/simple_cloud_engine.py +# +# This example creates a cloud engine of its own and adds it to a pipeline. +# A cloud engine gets its results from a remote service rather than working +# them out itself. Here the service takes a date of birth and answers with +# the star sign. +# +# It is the simple flow element example in fiftyone_pipeline_core with the +# work moved to a remote service. The 51Degrees cloud engines, such as +# device detection, work the same way with the 51Degrees cloud service. +# +# You will learn: +# +# 1. How to write a cloud engine, which reads its part of the answer that a +# cloud request engine gets from the service +# 2. How to add a cloud request engine and a cloud engine to a pipeline +# 3. How to read a property the service gives no value for, with the reason +# +# A cloud request engine makes three kinds of request. When the pipeline is +# built, it asks the service which properties the resource key gives, and +# which evidence the service reads. Then for each flow data it sends the +# evidence and gets the results back, with a section for each product. A +# cloud engine reads the section named by its data key. +# +# So that the example runs anywhere, with no key and no network, it starts +# a small star sign service of its own on this machine. The service answers +# those three requests in the shapes the 51Degrees cloud service uses. To use +# a real service, give its address to the cloud request engine instead. +# +# This example is available in full on [GitHub](https://github.com/51Degrees/51degrees-python/blob/main/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/simple_cloud_engine.py). +# +# Run it from the examples folder, once the requirements there are +# installed, with +# ``` +# python -m fiftyone_pipeline_examples.cloud.simple_cloud_engine +# ``` +# +# Expected output, before the Find out more section: +# ``` +# With a date of birth of 1992-12-18, your star sign is Sagittarius. +# With a date of birth of 1990-12-25, your star sign is Capricorn. +# With a date of birth of 1992-04-15, your star sign is Aries. +# With no date of birth, there is no star sign. The service needs a date of birth in the form YYYY-MM-DD to find a star sign. +# ``` + +import json +import threading +from datetime import date +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from urllib.parse import parse_qs, urlsplit + +from fiftyone_pipeline_cloudrequestengine.cloudengine import CloudEngine +from fiftyone_pipeline_cloudrequestengine.cloudrequestengine import ( + CloudRequestEngine) +from fiftyone_pipeline_core.pipelinebuilder import PipelineBuilder + +# Where to go next, printed when the example ends. +FIND_OUT_MORE = [ + ("Pipeline API documentation", + "https://51degrees.com/documentation/_pipeline_api__concepts__pipeline_basics.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-simple_cloud_engine.py&utm_term=find-out-more-documentation"), + ("The 51Degrees cloud service", + "https://51degrees.com/documentation/_services__cloud__index.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-simple_cloud_engine.py&utm_term=find-out-more-cloud-service"), + ("Resource keys", + "https://51degrees.com/documentation/_services__cloud__resource_keys.html?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-simple_cloud_engine.py&utm_term=find-out-more-resource-keys"), + ("Contact us", + "https://51degrees.com/contact-us?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-fiftyone_pipeline_examples-cloud-simple_cloud_engine.py&utm_term=find-out-more-contact"), + ("Pipeline API for Python", + "https://github.com/51Degrees/51degrees-python/tree/main/pipeline"), + ("Device detection for Python, with cloud engines like this one", + "https://github.com/51Degrees/51degrees-python/tree/main/device-detection"), + ("Pipeline API specification", + "https://github.com/51Degrees/specifications/tree/main/pipeline-specification"), +] + +# The evidence the service reads, a date of birth in the form YYYY-MM-DD, as +# a date input in a web form sends it in the query string. +DATE_OF_BIRTH = "query.dateOfBirth" + +# The dates of birth the example looks up. None sends no date of birth, to +# show a property the service gives no value for. +DATES_OF_BIRTH = ["1992-12-18", "1990-12-25", "1992-04-15", None] + +# The resource key sent to the star sign service, which accepts any key. +RESOURCE_KEY = "star-sign-example" + + +class SimpleCloudEngine(CloudEngine): + + """! + Star sign results, read from the "astrology" section of the service's + answer and available as flowdata.astrology. + + CloudEngine does the work. When the pipeline is built, it takes its + properties from the ones the service lists under the data key. For each + flow data, it reads the section of the same name from the answer the + cloud request engine got, and keeps each value as an + AspectPropertyValue, which holds the value or the reason the service + gave for having none. + """ + + def __init__(self): + + super(SimpleCloudEngine, self).__init__() + + self.datakey = "astrology" + + +def look_up(pipeline, date_of_birth): + + """! + Process one date of birth, or none, and print the star sign or the + reason the service gave for having none. + """ + + # Flow data carries the evidence into the pipeline and the results out + # of it. + flowdata = pipeline.create_flowdata() + if date_of_birth is None: + described = "no date of birth" + else: + flowdata.evidence.add(DATE_OF_BIRTH, date_of_birth) + described = f"a date of birth of {date_of_birth}" + + # The cloud request engine sends the evidence to the service, and the + # cloud engine reads its section of the answer. + flowdata.process() + + star_sign = flowdata.astrology.starsign + if star_sign.has_value(): + print(f"With {described}, your star sign is {star_sign.value()}.") + else: + print(f"With {described}, there is no star sign. " + f"{star_sign.no_value_message()}") + + +def print_find_out_more(): + + """! + Print the "Find out more" section, a line of "=" and then each label + with its link. + """ + + print("=" * 79) + print("Find out more:") + for label, url in FIND_OUT_MORE: + print(f"\t{label}: {url}") + + +def main(): + + server, endpoint = start_star_sign_service() + try: + # The cloud request engine makes the requests to the service. The + # endpoint is given here because the star sign service is not the + # 51Degrees cloud service. A pipeline for a 51Degrees product + # leaves it out, and the cloud request engine then reads it from + # the _51DEGREES_CLOUD_ENDPOINT environment variable, or uses + # cloud.51degrees.com. + cloud_request_engine = CloudRequestEngine({ + "resource_key": RESOURCE_KEY, + "cloud_endpoint": endpoint, + }) + + # A console has no page, so leave out the elements that write the + # client-side script and set response headers. + settings = { + "add_javascript_builder": False, + "use_setheader_properties": False, + } + + # A cloud engine goes after the cloud request engine whose answer + # it reads. Building the pipeline asks the service for its + # properties. + pipeline = PipelineBuilder(settings) \ + .add(cloud_request_engine) \ + .add(SimpleCloudEngine()) \ + .build() + + # Closing the pipeline closes the engines in it. + with pipeline: + for date_of_birth in DATES_OF_BIRTH: + look_up(pipeline, date_of_birth) + + finally: + server.shutdown() + server.server_close() + + print_find_out_more() + + +# The star sign service, which stands in for a remote service so that the +# example runs with no key and no network. A real service runs on another +# machine, and the example needs nothing below this line to use one. + +# Each star sign, with the month and day it starts and the month and day it +# ends. Capricorn runs over the end of the year. +STAR_SIGNS = [ + ("Aries", (3, 21), (4, 19)), + ("Taurus", (4, 20), (5, 20)), + ("Gemini", (5, 21), (6, 20)), + ("Cancer", (6, 21), (7, 22)), + ("Leo", (7, 23), (8, 22)), + ("Virgo", (8, 23), (9, 22)), + ("Libra", (9, 23), (10, 22)), + ("Scorpio", (10, 23), (11, 21)), + ("Sagittarius", (11, 22), (12, 21)), + ("Capricorn", (12, 22), (1, 19)), + ("Aquarius", (1, 20), (2, 18)), + ("Pisces", (2, 19), (3, 20)), +] + +# The products the service offers for a resource key, each with its +# properties. A cloud engine's data key names its product. +ACCESSIBLE_PROPERTIES = { + "Products": { + "astrology": { + "DataTier": "Free", + "Properties": [{ + "Name": "StarSign", + "Type": "String", + "Category": "Astrology", + "Description": "The star sign for the date of birth.", + }], + }, + }, +} + +# The evidence the service reads. +EVIDENCE_KEYS = [DATE_OF_BIRTH] + +# The reason the service gives in place of a star sign when it has none. +NO_STAR_SIGN = ("The service needs a date of birth in the form YYYY-MM-DD " + "to find a star sign.") + + +def find_star_sign(month, day): + + """! + The star sign for a month and day, from the table above. + """ + + birthday = (month, day) + for name, start, end in STAR_SIGNS: + if start <= end: + if start <= birthday <= end: + return name + # A star sign that runs over the end of the year. + elif birthday >= start or birthday <= end: + return name + return None + + +def astrology_section(date_of_birth): + + """! + The astrology section of an answer. A property with no value is null, + with the reason under its name followed by "nullreason", as the + 51Degrees cloud service gives it. + """ + + try: + born = date.fromisoformat(date_of_birth) + except (TypeError, ValueError): + return {"starsign": None, "starsignnullreason": NO_STAR_SIGN} + return {"starsign": find_star_sign(born.month, born.day)} + + +class StarSignRequestHandler(BaseHTTPRequestHandler): + + """! + Answers the requests a cloud request engine makes, at the paths it + makes them to. + """ + + def do_GET(self): + + path = urlsplit(self.path).path.lower() + if path.endswith("/accessibleproperties"): + self.send_json(ACCESSIBLE_PROPERTIES) + elif path.endswith("/evidencekeys"): + self.send_json(EVIDENCE_KEYS) + else: + self.send_error(404) + + def do_POST(self): + + # The results for one flow data, posted to .json. The + # evidence arrives as a form, each field named by an evidence key + # without its prefix, so query.dateOfBirth arrives as dateOfBirth. + if not urlsplit(self.path).path.lower().endswith(".json"): + self.send_error(404) + return + length = int(self.headers.get("Content-Length", 0)) + form = parse_qs(self.rfile.read(length).decode("utf-8")) + # Evidence keys ignore letter case, so field names do as well. + fields = {name.lower(): values[0] for name, values in form.items()} + self.send_json( + {"astrology": astrology_section(fields.get("dateofbirth"))}) + + def send_json(self, value): + + body = json.dumps(value).encode("utf-8") + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, format, *args): + + # Leave the console to the example's own output. + pass + + +def start_star_sign_service(): + + """! + Start the star sign service on this machine and return the server and + the endpoint to give a cloud request engine. Port 0 lets the operating + system choose a free port. + """ + + server = ThreadingHTTPServer(("127.0.0.1", 0), StarSignRequestHandler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + return server, f"http://127.0.0.1:{server.server_address[1]}/api/" + + +if __name__ == "__main__": + main() diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/example_utils.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/example_utils.py index e1534c4d..3bfb42ba 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/example_utils.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/example_utils.py @@ -36,89 +36,50 @@ class ExampleUtils: # "_51DEGREES_RESOURCE_KEY". RESOURCE_KEY_ENV_VAR = "_51DEGREES_RESOURCE_KEY" - # Deprecated. Use RESOURCE_KEY_ENV_VAR. The name the resource key - # variable had before, read when RESOURCE_KEY_ENV_VAR is not set. - LEGACY_RESOURCE_KEY_ENV_VAR = "resource_key" - # The environment variable the examples read a licence key from, to use # in place of a resource key. LICENSE_KEY_ENV_VAR = "_51DEGREES_LICENSE_KEY" - # Deprecated. Use LICENSE_KEY_ENV_VAR. The name the licence key - # variable had before, read when LICENSE_KEY_ENV_VAR is not set. - LEGACY_LICENSE_KEY_ENV_VAR = "license_key" - # The environment variable naming a cloud service other than the public # one, for example one hosted privately. The value includes the api/v4 # path, as in https://cloud.51degrees.com/api/v4/. CLOUD_ENDPOINT_ENV_VAR = "_51DEGREES_CLOUD_ENDPOINT" - # Deprecated. Use CLOUD_ENDPOINT_ENV_VAR. The name that variable had - # before, read when CLOUD_ENDPOINT_ENV_VAR is not set. - ENDPOINT_ENV_VAR = "cloud_endpoint" - # The environment variable holding the origin to send with each request # to the cloud service, for a resource key limited to particular # domains, which only answers a request whose origin is one of them. CLOUD_REQUEST_ORIGIN_ENV_VAR = "_51DEGREES_CLOUD_REQUEST_ORIGIN" - # Deprecated. Use CLOUD_REQUEST_ORIGIN_ENV_VAR. The name that variable - # had before, read when CLOUD_REQUEST_ORIGIN_ENV_VAR is not set. - ORIGIN_ENV_VAR = "cloud_request_origin" - # The text shown for a value the results do not hold. UNKNOWN = "Unknown" @staticmethod def get_resource_key(): return ExampleUtils.__get_env_variable( - ExampleUtils.RESOURCE_KEY_ENV_VAR, - ExampleUtils.LEGACY_RESOURCE_KEY_ENV_VAR) + ExampleUtils.RESOURCE_KEY_ENV_VAR) @staticmethod def get_license_key(): return ExampleUtils.__get_env_variable( - ExampleUtils.LICENSE_KEY_ENV_VAR, - ExampleUtils.LEGACY_LICENSE_KEY_ENV_VAR) + ExampleUtils.LICENSE_KEY_ENV_VAR) @staticmethod def get_cloud_endpoint(): return ExampleUtils.__get_env_variable( - ExampleUtils.CLOUD_ENDPOINT_ENV_VAR, - ExampleUtils.ENDPOINT_ENV_VAR) + ExampleUtils.CLOUD_ENDPOINT_ENV_VAR) @staticmethod def get_cloud_request_origin(): return ExampleUtils.__get_env_variable( - ExampleUtils.CLOUD_REQUEST_ORIGIN_ENV_VAR, - ExampleUtils.ORIGIN_ENV_VAR) - - # The old names already reported as deprecated, so each is reported - # once. - __reported_old_names = set() + ExampleUtils.CLOUD_REQUEST_ORIGIN_ENV_VAR) @staticmethod - def __get_env_variable(name, old_name): + def __get_env_variable(name): """! The value of the environment variable name, or an empty string. - When name is unset or empty the name the variable had before is - read, and using it prints once that the old name is deprecated. """ - value = os.environ.get(name) - if value: - return value - value = os.environ.get(old_name) - if not value: - return "" - if old_name not in ExampleUtils.__reported_old_names: - ExampleUtils.__reported_old_names.add(old_name) - print( - f"The {old_name} environment variable is deprecated and {name} " - f"replaces it. The value was read from {old_name} because {name} " - f"is not set, so set {name} to the same value.", - file=sys.stderr) - return value + return os.environ.get(name) or "" @staticmethod def name_values(section, property_names): diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/conftest.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/conftest.py new file mode 100644 index 00000000..7e12799f --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/conftest.py @@ -0,0 +1,54 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +# The tests that call the live cloud service are marked live here, so the +# released test files stay as they are. ci/run-integration-tests.ps1 leaves +# the live tests out when no resource key is passed, and the other tests run. + +import pytest + + +# The tests given the "resource key" case of helpers.KEYS. The "licence key" +# case skips itself when no licence key is set. +def _is_live(item): + callspec = getattr(item, "callspec", None) + return callspec is not None and "resource key" in callspec.id.split("-") + + +def pytest_configure(config): + config.addinivalue_line( + "markers", + "live: calls the live 51Degrees cloud service and needs a resource " + "key") + config.addinivalue_line( + "markers", + "staging: calls the staging cloud service CLOUD_STAGING_ENDPOINT " + "names, for what the production cloud does not serve yet. The " + "Cloud Human Confidence workflow runs these with -m staging") + + +@pytest.hookimpl(tryfirst=True) +def pytest_collection_modifyitems(config, items): + # Runs before -m deselects, so the selection sees the marker. + for item in items: + if _is_live(item): + item.add_marker(pytest.mark.live) diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/helpers.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/helpers.py index 60ec92d8..09ebf536 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/helpers.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/helpers.py @@ -27,41 +27,45 @@ import pytest -from fiftyone_pipeline_examples.example_utils import ExampleUtils - -from live_cloud import find_resource_key, no_resource_key +from live_cloud import find_resource_key, no_resource_key, read_environment NO_KEY = no_resource_key( "the device, ip and countrynamestranslated products", "device detection and IP Intelligence properties, and the translated " "country names", several=True) +# The cloud license key the tests pass to the examples. It is not the +# examples' own _51DEGREES_LICENSE_KEY, which holds the data license in CI, +# and which the cloud does not take on its own. +LICENSE_KEY_NAME = "_51DEGREES_LICENSE_KEY_BESPOKE" +LICENSE_KEY = read_environment(LICENSE_KEY_NAME) + # The ways a test can reach the cloud service, as the keyword arguments the # examples' create_pipeline takes, each passed through credentials(). A test -# with a resource key fails when none is set. A test with a licence key is -# skipped when none is set, because CI has no cloud licence key to give it. +# with a resource key or a license key is skipped, naming the variables it +# reads, when none is set. KEYS = [ pytest.param( {"resource_key": find_resource_key()}, id="resource key"), pytest.param( - {"license_key": ExampleUtils.get_license_key()}, + {"license_key": LICENSE_KEY}, id="licence key", marks=pytest.mark.skipif( - not ExampleUtils.get_license_key(), - reason=f"Set {ExampleUtils.LICENSE_KEY_ENV_VAR} to a licence " - "key entitled to device detection and IP intelligence " - "properties to run the cloud tests with a licence " - "key.")), + not LICENSE_KEY, + reason=f"{LICENSE_KEY_NAME} is not set. Set it to a cloud " + "license key entitled to device detection and IP " + "intelligence properties to run the cloud tests with a " + "license key.")), ] def credentials(keys): - """The keyword arguments from KEYS, failing the test when they hold a + """The keyword arguments from KEYS, skipping the test when they hold a resource key that is not set.""" if "resource_key" in keys and not keys["resource_key"]: - pytest.fail(NO_KEY, pytrace=False) + pytest.skip(NO_KEY) return keys diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/live_cloud.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/live_cloud.py index 36bc26ad..b86793bf 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/live_cloud.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/live_cloud.py @@ -21,94 +21,57 @@ # ********************************************************************* """Where the tests that call the live 51Degrees cloud service find their -resource key, and what they fail with when there is none or when the -answer lacks what they asked for. Also how a test reads any setting from -an environment variable whose name has changed. +resource key, what they skip with when there is none, and what they +fail with when the answer lacks what they asked for. Also how a test reads a setting from an +environment variable. The same file is in each test folder whose tests read a setting from the -environment. There is no fallback to a skip, because a cloud test that -passes without calling the cloud has proved nothing. +environment. A test with no key skips, naming the variable it reads, +and never fails for want of one. CI checks that the key is set before +it runs them, so a run that called nothing is not taken for a pass. """ import os -import sys -# Tried in this order. _51DEGREES_RESOURCE_KEY is first because the Cloud -# 51Did workflow sets it to each key in turn, and each product's -# integration test script sets it too. -RESOURCE_KEY_NAMES = ( - "_51DEGREES_RESOURCE_KEY", - "_51DEGREES_RESOURCE_KEY_BESPOKE", -) +# The key that carries every property, which a test reads unless it names +# another. +RESOURCE_KEY_NAMES = ("_51DEGREES_RESOURCE_KEY_BESPOKE",) -# Deprecated. The name the resource key variable had before, read when -# none of RESOURCE_KEY_NAMES is set. -OLD_RESOURCE_KEY_NAME = "resource_key" - -# The old names already reported as deprecated, so each is reported once. -_reported_old_names = set() +# The name a person running an example sets. A test of an example gives the +# example its key under this name. +RESOURCE_KEY_VARIABLE = "_51DEGREES_RESOURCE_KEY" ACCESSIBLE_PROPERTIES_URL = ( "https://cloud.51degrees.com/api/v4/accessibleproperties?resource=") -CREATE_KEY_URL = "https://configure.51degrees.com?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=live_cloud.py&utm_term=resource-key-required" - - -def _report_old_name(name, old_name): - """Prints, once for each old name, that it is deprecated and which - name replaces it.""" - if old_name in _reported_old_names: - return - _reported_old_names.add(old_name) - print( - f"The {old_name} environment variable is deprecated and {name} " - f"replaces it. The value was read from {old_name} because {name} " - f"is not set, so set {name} to the same value.", - file=sys.stderr) +CREATE_KEY_URL = "https://51degrees.com/configure?utm_source=code&utm_medium=example&utm_campaign=51degrees-python&utm_content=live_cloud.py&utm_term=resource-key-required" -def read_environment(name, old_name): +def read_environment(name): """The value of the environment variable name, or None when it has - none. When name is unset or empty the name the variable had before is - read, and using it prints once that the old name is deprecated.""" + none.""" value = os.environ.get(name, "").strip() - if value: - return value - value = os.environ.get(old_name, "").strip() - if not value: - return None - _report_old_name(name, old_name) - return value + return value or None -def is_set(name, old_name): +def is_set(name): """Whether the environment variable name is set, whatever it holds, - which is how a switch is read. When it is not set, the name the - variable had before counts, and using it prints once that the old name - is deprecated.""" - if name in os.environ: - return True - if old_name not in os.environ: - return False - _report_old_name(name, old_name) - return True + which is how a switch is read.""" + return name in os.environ def find_resource_key(names=RESOURCE_KEY_NAMES): - """The first resource key set under any of the names, or None. When - none of RESOURCE_KEY_NAMES is set, the deprecated old name is read.""" + """The resource key set under the names, or None.""" for name in names: value = os.environ.get(name, "").strip() if value: return value - if names is RESOURCE_KEY_NAMES: - return read_environment(names[0], OLD_RESOURCE_KEY_NAME) return None def no_resource_key(product, asks_for, several=False, names=RESOURCE_KEY_NAMES): - """What to fail with when no resource key is set. + """What to skip with when no resource key is set. product names the product the key has to carry, with its article, as in "the device product". asks_for says what the test asks the service for. @@ -123,8 +86,8 @@ def no_resource_key(product, asks_for, several=False, "it needs a resource key") asker = "the test asks" return ( - f"{opening} and there is nothing to fall back on. None of " - f"{', '.join(names)} is set, tried in that order. The key has to " + f"{opening} and there is nothing to fall back on. " + f"{', '.join(names)} is not set. The key has to " f"carry {product}, because {asker} the service for {asks_for}. To " f"see the products a key carries, open {ACCESSIBLE_PROPERTIES_URL}. " f"Create a key at {CREATE_KEY_URL}.") diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web.py new file mode 100644 index 00000000..6ab34396 --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web.py @@ -0,0 +1,212 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +""" +Runs the Human Confidence web example against the cloud service through +Flask's test client. The resource key has to carry HumanConfidence, which +the example asks the cloud service about before anything else, and these +tests skip themselves when no key is set or the key does not carry it. + +The passive tests check that HumanConfidenceSource comes back. The Pro and +Bespoke products offer it, and the Bespoke key gets Passive, as no browser +tests have run. The Basic product does not offer HumanConfidenceSource, so +a Basic key gets no source. + +The production cloud does not serve HumanConfidenceSource yet, so the two +tests that check it are marked staging and call the staging cloud that +CLOUD_STAGING_ENDPOINT names, with the Bespoke key in +RESOURCE_KEY_BESPOKE_STAGING and the Basic key in +_51DEGREES_RESOURCE_KEY_BASIC. Only the Cloud Human Confidence workflow sets +the two staging names, and without them these tests skip. The other tests +call the cloud _51DEGREES_CLOUD_ENDPOINT names. + +Only the passive step is run here. The active step needs the browser tests, +which only a browser runs. +""" + +import pytest +import requests + +from fiftyone_pipeline_examples.cloud.humanconfidence_web import ( + app as example) +from fiftyone_pipeline_examples.example_utils import ExampleUtils + +from live_cloud import ( + RESOURCE_KEY_NAMES, find_resource_key, read_environment) + +DESKTOP_CHROME = ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36") + +HEADERS = {"User-Agent": DESKTOP_CHROME} + +# Every value the property has. Unknown is the one the cloud gives when it +# has too little to rate the request. +LEVELS = ("High", "Medium", "Low", "Unknown") + +# The variable holding a resource key of the Basic product. +BASIC_KEY_NAME = "_51DEGREES_RESOURCE_KEY_BASIC" + +# The variable holding the staging cloud's API base, ending /api/v4/. Only +# CI sets it, and there is no default, so a staging test never calls the +# production cloud. +STAGING_ENDPOINT_NAME = "CLOUD_STAGING_ENDPOINT" + +# The variable holding a Bespoke resource key the staging cloud knows. +STAGING_KEY_NAME = "RESOURCE_KEY_BESPOKE_STAGING" + +# The properties the passive tests name in their request, so the answer +# carries both whatever the key's own list of properties holds. +PROPERTIES = "derived.humanconfidence,derived.humanconfidencesource" + + +@pytest.fixture(scope="module") +def key(): + resource_key = find_resource_key() + if not resource_key: + pytest.skip( + f"{', '.join(RESOURCE_KEY_NAMES)} is not set. Set it to a " + "resource key that carries HumanConfidence to run the Human " + "Confidence cloud tests.") + return resource_key + + +@pytest.fixture(scope="module") +def api(): + return example.api_base(ExampleUtils.get_cloud_endpoint()) + + +@pytest.fixture +def naming_the_properties(monkeypatch): + """Adds the properties to each request the example makes for the + passive level, and leaves its evidence as it is. Gives the cloud's + answers to those requests, in order, so a test can check what the + cloud sent as well as what the example made of it.""" + + real = requests.request + answers = [] + + def request(method, url, data=None, **kwargs): + named = method == "POST" and url.endswith(".json") + if named: + data = dict(data or {}, values=PROPERTIES) + response = real(method, url, data=data, **kwargs) + if named: + answers.append(response) + return response + + monkeypatch.setattr(requests, "request", request) + return answers + + +@pytest.fixture(scope="module") +def client(key, api): + if not example.carries_human_confidence(api, key): + pytest.skip( + "The resource key does not carry HumanConfidence, so the Human " + "Confidence cloud tests cannot run with it.") + return example.create_app( + key, ExampleUtils.get_license_key(), api).test_client() + + +@pytest.fixture(scope="module") +def staging_api(): + endpoint = read_environment(STAGING_ENDPOINT_NAME) + if not endpoint: + pytest.skip( + f"{STAGING_ENDPOINT_NAME} is not set. Set it to the staging " + "cloud's API base to run the tests the production cloud cannot " + "answer yet.") + return example.api_base(endpoint) + + +@pytest.fixture(scope="module") +def staging_client(staging_api): + staging_key = read_environment(STAGING_KEY_NAME) + if not staging_key: + pytest.skip( + f"{STAGING_KEY_NAME} is not set. Set it to a Bespoke resource " + "key the staging cloud knows.") + if not example.carries_human_confidence(staging_api, staging_key): + pytest.skip( + f"The key in {STAGING_KEY_NAME} does not carry HumanConfidence " + "on the staging cloud.") + # The passive step never uses the License Key. + return example.create_app(staging_key, None, staging_api).test_client() + + +def test_page_is_served_and_never_kept(client, key): + response = client.get("/", headers=HEADERS) + assert response.status_code == 200 + assert response.headers["Cache-Control"] == "no-store" + assert key in response.get_data(as_text=True) + + +@pytest.mark.staging +def test_passive_source_and_level_come_from_the_cloud( + staging_client, naming_the_properties): + answer = staging_client.get("/passive", headers=HEADERS).get_json() + assert "error" not in answer, answer + assert answer["source"] == "Passive", answer + assert answer["humanConfidence"] in LEVELS + + +@pytest.mark.staging +def test_a_basic_key_gets_no_source(staging_api, naming_the_properties): + """The Basic product does not offer HumanConfidenceSource, so the cloud + answers the property with no value and the reason, and the example + gives no source.""" + basic = read_environment(BASIC_KEY_NAME) + if not basic: + pytest.skip( + f"{BASIC_KEY_NAME} is not set. The Basic product does not offer " + "HumanConfidenceSource. Set the variable to a Basic resource " + "key to check that such a key gets no source.") + client = example.create_app(basic, None, staging_api).test_client() + answer = client.get("/passive", headers=HEADERS).get_json() + assert "error" not in answer, "The cloud refused the request." + assert answer["source"] is None, answer + + # The example gives no source for a property the cloud left out too, + # so the cloud's own answer must name the property, with no value and + # a reason. + assert naming_the_properties, "The example did not ask the cloud." + derived = naming_the_properties[-1].json().get("derived") or {} + assert "humanconfidencesource" in derived, ( + "The cloud's answer leaves out humanconfidencesource, so it says " + "nothing about what the Basic product offers.") + assert derived["humanconfidencesource"] is None, ( + derived["humanconfidencesource"]) + assert isinstance( + derived.get("humanconfidencesourcenullreason"), str), ( + "The cloud gave no humanconfidencesourcenullreason.") + + +def test_licence_key_never_reaches_the_browser(client): + licence_key = ExampleUtils.get_license_key() + if not licence_key: + pytest.skip( + f"{ExampleUtils.LICENSE_KEY_ENV_VAR} is not set, so there is no " + "licence key to look for.") + for response in (client.get("/", headers=HEADERS), + client.get("/passive", headers=HEADERS)): + assert licence_key.encode() not in response.data diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web_offline.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web_offline.py new file mode 100644 index 00000000..73afb432 --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web_offline.py @@ -0,0 +1,545 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +""" +Runs the Human Confidence web example against a stand-in for the cloud +service, so each step is checked with known values and without a key. The +stand-in answers in the shapes the example reads, and keeps the requests it +was sent, so the tests see what the example passed on. +""" + +import json +import re + +import pytest +import requests + +from fiftyone_pipeline_examples.cloud.humanconfidence_web import ( + app as example) +from fiftyone_pipeline_examples.example_utils import ExampleUtils + +import test_cloud_humanconfidence_web as live + +API = "https://cloud.example/api/v4/" +RESOURCE_KEY = "a-resource-key" +LICENCE_KEY = "a-licence-key" + +DESKTOP_CHROME = ( + "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36") + +# Every name a setting of the example is read from. +SETTINGS = [ + ExampleUtils.RESOURCE_KEY_ENV_VAR, + ExampleUtils.LICENSE_KEY_ENV_VAR, + ExampleUtils.CLOUD_ENDPOINT_ENV_VAR, + "_51DEGREES_EXAMPLE_HTTP_PORTS", +] + +# A 51degrees.com link. +LINK = re.compile(r"https://51degrees\.com/\S+") + +# The tags every link the example prints carries, up to the name of its +# file. +TAGS = ( + "?utm_source=code&utm_medium=example&utm_campaign=51degrees-python" + "&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-" + "fiftyone_pipeline_examples-cloud-humanconfidence_web-app.py&utm_term=") + + +class StubResponse: + + def __init__(self, body, status_code=200): + self.status_code = status_code + self.text = body if isinstance(body, str) else json.dumps(body) + + def json(self): + return json.loads(self.text) + + +class StubCloud: + """ + Answers as the cloud service does for a key carrying the named + properties, and keeps the requests it was sent as method, address and + form fields. + """ + + def __init__(self, properties): + self.properties = properties + self.requests = [] + # The sealed values already redeemed, as each redeems once. + self.redeemed = set() + # An answer to give in place of the usual one, by the end of the + # address, as a StubResponse or an exception to raise. + self.instead = {} + + def sent_to(self, ending): + """The requests sent to the addresses with the ending.""" + return [sent for sent in self.requests if sent[1].endswith(ending)] + + def request(self, method, url, data=None, headers=None, timeout=None): + data = dict(data or {}) + self.requests.append((method, url, data)) + assert url.startswith(API), url + path = url[len(API):] + + for ending, answer in self.instead.items(): + if path.endswith(ending): + if isinstance(answer, BaseException): + raise answer + return answer + + if path.startswith("accessibleproperties"): + return StubResponse({"Products": {"derived": {"Properties": [ + {"Name": name, "Type": "String"} + for name in self.properties]}}}) + + if path == "evidencekeys": + return StubResponse([ + "header.user-agent", "header.sec-ch-ua", "query.client-ip"]) + + if path == RESOURCE_KEY + ".json": + return StubResponse({"derived": { + "humanconfidence": "Medium", + "humanconfidencesource": "Passive"}}) + + if path == "hc/redeem": + if data.get("value") in self.redeemed: + return StubResponse({"result": "replayed"}) + self.redeemed.add(data.get("value")) + return StubResponse({ + "humanConfidence": "High", "secondsSinceVerified": 2}) + + return StubResponse("Not Found", 404) + + +@pytest.fixture +def cloud(monkeypatch): + """Makes a stand-in for the cloud service answer every request.""" + + def stand_in(properties=("HumanConfidence", "HumanConfidenceSource")): + stub = StubCloud(properties) + monkeypatch.setattr(requests, "request", stub.request) + return stub + + return stand_in + + +def client_for(license_key=LICENCE_KEY): + return example.create_app(RESOURCE_KEY, license_key, API).test_client() + + +# The page. + +def test_page_carries_the_resource_key_and_the_cloud_address(cloud): + cloud() + client = client_for() + response = client.get("/") + html = response.get_data(as_text=True) + + assert response.status_code == 200 + assert "Human Confidence demo" in html + assert f'var RESOURCE = "{RESOURCE_KEY}";' in html + assert f'var API = "{API}";' in html + assert '' in html + assert client.get("/css/examples-main.min.css").status_code == 200 + + +def test_page_is_never_kept_by_a_cache(cloud): + cloud() + assert client_for().get("/").headers["Cache-Control"] == "no-store" + + +def test_page_is_served_without_asking_the_cloud(cloud): + stub = cloud() + client_for().get("/") + assert stub.requests == [] + + +def test_licence_key_never_reaches_the_page(cloud): + cloud() + assert LICENCE_KEY not in client_for().get("/").get_data(as_text=True) + + +def test_page_ends_with_its_find_out_more_section(cloud): + cloud() + html = client_for().get("/").get_data(as_text=True) + section = html.split("Find out more", 1)[1] + links = LINK.findall(section) + assert links + for link in links: + assert "utm_medium=example" in link + assert "utm_term=find-out-more" in link + assert "-humanconfidence_web-templates-index.html&" in link + + +# Step 1, passive. + +def test_passive_is_read_from_the_answer_of_the_cloud(cloud): + cloud() + response = client_for().get( + "/passive", headers={"User-Agent": DESKTOP_CHROME}) + + assert response.status_code == 200 + assert response.get_json() == { + "source": "Passive", "humanConfidence": "Medium"} + + +def test_passive_passes_on_the_headers_the_cloud_lists_and_the_address( + cloud): + stub = cloud() + client_for().get("/passive", headers={ + "User-Agent": DESKTOP_CHROME, + "Sec-CH-UA": '"Chromium";v="120"', + "Authorization": "Bearer a-secret", + "Cookie": "session=a-secret"}) + + method, url, data = stub.requests[-1] + assert method == "POST" + assert url == API + RESOURCE_KEY + ".json" + # The values as the browser sent them, under the names the cloud + # lists, with the address of the connection. Nothing else is sent. + assert data == { + "user-agent": DESKTOP_CHROME, + "sec-ch-ua": '"Chromium";v="120"', + "client-ip": "127.0.0.1"} + + +def test_address_of_the_connection_replaces_one_a_header_names(cloud): + stub = cloud() + stub.instead["evidencekeys"] = StubResponse( + ["header.user-agent", "header.client-ip"]) + client_for().get("/passive", headers={ + "User-Agent": DESKTOP_CHROME, "Client-IP": "203.0.113.9"}) + + assert stub.requests[-1][2]["client-ip"] == "127.0.0.1" + + +def test_list_of_headers_is_asked_for_once(cloud): + stub = cloud() + client = client_for() + client.get("/passive") + client.get("/passive") + + assert len(stub.sent_to("evidencekeys")) == 1 + assert len(stub.sent_to(".json")) == 2 + + +def test_passive_never_sends_the_licence_key(cloud): + stub = cloud() + client_for().get("/passive") + + for _, url, data in stub.requests: + assert LICENCE_KEY not in url + assert LICENCE_KEY not in data.values() + + +def test_passive_without_the_properties_returns_neither(cloud): + stub = cloud() + stub.instead[".json"] = StubResponse({"device": {"ismobile": False}}) + + assert client_for().get("/passive").get_json() == { + "source": None, "humanConfidence": None} + + +# The Basic product does not offer HumanConfidenceSource, so a Basic key is +# answered with no source, and with or without a level. The example gives +# what the cloud gave and makes up neither. +@pytest.mark.parametrize("level", [None, "Medium"]) +def test_passive_for_a_basic_key_returns_no_source(cloud, level): + stub = cloud() + derived = { + "humanconfidence": level, + "humanconfidencesource": None, + "humanconfidencesourcenullreason": + "The key does not give this property a value."} + if level is None: + derived["humanconfidencenullreason"] = ( + "The key does not give this property a value.") + stub.instead[".json"] = StubResponse({"derived": derived}) + + assert client_for().get("/passive").get_json() == { + "source": None, "humanConfidence": level} + + +# With no Basic key set, the live test skips, naming the variable it reads +# and what a Basic key is there to check. +def test_the_live_basic_key_test_skips_naming_its_variable(monkeypatch): + monkeypatch.delenv(live.BASIC_KEY_NAME, raising=False) + + with pytest.raises(pytest.skip.Exception) as skipped: + live.test_a_basic_key_gets_no_source(API, None) + + assert live.BASIC_KEY_NAME == "_51DEGREES_RESOURCE_KEY_BASIC" + assert f"{live.BASIC_KEY_NAME} is not set" in str(skipped.value) + assert ("The Basic product does not offer HumanConfidenceSource" + in str(skipped.value)) + + +def test_passive_says_what_the_cloud_refused(cloud): + stub = cloud() + stub.instead[".json"] = StubResponse( + '{"errors":["The resource key is not valid."]}', 400) + answer = client_for().get("/passive").get_json() + + assert answer["error"].startswith("HTTP 400: ") + assert "The resource key is not valid." in answer["error"] + + +def test_passive_answers_when_the_cloud_cannot_be_reached(cloud): + stub = cloud() + stub.instead[".json"] = requests.exceptions.ConnectionError( + "The stand-in service cannot be reached.") + response = client_for().get("/passive") + + assert response.status_code == 200 + assert "cannot be reached" in response.get_json()["error"] + + +# Step 3, redeem. + +def test_redeem_sends_the_sealed_value_with_the_licence_key(cloud): + stub = cloud() + response = client_for().post("/redeem", data={"value": "a-sealed-value"}) + + assert response.status_code == 200 + assert response.headers["Content-Type"].startswith("application/json") + assert response.get_json() == { + "humanConfidence": "High", "secondsSinceVerified": 2} + method, url, data = stub.requests[-1] + assert method == "POST" + assert url == API + "hc/redeem" + assert data == {"value": "a-sealed-value", "license": LICENCE_KEY} + + +def test_second_redeem_of_the_same_value_is_replayed(cloud): + cloud() + client = client_for() + first = client.post("/redeem", data={"value": "a-sealed-value"}) + second = client.post("/redeem", data={"value": "a-sealed-value"}) + + assert first.get_json()["humanConfidence"] == "High" + assert second.get_json() == {"result": "replayed"} + + +def test_redeem_without_a_licence_key_sends_none(cloud): + stub = cloud() + client_for(license_key="").post( + "/redeem", data={"value": "a-sealed-value"}) + + assert stub.requests[-1][2] == {"value": "a-sealed-value"} + + +def test_redeem_gives_the_answer_as_the_cloud_gave_it(cloud): + stub = cloud() + stub.instead["hc/redeem"] = StubResponse('{"result":"expired"}', 400) + response = client_for().post("/redeem", data={"value": "a-sealed-value"}) + + assert response.status_code == 400 + assert response.get_data(as_text=True) == '{"result":"expired"}' + + +def test_redeem_says_when_the_service_does_not_redeem(cloud): + stub = cloud() + stub.instead["hc/redeem"] = StubResponse("Not Found", 404) + response = client_for().post("/redeem", data={"value": "a-sealed-value"}) + + assert response.get_json() == { + "error": f"The service at {API} doesn't redeem Human Confidence."} + + +def test_redeem_answers_502_when_the_cloud_cannot_be_reached(cloud): + stub = cloud() + stub.instead["hc/redeem"] = requests.exceptions.ConnectionError( + "The stand-in service cannot be reached.") + response = client_for().post("/redeem", data={"value": "a-sealed-value"}) + + assert response.status_code == 502 + assert "cannot be reached" in response.get_json()["error"] + + +# The cloud address. + +def test_cloud_address_defaults_to_the_public_cloud(): + assert example.api_base("") == "https://cloud.51degrees.com/api/v4/" + assert example.api_base(None) == "https://cloud.51degrees.com/api/v4/" + + +@pytest.mark.parametrize("named", [ + "https://cloud.example.test/api/v4", + "https://cloud.example.test/api/v4/", + " https://cloud.example.test/api/v4// "]) +def test_cloud_address_named_ends_in_one_slash(named): + assert example.api_base(named) == \ + "https://cloud.example.test/api/v4/" + + +# Before the flow. + +class Started(Exception): + """Raised in place of starting the web server.""" + + +@pytest.fixture +def start(monkeypatch): + """Runs main with the settings given and no others but the address of + the stand-in for the cloud service, with a stand-in for the web server, + and returns what create_app and run were given, or None when the server + was not started.""" + + def run_main(argv=(), **settings): + for name in SETTINGS: + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv(ExampleUtils.CLOUD_ENDPOINT_ENV_VAR, API) + for name, value in settings.items(): + monkeypatch.setenv(name, value) + given = {} + + class Server: + + def run(self, **arguments): + given["run"] = arguments + raise Started() + + def create_app(*arguments): + given["create_app"] = arguments + return Server() + + monkeypatch.setattr(example, "create_app", create_app) + try: + example.main(list(argv)) + except Started: + return given + return None + + return run_main + + +def assert_ends_with_find_out_more(printed): + assert "Find out more:" in printed + for _, url in example.FIND_OUT_MORE: + assert url in printed + links = LINK.findall(printed.split("Find out more:", 1)[1]) + assert links + for link in links: + assert TAGS + "find-out-more" in link + + +def test_starts_when_the_key_carries_human_confidence(cloud, start, capsys): + stub = cloud() + given = start(**{ + ExampleUtils.RESOURCE_KEY_ENV_VAR: RESOURCE_KEY, + ExampleUtils.LICENSE_KEY_ENV_VAR: LICENCE_KEY, + ExampleUtils.CLOUD_ENDPOINT_ENV_VAR: API.rstrip("/")}) + + assert given["create_app"] == (RESOURCE_KEY, LICENCE_KEY, API) + assert given["run"] == {"port": 5151} + # The key was checked with the cloud named, before anything else. + method, url, _ = stub.requests[0] + assert method == "GET" + assert url == API + "accessibleproperties?resource=" + RESOURCE_KEY + assert f"http://localhost:5151/, using {API}" in capsys.readouterr().out + + +def test_listens_on_the_port_named(cloud, start): + cloud() + given = start(**{ + "_51DEGREES_EXAMPLE_HTTP_PORTS": "8080", + ExampleUtils.RESOURCE_KEY_ENV_VAR: RESOURCE_KEY}) + + assert given["run"] == {"port": 8080} + + +def test_resource_key_can_be_the_first_argument(cloud, start): + cloud() + given = start([RESOURCE_KEY]) + + assert given["create_app"][0] == RESOURCE_KEY + + +def test_starts_without_a_licence_key_and_says_so(cloud, start, capsys): + cloud() + given = start(**{ExampleUtils.RESOURCE_KEY_ENV_VAR: RESOURCE_KEY}) + + assert given is not None + assert ExampleUtils.LICENSE_KEY_ENV_VAR in capsys.readouterr().out + + +def test_without_a_key_says_how_to_get_one_and_ends(start, capsys): + assert start() is None + + printed = capsys.readouterr().out + assert ExampleUtils.RESOURCE_KEY_ENV_VAR in printed + assert "https://51degrees.com/configure" + TAGS in printed + assert_ends_with_find_out_more(printed) + + +def test_key_without_human_confidence_is_given_a_contact_link( + cloud, start, capsys): + stub = cloud(properties=("IsMobile",)) + + with pytest.raises(SystemExit): + start(**{ExampleUtils.RESOURCE_KEY_ENV_VAR: RESOURCE_KEY}) + + printed = capsys.readouterr().out + assert "https://51degrees.com/contact-us" + TAGS in printed + assert_ends_with_find_out_more(printed) + # Nothing was asked of the cloud beyond what the key carries. + assert len(stub.requests) == 1 + + +def test_key_the_cloud_refuses_ends_with_what_the_cloud_said( + cloud, start, capsys): + stub = cloud() + stub.instead["accessibleproperties?resource=" + RESOURCE_KEY] = \ + StubResponse('{"errors":["The resource key is not valid."]}', 400) + + with pytest.raises(SystemExit): + start(**{ExampleUtils.RESOURCE_KEY_ENV_VAR: RESOURCE_KEY}) + + printed = capsys.readouterr().out + assert "The resource key is not valid." in printed + assert_ends_with_find_out_more(printed) + + +def test_cloud_that_cannot_be_reached_ends_saying_so(cloud, start, capsys): + stub = cloud() + stub.instead["accessibleproperties?resource=" + RESOURCE_KEY] = \ + requests.exceptions.ConnectionError( + "The stand-in service cannot be reached.") + + with pytest.raises(SystemExit): + start(**{ExampleUtils.RESOURCE_KEY_ENV_VAR: RESOURCE_KEY}) + + printed = capsys.readouterr().out + assert "cannot be reached" in printed + assert_ends_with_find_out_more(printed) + + +def test_property_is_found_whichever_product_holds_it(cloud): + stub = cloud() + stub.instead["accessibleproperties?resource=" + RESOURCE_KEY] = \ + StubResponse({"Products": { + "device": {"Properties": [{"Name": "IsMobile"}]}, + "another": {"Properties": [{"Name": "humanconfidence"}]}}}) + + assert example.carries_human_confidence(API, RESOURCE_KEY) is True diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web_port.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web_port.py new file mode 100644 index 00000000..a8762b5b --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web_port.py @@ -0,0 +1,67 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +""" +The Human Confidence web example listens on port 5151 by default, and on +the port the _51DEGREES_EXAMPLE_HTTP_PORTS environment variable names when +it is set. The check +reads the example's source, so it starts no server and needs no network. +""" + +import ast +import os +import unittest + +APP = os.path.join( + os.path.dirname(os.path.abspath(__file__)), "..", "src", + "fiftyone_pipeline_examples", "cloud", "humanconfidence_web", "app.py") + + +def run_port(): + # The expression the example passes to run as its port. + with open(APP, encoding="utf-8") as source: + tree = ast.parse(source.read()) + for node in ast.walk(tree): + if (isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "run"): + for keyword in node.keywords: + if keyword.arg == "port": + return keyword.value + return None + + +class CloudHumanConfidenceWebPortTests(unittest.TestCase): + + def test_listens_on_5151_unless_port_names_another(self): + port = run_port() + # int() of the variable read from os.environ, or of 5151. + self.assertIsInstance(port, ast.Call) + get = port.args[0] + self.assertEqual("get", get.func.attr) + self.assertEqual( + ["_51DEGREES_EXAMPLE_HTTP_PORTS", 5151], + [arg.value for arg in get.args]) + + +if __name__ == "__main__": + unittest.main() diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_mixed_web_offline.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_mixed_web_offline.py index 95471e1e..14266ca4 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_mixed_web_offline.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_mixed_web_offline.py @@ -123,7 +123,7 @@ def __init__(self, sections): # The Origin header of each request, kept apart from the body. self.origins = [] - def request(self, method, url, data=None, headers=None): + def request(self, method, url, data=None, headers=None, timeout=None): data = dict(data or {}) self.requests.append((url, data)) self.origins.append(dict(headers or {}).get("Origin")) diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_mixed_web_port.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_mixed_web_port.py new file mode 100644 index 00000000..ae72cb62 --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_mixed_web_port.py @@ -0,0 +1,68 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +""" +The mixed web example listens on port 5151 by default, and on the port the +_51DEGREES_EXAMPLE_HTTP_PORTS environment variable names when it is set. The +check reads the example's source, so it starts no server and needs no +network. +""" + +import ast +import os +import unittest + +APP = os.path.join( + os.path.dirname(os.path.abspath(__file__)), "..", "src", + "fiftyone_pipeline_examples", "cloud", "mixed", "gettingstarted_web", + "app.py") + + +def run_port(): + # The expression the example passes to run as its port. + with open(APP, encoding="utf-8") as source: + tree = ast.parse(source.read()) + for node in ast.walk(tree): + if (isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr == "run"): + for keyword in node.keywords: + if keyword.arg == "port": + return keyword.value + return None + + +class CloudMixedWebPortTests(unittest.TestCase): + + def test_listens_on_5151_unless_port_names_another(self): + port = run_port() + # int() of the variable read from os.environ, or of 5151. + self.assertIsInstance(port, ast.Call) + get = port.args[0] + self.assertEqual("get", get.func.attr) + self.assertEqual( + ["_51DEGREES_EXAMPLE_HTTP_PORTS", 5151], + [arg.value for arg in get.args]) + + +if __name__ == "__main__": + unittest.main() diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_mixed_without_key.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_mixed_without_key.py new file mode 100644 index 00000000..31507975 --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_mixed_without_key.py @@ -0,0 +1,99 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +""" +Runs the mixed cloud console and web examples as they run from a fresh +clone, with no key set. Each must end without an error, naming the +environment variables to set and giving a tagged link to the page where a +key is created. +""" + +import io +import logging +import os +import unittest +from contextlib import redirect_stdout +from unittest import mock + +from fiftyone_pipeline_examples.cloud.mixed import gettingstarted_console +from fiftyone_pipeline_examples.cloud.mixed.gettingstarted_web import app +from fiftyone_pipeline_examples.example_utils import ExampleUtils + +# Every name a key can be read from, which a fresh clone does not set. +KEY_SETTINGS = [ + "_51DEGREES_RESOURCE_KEY", + "_51DEGREES_LICENSE_KEY"] + +# A link to the page where a resource key is created, with the campaign +# tags every example's links carry. +CONFIGURE_LINK = ( + r"https://51degrees\.com/configure[^\s?]*\?utm_source=code" + r"&utm_medium=example&utm_campaign=51degrees-python&utm_content=") + + +class Recorder(logging.Handler): + """Keeps every message logged while it is attached.""" + + def __init__(self): + super().__init__(logging.DEBUG) + self.messages = [] + + def emit(self, record): + self.messages.append(record.getMessage()) + + +class MixedExamplesWithoutKeyTests(unittest.TestCase): + + def run_without_key(self, main): + """Runs main with no arguments and no key in the environment, fails + the test if it exits, and returns what it printed and logged.""" + printed = io.StringIO() + recorder = Recorder() + root = logging.getLogger() + root.addHandler(recorder) + try: + with mock.patch.dict(os.environ), redirect_stdout(printed): + for name in KEY_SETTINGS: + os.environ.pop(name, None) + try: + main([]) + except SystemExit as stopped: + self.fail(f"The example exited with {stopped.code!r}") + finally: + root.removeHandler(recorder) + return printed.getvalue() + "\n".join(recorder.messages) + + def test_says_how_to_get_a_key(self): + said = self.run_without_key(gettingstarted_console.main) + self.assertIn(ExampleUtils.RESOURCE_KEY_ENV_VAR, said) + self.assertRegex(said, CONFIGURE_LINK) + + def test_web_says_how_to_get_a_key_and_ends(self): + started = AssertionError("The web server was started") + with mock.patch.object(app, "create_app", side_effect=started): + said = self.run_without_key(app.main) + self.assertIn(ExampleUtils.RESOURCE_KEY_ENV_VAR, said) + self.assertRegex(said, CONFIGURE_LINK) + + +if __name__ == "__main__": + unittest.main() diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_example_utils.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_example_utils.py index 1b6cc187..fa561f4f 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_example_utils.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_example_utils.py @@ -32,67 +32,47 @@ import pytest -# Each reader of a setting, with the new name of its variable and the old -# one, which is still read when the new name is not set. -OLD_NAMES = [ - ("get_resource_key", "_51DEGREES_RESOURCE_KEY", "resource_key"), - ("get_license_key", "_51DEGREES_LICENSE_KEY", "license_key"), - ("get_cloud_endpoint", "_51DEGREES_CLOUD_ENDPOINT", "cloud_endpoint"), - ("get_cloud_request_origin", "_51DEGREES_CLOUD_REQUEST_ORIGIN", - "cloud_request_origin"), +# Each reader of a setting, with the name of its variable. +NAMES = [ + ("get_resource_key", "_51DEGREES_RESOURCE_KEY"), + ("get_license_key", "_51DEGREES_LICENSE_KEY"), + ("get_cloud_endpoint", "_51DEGREES_CLOUD_ENDPOINT"), + ("get_cloud_request_origin", "_51DEGREES_CLOUD_REQUEST_ORIGIN"), ] @pytest.fixture def no_settings(monkeypatch): - """None of the settings in the environment, and no old name reported - as deprecated yet.""" - for _, name, old_name in OLD_NAMES: + """None of the settings in the environment.""" + for _, name in NAMES: monkeypatch.delenv(name, raising=False) - monkeypatch.delenv(old_name, raising=False) - monkeypatch.setattr( - ExampleUtils, "_ExampleUtils__reported_old_names", set()) return monkeypatch -@pytest.mark.parametrize("getter, name, old_name", OLD_NAMES) -def test_setting_is_read_from_its_old_name_and_reported_once( - getter, name, old_name, no_settings, capsys): - no_settings.setenv(old_name, "old-value") - assert getattr(ExampleUtils, getter)() == "old-value" - assert getattr(ExampleUtils, getter)() == "old-value" - errors = capsys.readouterr().err - assert errors.count( - old_name + " environment variable is deprecated") == 1 - assert name in errors - - -@pytest.mark.parametrize("getter, name, old_name", OLD_NAMES) -def test_new_name_wins_and_nothing_is_printed( - getter, name, old_name, no_settings, capsys): +@pytest.mark.parametrize("getter, name", NAMES) +def test_setting_is_read(getter, name, no_settings): no_settings.setenv(name, "new-value") - no_settings.setenv(old_name, "old-value") assert getattr(ExampleUtils, getter)() == "new-value" - assert capsys.readouterr().err == "" -@pytest.mark.parametrize("getter, name, old_name", OLD_NAMES) -def test_neither_name_gives_an_empty_string( - getter, name, old_name, no_settings, capsys): +@pytest.mark.parametrize("getter, name", NAMES) +def test_no_setting_gives_an_empty_string(getter, name, no_settings): assert getattr(ExampleUtils, getter)() == "" - assert capsys.readouterr().err == "" - -def test_constants_hold_the_old_and_the_new_names(): +def test_constants_hold_the_names(): assert ExampleUtils.RESOURCE_KEY_ENV_VAR == "_51DEGREES_RESOURCE_KEY" - assert ExampleUtils.LEGACY_RESOURCE_KEY_ENV_VAR == "resource_key" assert ExampleUtils.LICENSE_KEY_ENV_VAR == "_51DEGREES_LICENSE_KEY" - assert ExampleUtils.LEGACY_LICENSE_KEY_ENV_VAR == "license_key" assert ExampleUtils.CLOUD_ENDPOINT_ENV_VAR == "_51DEGREES_CLOUD_ENDPOINT" - assert ExampleUtils.ENDPOINT_ENV_VAR == "cloud_endpoint" assert (ExampleUtils.CLOUD_REQUEST_ORIGIN_ENV_VAR == "_51DEGREES_CLOUD_REQUEST_ORIGIN") - assert ExampleUtils.ORIGIN_ENV_VAR == "cloud_request_origin" + + +def test_no_other_constant_names_a_variable(): + named = sorted( + name for name in vars(ExampleUtils) if name.endswith("_ENV_VAR")) + assert named == [ + "CLOUD_ENDPOINT_ENV_VAR", "CLOUD_REQUEST_ORIGIN_ENV_VAR", + "LICENSE_KEY_ENV_VAR", "RESOURCE_KEY_ENV_VAR"] class Results: diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_find_out_more.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_find_out_more.py new file mode 100644 index 00000000..b9617572 --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_find_out_more.py @@ -0,0 +1,120 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +""" +The mixed console and the mixed web example each end with their "Find out +more" section when they stop early, as they do after a run. These run each +of them to each early end, so they need no key and no network. +""" + +import re + +import pytest + +from fiftyone_pipeline_examples.cloud.mixed import gettingstarted_console +from fiftyone_pipeline_examples.cloud.mixed.gettingstarted_web import app +from fiftyone_pipeline_examples.example_utils import ExampleUtils + +# Every name a key is read from. +KEY_SETTINGS = [ + ExampleUtils.RESOURCE_KEY_ENV_VAR, + ExampleUtils.LICENSE_KEY_ENV_VAR, +] + +# A 51degrees.com link. +LINK = re.compile(r"https://51degrees\.com/\S+") + +# The utm_content the web example's links carry, naming its file. +WEB_CONTENT = ( + "&utm_content=fiftyone_pipeline_cloudrequestengine-examples-src-" + "fiftyone_pipeline_examples-cloud-mixed-gettingstarted_web-app.py&") + + +def assert_tagged(printed, content): + """Each 51degrees.com link printed in the section is tagged as being + in the section and in the file named.""" + links = LINK.findall(printed.split("Find out more:", 1)[1]) + assert links + for link in links: + assert "utm_medium=example" in link + assert "utm_term=find-out-more" in link + assert content in link + + +def test_without_a_key(monkeypatch, capsys): + for name in KEY_SETTINGS: + monkeypatch.delenv(name, raising=False) + + gettingstarted_console.main([]) + + printed = capsys.readouterr().out + assert "Find out more:" in printed + for _, url in gettingstarted_console.GettingStartedConsole.FIND_OUT_MORE: + assert url in printed + + +def test_when_the_pipeline_cannot_be_built(monkeypatch, capsys): + # Stands in for a key the cloud service refuses, or one that carries + # none of the properties the example shows. + def refuse(*args, **kwargs): + raise ValueError("The key carries none of the properties.") + + monkeypatch.setattr(gettingstarted_console, "create_pipeline", refuse) + + gettingstarted_console.main(["a-resource-key"]) + + assert "Find out more:" in capsys.readouterr().out + + +def test_the_web_example_without_a_key(monkeypatch, capsys): + for name in KEY_SETTINGS: + monkeypatch.delenv(name, raising=False) + + def started(*args, **kwargs): + raise AssertionError("The web server was started") + + monkeypatch.setattr(app, "create_app", started) + + app.main([]) + + printed = capsys.readouterr().out + assert "Find out more:" in printed + for _, url in app.FIND_OUT_MORE: + assert url in printed + assert_tagged(printed, WEB_CONTENT) + + +def test_the_web_example_when_the_pipeline_cannot_be_built(monkeypatch, + capsys): + # Stands in for a key the cloud service refuses, or one that carries + # none of the properties the example shows. + def refuse(*args, **kwargs): + raise ValueError("The key carries none of the properties.") + + monkeypatch.setattr(app, "create_pipeline", refuse) + + with pytest.raises(SystemExit): + app.main(["a-resource-key"]) + + printed = capsys.readouterr().out + assert "Find out more:" in printed + assert_tagged(printed, WEB_CONTENT) diff --git a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_simple_cloud_engine.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_simple_cloud_engine.py new file mode 100644 index 00000000..6538f179 --- /dev/null +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_simple_cloud_engine.py @@ -0,0 +1,153 @@ +# ********************************************************************* +# This Original Work is copyright of 51 Degrees Mobile Experts Limited. +# Copyright 2026 51 Degrees Mobile Experts Limited, Davidson House, +# Forbury Square, Reading, Berkshire, United Kingdom RG1 3EU. +# +# This Original Work is licensed under the European Union Public Licence +# (EUPL) v.1.2 and is subject to its terms as set out below. +# +# If a copy of the EUPL was not distributed with this file, You can obtain +# one at https://opensource.org/licenses/EUPL-1.2. +# +# The 'Compatible Licences' set out in the Appendix to the EUPL (as may be +# amended by the European Commission) shall be deemed incompatible for +# the purposes of the Work and the provisions of the compatibility +# clause in Article 5 of the EUPL shall not apply. +# +# If using the Work as, or as part of, a network application, by +# including the attribution notice(s) required under Article 5 of the EUPL +# in the end user terms of the application under an appropriate heading, +# such notice(s) shall fulfill the requirements of that article. +# ********************************************************************* + +""" +The cloud engine example starts a star sign service of its own on this +machine, so it needs no key and no network. It is run here as a person runs +it, from the command line, with none of the _51DEGREES_ environment +variables set, so a key or endpoint set for the other tests cannot reach it. +What it prints is checked, being the star signs, the reason the service +gives when there is no date of birth, and the Find out more section it ends +with. +""" + +import os +import re +import subprocess +import sys + +import pytest + +# The product folder. Each link's utm_content is the path of the example +# below this folder. +PRODUCT = os.path.abspath(os.path.join( + os.path.dirname(os.path.abspath(__file__)), "..", "..", "..")) + +EXAMPLE = os.path.join( + PRODUCT, "fiftyone_pipeline_cloudrequestengine", "examples", "src", + "fiftyone_pipeline_examples", "cloud", "simple_cloud_engine.py") + +# The example as the readme runs it. +MODULE = "fiftyone_pipeline_examples.cloud.simple_cloud_engine" + +# How long to wait for the example before failing, so a run that never +# ends cannot hold up the tests. +RUN_TIMEOUT_SECONDS = 120 + +# The start of the name of every 51Degrees environment variable. Each one is +# removed from the example's environment, to show it needs none of them. +SETTING_PREFIX = "_51DEGREES_" + +# What the example prints for each date of birth it looks up, and for the +# request with none. +STAR_SIGNS = [ + "With a date of birth of 1992-12-18, your star sign is Sagittarius.", + "With a date of birth of 1990-12-25, your star sign is Capricorn.", + "With a date of birth of 1992-04-15, your star sign is Aries.", + "With no date of birth, there is no star sign. The service needs a " + "date of birth in the form YYYY-MM-DD to find a star sign.", +] + +# The heading of the Find out more section, and the line above it. +HEADING = "Find out more:" +RULE = "=" * 79 + +# A line of the section, which is a tab, a label and a link. +SECTION_LINE = re.compile(r"\t(?P