diff --git a/.github/workflows/examples-published.yml b/.github/workflows/examples-published.yml new file mode 100644 index 000000000..88bb69f15 --- /dev/null +++ b/.github/workflows/examples-published.yml @@ -0,0 +1,161 @@ +name: Examples vs Published Packages + +# Runs the examples' own tests against the packages on Maven Central. Only +# the two examples trees and their tests come from this checkout. The +# packages the examples name by version are pinned to the version given when +# the workflow is run by hand, after a publish to the version the publish +# released each at, and otherwise to the latest release on Maven Central. +# ci/run-published-examples.ps1 chooses the versions and runs the tests. +# +# It runs by hand on a branch (gh workflow run "Examples vs Published +# Packages" --ref ), after each run of the two workflows that +# publish, and on a pull request that changes this file or the script. An +# example that needs a change not yet released fails here until the release, +# which is why it does not run on other pull requests. +# +# The tests run on the free data files, with the TAC and Enterprise IP +# Intelligence data files the data file update examples' tests need, and the +# keys the cloud tests need. A missing key or data file fails the run, and so +# do a tree that ran no tests and a test that skipped, except the few the +# script lists as skipping here by design. A pull request from a fork gets no +# secrets, so the job does not run for one. + +on: + workflow_dispatch: + inputs: + version: + description: 'Version of every published package, such as 4.6.2, or empty for the latest of each on Maven Central' + type: string + default: '' + # A run of either may publish packages, and one that failed may still have + # published some, so only a cancelled run is passed over. + workflow_run: + workflows: [Publish, Nightly Pipeline] + types: [completed] + pull_request: + paths: + - '.github/workflows/examples-published.yml' + - 'ci/run-published-examples.ps1' + - 'ci/run-published-examples.Tests.ps1' + - 'ci/packages.ps1' + +permissions: + contents: read + +# Every compiler and tool warning is an error in the builds 51Degrees runs. +# The poms read this variable. +env: + _51DEGREES_WARNINGS_AS_ERRORS: 'true' + +defaults: + run: + shell: pwsh + +jobs: + published: + name: examples vs published packages + if: >- + (github.event_name != 'workflow_run' || + github.event.workflow_run.conclusion != 'cancelled') && + github.event.pull_request.head.repo.fork != true + runs-on: ubuntu-latest + timeout-minutes: 120 + steps: + # A missing key would leave the cloud tests skipped, so it fails the + # run here, naming it. + - name: Check the keys are available + env: + _51DEGREES_RESOURCE_KEY_BESPOKE: ${{ secrets._51DEGREES_RESOURCE_KEY_BESPOKE }} + _51DEGREES_RESOURCE_KEY_BASIC: ${{ secrets._51DEGREES_RESOURCE_KEY_BASIC }} + run: | + $missing = @('_51DEGREES_RESOURCE_KEY_BESPOKE', '_51DEGREES_RESOURCE_KEY_BASIC' | + Where-Object { -not [Environment]::GetEnvironmentVariable($_) }) + if ($missing) { + throw ("The organization secret $($missing -join ', ') is " + + 'empty or missing, so the cloud examples cannot be tested.') + } + + # After a publish, the commit that was published. The data repository + # inside cxx holds a link for each data file, where the examples look. + # The tags a publish pushes are read from origin, so none are fetched. + - name: Checkout repository + uses: actions/checkout@v4 + with: + ref: ${{ github.event.workflow_run.head_sha }} + persist-credentials: false + submodules: recursive + + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '17' + + # The free data files, from the one shared copy that common-ci's + # Nightly Shared Assets workflow downloads each day, so nothing follows + # the links here. + - name: Restore the free data files + uses: 51Degrees/common-ci/actions/fetch-assets@main + with: + assets: | + 51Degrees-LiteV4.1.hash + 20000 Evidence Records.yml + 51Degrees-IPIV4AsnIpiV41.ipi + 51Degrees-LiteIpiV41.ipi + + # The data file update examples' tests serve a copy of the TAC data + # file and of the Enterprise IP Intelligence data file. They come from + # the same shared copy, decrypted with CACHE_ENCRYPTION_KEY, which + # common-ci's step reads from this step's environment. Nothing here + # keeps them. + - name: Restore the licensed data files + uses: 51Degrees/common-ci/actions/fetch-assets@main + env: + CACHE_ENCRYPTION_KEY: ${{ secrets.CACHE_ENCRYPTION_KEY }} + with: + assets: | + TAC-HashV41.hash + 51Degrees-EnterpriseIpiV41.ipi + + # Under the names the data repository saves them as, where the + # examples look. A missing file fails the job here, because the tests + # would skip or fail without it. + - name: Put the data files where the examples look for them + run: | + $dd = 'cxx/data/device-detection' + $ipi = 'cxx/data/ip-intelligence' + $files = [ordered]@{ + '51Degrees-LiteV4.1.hash' = "$dd/51Degrees-LiteV4.1.hash" + '20000 Evidence Records.yml' = "$dd/20000 Evidence Records.yml" + 'TAC-HashV41.hash' = "$dd/TAC-HashV41.hash" + '51Degrees-IPIV4AsnIpiV41.ipi' = "$ipi/51Degrees-IPIV4AsnIpiV41.ipi" + '51Degrees-LiteIpiV41.ipi' = "$ipi/51Degrees-LiteV41.ipi" + '51Degrees-EnterpriseIpiV41.ipi' = "$ipi/51Degrees-EnterpriseIpiV41.ipi" + } + foreach ($asset in $files.Keys) { + $source = Join-Path assets $asset + if (-not (Test-Path -LiteralPath $source -PathType Leaf)) { + Write-Host "::error title=Missing data file::$asset was not fetched." + exit 1 + } + Move-Item -LiteralPath $source -Destination $files[$asset] + } + + # The cloud tests read _51DEGREES_RESOURCE_KEY_BESPOKE, and the Human + # Confidence test also _51DEGREES_RESOURCE_KEY_BASIC. After a publish, + # each package it tagged is pinned to the version its tag names. + - name: Test the examples against the published packages + env: + _51DEGREES_RESOURCE_KEY_BESPOKE: ${{ secrets._51DEGREES_RESOURCE_KEY_BESPOKE }} + _51DEGREES_RESOURCE_KEY_BASIC: ${{ secrets._51DEGREES_RESOURCE_KEY_BASIC }} + # The cloud service the tests ask. The name is removed when the + # variable is not set, so the tests ask the public one. + _51DEGREES_CLOUD_ENDPOINT: ${{ vars._51DEGREES_CLOUD_ENDPOINT }} + # The version typed when the workflow is run by hand, which is read + # from here rather than written into the script. + _51DEGREES_PACKAGE_VERSION: ${{ inputs.version }} + run: | + if (-not $env:_51DEGREES_CLOUD_ENDPOINT) { + Remove-Item Env:_51DEGREES_CLOUD_ENDPOINT -ErrorAction SilentlyContinue + } + ./ci/run-published-examples.ps1 -Version "$env:_51DEGREES_PACKAGE_VERSION".Trim() ` + -PublishedCommit '${{ github.event.workflow_run.head_sha }}' diff --git a/ci/README.md b/ci/README.md index ff2945c50..dc22c44f5 100644 --- a/ci/README.md +++ b/ci/README.md @@ -81,6 +81,23 @@ repositories used to do for one package tree each. [run-fresh-clone-example.Tests.ps1](run-fresh-clone-example.Tests.ps1) tests it with `pwsh -File` and with the workflow's own calls. +- [run-published-examples.ps1](run-published-examples.ps1) runs the tests of + both examples trees against the packages on Maven Central for + [examples-published.yml](../.github/workflows/examples-published.yml). It + pins the packages the examples name by version to the version given, to the + version a publish tagged once Maven Central lists it, or to the latest + release, and starts Maven from an empty local repository. It fails unless + each tree ran tests, every test passed or is one of the few it lists as + skipping by design, and every pinned package came from Maven Central. To + run it by hand, put the data files in `cxx/data` and set the keys, then from + the repository root give + + ``` + pwsh -File ./ci/run-published-examples.ps1 -Version 4.6.2 + ``` + + [run-published-examples.Tests.ps1](run-published-examples.Tests.ps1) tests + it with a stand-in for Maven and a folder in place of Maven Central. - [run-performance-tests.ps1](run-performance-tests.ps1) measures the Pipeline API, Device Detection and IP Intelligence and writes one results file per configuration. The Device Detection and IP Intelligence metrics are prefixed diff --git a/ci/check-environment-variable-names.ps1 b/ci/check-environment-variable-names.ps1 index 6eff882d4..bfbf7ed9b 100644 --- a/ci/check-environment-variable-names.ps1 +++ b/ci/check-environment-variable-names.ps1 @@ -58,8 +58,8 @@ $script:PlatformNames = @( # check. 'polyglot.engine.WarnInterpreterOnly' # GitHub Actions and its runners. - 'CI', 'GITHUB_ACTIONS', 'GITHUB_ENV', 'GITHUB_TOKEN', 'CHROME_BIN', - 'CHROMEWEBDRIVER' + 'CI', 'GITHUB_ACTIONS', 'GITHUB_ENV', 'GITHUB_STEP_SUMMARY', 'GITHUB_TOKEN', + 'CHROME_BIN', 'CHROMEWEBDRIVER' ) # The names only CI uses. No customer sets them, so they have no @@ -71,6 +71,9 @@ $script:CiNames = @( # False on the entries that leave the live cloud tests to another entry # of the same operating system. setup-environment.ps1 sets it. 'LIVE_CLOUD_TESTS' + # The key that decrypts the licensed data files in common-ci's shared + # copy, which its fetch-assets step reads. + 'CACHE_ENCRYPTION_KEY' ) # The system properties the JDK defines start with one of these. diff --git a/ci/packages.ps1 b/ci/packages.ps1 index 25241f0ce..ffdc35e4f 100644 --- a/ci/packages.ps1 +++ b/ci/packages.ps1 @@ -50,6 +50,16 @@ $env:_51DEGREES_WARNINGS_AS_ERRORS = 'true' # Arguments every Maven call in these scripts passes. $MavenOptions = '--batch-mode', '--no-transfer-progress' +# The examples' properties that name the version of a package they use, which +# the publish sets to the version it built and the Examples vs Published +# Packages workflow to the versions on Maven Central. +$ExampleVersionProperties = @{ + 'device-detection.version' = 'device-detection' + 'ip-intelligence.version' = 'ip-intelligence' + 'pipeline.cloudrequestengine.version' = 'pipeline.cloudrequestengine' + 'pipeline.jsonbuilder.version' = 'pipeline.jsonbuilder' +} + # Every Maven call that compiles runs on this JDK, which compiles for Java 8 # through each tree's java-8-api profile. The tests still run on each entry's # own JDK. javac 21 warns that release 8 is obsolete, which -Werror makes an diff --git a/ci/release.ps1 b/ci/release.ps1 index 704c177f7..a72048823 100644 --- a/ci/release.ps1 +++ b/ci/release.ps1 @@ -23,15 +23,6 @@ if ($null -eq $releasePlan) { . $releasePlan Remove-Variable releasePlan -# The examples' properties that name the version of a package they use, which -# the publish sets to the version it built. -$ExampleVersionProperties = @{ - 'device-detection.version' = 'device-detection' - 'ip-intelligence.version' = 'ip-intelligence' - 'pipeline.cloudrequestengine.version' = 'pipeline.cloudrequestengine' - 'pipeline.jsonbuilder.version' = 'pipeline.jsonbuilder' -} - # The packages a publish builds. When nothing is to be released, every package # is built at its released version, so that the tests have packages to install # and the nightly publish passes without publishing anything. diff --git a/ci/run-published-examples.Tests.ps1 b/ci/run-published-examples.Tests.ps1 new file mode 100644 index 000000000..8d5e18f2b --- /dev/null +++ b/ci/run-published-examples.Tests.ps1 @@ -0,0 +1,239 @@ +# Tests for ci/run-published-examples.ps1. +# +# Each case runs the script in a new pwsh process, in a folder that is a git +# repository whose origin holds the tags a publish pushes, with a folder laid +# out as Maven Central is in place of Maven Central, and a stand-in for mvn +# first on the PATH. The stand-in records each call, writes a surefire report +# with the counts the case asks for, and records each pinned package in the +# local repository as downloaded from the repository the case names. + +BeforeAll { + $script:Script = Join-Path $PSScriptRoot 'run-published-examples.ps1' + $script:Pwsh = (Get-Process -Id $PID).Path + $script:Artifacts = 'device-detection', 'ip-intelligence', + 'pipeline.cloudrequestengine', 'pipeline.jsonbuilder' + + # The repository, with the script and the file it loads, the two example + # trees and a commit with one package's tag on it in origin. + $script:Root = Join-Path $TestDrive 'repository' + New-Item -ItemType Directory (Join-Path $Root 'ci') -Force | Out-Null + foreach ($file in 'run-published-examples.ps1', 'packages.ps1') { + Copy-Item (Join-Path $PSScriptRoot $file) (Join-Path $Root 'ci') + } + foreach ($tree in 'examples/device-detection', 'examples/ip-intelligence') { + New-Item -ItemType Directory (Join-Path $Root $tree) -Force | Out-Null + } + $origin = Join-Path $TestDrive 'origin.git' + git init -q --bare $origin + git -C $Root init -q + # A runner has no git identity, and the annotated tag below needs one as + # much as the commit does. + git -C $Root config user.name test + git -C $Root config user.email test@example.com + git -C $Root remote add origin $origin + git -C $Root commit -q --allow-empty -m published + $script:Commit = git -C $Root rev-parse HEAD + git -C $Root tag pipeline.jsonbuilder/4.6.3 + git -C $Root tag -a -m 'annotated' device-detection/4.6.3 + git -C $Root tag ip-intelligence/4.6.9 + git -C $Root tag ip-intelligence/4.6.10 + git -C $Root push -q origin --tags + + # Maven Central, with 4.6.2 as every package's latest release and 4.6.3 + # of the packages tagged above, as Maven Central lists a version once it + # has its pom. + $script:Central = Join-Path $TestDrive 'central' + function Add-Pom([string]$Artifact, [string]$Version) { + $folder = Join-Path $Central "com/51degrees/$Artifact/$Version" + New-Item -ItemType Directory $folder -Force | Out-Null + Set-Content (Join-Path $folder "$Artifact-$Version.pom") '' + } + foreach ($artifact in $Artifacts) { + $folder = Join-Path $Central "com/51degrees/$artifact" + New-Item -ItemType Directory $folder -Force | Out-Null + Set-Content (Join-Path $folder 'maven-metadata.xml') ( + "4.6.2") + Add-Pom $artifact '4.6.2' + } + + # The stand-in for mvn. The case's settings file gives the counts for the + # surefire report, the exit code, and the repository id the packages are + # recorded as downloaded from. + $script:Bin = Join-Path $TestDrive 'bin' + New-Item -ItemType Directory $Bin | Out-Null + $script:Calls = Join-Path $Bin 'calls.txt' + $script:Settings = Join-Path $Bin 'settings.json' + # Not named mvn.ps1, which pwsh on Windows would run in place of mvn.cmd. + $standIn = Join-Path $Bin 'mvn-stand-in.ps1' + Set-Content $standIn @' +$settings = Get-Content -Raw (Join-Path $PSScriptRoot 'settings.json') | ConvertFrom-Json +Add-Content (Join-Path $PSScriptRoot 'calls.txt') "$(Split-Path -Leaf $PWD) $($args -join ' ')" +$reports = New-Item -ItemType Directory -Force (Join-Path $PWD 'module/target/surefire-reports') +# Each skip is the test's class and method, with the reason after a | when +# it is not 'a key is set'. +$skips = @($settings.Skips | ForEach-Object { + $test, $reason = $_ -split '\|', 2 + if (-not $reason) { $reason = 'a key is set' } + $class, $method = $test -split '\.(?=[^.]+$)' + "" +}) -join '' +Set-Content (Join-Path $reports 'TEST-Example.xml') ( + "$skips") +$local = ($args | Where-Object { $_ -like '-Dmaven.repo.local=*' }) -replace '^-Dmaven\.repo\.local=' +foreach ($argument in $args) { + if ($argument -notmatch '^-D(?.+)\.version=(?.+)$') { + continue + } + $folder = New-Item -ItemType Directory -Force (Join-Path $local "com/51degrees/$($Matches.artifact)/$($Matches.version)") + Set-Content (Join-Path $folder '_remote.repositories') ( + "#NOTE: This is a Maven Resolver internal implementation file`n" + + "$($Matches.artifact)-$($Matches.version).pom>$($settings.Remote)=") +} +exit $settings.Exit +'@ + if ($IsWindows) { + Set-Content (Join-Path $Bin 'mvn.cmd') "@`"$Pwsh`" -NoProfile -File `"$standIn`" %*" + } else { + $mvn = Join-Path $Bin 'mvn' + Set-Content $mvn "#!/bin/sh`nexec `"$Pwsh`" -NoProfile -File `"$standIn`" `"`$@`"" + chmod +x $mvn + } + + # Runs the script with the arguments in the repository folder, with the + # stand-in first on the PATH, and returns the exit code, the output and + # the stand-in's calls. + function Invoke-Script([string[]]$Arguments, [int]$Tests = 3, [string[]]$Skips = @(), + [int]$Exit = 0, [string]$Remote = 'central') { + @{ Tests = $Tests; Skips = $Skips; Exit = $Exit; Remote = $Remote } | + ConvertTo-Json | Set-Content $Settings + Remove-Item $Calls -ErrorAction SilentlyContinue + $summary = Join-Path $TestDrive 'summary.md' + Remove-Item $summary -ErrorAction SilentlyContinue + $path = $env:PATH + Push-Location $Root + try { + $env:PATH = $Bin + [IO.Path]::PathSeparator + $path + $output = & $Pwsh -NoProfile -NonInteractive -File (Join-Path $Root 'ci/run-published-examples.ps1') ` + -Repository $Central -Summary $summary -WaitSeconds 0 -RetrySeconds 0 @Arguments 2>&1 | + ForEach-Object { "$_" } + [pscustomobject]@{ + Code = $LASTEXITCODE + Text = $output -join "`n" + Calls = @(if (Test-Path $Calls) { Get-Content $Calls }) + Summary = if (Test-Path $summary) { Get-Content -Raw $summary } else { '' } + } + } finally { + $env:PATH = $path + Pop-Location + } + } +} + +Describe 'run-published-examples.ps1' { + + It 'pins every package to the latest release on Maven Central and tests both trees' { + $run = Invoke-Script @() + $run.Code | Should -Be 0 -Because $run.Text + $run.Calls.Count | Should -Be 2 + $run.Calls[0] | Should -BeLike 'device-detection clean test *' + $run.Calls[1] | Should -BeLike 'ip-intelligence clean test *' + $run.Text | Should -Not -Match '::(warning|error)' + foreach ($artifact in $Artifacts) { + $run.Calls | Should -BeLike "*-D$artifact.version=4.6.2*" + $run.Summary | Should -Match "\| $([regex]::Escape($artifact)) \| 4\.6\.2 \|" + } + } + + It 'pins every package to the version given' { + foreach ($artifact in $Artifacts) { + Add-Pom $artifact '4.6.1' + } + $run = Invoke-Script @('-Version', '4.6.1') + $run.Code | Should -Be 0 + foreach ($artifact in $Artifacts) { + $run.Calls[0] | Should -BeLike "*-D$artifact.version=4.6.1*" + } + } + + It 'fails before testing when Maven Central has no package at the version given' { + $run = Invoke-Script @('-Version', '4.6.9') + $run.Code | Should -Not -Be 0 + $run.Text | Should -Match 'Maven Central has no device-detection 4\.6\.9' + $run.Calls.Count | Should -Be 0 + } + + It 'refuses a version that is not one' { + $run = Invoke-Script @('-Version', '4.6') + $run.Code | Should -Not -Be 0 + $run.Text | Should -Match "'4\.6' is not a version" + } + + It 'pins each package the publish tagged to its tag, lightweight or annotated, the highest of two, and the rest to the latest' { + Add-Pom 'device-detection' '4.6.3' + Add-Pom 'pipeline.jsonbuilder' '4.6.3' + Add-Pom 'ip-intelligence' '4.6.10' + $run = Invoke-Script @('-PublishedCommit', $Commit) + $run.Code | Should -Be 0 -Because $run.Text + $run.Calls[0] | Should -BeLike '*-Ddevice-detection.version=4.6.3*' + $run.Calls[0] | Should -BeLike '*-Dpipeline.jsonbuilder.version=4.6.3*' + $run.Calls[0] | Should -BeLike '*-Dip-intelligence.version=4.6.10*' + $run.Calls[0] | Should -BeLike '*-Dpipeline.cloudrequestengine.version=4.6.2*' + } + + It 'fails when Maven Central does not list a tagged version in time' { + Add-Pom 'device-detection' '4.6.3' + Remove-Item -Recurse -ErrorAction SilentlyContinue (Join-Path $Central 'com/51degrees/pipeline.jsonbuilder/4.6.3') + $run = Invoke-Script @('-PublishedCommit', $Commit) + $run.Code | Should -Not -Be 0 + $run.Text | Should -Match 'tagged pipeline\.jsonbuilder 4\.6\.3, which Maven Central did not list' + $run.Calls.Count | Should -Be 0 + } + + It 'fails when a tree fails, and still tests the other' { + $run = Invoke-Script @() -Exit 1 + $run.Code | Should -Not -Be 0 + $run.Calls.Count | Should -Be 2 + $run.Text | Should -Match 'examples/device-detection exited with code 1' + } + + It 'passes, with a warning, when only a test that skips by design skipped' { + $expected = 'fiftyone.ipintelligence.examples.shared.KeyHelperTest.requireTestResourceKey_ReadsTheKeyWithEveryProperty' + $run = Invoke-Script @() -Skips $expected + $run.Code | Should -Be 0 -Because $run.Text + $run.Text | Should -Match "::warning title=Test skipped::$([regex]::Escape($expected)) skipped, as expected, because it checks the key lookup" + $run.Summary | Should -Match "- $([regex]::Escape($expected)): a key is set" + } + + It 'passes, with a warning, when a test skips naming a setting of the staging cloud, whichever test it is' { + $run = Invoke-Script @() -Skips @( + 'example.LiveTest.basicKeysPassiveAnswerCarriesNoSource|CLOUD_STAGING_ENDPOINT is not set, so this live cloud test is skipped.' + 'example.LiveTest.bespokeKeys|RESOURCE_KEY_BESPOKE_STAGING is not set, so this live cloud test is skipped.') + $run.Code | Should -Be 0 -Because $run.Text + $run.Text | Should -Match 'basicKeysPassiveAnswerCarriesNoSource skipped, as expected, because it asks the staging cloud, whose CLOUD_STAGING_ENDPOINT' + $run.Text | Should -Match 'bespokeKeys skipped, as expected, because it asks the staging cloud, whose RESOURCE_KEY_BESPOKE_STAGING' + } + + It 'fails when a live test skips for a key the run should have' { + $run = Invoke-Script @() -Skips 'example.LiveTest.basicKeys|_51DEGREES_RESOURCE_KEY_BASIC is not set, so this live cloud test is skipped.' + $run.Code | Should -Not -Be 0 + $run.Text | Should -Match '::error title=Test skipped::example\.LiveTest\.basicKeys skipped: _51DEGREES_RESOURCE_KEY_BASIC is not set' + } + + It 'fails when any other test skipped, naming it and its reason' { + $run = Invoke-Script @() -Skips 'example.ConsoleTest.runsOnPremise' + $run.Code | Should -Not -Be 0 + $run.Text | Should -Match '::error title=Test skipped::example\.ConsoleTest\.runsOnPremise skipped: a key is set' + } + + It 'fails when a tree ran no tests' { + $run = Invoke-Script @() -Tests 0 + $run.Code | Should -Not -Be 0 + $run.Text | Should -Match 'examples/ip-intelligence ran no tests' + } + + It 'fails when a package did not come from Maven Central' { + $run = Invoke-Script @() -Remote 'local' + $run.Code | Should -Not -Be 0 + $run.Text | Should -Match 'device-detection 4\.6\.2 was not downloaded from Maven Central' + } +} diff --git a/ci/run-published-examples.ps1 b/ci/run-published-examples.ps1 new file mode 100644 index 000000000..7754bdeea --- /dev/null +++ b/ci/run-published-examples.ps1 @@ -0,0 +1,229 @@ +param ( + # Every package at this version, such as 4.6.2. Empty to choose each + # package's version as below. + [string]$Version = '', + # After a publish, the commit it published. A package with the tag + # '/' on that commit is pinned to the version the tag + # names, once Maven Central lists it. Any other package is pinned to the + # latest release Maven Central lists. + [string]$PublishedCommit = '', + # The longest to wait for Maven Central to list a version a publish + # tagged, and how long to wait between asking, in seconds. + [int]$WaitSeconds = 2700, + [int]$RetrySeconds = 30, + # Maven Central, or a folder laid out the same way, as the tests give. + [string]$Repository = 'https://repo1.maven.org/maven2', + # Where the summary table is added, as GITHUB_STEP_SUMMARY names it. + [string]$Summary = $env:GITHUB_STEP_SUMMARY +) + +# Runs the examples' own tests from the repository root against the packages +# published on Maven Central, and fails unless each tree ran tests, every +# test passed or is one of the few that skip here by design, and every package +# came from Maven Central at the version chosen. Maven starts +# from an empty local repository, so nothing a build installed is used. + +$ErrorActionPreference = 'Stop' +# Each tree's exit code is checked below, so one failing tree does not stop +# the other from running. +$PSNativeCommandUseErrorActionPreference = $false +. "$PSScriptRoot/packages.ps1" + +$GroupPath = 'com/51degrees' +$ExampleTrees = 'examples/device-detection', 'examples/ip-intelligence' + +# The tests that skip in every run of this script, each by its class and +# method, with why. Any other test that skips fails the run, because a test +# that skipped has checked nothing, and a skip here most often means a key or +# a data file is missing. +$ExpectedSkips = @{ + 'fiftyone.devicedetection.examples.shared.KeyHelperTest.requireTestResourceKey_ReadsTheKeyWithEveryProperty' = + 'it checks the key lookup with no key set, and the run sets _51DEGREES_RESOURCE_KEY_BESPOKE' + 'fiftyone.ipintelligence.examples.shared.KeyHelperTest.requireTestResourceKey_ReadsTheKeyWithEveryProperty' = + 'it checks the key lookup with no key set, and the run sets _51DEGREES_RESOURCE_KEY_BESPOKE' +} + +# A test that asks the staging cloud skips naming one of its settings, which +# only the Cloud Human Confidence workflow is given, so such a skip is +# expected too, whichever test it is. +$StagingSettings = 'CLOUD_STAGING_ENDPOINT', 'RESOURCE_KEY_BESPOKE_STAGING' + +# Why a skip is expected, or nothing when it is not. +function Get-ExpectedSkipReason($Skip) { + if ($ExpectedSkips.ContainsKey($Skip.Name)) { + return $ExpectedSkips[$Skip.Name] + } + $setting = $StagingSettings | Where-Object { "$($Skip.Reason)" -match "\b$_\b" } | + Select-Object -First 1 + if ($setting) { + return "it asks the staging cloud, whose $setting only the Cloud Human Confidence workflow is given" + } + return $null +} + +# Ends the run before anything is tested, with an error GitHub shows. +function Stop-Run([string]$Title, [string]$Message) { + Write-Output "::error title=$Title::$Message" + exit 1 +} + +# A file from the repository, or nothing when it is not there. +function Get-RepositoryFile([string]$Path) { + if ($Repository -match '^https?://') { + try { + return (Invoke-WebRequest "$Repository/$Path").Content + } catch { + return $null + } + } + $file = Join-Path $Repository $Path + if (Test-Path -LiteralPath $file -PathType Leaf) { + return Get-Content -Raw -LiteralPath $file + } + return $null +} + +# Whether the repository has a version's pom, which Maven reads first. +function Test-Published([string]$Artifact, [string]$PackageVersion) { + return $null -ne (Get-RepositoryFile "$GroupPath/$Artifact/$PackageVersion/$Artifact-$PackageVersion.pom") +} + +# The latest release the repository lists for an artifact. +function Get-LatestRelease([string]$Artifact) { + $metadata = Get-RepositoryFile "$GroupPath/$Artifact/maven-metadata.xml" + if ($null -eq $metadata) { + Stop-Run 'Not on Maven Central' "Maven Central lists no versions of $Artifact." + } + return ([xml]$metadata).metadata.versioning.release +} + +if ($Version -and $Version -notmatch '^\d+\.\d+\.\d+$') { + Stop-Run 'Not a version' "'$Version' is not a version such as 4.6.2." +} + +# The version of each package the publish released, read from the tags on +# the published commit. An annotated tag is listed twice, the second time +# with the commit it points at. +$tagged = @{} +if (-not $Version -and $PublishedCommit) { + foreach ($line in (git ls-remote --tags origin)) { + $sha, $ref = $line -split "`t", 2 + $tag = $ref -replace '^refs/tags/' -replace '\^\{\}$' + # A commit can hold two tags of one package, such as when a publish + # was made again, and the later version is the one it released. + if ($sha -eq $PublishedCommit -and $tag -match '^(?[\w.-]+)/(?\d+\.\d+\.\d+)$' -and + (-not $tagged.ContainsKey($Matches.name) -or [version]$Matches.version -gt [version]$tagged[$Matches.name])) { + $tagged[$Matches.name] = $Matches.version + } + } + if ($LASTEXITCODE -ne 0) { + Stop-Run 'No tags' 'The tags on origin could not be listed.' + } +} + +# One deadline for every tagged package, so the wait is never longer than +# WaitSeconds in all. +$deadline = (Get-Date).AddSeconds($WaitSeconds) +$pins = [ordered]@{} +foreach ($property in $ExampleVersionProperties.Keys | Sort-Object) { + $artifact = $ExampleVersionProperties[$property] + if ($Version) { + $pinned = $Version + if (-not (Test-Published $artifact $pinned)) { + Stop-Run 'Not on Maven Central' "Maven Central has no $artifact $pinned." + } + } elseif ($tagged.ContainsKey($artifact)) { + $pinned = $tagged[$artifact] + while (-not (Test-Published $artifact $pinned)) { + if ((Get-Date) -ge $deadline) { + Stop-Run 'Not on Maven Central' "The publish tagged $artifact $pinned, which Maven Central did not list within $WaitSeconds seconds." + } + Start-Sleep -Seconds $RetrySeconds + } + } else { + $pinned = Get-LatestRelease $artifact + } + $pins[$artifact] = $pinned + Write-Output "$artifact $pinned" +} +[string[]]$versionArgs = foreach ($property in $ExampleVersionProperties.Keys | Sort-Object) { + "-D$property=$($pins[$ExampleVersionProperties[$property]])" +} + +$localRepository = Join-Path ([IO.Path]::GetTempPath()) "examples-published-$([Guid]::NewGuid())" +New-Item -ItemType Directory $localRepository | Out-Null +try { + $failed = @() + $rows = @() + $skipped = @() + foreach ($tree in $ExampleTrees) { + Write-Output "::group::$tree against $($versionArgs -join ' ')" + Push-Location $tree + try { + # --fail-at-end runs every module's tests after one fails. + mvn clean test @MavenOptions --fail-at-end "-Dmaven.repo.local=$localRepository" @versionArgs + $code = $LASTEXITCODE + } finally { + Pop-Location + } + Write-Output '::endgroup::' + $counts = @{ tests = 0; failures = 0; errors = 0; skipped = 0 } + $skips = @() + foreach ($report in Get-ChildItem $tree -Recurse -Filter 'TEST-*.xml' | + Where-Object { $_.Directory.Name -eq 'surefire-reports' }) { + $suite = ([xml](Get-Content -Raw -LiteralPath $report.FullName)).testsuite + foreach ($name in @($counts.Keys)) { + $counts[$name] += [int]$suite.$name + } + foreach ($case in $suite.SelectNodes("testcase[skipped]")) { + $skips += [pscustomobject]@{ + Name = "$($case.classname).$($case.name)" + Reason = $case.skipped.message + } + } + } + $rows += "| $tree | $($counts.tests) | $($counts.failures) | $($counts.errors) | $($counts.skipped) |" + if ($code -ne 0) { + Write-Output "::error title=Examples failed::$tree exited with code $code." + $failed += $tree + } elseif ($counts.tests -eq 0) { + Write-Output "::error title=No tests ran::$tree ran no tests, so nothing was checked." + $failed += $tree + } + foreach ($skip in $skips) { + $expected = Get-ExpectedSkipReason $skip + if ($expected) { + Write-Output "::warning title=Test skipped::$($skip.Name) skipped, as expected, because $expected." + } else { + Write-Output "::error title=Test skipped::$($skip.Name) skipped: $($skip.Reason)" + $failed += $skip.Name + } + } + $skipped += $skips + } + + # Maven records where it downloaded each artifact from, by repository id, in + # _remote.repositories beside it. + foreach ($artifact in $pins.Keys) { + $record = Join-Path $localRepository "$GroupPath/$artifact/$($pins[$artifact])/_remote.repositories" + if (-not (Test-Path -LiteralPath $record) -or + -not (Select-String -LiteralPath $record -Pattern '^[^#].*>central=$' -Quiet)) { + Write-Output "::error title=Not from Maven Central::$artifact $($pins[$artifact]) was not downloaded from Maven Central." + $failed += $artifact + } + } +} finally { + Remove-Item -Recurse -Force -LiteralPath $localRepository +} + +if ($Summary) { + @('| Package | Version |', '| --- | --- |') + + ($pins.Keys | ForEach-Object { "| $_ | $($pins[$_]) |" }) + + @('', '| Examples | Tests | Failed | Errors | Skipped |', '| --- | --- | --- | --- | --- |') + + $rows + + @(if ($skipped) { @('', 'Skipped:', '') + ($skipped | ForEach-Object { "- $($_.Name): $($_.Reason)" }) }) | + Add-Content -LiteralPath $Summary +} +if ($failed) { + exit 1 +} diff --git a/ci/workflow-keys.Tests.ps1 b/ci/workflow-keys.Tests.ps1 index 578889a6c..ea4c35437 100644 --- a/ci/workflow-keys.Tests.ps1 +++ b/ci/workflow-keys.Tests.ps1 @@ -5,9 +5,10 @@ Describe 'the workflows' { # Each name holds one thing, so a workflow never fills one name from the # secret or variable of another. The 51Did license key, for one, unseals - # only results made with the resource key of its own account. The one - # setting a workflow writes as it is, rather than from a secret, is that - # warnings are errors. + # only results made with the resource key of its own account. A workflow + # writes two settings itself, rather than from a secret: that warnings are + # errors, and the package version Examples vs Published Packages is given + # when run by hand, under the name python's copy gives it. It 'fill every _51DEGREES_ name from the secret or variable of the same name' { $workflows = Join-Path $PSScriptRoot '../.github/workflows' $lines = @(Get-ChildItem $workflows -Filter *.yml | @@ -22,7 +23,8 @@ Describe 'the workflows' { $lines | Where-Object { $_.Text -notmatch (':\s*\$\{\{\s*(?:secrets|vars)\.' + [regex]::Escape($_.Name) + '\s*\}\}\s*$') -and - $_.Text -cnotmatch ':\s*_51DEGREES_WARNINGS_AS_ERRORS:\s*''true''$' + $_.Text -cnotmatch ':\s*_51DEGREES_WARNINGS_AS_ERRORS:\s*''true''$' -and + $_.Text -cnotmatch '^examples-published\.yml:\d+:\s*_51DEGREES_PACKAGE_VERSION:\s*\$\{\{\s*inputs\.version\s*\}\}$' } | ForEach-Object Text | Should -BeNullOrEmpty }