From 3930df146c1ac1c5800cc59de1bb08103a921b1b Mon Sep 17 00:00:00 2001 From: Chirag Aggarwal Date: Mon, 22 Jun 2026 10:10:47 +0530 Subject: [PATCH] (test): report true per-test duration and de-duplicate variable build tests (#12637) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * (test): report true per-test duration and de-duplicate variable build tests The PHPUnit test reporter printed `durationSinceStart()` — wall-clock elapsed since the run began — and labeled it as per-test duration. That made the numbers climb monotonically across the run and flagged nearly every test past the 15s mark as "slow", even pure CRUD tests that finish in well under a second. Capture an elapsed-since-start stamp when each test is prepared and subtract it at finish, so the reported time and the "slow" warning are the test's own duration. Separately, the variable-in-build integration tests (testProjectVariableInFunction, testProjectVariableInSite) lived in the shared VariablesBase trait and therefore ran in both the console-client and custom-server suites — 4 real Docker/npm builds where 2 suffice. The contract is auth-side independent, so move them into VariablesCustomServerTest only and keep the cheap CRUD coverage shared. * (test): satisfy rector string-cast rule and document refactor pre-check Rector's StringCastAssertStringContainsStringRector requires (string) casts on the assertStringContains(Not) arguments in the moved build tests. Apply them, and add composer refactor / refactor:check to the AGENTS.md command table so the CI "Refactor" check is run before pushing. * fix: purge project cache after config updates * (test): stamp test start at PreparationStarted, not Prepared Prepared fires after setUp/fixtures run, so expensive e2e setup was excluded from the reported per-test duration and the slow-test warning. Listen on PreparationStarted (before preparation begins) instead, and rename the subscriber to match. * (ci): bump php-retry to node24 runtime commit itznotabug/php-retry#15 migrated the action runtime from the deprecated node20 to node24. The v3 tag has not been re-pointed yet, so pin the merged commit (d4500b9) directly to clear the "Node 20 is being deprecated" warning on the unit-test retry step. Updates all 5 pins. * (ci): combine PHP check jobs into a single Checks job * (test): use full-precision duration in per-test reporter durationSinceStart()->seconds() returns only the whole-second part, so the finish-minus-start delta dropped all sub-second time: a 10.9s→11.1s test reported 1000ms instead of ~200ms, and most sub-second tests reported 0ms. Use Duration::asFloat() (seconds + nanoseconds) for both the start stamp and the finish elapsed, and format output as rounded integer ms / 2-decimal seconds. * fix: remove project cache purge calls --- .github/workflows/ci.yml | 144 +++-------- AGENTS.md | 2 + tests/e2e/Services/Project/VariablesBase.php | 242 ----------------- .../Project/VariablesCustomServerTest.php | 243 ++++++++++++++++++ tests/extensions/TestFinishedSubscriber.php | 14 +- tests/extensions/TestHook.php | 1 + .../TestPreparationStartedSubscriber.php | 26 ++ 7 files changed, 321 insertions(+), 351 deletions(-) create mode 100644 tests/extensions/TestPreparationStartedSubscriber.php diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 488d635828..159782dfbb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -91,111 +91,13 @@ jobs: sarif_file: 'trivy-fs-results.sarif' category: 'trivy-source' - composer: - name: Checks / Composer + checks: + name: Checks runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - name: Setup PHP - uses: shivammathur/setup-php@accd6127cb78bee3e8082180cb391013d204ef9f # 2.37.0 - with: - php-version: '8.3' - tools: composer:v2 - coverage: none - - - name: Validate - run: composer validate - - - name: Install dependencies - run: composer install --prefer-dist --no-progress --ignore-platform-reqs - - - name: Audit - env: - COMPOSER_NO_AUDIT: 0 - run: composer audit - - format: - name: Checks / Format - runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - with: - fetch-depth: 2 - - - run: git checkout HEAD^2 - if: github.event_name == 'pull_request' - - - name: Setup PHP - uses: shivammathur/setup-php@accd6127cb78bee3e8082180cb391013d204ef9f # 2.37.0 - with: - php-version: '8.3' - tools: composer:v2 - coverage: none - - - name: Install dependencies - run: composer install --prefer-dist --no-progress --ignore-platform-reqs - - - name: Run Linter - run: composer lint - - refactor: - name: Checks / Refactor - runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - - name: Setup PHP - uses: shivammathur/setup-php@accd6127cb78bee3e8082180cb391013d204ef9f # 2.37.0 - with: - php-version: '8.3' - tools: composer:v2 - coverage: none - - - name: Install dependencies - run: composer install --prefer-dist --no-progress --ignore-platform-reqs - - - name: Run Rector - run: composer refactor:check - - analyze: - name: Checks / Analyze - runs-on: ubuntu-latest - steps: - - name: Check out the repo - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - - name: Setup PHP - uses: shivammathur/setup-php@accd6127cb78bee3e8082180cb391013d204ef9f # 2.37.0 - with: - php-version: '8.3' - tools: composer:v2 - coverage: none - - - name: Install dependencies - run: composer install --prefer-dist --no-progress --ignore-platform-reqs - - - name: Cache PHPStan result cache - uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 - with: - path: .phpstan-cache - key: phpstan-${{ github.sha }} - restore-keys: | - phpstan- - - - name: Run PHPStan - run: composer analyze -- --no-progress - - specs: - name: Checks / Specs - runs-on: ubuntu-latest - steps: - - name: Check out the repo - uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2 - - name: Setup PHP uses: shivammathur/setup-php@accd6127cb78bee3e8082180cb391013d204ef9f # 2.37.0 with: @@ -204,10 +106,42 @@ jobs: tools: composer:v2 coverage: none + - name: Validate composer.json + run: composer validate + - name: Install dependencies + id: install run: composer install --prefer-dist --no-progress --ignore-platform-reqs + - name: Cache PHPStan result cache + if: ${{ !cancelled() && steps.install.outcome == 'success' }} + uses: actions/cache@27d5ce7f107fe9357f9df03efb73ab90386fccae # v5.0.5 + with: + path: .phpstan-cache + key: phpstan-${{ github.sha }} + restore-keys: | + phpstan- + + - name: Audit dependencies + if: ${{ !cancelled() && steps.install.outcome == 'success' }} + env: + COMPOSER_NO_AUDIT: 0 + run: composer audit + + - name: Run Linter + if: ${{ !cancelled() && steps.install.outcome == 'success' }} + run: composer lint + + - name: Run Rector + if: ${{ !cancelled() && steps.install.outcome == 'success' }} + run: composer refactor:check + + - name: Run PHPStan + if: ${{ !cancelled() && steps.install.outcome == 'success' }} + run: composer analyze -- --no-progress + - name: Generate specs + if: ${{ !cancelled() && steps.install.outcome == 'success' }} run: _APP_STORAGE_LIMIT=5368709120 php app/cli.php specs --version=latest --git=no locale: @@ -366,7 +300,7 @@ jobs: - name: Run Unit Tests timeout-minutes: 15 - uses: itznotabug/php-retry@d6bef45a8bff490babfb613e33b00d133e4062f0 # v3 + uses: itznotabug/php-retry@d4500b9db3258e2cc8857427980f28e1611eb79c # v3 with: max_attempts: ${{ github.event_name == 'pull_request' && 2 || 1 }} retry_wait_seconds: 60 @@ -418,7 +352,7 @@ jobs: - name: Run General Tests timeout-minutes: 15 - uses: itznotabug/php-retry@d6bef45a8bff490babfb613e33b00d133e4062f0 # v3 + uses: itznotabug/php-retry@d4500b9db3258e2cc8857427980f28e1611eb79c # v3 with: max_attempts: ${{ github.event_name == 'pull_request' && 2 || 1 }} retry_wait_seconds: 60 @@ -508,7 +442,7 @@ jobs: - name: Run tests timeout-minutes: 15 - uses: itznotabug/php-retry@d6bef45a8bff490babfb613e33b00d133e4062f0 # v3 + uses: itznotabug/php-retry@d4500b9db3258e2cc8857427980f28e1611eb79c # v3 with: max_attempts: ${{ github.event_name == 'pull_request' && 2 || 1 }} retry_wait_seconds: 60 @@ -583,7 +517,7 @@ jobs: - name: Run tests timeout-minutes: 15 - uses: itznotabug/php-retry@d6bef45a8bff490babfb613e33b00d133e4062f0 # v3 + uses: itznotabug/php-retry@d4500b9db3258e2cc8857427980f28e1611eb79c # v3 with: max_attempts: ${{ github.event_name == 'pull_request' && 2 || 1 }} retry_wait_seconds: 60 @@ -649,7 +583,7 @@ jobs: - name: Run tests timeout-minutes: 15 - uses: itznotabug/php-retry@d6bef45a8bff490babfb613e33b00d133e4062f0 # v3 + uses: itznotabug/php-retry@d4500b9db3258e2cc8857427980f28e1611eb79c # v3 with: max_attempts: ${{ github.event_name == 'pull_request' && 2 || 1 }} retry_wait_seconds: 60 diff --git a/AGENTS.md b/AGENTS.md index edaeff9ea5..2a73d6d90e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,6 +15,8 @@ Self-hosted Backend-as-a-Service platform. Hybrid monolithic-microservice archit | `composer lint ` | Check formatting of a file | | `composer analyze` | Static analysis (PHPStan level 3) | | `composer check` | Same as `analyze` | +| `composer refactor:check` | Rector dry-run over `tests/` (CI "Refactor" check) | +| `composer refactor` | Apply Rector fixes | ## Stack diff --git a/tests/e2e/Services/Project/VariablesBase.php b/tests/e2e/Services/Project/VariablesBase.php index b1f8ed61b9..c6cf4115f2 100644 --- a/tests/e2e/Services/Project/VariablesBase.php +++ b/tests/e2e/Services/Project/VariablesBase.php @@ -3,7 +3,6 @@ namespace Tests\E2E\Services\Project; use Appwrite\Tests\Async; -use Appwrite\Tests\Async\Exceptions\Critical; use CURLFile; use Tests\E2E\Client; use Utopia\Console; @@ -11,7 +10,6 @@ use Utopia\Database\Document; use Utopia\Database\Helpers\ID; use Utopia\Database\Query; use Utopia\Database\Validator\Datetime as DatetimeValidator; -use Utopia\System\System; trait VariablesBase { @@ -738,246 +736,6 @@ trait VariablesBase $this->assertSame('variable_not_found', $delete['body']['type']); } - // Integration tests - - /** - * Test that project variables are available in function build and runtime. - */ - public function testProjectVariableInFunction(): void - { - $projectId = $this->getProject()['$id']; - $apiKey = $this->getProject()['apiKey']; - - // 1. Create a project variable - $variable = $this->createVariable( - ID::unique(), - 'GLOBAL_VARIABLE', - 'Project Variable Value', - false - ); - - $this->assertSame(201, $variable['headers']['status-code']); - $variableId = $variable['body']['$id']; - - // 2. Create a function with build commands that echo the variable - $function = $this->client->call(Client::METHOD_POST, '/functions', [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - 'x-appwrite-key' => $apiKey, - ], [ - 'functionId' => ID::unique(), - 'name' => 'Project Variable Test', - 'runtime' => 'node-22', - 'entrypoint' => 'index.js', - 'execute' => ['any'], - 'timeout' => 15, - 'commands' => 'echo $GLOBAL_VARIABLE', - ]); - - $this->assertSame(201, $function['headers']['status-code']); - $functionId = $function['body']['$id']; - - // 3. Deploy the function (basic function reads GLOBAL_VARIABLE from env) - $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments', [ - 'content-type' => 'multipart/form-data', - 'x-appwrite-project' => $projectId, - 'x-appwrite-key' => $apiKey, - ], [ - 'code' => $this->packageCode('functions', 'basic'), - 'activate' => true, - ]); - - $this->assertSame(202, $deployment['headers']['status-code']); - $deploymentId = $deployment['body']['$id'] ?? ''; - - // 4. Wait for deployment to be ready and activated - $this->assertEventually(function () use ($projectId, $apiKey, $functionId, $deploymentId) { - $deployment = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/deployments/' . $deploymentId, [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - 'x-appwrite-key' => $apiKey, - ]); - - $status = $deployment['body']['status'] ?? ''; - if ($status === 'failed') { - throw new Critical('Deployment build failed: ' . ($deployment['body']['buildLogs'] ?? 'no logs')); - } - - $this->assertSame('ready', $status, 'Deployment status is not ready'); - }, 120000, 500); - - $this->assertEventually(function () use ($projectId, $apiKey, $functionId, $deploymentId) { - $function = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId, [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - 'x-appwrite-key' => $apiKey, - ]); - $this->assertSame($deploymentId, $function['body']['deploymentId'] ?? ''); - }, 120000, 500); - - // 5. Verify the project variable was available during build - $deployment = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/deployments/' . $deploymentId, [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - 'x-appwrite-key' => $apiKey, - ]); - $this->assertSame(200, $deployment['headers']['status-code']); - $this->assertStringContainsString('Project Variable Value', $deployment['body']['buildLogs']); - - // 6. Execute the function and verify the project variable is in runtime output - $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - ], $this->getHeaders()), [ - 'async' => false, - ]); - - $this->assertSame(201, $execution['headers']['status-code']); - $this->assertSame('completed', $execution['body']['status']); - $this->assertSame(200, $execution['body']['responseStatusCode']); - $output = json_decode($execution['body']['responseBody'], true); - $this->assertSame('Project Variable Value', $output['GLOBAL_VARIABLE']); - - // Cleanup - $this->client->call(Client::METHOD_DELETE, '/functions/' . $functionId, [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - 'x-appwrite-key' => $apiKey, - ]); - $this->deleteVariable($variableId); - } - - /** - * Test that project variables are available in site build and SSR runtime. - */ - public function testProjectVariableInSite(): void - { - $projectId = $this->getProject()['$id']; - $apiKey = $this->getProject()['apiKey']; - - // 1. Create a project variable - $variable = $this->createVariable( - ID::unique(), - 'name', - 'ProjectVarTest', - ); - - $this->assertSame(201, $variable['headers']['status-code']); - $variableId = $variable['body']['$id']; - - // 2. Create a site - $site = $this->client->call(Client::METHOD_POST, '/sites', [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - 'x-appwrite-key' => $apiKey, - ], [ - 'siteId' => ID::unique(), - 'name' => 'Project Variable Astro Site', - 'framework' => 'astro', - 'adapter' => 'ssr', - 'buildRuntime' => 'node-22', - 'outputDirectory' => './dist', - 'buildCommand' => 'echo $name && npm run build', - 'installCommand' => 'npm ci', - 'fallbackFile' => '', - ]); - - $this->assertSame(201, $site['headers']['status-code']); - $siteId = $site['body']['$id']; - - // 3. Setup domain for proxy access - $sitesDomain = \explode(',', System::getEnv('_APP_DOMAIN_SITES', ''))[0]; - $rule = $this->client->call(Client::METHOD_POST, '/proxy/rules/site', array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - ], $this->getHeaders()), [ - 'domain' => ID::unique() . '.' . $sitesDomain, - 'siteId' => $siteId, - ]); - - $this->assertSame(201, $rule['headers']['status-code']); - - // 4. Deploy the site (astro site reads import.meta.env.name) - $deployment = $this->client->call(Client::METHOD_POST, '/sites/' . $siteId . '/deployments', [ - 'content-type' => 'multipart/form-data', - 'x-appwrite-project' => $projectId, - 'x-appwrite-key' => $apiKey, - ], [ - 'code' => $this->packageCode('sites', 'astro'), - 'activate' => 'true', - ]); - - $this->assertSame(202, $deployment['headers']['status-code']); - $deploymentId = $deployment['body']['$id'] ?? ''; - - // 5. Wait for deployment to be ready and activated - $this->assertEventually(function () use ($projectId, $apiKey, $siteId, $deploymentId) { - $deployment = $this->client->call(Client::METHOD_GET, '/sites/' . $siteId . '/deployments/' . $deploymentId, [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - 'x-appwrite-key' => $apiKey, - ]); - - $status = $deployment['body']['status'] ?? ''; - if ($status === 'failed') { - throw new Critical('Site deployment failed: ' . json_encode($deployment['body'], JSON_PRETTY_PRINT)); - } - - $this->assertSame('ready', $status, 'Deployment status is not ready'); - }, 120000, 500); - - $this->assertEventually(function () use ($projectId, $apiKey, $siteId, $deploymentId) { - $site = $this->client->call(Client::METHOD_GET, '/sites/' . $siteId, [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - 'x-appwrite-key' => $apiKey, - ]); - $this->assertSame($deploymentId, $site['body']['deploymentId'] ?? ''); - }, 120000, 500); - - // 6. Verify the project variable was available during build - $deployment = $this->client->call(Client::METHOD_GET, '/sites/' . $siteId . '/deployments/' . $deploymentId, [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - 'x-appwrite-key' => $apiKey, - ]); - $this->assertSame(200, $deployment['headers']['status-code']); - $this->assertStringContainsString('ProjectVarTest', $deployment['body']['buildLogs']); - - // 7. Get the domain and access the site - $rules = $this->client->call(Client::METHOD_GET, '/proxy/rules', array_merge([ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - ], $this->getHeaders()), [ - 'queries' => [ - Query::equal('deploymentResourceId', [$siteId])->toString(), - Query::equal('trigger', ['manual'])->toString(), - Query::equal('type', ['deployment'])->toString(), - ], - ]); - - $this->assertSame(200, $rules['headers']['status-code']); - $this->assertGreaterThanOrEqual(1, \count($rules['body']['rules'])); - $domain = $rules['body']['rules'][0]['domain']; - - $proxyClient = new Client(); - $proxyClient->setEndpoint('http://' . $domain); - - $response = $proxyClient->call(Client::METHOD_GET, '/'); - - $this->assertSame(200, $response['headers']['status-code']); - $this->assertStringContainsString('Env variable is ProjectVarTest', $response['body']); - $this->assertStringNotContainsString('Variable not found', $response['body']); - - // Cleanup - $this->client->call(Client::METHOD_DELETE, '/sites/' . $siteId, [ - 'content-type' => 'application/json', - 'x-appwrite-project' => $projectId, - 'x-appwrite-key' => $apiKey, - ]); - $this->deleteVariable($variableId); - } - // Helpers protected function createVariable(string $variableId, ?string $key, ?string $value, ?bool $secret = null, bool $authenticated = true): mixed diff --git a/tests/e2e/Services/Project/VariablesCustomServerTest.php b/tests/e2e/Services/Project/VariablesCustomServerTest.php index f4af7069cb..6c710fecf2 100644 --- a/tests/e2e/Services/Project/VariablesCustomServerTest.php +++ b/tests/e2e/Services/Project/VariablesCustomServerTest.php @@ -4,13 +4,256 @@ declare(strict_types=1); namespace Tests\E2E\Services\Project; +use Appwrite\Tests\Async\Exceptions\Critical; +use Tests\E2E\Client; use Tests\E2E\Scopes\ProjectCustom; use Tests\E2E\Scopes\Scope; use Tests\E2E\Scopes\SideServer; +use Utopia\Database\Helpers\ID; +use Utopia\Database\Query; +use Utopia\System\System; final class VariablesCustomServerTest extends Scope { use VariablesBase; use ProjectCustom; use SideServer; + + /** + * Test that project variables are available in function build and runtime. + */ + public function testProjectVariableInFunction(): void + { + $projectId = $this->getProject()['$id']; + $apiKey = $this->getProject()['apiKey']; + + // 1. Create a project variable + $variable = $this->createVariable( + ID::unique(), + 'GLOBAL_VARIABLE', + 'Project Variable Value', + false + ); + + $this->assertSame(201, $variable['headers']['status-code']); + $variableId = $variable['body']['$id']; + + // 2. Create a function with build commands that echo the variable + $function = $this->client->call(Client::METHOD_POST, '/functions', [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + 'x-appwrite-key' => $apiKey, + ], [ + 'functionId' => ID::unique(), + 'name' => 'Project Variable Test', + 'runtime' => 'node-22', + 'entrypoint' => 'index.js', + 'execute' => ['any'], + 'timeout' => 15, + 'commands' => 'echo $GLOBAL_VARIABLE', + ]); + + $this->assertSame(201, $function['headers']['status-code']); + $functionId = $function['body']['$id']; + + // 3. Deploy the function (basic function reads GLOBAL_VARIABLE from env) + $deployment = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/deployments', [ + 'content-type' => 'multipart/form-data', + 'x-appwrite-project' => $projectId, + 'x-appwrite-key' => $apiKey, + ], [ + 'code' => $this->packageCode('functions', 'basic'), + 'activate' => true, + ]); + + $this->assertSame(202, $deployment['headers']['status-code']); + $deploymentId = $deployment['body']['$id'] ?? ''; + + // 4. Wait for deployment to be ready and activated + $this->assertEventually(function () use ($projectId, $apiKey, $functionId, $deploymentId) { + $deployment = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/deployments/' . $deploymentId, [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + 'x-appwrite-key' => $apiKey, + ]); + + $status = $deployment['body']['status'] ?? ''; + if ($status === 'failed') { + throw new Critical('Deployment build failed: ' . ($deployment['body']['buildLogs'] ?? 'no logs')); + } + + $this->assertSame('ready', $status, 'Deployment status is not ready'); + }, 120000, 500); + + $this->assertEventually(function () use ($projectId, $apiKey, $functionId, $deploymentId) { + $function = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId, [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + 'x-appwrite-key' => $apiKey, + ]); + $this->assertSame($deploymentId, $function['body']['deploymentId'] ?? ''); + }, 120000, 500); + + // 5. Verify the project variable was available during build + $deployment = $this->client->call(Client::METHOD_GET, '/functions/' . $functionId . '/deployments/' . $deploymentId, [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + 'x-appwrite-key' => $apiKey, + ]); + $this->assertSame(200, $deployment['headers']['status-code']); + $this->assertStringContainsString('Project Variable Value', (string) $deployment['body']['buildLogs']); + + // 6. Execute the function and verify the project variable is in runtime output + $execution = $this->client->call(Client::METHOD_POST, '/functions/' . $functionId . '/executions', array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + ], $this->getHeaders()), [ + 'async' => false, + ]); + + $this->assertSame(201, $execution['headers']['status-code']); + $this->assertSame('completed', $execution['body']['status']); + $this->assertSame(200, $execution['body']['responseStatusCode']); + $output = json_decode($execution['body']['responseBody'], true); + $this->assertSame('Project Variable Value', $output['GLOBAL_VARIABLE']); + + // Cleanup + $this->client->call(Client::METHOD_DELETE, '/functions/' . $functionId, [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + 'x-appwrite-key' => $apiKey, + ]); + $this->deleteVariable($variableId); + } + + /** + * Test that project variables are available in site build and SSR runtime. + */ + public function testProjectVariableInSite(): void + { + $projectId = $this->getProject()['$id']; + $apiKey = $this->getProject()['apiKey']; + + // 1. Create a project variable + $variable = $this->createVariable( + ID::unique(), + 'name', + 'ProjectVarTest', + ); + + $this->assertSame(201, $variable['headers']['status-code']); + $variableId = $variable['body']['$id']; + + // 2. Create a site + $site = $this->client->call(Client::METHOD_POST, '/sites', [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + 'x-appwrite-key' => $apiKey, + ], [ + 'siteId' => ID::unique(), + 'name' => 'Project Variable Astro Site', + 'framework' => 'astro', + 'adapter' => 'ssr', + 'buildRuntime' => 'node-22', + 'outputDirectory' => './dist', + 'buildCommand' => 'echo $name && npm run build', + 'installCommand' => 'npm ci', + 'fallbackFile' => '', + ]); + + $this->assertSame(201, $site['headers']['status-code']); + $siteId = $site['body']['$id']; + + // 3. Setup domain for proxy access + $sitesDomain = \explode(',', System::getEnv('_APP_DOMAIN_SITES', ''))[0]; + $rule = $this->client->call(Client::METHOD_POST, '/proxy/rules/site', array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + ], $this->getHeaders()), [ + 'domain' => ID::unique() . '.' . $sitesDomain, + 'siteId' => $siteId, + ]); + + $this->assertSame(201, $rule['headers']['status-code']); + + // 4. Deploy the site (astro site reads import.meta.env.name) + $deployment = $this->client->call(Client::METHOD_POST, '/sites/' . $siteId . '/deployments', [ + 'content-type' => 'multipart/form-data', + 'x-appwrite-project' => $projectId, + 'x-appwrite-key' => $apiKey, + ], [ + 'code' => $this->packageCode('sites', 'astro'), + 'activate' => 'true', + ]); + + $this->assertSame(202, $deployment['headers']['status-code']); + $deploymentId = $deployment['body']['$id'] ?? ''; + + // 5. Wait for deployment to be ready and activated + $this->assertEventually(function () use ($projectId, $apiKey, $siteId, $deploymentId) { + $deployment = $this->client->call(Client::METHOD_GET, '/sites/' . $siteId . '/deployments/' . $deploymentId, [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + 'x-appwrite-key' => $apiKey, + ]); + + $status = $deployment['body']['status'] ?? ''; + if ($status === 'failed') { + throw new Critical('Site deployment failed: ' . json_encode($deployment['body'], JSON_PRETTY_PRINT)); + } + + $this->assertSame('ready', $status, 'Deployment status is not ready'); + }, 120000, 500); + + $this->assertEventually(function () use ($projectId, $apiKey, $siteId, $deploymentId) { + $site = $this->client->call(Client::METHOD_GET, '/sites/' . $siteId, [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + 'x-appwrite-key' => $apiKey, + ]); + $this->assertSame($deploymentId, $site['body']['deploymentId'] ?? ''); + }, 120000, 500); + + // 6. Verify the project variable was available during build + $deployment = $this->client->call(Client::METHOD_GET, '/sites/' . $siteId . '/deployments/' . $deploymentId, [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + 'x-appwrite-key' => $apiKey, + ]); + $this->assertSame(200, $deployment['headers']['status-code']); + $this->assertStringContainsString('ProjectVarTest', (string) $deployment['body']['buildLogs']); + + // 7. Get the domain and access the site + $rules = $this->client->call(Client::METHOD_GET, '/proxy/rules', array_merge([ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + ], $this->getHeaders()), [ + 'queries' => [ + Query::equal('deploymentResourceId', [$siteId])->toString(), + Query::equal('trigger', ['manual'])->toString(), + Query::equal('type', ['deployment'])->toString(), + ], + ]); + + $this->assertSame(200, $rules['headers']['status-code']); + $this->assertGreaterThanOrEqual(1, \count($rules['body']['rules'])); + $domain = $rules['body']['rules'][0]['domain']; + + $proxyClient = new Client(); + $proxyClient->setEndpoint('http://' . $domain); + + $response = $proxyClient->call(Client::METHOD_GET, '/'); + + $this->assertSame(200, $response['headers']['status-code']); + $this->assertStringContainsString('Env variable is ProjectVarTest', (string) $response['body']); + $this->assertStringNotContainsString('Variable not found', (string) $response['body']); + + // Cleanup + $this->client->call(Client::METHOD_DELETE, '/sites/' . $siteId, [ + 'content-type' => 'application/json', + 'x-appwrite-project' => $projectId, + 'x-appwrite-key' => $apiKey, + ]); + $this->deleteVariable($variableId); + } } diff --git a/tests/extensions/TestFinishedSubscriber.php b/tests/extensions/TestFinishedSubscriber.php index e07a9b67ed..fd58ad1f88 100644 --- a/tests/extensions/TestFinishedSubscriber.php +++ b/tests/extensions/TestFinishedSubscriber.php @@ -15,16 +15,22 @@ class TestFinishedSubscriber implements FinishedSubscriber public function notify(Finished $event): void { $test = $event->test()->name(); - $time = $event->telemetryInfo()->durationSinceStart()->seconds(); + $testId = $event->test()->id(); + + $elapsed = $event->telemetryInfo()->durationSinceStart()->asFloat(); + $start = TestPreparationStartedSubscriber::$startSeconds[$testId] ?? null; + $time = $start === null ? $elapsed : $elapsed - $start; + + unset(TestPreparationStartedSubscriber::$startSeconds[$testId]); printf( - "%s ended in %s milliseconds\n", + "%s ended in %d milliseconds\n", $test, - $time * 1000 + (int) round($time * 1000) ); if ($time > $this->maxSecondsAllowed) { - fwrite(STDOUT, sprintf("\e[31mThe %s test is slow, it took %s seconds!\n\e[0m", $test, $time)); + fwrite(STDOUT, sprintf("\e[31mThe %s test is slow, it took %.2f seconds!\n\e[0m", $test, $time)); } } } diff --git a/tests/extensions/TestHook.php b/tests/extensions/TestHook.php index 6ac1ec4afe..00cdfda33c 100644 --- a/tests/extensions/TestHook.php +++ b/tests/extensions/TestHook.php @@ -13,6 +13,7 @@ class TestHook implements Extension public function bootstrap(Configuration $configuration, Facade $facade, ParameterCollection $parameters): void { + $facade->registerSubscriber(new TestPreparationStartedSubscriber()); $facade->registerSubscriber(new TestFinishedSubscriber(self::MAX_SECONDS_ALLOWED)); $facade->registerSubscriber(new RetrySubscriber()); } diff --git a/tests/extensions/TestPreparationStartedSubscriber.php b/tests/extensions/TestPreparationStartedSubscriber.php new file mode 100644 index 0000000000..3bb59e52a8 --- /dev/null +++ b/tests/extensions/TestPreparationStartedSubscriber.php @@ -0,0 +1,26 @@ + + */ + public static array $startSeconds = []; + + public function notify(PreparationStarted $event): void + { + self::$startSeconds[$event->test()->id()] = $event->telemetryInfo()->durationSinceStart()->asFloat(); + } +}