diff --git a/.github/workflows/cloud-human-confidence.yml b/.github/workflows/cloud-human-confidence.yml new file mode 100644 index 00000000..f13bffa2 --- /dev/null +++ b/.github/workflows/cloud-human-confidence.yml @@ -0,0 +1,130 @@ +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] + paths: + - 'pipeline/fiftyone_pipeline_cloudrequestengine/examples/src/fiftyone_pipeline_examples/cloud/humanconfidence_web/**' + - 'pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/conftest.py' + - 'pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web.py' + - '.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" + 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.tests -eq 0) { + Write-Host '::error::No staging test ran.' + exit 1 + } + 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/AGENTS.md b/AGENTS.md index fac78f6a..145ff519 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -263,15 +263,28 @@ that GitHub, the operating system or a tool defines, such as `GITHUB_JOB` or [`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. +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 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. +`_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 diff --git a/ci/check-environment-variable-names.Tests.ps1 b/ci/check-environment-variable-names.Tests.ps1 index 4a173f87..2274ab4f 100644 --- a/ci/check-environment-variable-names.Tests.ps1 +++ b/ci/check-environment-variable-names.Tests.ps1 @@ -104,6 +104,8 @@ Describe 'Find-EnvironmentNameProblem in a workflow' { 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' } @@ -130,6 +132,9 @@ Describe 'Test-EnvironmentName' { @{ Name = 'GITHUB_ENV' } @{ Name = 'TEMP' } @{ Name = 'PSModulePath' } + # Names only CI uses. + @{ Name = 'CLOUD_STAGING_ENDPOINT' } + @{ Name = 'RESOURCE_KEY_BESPOKE_STAGING' } ) { Test-EnvironmentName $Name | Should -BeTrue } @@ -140,6 +145,12 @@ Describe 'Test-EnvironmentName' { @{ 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' } ) { Test-EnvironmentName $Name | Should -BeFalse } diff --git a/ci/check-environment-variable-names.ps1 b/ci/check-environment-variable-names.ps1 index 084f73af..e808fdd7 100644 --- a/ci/check-environment-variable-names.ps1 +++ b/ci/check-environment-variable-names.ps1 @@ -4,7 +4,8 @@ # line that reads or sets an environment variable under another name. # # A name that GitHub, the operating system or a tool defines is used as it -# is. $PlatformNames lists the ones this repository uses. +# is. $PlatformNames lists the ones this repository uses. The few names only +# CI uses, which no customer sets, are in $CiNames. # # 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 @@ -33,6 +34,10 @@ $script:PlatformNames = @( 'TEMP', 'TMP', 'TMPDIR') $script:PlatformPrefixes = @('GITHUB_') +# The names only CI uses. No customer sets them, so they have no _51DEGREES_ +# prefix, and each name says what it holds. +$script:CiNames = @('CLOUD_STAGING_ENDPOINT', 'RESOURCE_KEY_BESPOKE_STAGING') + $name = '(?[A-Za-z0-9_]+)' $quoted = "['`"]$name['`"]" @@ -62,12 +67,15 @@ $script:ReadOrSetPatterns = @( # "NAME: value". $script:WorkflowKeyPattern = [regex]::new('^\s+(?[A-Z_][A-Z0-9_]*):(?:\s|$)') -# Whether a name may be read or set: one this repository defines, or one the -# platform does. +# 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 } + if ($script:CiNames -ccontains $Name) { + return $true + } if ($script:PlatformNames -contains $Name) { return $true } @@ -144,9 +152,10 @@ Write-Output ("$read paths read, $($skipped.Count) skipped as not files: " + if ($found.Count -gt 0) { Write-Output $found throw ("$($found.Count) environment variables are read or set under a " + - "name that does not start with $($script:Prefix) and is not one the " + - 'platform defines.') + "name that does not start with $($script:Prefix) and is not one only " + + 'CI uses or one the platform defines.') } Write-Output ('Every environment variable a tracked file reads or sets ' + - "starts with $($script:Prefix) or is one the platform defines.") + "starts with $($script:Prefix), is one only CI uses or is one the " + + 'platform defines.') diff --git a/ci/key-names.Tests.ps1 b/ci/key-names.Tests.ps1 index c24fdcb4..2146b363 100644 --- a/ci/key-names.Tests.ps1 +++ b/ci/key-names.Tests.ps1 @@ -12,6 +12,12 @@ # 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 @@ -81,6 +87,80 @@ foreach ($asset in $Assets) { Set-Content -LiteralPath "assets/$asset" '' } $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. Gives the exit + # code and the output. + function Invoke-StagingStep([hashtable]$Names, [string]$Report) { + $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 = 0' + '}' + ) + @($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' { @@ -400,6 +480,66 @@ Describe 'Keys under their _51DEGREES_ names' { $output | Should -Match '_51DEGREES_RESOURCE_KEY_51DID' $output | Should -Not -Match 'tox ran' } + + # Only the workflow that runs the tests marked staging sets the + # staging names, so no other workflow's tests call the staging cloud. + It 'are given from the organization of the same name by the Cloud Human Confidence workflow alone' -ForEach @( + @{ Variable = 'CLOUD_STAGING_ENDPOINT'; Kind = 'variable'; Context = 'vars' } + @{ Variable = 'RESOURCE_KEY_BESPOKE_STAGING'; Kind = 'secret'; Context = 'secrets' } + ) { + $lines = @(Get-ChildItem (Join-Path $script:Root '.github/workflows') -Include *.yml, *.yaml -Recurse | + Select-String -Pattern "\b$Variable\b" | + Where-Object { $_.Line.Trim() -notmatch '^#' } | + ForEach-Object { "$($_.Filename):$($_.LineNumber): $($_.Line.Trim())" }) + $lines | Where-Object { $_ -notmatch '^cloud-human-confidence\.yml:' } | + Should -BeNullOrEmpty + $given = @($lines | Where-Object { $_ -match ":\s*$Variable\s*:" }) + $given.Count | Should -Be 1 + $given[0] | Should -Match ":\s*$Variable\s*:\s*\$\{\{\s*$Context\.$Variable\s*\}\}\s*$" + } + + It 'read the staging cloud and its key from CLOUD_STAGING_ENDPOINT and RESOURCE_KEY_BESPOKE_STAGING in the Human Confidence live test' { + $text = Get-Content -Raw (Join-Path $script:Root 'pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web.py') + $text | Should -Match '"CLOUD_STAGING_ENDPOINT"' + $text | Should -Match '"RESOURCE_KEY_BESPOKE_STAGING"' + $text | Should -Match '@pytest\.mark\.staging' + } + + It 'fail the Cloud Human Confidence step, naming , when it is empty, before any test runs' -ForEach @( + @{ Missing = 'CLOUD_STAGING_ENDPOINT' } + @{ Missing = 'RESOURCE_KEY_BESPOKE_STAGING' } + @{ Missing = '_51DEGREES_RESOURCE_KEY_BASIC' } + ) { + $names = $script:StagingNames.Clone() + $names[$Missing] = $null + $result = Invoke-StagingStep $names (New-JunitReport 2 0) + + $result.ExitCode | Should -Not -Be 0 + $result.Output | Should -Match "$Missing is empty or missing" + $result.Output | Should -Not -Match 'pytest ran' + } + + It 'fail the Cloud Human Confidence step when a staging test skipped' { + $result = Invoke-StagingStep $script:StagingNames (New-JunitReport 2 1) + + $result.ExitCode | Should -Not -Be 0 + $result.Output | Should -Match 'pytest ran' + $result.Output | Should -Match 'test_0 skipped' + } + + It 'fail the Cloud Human Confidence step when no staging test ran' { + $result = Invoke-StagingStep $script:StagingNames (New-JunitReport 0 0) + + $result.ExitCode | Should -Not -Be 0 + $result.Output | Should -Match 'No staging test ran' + } + + It 'pass the Cloud Human Confidence step when every staging test ran' { + $result = Invoke-StagingStep $script:StagingNames (New-JunitReport 2 0) + + $result.ExitCode | Should -Be 0 + $result.Output | Should -Match 'pytest ran' + } } Describe 'The live cloud tests' { diff --git a/pipeline/ci/README.md b/pipeline/ci/README.md index 11565ebf..8b6a36ef 100644 --- a/pipeline/ci/README.md +++ b/pipeline/ci/README.md @@ -6,8 +6,12 @@ The following secrets are required: * Example: `github_pat_l0ng_r4nd0m_s7r1ng` * `_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` -* `_51DEGREES_RESOURCE_KEY_BASIC` - resource key of the Basic product, an organization secret. The Basic Human Confidence test and the 51Did tier test read it, and skip naming it when it is not set. +* `_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/fiftyone_pipeline_cloudrequestengine/examples/tests/conftest.py b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/conftest.py index 16bcd169..7e12799f 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/conftest.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/conftest.py @@ -39,6 +39,11 @@ def pytest_configure(config): "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) 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 index a436ebcb..6ab34396 100644 --- a/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web.py +++ b/pipeline/fiftyone_pipeline_cloudrequestengine/examples/tests/test_cloud_humanconfidence_web.py @@ -31,6 +31,14 @@ 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. """ @@ -58,6 +66,14 @@ # 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" @@ -82,16 +98,24 @@ def api(): @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.""" + 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): - if method == "POST" and url.endswith(".json"): + named = method == "POST" and url.endswith(".json") + if named: data = dict(data or {}, values=PROPERTIES) - return real(method, url, data=data, **kwargs) + 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") @@ -104,6 +128,32 @@ def client(key, api): 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 @@ -111,27 +161,45 @@ def test_page_is_served_and_never_kept(client, key): assert key in response.get_data(as_text=True) +@pytest.mark.staging def test_passive_source_and_level_come_from_the_cloud( - client, naming_the_properties): - answer = client.get("/passive", headers=HEADERS).get_json() + 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 -def test_a_basic_key_gets_no_source(api, naming_the_properties): - """The Basic product does not offer HumanConfidenceSource.""" +@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, api).test_client() + 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() diff --git a/pipeline/readme.md b/pipeline/readme.md index cb117deb..2e3c01be 100644 --- a/pipeline/readme.md +++ b/pipeline/readme.md @@ -51,7 +51,7 @@ and examples that are available. To run tests: * Go to each directory (for example `fiftyone_pipeline_core`) * Run `tox -e py` -The tests that call the 51Degrees cloud service need a resource key. The cloud request engine's tests and its examples' tests read it from the `_51DEGREES_RESOURCE_KEY_BESPOKE` environment variable, and the 51Did tests from `_51DEGREES_RESOURCE_KEY_51DID`. Without one, those tests skip. +The tests that call the 51Degrees cloud service need a resource key. The cloud request engine's tests and its examples' tests read it from the `_51DEGREES_RESOURCE_KEY_BESPOKE` environment variable, and the 51Did tests from `_51DEGREES_RESOURCE_KEY_51DID`. Without one, those tests skip. The Human Confidence example tests marked `staging` call the staging cloud that `CLOUD_STAGING_ENDPOINT` names instead, with the key in `RESOURCE_KEY_BESPOKE_STAGING`. Only CI sets those names, and without them those tests skip. ## Examples