From 22ae66fe2da911c1e8e28230e96946a94ee23b3e Mon Sep 17 00:00:00 2001 From: biss Date: Thu, 29 Oct 2026 10:30:44 +0800 Subject: [PATCH] ci: add RC production acceptance gate --- .gitea/workflows/rc-acceptance.yml | 119 +++++++++++++++ README.md | 9 ++ scripts/rc-acceptance.ps1 | 138 ++++++++++++++++++ .../AuthorizationMatrixTests.cs | 69 +++++++++ .../LiveMySqlAcceptanceTests.cs | 102 +++++++++++++ tests/Jiaowu.Api.Tests/MySqlMigrationTests.cs | 5 +- web/.gitignore | 2 + web/e2e/rc-smoke.spec.ts | 29 ++++ web/package-lock.json | 64 ++++++-- web/package.json | 3 + web/playwright.config.ts | 38 +++++ 11 files changed, 568 insertions(+), 10 deletions(-) create mode 100644 .gitea/workflows/rc-acceptance.yml create mode 100644 scripts/rc-acceptance.ps1 create mode 100644 tests/Jiaowu.Api.Tests/AuthorizationMatrixTests.cs create mode 100644 tests/Jiaowu.Api.Tests/LiveMySqlAcceptanceTests.cs create mode 100644 web/e2e/rc-smoke.spec.ts create mode 100644 web/playwright.config.ts diff --git a/.gitea/workflows/rc-acceptance.yml b/.gitea/workflows/rc-acceptance.yml new file mode 100644 index 0000000..d41a23d --- /dev/null +++ b/.gitea/workflows/rc-acceptance.yml @@ -0,0 +1,119 @@ +name: RC production acceptance + +on: + push: + branches: [master] + pull_request: + branches: [master] + workflow_dispatch: + +jobs: + acceptance: + name: MySQL, permission, browser and package acceptance + runs-on: ubuntu-latest + permissions: + code: read + services: + mysql: + image: mysql:8.4 + env: + MYSQL_ROOT_PASSWORD: rc-acceptance-password + ports: + - 3306:3306 + options: >- + --health-cmd="mysqladmin ping -h 127.0.0.1 -prc-acceptance-password" + --health-interval=10s + --health-timeout=5s + --health-retries=12 + + steps: + - name: Check out repository + uses: https://github.com/actions/checkout@v4 + + - name: Initialize CaptchaKit submodule + run: git submodule update --init --recursive packages/CaptchaKit + + - name: Set up .NET + uses: https://github.com/actions/setup-dotnet@v4 + with: + dotnet-version: "10.0.400" + + - name: Set up Node.js + uses: https://github.com/actions/setup-node@v4 + with: + node-version: "24" + cache: npm + cache-dependency-path: web/package-lock.json + + - name: Install Chinese PDF font + run: | + sudo apt-get update + sudo apt-get install --yes fonts-noto-cjk + + - name: Restore and build backend + run: | + dotnet restore Jiaowu.slnx + dotnet build Jiaowu.slnx --configuration Release --no-restore + + - name: Run backend regression and permission matrix + run: dotnet test Jiaowu.slnx --configuration Release --no-build --no-restore + + - name: Run disposable MySQL 8.4 migration and query acceptance + env: + JIAOWU_REQUIRE_MYSQL_TESTS: "1" + JIAOWU_TEST_MYSQL: Server=127.0.0.1;Port=3306;User=root;Password=rc-acceptance-password;SslMode=None;AllowPublicKeyRetrieval=True; + run: dotnet test tests/Jiaowu.Api.Tests/Jiaowu.Api.Tests.csproj --configuration Release --no-build --no-restore --filter Category=LiveMySql + + - name: Install and audit frontend dependencies + working-directory: web + run: | + npm ci --ignore-scripts + npm audit --audit-level=moderate + + - name: Build web and Capacitor frontends + working-directory: web + run: | + npm run build + npm run build:capacitor + + - name: Install Playwright Chromium + working-directory: web + run: npx playwright install --with-deps chromium + + - name: Run browser smoke tests + working-directory: web + run: npm run test:e2e + + - name: Verify migrations and publish artifact + run: | + dotnet ef migrations list --project src/Jiaowu.Api/Jiaowu.Api.csproj --startup-project src/Jiaowu.Api/Jiaowu.Api.csproj --no-connect + dotnet publish src/Jiaowu.Api/Jiaowu.Api.csproj --configuration Release --no-restore --output artifacts/publish -p:BuildFrontendOnPublish=false + + - name: Write retained acceptance report + if: always() + shell: bash + run: | + mkdir -p artifacts/rc-acceptance + cat > artifacts/rc-acceptance/report.md < $Name" + try { + & $Action + if ($LASTEXITCODE -ne 0) { + throw "Command exited with code $LASTEXITCODE." + } + Add-Result $Name 'PASS' 'completed' + } catch { + Add-Result $Name 'FAIL' $_.Exception.Message + } +} + +New-Item -ItemType Directory -Path $reportRoot -Force | Out-Null +Push-Location $repositoryRoot +$previousMySql = $env:JIAOWU_TEST_MYSQL +$previousRequired = $env:JIAOWU_REQUIRE_MYSQL_TESTS +try { + Invoke-Check 'Restore .NET dependencies' { + & dotnet restore 'Jiaowu.slnx' + } + Invoke-Check 'Build backend (Release)' { + & dotnet build 'Jiaowu.slnx' '--configuration' 'Release' '--no-restore' + } + Invoke-Check 'Run backend regression tests' { + & dotnet test 'Jiaowu.slnx' '--configuration' 'Release' '--no-build' '--no-restore' + } + + if ([string]::IsNullOrWhiteSpace($MySqlConnectionString)) { + Add-Result 'Run disposable MySQL 8.4 acceptance' 'SKIP' 'Pass -MySqlConnectionString to execute the live migration/query test.' + } else { + $env:JIAOWU_TEST_MYSQL = $MySqlConnectionString + $env:JIAOWU_REQUIRE_MYSQL_TESTS = '1' + Invoke-Check 'Run disposable MySQL 8.4 acceptance' { + & dotnet test 'tests/Jiaowu.Api.Tests/Jiaowu.Api.Tests.csproj' '--configuration' 'Release' '--no-build' '--no-restore' '--filter' 'Category=LiveMySql' + } + } + + Push-Location (Join-Path $repositoryRoot 'web') + try { + Invoke-Check 'Install locked frontend dependencies' { + & npm ci '--ignore-scripts' + } + Invoke-Check 'Audit frontend dependencies' { + & npm audit '--audit-level=moderate' + } + Invoke-Check 'Build web frontend' { + & npm run build + } + Invoke-Check 'Build Capacitor frontend' { + & npm run 'build:capacitor' + } + if ($SkipBrowser) { + Add-Result 'Run Chromium smoke tests' 'SKIP' 'Skipped by -SkipBrowser.' + } else { + Invoke-Check 'Install Playwright Chromium' { + & npx playwright install chromium + } + Invoke-Check 'Run Chromium smoke tests' { + & npm run 'test:e2e' + } + } + } finally { + Pop-Location + } + + Invoke-Check 'List production MySQL migrations' { + & dotnet ef migrations list '--project' 'src/Jiaowu.Api/Jiaowu.Api.csproj' '--startup-project' 'src/Jiaowu.Api/Jiaowu.Api.csproj' '--no-connect' + } + Invoke-Check 'Publish backend artifact' { + & dotnet publish 'src/Jiaowu.Api/Jiaowu.Api.csproj' '--configuration' 'Release' '--no-restore' '--output' (Join-Path $reportRoot 'publish') '-p:BuildFrontendOnPublish=false' + } + Invoke-Check 'Check whitespace errors' { + & git diff '--check' + } +} finally { + $env:JIAOWU_TEST_MYSQL = $previousMySql + $env:JIAOWU_REQUIRE_MYSQL_TESTS = $previousRequired + Pop-Location +} + +$failed = @($results | Where-Object Status -eq 'FAIL').Count +$skipped = @($results | Where-Object Status -eq 'SKIP').Count +$overall = if ($failed -gt 0) { 'FAIL' } elseif ($skipped -gt 0) { 'PARTIAL' } else { 'PASS' } +$timestamp = Get-Date -Format 'yyyy-MM-dd HH:mm:ss K' +$rows = $results | ForEach-Object { + $detail = $_.Detail.Replace('|', '\|').Replace("`r", ' ').Replace("`n", ' ') + "| $($_.Name) | $($_.Status) | $detail |" +} +$markdown = @( + '# Jiaowu RC acceptance report' + '' + "- Result: **$overall**" + "- Generated: $timestamp" + "- Commit: $(& git -C $repositoryRoot rev-parse HEAD)" + '' + '| Check | Status | Detail |' + '|---|---|---|' + $rows +) -join "`n" + +$markdown | Set-Content -LiteralPath (Join-Path $reportRoot 'report.md') -Encoding utf8 +[pscustomobject]@{ + Result = $overall + GeneratedAt = $timestamp + Commit = (& git -C $repositoryRoot rev-parse HEAD) + Checks = $results +} | ConvertTo-Json -Depth 5 | Set-Content -LiteralPath (Join-Path $reportRoot 'report.json') -Encoding utf8 + +Write-Host "`nRC acceptance result: $overall" +Write-Host "Report: $(Join-Path $reportRoot 'report.md')" +if ($failed -gt 0) { exit 1 } diff --git a/tests/Jiaowu.Api.Tests/AuthorizationMatrixTests.cs b/tests/Jiaowu.Api.Tests/AuthorizationMatrixTests.cs new file mode 100644 index 0000000..a5b0c20 --- /dev/null +++ b/tests/Jiaowu.Api.Tests/AuthorizationMatrixTests.cs @@ -0,0 +1,69 @@ +using System.Reflection; +using Jiaowu.Api.Controllers; +using Jiaowu.Api.Domain.Identity; +using Microsoft.AspNetCore.Authorization; + +namespace Jiaowu.Api.Tests; + +public sealed class AuthorizationMatrixTests +{ + public static TheoryData CriticalEndpoints => new() + { + { + typeof(GradeAppealsController), + nameof(GradeAppealsController.Create), + [SystemRoles.Student] + }, + { + typeof(GradeAppealsController), + nameof(GradeAppealsController.Withdraw), + [SystemRoles.Student] + }, + { + typeof(GradeAppealsController), + nameof(GradeAppealsController.Review), + [SystemRoles.SuperAdmin, SystemRoles.AcademicAdmin, SystemRoles.CollegeAdmin, SystemRoles.Teacher] + }, + { + typeof(TeachingMonitoringController), + nameof(TeachingMonitoringController.SaveSetting), + [SystemRoles.SuperAdmin, SystemRoles.AcademicAdmin] + }, + { + typeof(TeachingMonitoringController), + nameof(TeachingMonitoringController.Remind), + [SystemRoles.SuperAdmin, SystemRoles.AcademicAdmin, SystemRoles.CollegeAdmin, SystemRoles.Leader] + }, + { + typeof(ApprovalsController), + nameof(ApprovalsController.FinalApproveGradeMod), + [SystemRoles.SuperAdmin, SystemRoles.AcademicAdmin] + } + }; + + [Theory] + [MemberData(nameof(CriticalEndpoints))] + public void Critical_endpoint_keeps_its_server_side_role_contract( + Type controllerType, + string methodName, + string[] expectedRoles) + { + Assert.NotEmpty(controllerType.GetCustomAttributes(inherit: true)); + + var method = controllerType.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public); + Assert.NotNull(method); + Assert.Empty(method!.GetCustomAttributes(inherit: true)); + + var actualRoles = method + .GetCustomAttributes(inherit: true) + .SelectMany(x => (x.Roles ?? string.Empty).Split(',', StringSplitOptions.RemoveEmptyEntries)) + .Select(x => x.Trim()) + .Distinct(StringComparer.Ordinal) + .Order(StringComparer.Ordinal) + .ToArray(); + + Assert.Equal( + expectedRoles.Order(StringComparer.Ordinal).ToArray(), + actualRoles); + } +} diff --git a/tests/Jiaowu.Api.Tests/LiveMySqlAcceptanceTests.cs b/tests/Jiaowu.Api.Tests/LiveMySqlAcceptanceTests.cs new file mode 100644 index 0000000..29d0416 --- /dev/null +++ b/tests/Jiaowu.Api.Tests/LiveMySqlAcceptanceTests.cs @@ -0,0 +1,102 @@ +using Jiaowu.Api.Domain.Academic; +using Jiaowu.Api.Infrastructure.Persistence; +using Microsoft.EntityFrameworkCore; +using MySql.Data.MySqlClient; + +namespace Jiaowu.Api.Tests; + +[CollectionDefinition(Name, DisableParallelization = true)] +public sealed class LiveMySqlAcceptanceCollection +{ + public const string Name = "Live MySQL acceptance"; +} + +[Collection(LiveMySqlAcceptanceCollection.Name)] +public sealed class LiveMySqlAcceptanceTests +{ + private const string ConnectionVariable = "JIAOWU_TEST_MYSQL"; + private const string RequiredVariable = "JIAOWU_REQUIRE_MYSQL_TESTS"; + + [Fact] + [Trait("Category", "LiveMySql")] + public async Task Latest_migrations_apply_and_core_queries_run_on_disposable_database() + { + var sourceConnection = Environment.GetEnvironmentVariable(ConnectionVariable); + if (string.IsNullOrWhiteSpace(sourceConnection)) + { + Assert.False( + string.Equals( + Environment.GetEnvironmentVariable(RequiredVariable), + "1", + StringComparison.Ordinal), + $"{ConnectionVariable} must be set when {RequiredVariable}=1."); + return; + } + + var databaseName = $"jiaowu_acceptance_{Guid.NewGuid():N}"; + Assert.Matches("^jiaowu_acceptance_[a-f0-9]{32}$", databaseName); + + var adminBuilder = new MySqlConnectionStringBuilder(sourceConnection) + { + Database = string.Empty, + AllowUserVariables = true + }; + var databaseBuilder = new MySqlConnectionStringBuilder(sourceConnection) + { + Database = databaseName, + AllowUserVariables = true + }; + + await using var adminConnection = new MySqlConnection(adminBuilder.ConnectionString); + await adminConnection.OpenAsync(); + await ExecuteAsync( + adminConnection, + $"CREATE DATABASE `{databaseName}` CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;"); + + try + { + var options = new DbContextOptionsBuilder() + .UseMySQL(databaseBuilder.ConnectionString) + .Options; + + await using (var db = new AppDbContext(options)) + { + await db.Database.MigrateAsync(); + Assert.Empty(await db.Database.GetPendingMigrationsAsync()); + + db.Colleges.Add(new College + { + Code = "RC-ACCEPTANCE", + Name = "RC 验收学院" + }); + await db.SaveChangesAsync(); + + Assert.Equal( + "RC 验收学院", + await db.Colleges + .Where(x => x.Code == "RC-ACCEPTANCE") + .Select(x => x.Name) + .SingleAsync()); + } + + await using (var db = new AppDbContext(options)) + { + await db.Database.MigrateAsync(); + Assert.Empty(await db.Database.GetPendingMigrationsAsync()); + Assert.Equal(0, await db.GradeAppeals.CountAsync()); + } + } + finally + { + MySqlConnection.ClearAllPools(); + await ExecuteAsync(adminConnection, $"DROP DATABASE IF EXISTS `{databaseName}`;"); + } + } + + private static async Task ExecuteAsync(MySqlConnection connection, string sql) + { + await using var command = connection.CreateCommand(); + command.CommandText = sql; + await command.ExecuteNonQueryAsync(); + } +} diff --git a/tests/Jiaowu.Api.Tests/MySqlMigrationTests.cs b/tests/Jiaowu.Api.Tests/MySqlMigrationTests.cs index f0147e2..fb22f5c 100644 --- a/tests/Jiaowu.Api.Tests/MySqlMigrationTests.cs +++ b/tests/Jiaowu.Api.Tests/MySqlMigrationTests.cs @@ -12,7 +12,7 @@ namespace Jiaowu.Api.Tests; public sealed class MySqlMigrationTests { private const string LatestMigration = - "20260727133346_ExamArrangementJobs"; + "20261029020925_TeachingMonitoringWorkflow"; [Fact] public void Production_migration_is_discoverable_and_generates_mysql_sql() @@ -67,6 +67,9 @@ public sealed class MySqlMigrationTests Assert.Contains("DEFAULT 1", script); Assert.DoesNotContain("0001-01-01", script); Assert.DoesNotContain("0000-00-00", script); + Assert.Contains("CREATE TABLE `GradeAppeals`", script); + Assert.Contains("CREATE TABLE `TeachingMonitoringSettings`", script); + Assert.Contains("CREATE TABLE `TeachingMonitoringReminders`", script); } [Fact] diff --git a/web/.gitignore b/web/.gitignore index c401510..eb78cc2 100644 --- a/web/.gitignore +++ b/web/.gitignore @@ -15,6 +15,8 @@ lerna-debug.log* node_modules dist dist-ssr +playwright-report +test-results *.local # Editor directories and files diff --git a/web/e2e/rc-smoke.spec.ts b/web/e2e/rc-smoke.spec.ts new file mode 100644 index 0000000..68e7d27 --- /dev/null +++ b/web/e2e/rc-smoke.spec.ts @@ -0,0 +1,29 @@ +import { expect, test } from '@playwright/test' + +test('health endpoint reports a live process', async ({ request }) => { + const response = await request.get('/health/live') + expect(response.ok()).toBeTruthy() + await expect(response.json()).resolves.toMatchObject({ status: 'healthy' }) +}) + +test('login renders branding, credentials and a live captcha challenge', async ({ page }) => { + await page.goto('/login') + await expect(page.getByRole('heading', { name: '登录教务工作台' })).toBeVisible() + await expect(page.getByLabel('验证码')).toBeVisible() + await expect(page.getByRole('button', { name: '进入工作台' })).toBeDisabled() + await expect(page.getByRole('link', { name: /无需登录/ })).toBeVisible() +}) + +test('protected routes preserve the return target when redirecting to login', async ({ page }) => { + await page.goto('/teaching-monitoring') + await expect(page).toHaveURL(url => + url.pathname === '/login' && + url.searchParams.get('redirect') === '/teaching-monitoring') + await expect(page.getByRole('heading', { name: '登录教务工作台' })).toBeVisible() +}) + +test('public timetable stays accessible without an authenticated session', async ({ page }) => { + await page.goto('/timetable') + await expect(page.getByRole('heading', { name: '班级课表查询' })).toBeVisible() + await expect(page).not.toHaveURL(/\/login/) +}) diff --git a/web/package-lock.json b/web/package-lock.json index 200f712..341ddc0 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -30,6 +30,7 @@ }, "devDependencies": { "@capacitor/cli": "^8.5.3", + "@playwright/test": "^1.64.1", "@types/node": "^26.6.5", "@types/qrcode": "1.5.6", "@vitejs/plugin-vue": "^6.0.10", @@ -2929,6 +2930,22 @@ "url": "https://github.com/sponsors/oxc-project" } }, + "node_modules/@playwright/test": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.64.1.tgz", + "integrity": "sha512-IaYGml/nSOiZWROfPtuIL7neuu9qDOZ3TNvNljUIrhDMxiGTgPjzj/g9p9RxpS2tSepPDRY+UwAaEeiKtUvIAg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.64.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/@popperjs/core": { "name": "@sxzz/popperjs-es", "version": "2.11.8", @@ -5972,9 +5989,9 @@ } }, "node_modules/fast-uri": { - "version": "3.1.8", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.8.tgz", - "integrity": "sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg==", + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", + "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", "dev": true, "funding": [ { @@ -6075,9 +6092,9 @@ } }, "node_modules/follow-redirects": { - "version": "1.16.0", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", - "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.2.tgz", + "integrity": "sha512-/kVP2U8z596Ia0gwFrwyIeo74ta5aVmSeU1FfAUMAmcEP5EP7zydmag3SLiN64NaRKef3lxsq7i/g7ltJQDGow==", "funding": [ { "type": "individual", @@ -9089,6 +9106,35 @@ "pathe": "^2.0.3" } }, + "node_modules/playwright": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz", + "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.64.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", + "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/plist": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/plist/-/plist-3.1.1.tgz", @@ -9805,9 +9851,9 @@ } }, "node_modules/serialize-javascript": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.1.2.tgz", - "integrity": "sha512-GL2BWwVa6JydKO6l/ljVgjAZF4QJ3S7dWDWi53s5GZT8PJzD2fNxi67HANQGKAqPrwEpL5ba7gUBGi0Ls/sEoQ==", + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.1.4.tgz", + "integrity": "sha512-FqlEuoTq/zRmA4Lg6aOqyH3lCHbUtCB0bmHCeFniX2GBdDqMJM3FwdvEhlE5Pim1dlt2FfBdVPmUNNiGhhKqpw==", "dev": true, "license": "BSD-3-Clause", "engines": { diff --git a/web/package.json b/web/package.json index 7609124..6aa27bd 100644 --- a/web/package.json +++ b/web/package.json @@ -8,6 +8,8 @@ "build:capacitor": "vue-tsc -b && vite build --mode capacitor", "ota:package": "npm run build:capacitor && node scripts/package-app-update.mjs", "preview": "vite preview", + "test:e2e": "playwright test", + "test:e2e:report": "playwright test --reporter=html", "cap:configure": "node scripts/configure-capacitor.mjs", "cap:sync": "npx cap sync && npm run cap:configure", "cap:open:android": "npx cap open android", @@ -40,6 +42,7 @@ }, "devDependencies": { "@capacitor/cli": "^8.5.3", + "@playwright/test": "^1.64.1", "@types/node": "^26.6.5", "@types/qrcode": "1.5.6", "@vitejs/plugin-vue": "^6.0.10", diff --git a/web/playwright.config.ts b/web/playwright.config.ts new file mode 100644 index 0000000..3f4fc1d --- /dev/null +++ b/web/playwright.config.ts @@ -0,0 +1,38 @@ +import { defineConfig, devices } from '@playwright/test' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + +const externalServer = process.env.PLAYWRIGHT_EXTERNAL_SERVER === 'true' +const baseURL = process.env.PLAYWRIGHT_BASE_URL ?? 'http://127.0.0.1:5255' +const acceptanceDatabase = join(tmpdir(), `jiaowu-playwright-${process.pid}.sqlite`) + +export default defineConfig({ + testDir: './e2e', + timeout: 30_000, + expect: { timeout: 8_000 }, + fullyParallel: false, + retries: process.env.CI ? 1 : 0, + reporter: process.env.CI + ? [['line'], ['html', { outputFolder: 'playwright-report', open: 'never' }]] + : 'line', + use: { + baseURL, + trace: 'retain-on-failure', + screenshot: 'only-on-failure', + video: 'retain-on-failure', + }, + projects: [ + { name: 'chromium', use: { ...devices['Desktop Chrome'] } }, + ], + webServer: externalServer ? undefined : { + command: 'dotnet run --project ../src/Jiaowu.Api/Jiaowu.Api.csproj --configuration Release --no-build', + url: `${baseURL}/health/live`, + reuseExistingServer: true, + timeout: 120_000, + env: { + ASPNETCORE_ENVIRONMENT: 'Development', + ASPNETCORE_URLS: baseURL, + ConnectionStrings__SQLite: `Data Source=${acceptanceDatabase}`, + }, + }, +})