feat: vendor gitea 1.16.2

This commit is contained in:
2026-06-02 08:36:01 +00:00
parent 247cd60f69
commit 54798b4615
2145 changed files with 162965 additions and 126447 deletions
-92
View File
@@ -1,92 +0,0 @@
# End to end tests
E2e tests largely follow the same syntax as [integration tests](../integration).
Whereas integration tests are intended to mock and stress the back-end, server-side code, e2e tests the interface between front-end and back-end, as well as visual regressions with both assertions and visual comparisons.
They can be run with make commands for the appropriate backends, namely:
```shell
make test-sqlite
make test-pgsql
make test-mysql
make test-mssql
```
Make sure to perform a clean front-end build before running tests:
```
make clean frontend
```
## Install playwright system dependencies
```
npx playwright install-deps
```
## Run all tests via local act_runner
```
act_runner exec -W ./.github/workflows/pull-e2e-tests.yml --event=pull_request --default-actions-url="https://github.com" -i catthehacker/ubuntu:runner-latest
```
## Run sqlite e2e tests
Start tests
```
make test-e2e-sqlite
```
## Run MySQL e2e tests
Setup a MySQL database inside docker
```
docker run -e "MYSQL_DATABASE=test" -e "MYSQL_ALLOW_EMPTY_PASSWORD=yes" -p 3306:3306 --rm --name mysql mysql:latest #(just ctrl-c to stop db and clean the container)
docker run -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" --rm --name elasticsearch elasticsearch:7.6.0 #(in a second terminal, just ctrl-c to stop db and clean the container)
```
Start tests based on the database container
```
TEST_MYSQL_HOST=localhost:3306 TEST_MYSQL_DBNAME=test TEST_MYSQL_USERNAME=root TEST_MYSQL_PASSWORD='' make test-e2e-mysql
```
## Run pgsql e2e tests
Setup a pgsql database inside docker
```
docker run -e "POSTGRES_DB=test" -p 5432:5432 --rm --name pgsql postgres:latest #(just ctrl-c to stop db and clean the container)
```
Start tests based on the database container
```
TEST_PGSQL_HOST=localhost:5432 TEST_PGSQL_DBNAME=test TEST_PGSQL_USERNAME=postgres TEST_PGSQL_PASSWORD=postgres make test-e2e-pgsql
```
## Run mssql e2e tests
Setup a mssql database inside docker
```
docker run -e "ACCEPT_EULA=Y" -e "MSSQL_PID=Standard" -e "SA_PASSWORD=MwantsaSecurePassword1" -p 1433:1433 --rm --name mssql microsoft/mssql-server-linux:latest #(just ctrl-c to stop db and clean the container)
```
Start tests based on the database container
```
TEST_MSSQL_HOST=localhost:1433 TEST_MSSQL_DBNAME=gitea_test TEST_MSSQL_USERNAME=sa TEST_MSSQL_PASSWORD=MwantsaSecurePassword1 make test-e2e-mssql
```
## Running individual tests
Example command to run `example.test.e2e.ts` test file:
_Note: unlike integration tests, this filtering is at the file level, not function_
For SQLite:
```
make test-e2e-sqlite#example
```
For other databases(replace `mssql` to `mysql` or `pgsql`):
```
TEST_MSSQL_HOST=localhost:1433 TEST_MSSQL_DBNAME=test TEST_MSSQL_USERNAME=sa TEST_MSSQL_PASSWORD=MwantsaSecurePassword1 make test-e2e-mssql#example
```
## Visual testing
Although the main goal of e2e is assertion testing, we have added a framework for visual regress testing. If you are working on front-end features, please use the following:
- Check out `main`, `make clean frontend`, and run e2e tests with `VISUAL_TEST=1` to generate outputs. This will initially fail, as no screenshots exist. You can run the e2e tests again to assert it passes.
- Check out your branch, `make clean frontend`, and run e2e tests with `VISUAL_TEST=1`. You should be able to assert you front-end changes don't break any other tests unintentionally.
VISUAL_TEST=1 will create screenshots in tests/e2e/test-snapshots. The test will fail the first time this is enabled (until we get visual test image persistence figured out), because it will be testing against an empty screenshot folder.
ACCEPT_VISUAL=1 will overwrite the snapshot images with new images.
@@ -0,0 +1,20 @@
import {env} from 'node:process';
import {expect, test} from '@playwright/test';
import {login, apiCreateRepo, apiDeleteRepo, randomString} from './utils.ts';
test('codeeditor textarea updates correctly', async ({page, request}) => {
const repoName = `e2e-codeeditor-${randomString(8)}`;
await Promise.all([apiCreateRepo(request, {name: repoName}), login(page)]);
try {
await page.goto(`/${env.GITEA_TEST_E2E_USER}/${repoName}/_new/main`);
await page.getByPlaceholder('Name your file…').fill('test.js');
await expect(page.locator('.editor-loading')).toBeHidden();
const editor = page.locator('.cm-content[role="textbox"]');
await expect(editor).toBeVisible();
await editor.click();
await page.keyboard.type('const hello = "world";');
await expect(page.locator('textarea[name="content"]')).toHaveValue('const hello = "world";');
} finally {
await apiDeleteRepo(request, env.GITEA_TEST_E2E_USER, repoName);
}
});
-115
View File
@@ -1,115 +0,0 @@
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
// This is primarily coped from /tests/integration/integration_test.go
// TODO: Move common functions to shared file
//nolint:forbidigo // use of print functions is allowed in tests
package e2e
import (
"bytes"
"context"
"fmt"
"net/url"
"os"
"os/exec"
"path/filepath"
"testing"
"code.gitea.io/gitea/models/unittest"
"code.gitea.io/gitea/modules/graceful"
"code.gitea.io/gitea/modules/log"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/modules/testlogger"
"code.gitea.io/gitea/modules/util"
"code.gitea.io/gitea/modules/web"
"code.gitea.io/gitea/routers"
"code.gitea.io/gitea/tests"
)
var testE2eWebRoutes *web.Router
func TestMain(m *testing.M) {
defer log.GetManager().Close()
managerCtx, cancel := context.WithCancel(context.Background())
graceful.InitManager(managerCtx)
defer cancel()
tests.InitTest(false)
testE2eWebRoutes = routers.NormalRoutes()
err := unittest.InitFixtures(
unittest.FixturesOptions{
Dir: filepath.Join(filepath.Dir(setting.AppPath), "models/fixtures/"),
},
)
if err != nil {
fmt.Printf("Error initializing test database: %v\n", err)
os.Exit(1)
}
exitVal := m.Run()
testlogger.WriterCloser.Reset()
if err = util.RemoveAll(setting.Indexer.IssuePath); err != nil {
fmt.Printf("util.RemoveAll: %v\n", err)
os.Exit(1)
}
if err = util.RemoveAll(setting.Indexer.RepoPath); err != nil {
fmt.Printf("Unable to remove repo indexer: %v\n", err)
os.Exit(1)
}
os.Exit(exitVal)
}
// TestE2e should be the only test e2e necessary. It will collect all "*.test.e2e.ts" files in this directory and build a test for each.
func TestE2e(t *testing.T) {
// Find the paths of all e2e test files in test directory.
searchGlob := filepath.Join(filepath.Dir(setting.AppPath), "tests", "e2e", "*.test.e2e.ts")
paths, err := filepath.Glob(searchGlob)
if err != nil {
t.Fatal(err)
} else if len(paths) == 0 {
t.Fatal(fmt.Errorf("No e2e tests found in %s", searchGlob))
}
runArgs := []string{"npx", "playwright", "test"}
// To update snapshot outputs
if _, set := os.LookupEnv("ACCEPT_VISUAL"); set {
runArgs = append(runArgs, "--update-snapshots")
}
// Create new test for each input file
for _, path := range paths {
_, filename := filepath.Split(path)
testname := filename[:len(filename)-len(filepath.Ext(path))]
t.Run(testname, func(t *testing.T) {
// Default 2 minute timeout
onGiteaRun(t, func(*testing.T, *url.URL) {
cmd := exec.Command(runArgs[0], runArgs...)
cmd.Env = os.Environ()
cmd.Env = append(cmd.Env, "GITEA_URL="+setting.AppURL)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err = cmd.Run()
if err != nil {
// Currently colored output is conflicting. Using Printf until that is resolved.
fmt.Printf("%v", stdout.String())
fmt.Printf("%v", stderr.String())
log.Fatal("Playwright Failed: %s", err)
}
fmt.Printf("%v", stdout.String())
})
})
}
}
+9
View File
@@ -0,0 +1,9 @@
declare namespace NodeJS {
interface ProcessEnv {
GITEA_TEST_E2E_DOMAIN: string;
GITEA_TEST_E2E_USER: string;
GITEA_TEST_E2E_EMAIL: string;
GITEA_TEST_E2E_PASSWORD: string;
GITEA_TEST_E2E_URL: string;
}
}
@@ -0,0 +1,89 @@
import {test, expect} from '@playwright/test';
import {loginUser, baseUrl, apiUserHeaders, apiCreateUser, apiDeleteUser, apiCreateRepo, apiCreateIssue, apiStartStopwatch, timeoutFactor, randomString} from './utils.ts';
// These tests rely on a short EVENT_SOURCE_UPDATE_TIME in the e2e server config.
test.describe('events', () => {
test('notification count', async ({page, request}) => {
const owner = `ev-notif-owner-${randomString(8)}`;
const commenter = `ev-notif-commenter-${randomString(8)}`;
const repoName = `ev-notif-${randomString(8)}`;
await Promise.all([apiCreateUser(request, owner), apiCreateUser(request, commenter)]);
// Create repo and login in parallel — repo is needed for the issue, login for the event stream
await Promise.all([
apiCreateRepo(request, {name: repoName, headers: apiUserHeaders(owner)}),
loginUser(page, owner),
]);
const badge = page.locator('a.not-mobile .notification_count');
await expect(badge).toBeHidden();
// Create issue as another user — this generates a notification delivered via server push
await apiCreateIssue(request, owner, repoName, {title: 'events notification test', headers: apiUserHeaders(commenter)});
// Wait for the notification badge to appear via server event
await expect(badge).toBeVisible({timeout: 15000 * timeoutFactor});
// Cleanup
await Promise.all([apiDeleteUser(request, commenter), apiDeleteUser(request, owner)]);
});
test('stopwatch', async ({page, request}) => {
const name = `ev-sw-${randomString(8)}`;
const headers = apiUserHeaders(name);
await apiCreateUser(request, name);
// Create repo, issue, and start stopwatch before login
await apiCreateRepo(request, {name, headers});
await apiCreateIssue(request, name, name, {title: 'events stopwatch test', headers});
await apiStartStopwatch(request, name, name, 1, {headers});
// Login — page renders with the active stopwatch element
await loginUser(page, name);
// Verify stopwatch is visible and links to the correct issue
const stopwatch = page.locator('.active-stopwatch.not-mobile');
await expect(stopwatch).toBeVisible();
// Cleanup
await apiDeleteUser(request, name);
});
test('logout propagation', async ({browser, request}) => {
const name = `ev-logout-${randomString(8)}`;
await apiCreateUser(request, name);
// Use a single context so both pages share the same session and SharedWorker
const context = await browser.newContext({baseURL: baseUrl()});
const page1 = await context.newPage();
const page2 = await context.newPage();
await loginUser(page1, name);
// Navigate page2 so it connects to the shared event stream
await page2.goto('/');
// Verify page2 is logged in
await expect(page2.getByRole('link', {name: 'Sign In'})).toBeHidden();
// Give page2's SharedWorker time to register its SSE connection on the
// server — otherwise the logout event can race the connection and be
// silently dropped. See https://github.com/go-gitea/gitea/pull/37403
// In the future, we can set an attribute to HTML page when the connection is established,
// then here we can just wait for that attribute (it should also work for the planned WebSocket SharedWorker)
await page2.waitForTimeout(500); // eslint-disable-line playwright/no-wait-for-timeout
// Logout from page1 — this sends a logout event to all tabs
await page1.goto('/user/logout');
// page2 should be redirected via the logout event
await expect(page2.getByRole('link', {name: 'Sign In'})).toBeVisible();
await context.close();
// Cleanup
await apiDeleteUser(request, name);
});
});
@@ -1,56 +0,0 @@
import {test, expect} from '@playwright/test';
import {login_user, save_visual, load_logged_in_context} from './utils_e2e.ts';
test.beforeAll(async ({browser}, workerInfo) => {
await login_user(browser, workerInfo, 'user2');
});
test('homepage', async ({page}) => {
const response = await page.goto('/');
expect(response?.status()).toBe(200); // Status OK
await expect(page).toHaveTitle(/^Gitea: Git with a cup of tea\s*$/);
await expect(page.locator('.logo')).toHaveAttribute('src', '/assets/img/logo.svg');
});
test('register', async ({page}, workerInfo) => {
const response = await page.goto('/user/sign_up');
expect(response?.status()).toBe(200); // Status OK
await page.locator('input[name=user_name]').fill(`e2e-test-${workerInfo.workerIndex}`);
await page.locator('input[name=email]').fill(`e2e-test-${workerInfo.workerIndex}@test.com`);
await page.locator('input[name=password]').fill('test123test123');
await page.locator('input[name=retype]').fill('test123test123');
await page.click('form button.ui.primary.button:visible');
// Make sure we routed to the home page. Else login failed.
expect(page.url()).toBe(`${workerInfo.project.use.baseURL}/`);
await expect(page.locator('.secondary-nav span>img.ui.avatar')).toBeVisible();
await expect(page.locator('.ui.positive.message.flash-success')).toHaveText('Account was successfully created. Welcome!');
save_visual(page);
});
test('login', async ({page}, workerInfo) => {
const response = await page.goto('/user/login');
expect(response?.status()).toBe(200); // Status OK
await page.locator('input[name=user_name]').fill(`user2`);
await page.locator('input[name=password]').fill(`password`);
await page.click('form button.ui.primary.button:visible');
await page.waitForLoadState('networkidle'); // eslint-disable-line playwright/no-networkidle
expect(page.url()).toBe(`${workerInfo.project.use.baseURL}/`);
save_visual(page);
});
test('logged in user', async ({browser}, workerInfo) => {
const context = await load_logged_in_context(browser, workerInfo, 'user2');
const page = await context.newPage();
await page.goto('/');
// Make sure we routed to the home page. Else login failed.
expect(page.url()).toBe(`${workerInfo.project.use.baseURL}/`);
save_visual(page);
});
@@ -0,0 +1,17 @@
import {test, expect} from '@playwright/test';
test('explore repositories', async ({page}) => {
await page.goto('/explore/repos');
await expect(page.getByPlaceholder('Search repos…')).toBeVisible();
await expect(page.getByRole('link', {name: 'Repositories'})).toBeVisible();
});
test('explore users', async ({page}) => {
await page.goto('/explore/users');
await expect(page.getByPlaceholder('Search users…')).toBeVisible();
});
test('explore organizations', async ({page}) => {
await page.goto('/explore/organizations');
await expect(page.getByPlaceholder('Search orgs…')).toBeVisible();
});
@@ -0,0 +1,61 @@
import {env} from 'node:process';
import {expect, test} from '@playwright/test';
import {login, apiCreateRepo, apiCreateFile, apiDeleteRepo, assertFlushWithParent, assertNoJsError, randomString} from './utils.ts';
test('external file', async ({page, request}) => {
const repoName = `e2e-external-render-${randomString(8)}`;
const owner = env.GITEA_TEST_E2E_USER;
await Promise.all([
apiCreateRepo(request, {name: repoName}),
login(page),
]);
try {
await apiCreateFile(request, owner, repoName, 'test.external', '<p>rendered content</p>');
await page.goto(`/${owner}/${repoName}/src/branch/main/test.external`);
const iframe = page.locator('iframe.external-render-iframe');
await expect(iframe).toBeVisible();
await expect(iframe).toHaveAttribute('data-src', new RegExp(`/${owner}/${repoName}/render/branch/main/test\\.external`));
const frame = page.frameLocator('iframe.external-render-iframe');
await expect(frame.locator('p')).toContainText('rendered content');
await assertFlushWithParent(iframe, page.locator('.file-view'));
await assertNoJsError(page);
} finally {
await apiDeleteRepo(request, owner, repoName);
}
});
test('openapi file', async ({page, request}) => {
const repoName = `e2e-openapi-render-${randomString(8)}`;
const owner = env.GITEA_TEST_E2E_USER;
await Promise.all([
apiCreateRepo(request, {name: repoName}),
login(page),
]);
try {
const title = 'Test <API> & "quoted"';
const spec = JSON.stringify({
openapi: '3.0.0',
info: {title, version: '1.0'},
paths: {'/pets': {get: {responses: {'200': {description: 'OK', content: {'application/json': {schema: {$ref: '#/components/schemas/Pet'}}}}}}}},
components: {schemas: {Pet: {type: 'object', properties: {children: {type: 'array', items: {$ref: '#/components/schemas/Pet'}}}}}},
});
await apiCreateFile(request, owner, repoName, 'openapi.json', spec);
await page.goto(`/${owner}/${repoName}/src/branch/main/openapi.json`);
const iframe = page.locator('iframe.external-render-iframe');
await expect(iframe).toBeVisible();
const viewer = page.frameLocator('iframe.external-render-iframe').locator('#frontend-render-viewer');
await expect(viewer.locator('.swagger-ui')).toBeVisible();
await expect(viewer.locator('.info .title')).toContainText(title);
// expanding the operation triggers swagger-ui's $ref resolver, which fetches window.location
// (about:srcdoc since the iframe is loaded via srcdoc); failure surfaces as "Could not resolve reference"
await viewer.locator('.opblock-tag').first().click();
await viewer.locator('.opblock').first().click();
await expect(viewer.getByText('Could not resolve reference')).toHaveCount(0);
// poll: postMessage resize may not have settled yet when the visibility checks pass
await expect.poll(async () => (await iframe.boundingBox())!.height).toBeGreaterThan(300);
await assertFlushWithParent(iframe, page.locator('.file-view'));
await assertNoJsError(page);
} finally {
await apiDeleteRepo(request, owner, repoName);
}
});
@@ -0,0 +1,69 @@
import {env} from 'node:process';
import {expect, test} from '@playwright/test';
import {apiCreateBranch, apiCreateRepo, apiCreateFile, apiDeleteRepo, assertFlushWithParent, assertNoJsError, login, randomString} from './utils.ts';
test('3d model file', async ({page, request}) => {
const repoName = `e2e-3d-render-${randomString(8)}`;
const owner = env.GITEA_TEST_E2E_USER;
await apiCreateRepo(request, {name: repoName});
try {
const stl = 'solid test\nfacet normal 0 0 1\nouter loop\nvertex 0 0 0\nvertex 1 0 0\nvertex 0 1 0\nendloop\nendfacet\nendsolid test\n';
await apiCreateFile(request, owner, repoName, 'test.stl', stl);
await page.goto(`/${owner}/${repoName}/src/branch/main/test.stl?display=rendered`);
const iframe = page.locator('iframe.external-render-iframe');
await expect(iframe).toBeVisible();
const frame = page.frameLocator('iframe.external-render-iframe');
const viewer = frame.locator('#frontend-render-viewer');
await expect(viewer.locator('canvas')).toBeVisible();
expect((await viewer.boundingBox())!.height).toBeGreaterThan(300);
await assertFlushWithParent(iframe, page.locator('.file-view'));
// bgcolor passed via gitea-iframe-bgcolor; 3D viewer reads it from body bgcolor — must match parent
const [parentBg, iframeBg] = await Promise.all([
page.evaluate(() => getComputedStyle(document.body).backgroundColor),
frame.locator('body').evaluate((el) => getComputedStyle(el).backgroundColor),
]);
expect(iframeBg).toBe(parentBg);
await assertNoJsError(page);
} finally {
await apiDeleteRepo(request, owner, repoName);
}
});
test('pdf file', async ({page, request}) => {
// headless playwright cannot render PDFs (PDFObject.embed returns false), so this is a limited test
const repoName = `e2e-pdf-render-${randomString(8)}`;
const owner = env.GITEA_TEST_E2E_USER;
await apiCreateRepo(request, {name: repoName});
try {
await apiCreateFile(request, owner, repoName, 'test.pdf', '%PDF-1.0\n%%EOF\n');
await page.goto(`/${owner}/${repoName}/src/branch/main/test.pdf`);
const container = page.locator('.file-view-render-container');
await expect(container).toHaveAttribute('data-render-name', 'pdf-viewer');
expect((await container.boundingBox())!.height).toBeGreaterThan(300);
await assertFlushWithParent(container, page.locator('.file-view'));
} finally {
await apiDeleteRepo(request, owner, repoName);
}
});
test('asciicast file', async ({page, request}) => {
// regression for repo_file.go's RefTypeNameSubURL double-escape: readme.cast on a non-ASCII branch
// is rendered via view_readme.go (no metas override), exposing the bug as a broken player URL
const repoName = `e2e-asciicast-render-${randomString(8)}`;
const owner = env.GITEA_TEST_E2E_USER;
const branch = '日本語-branch';
const branchEnc = encodeURIComponent(branch);
await Promise.all([apiCreateRepo(request, {name: repoName, autoInit: false}), login(page)]);
try {
const cast = '{"version": 2, "width": 80, "height": 24}\n[0.0, "o", "hi"]\n';
await apiCreateFile(request, owner, repoName, 'readme.cast', cast);
await apiCreateBranch(request, owner, repoName, branch);
await page.goto(`/${owner}/${repoName}/src/branch/${branchEnc}`);
const container = page.locator('.asciinema-player-container');
await expect(container).toHaveAttribute('data-asciinema-player-src', `/${owner}/${repoName}/raw/branch/${branchEnc}/readme.cast`);
await expect(container.locator('.ap-wrapper')).toBeVisible();
expect((await container.boundingBox())!.height).toBeGreaterThan(300);
} finally {
await apiDeleteRepo(request, owner, repoName);
}
});
@@ -0,0 +1,9 @@
import {test, expect} from '@playwright/test';
test('licenses.txt', async ({page}) => {
const resp = await page.goto('/assets/licenses.txt');
expect(resp?.status()).toBe(200);
const content = await resp!.text();
expect(content).toContain('@vue/');
expect(content).toContain('code.gitea.io/');
});
@@ -0,0 +1,12 @@
import {test, expect} from '@playwright/test';
import {login, logout} from './utils.ts';
test('homepage', async ({page}) => {
await page.goto('/');
await expect(page.getByRole('img', {name: 'Logo'})).toHaveAttribute('src', '/assets/img/logo.svg');
});
test('login and logout', async ({page}) => {
await login(page);
await logout(page);
});
@@ -0,0 +1,22 @@
import {env} from 'node:process';
import {expect, test} from '@playwright/test';
import {apiCreateRepo, apiHeaders, assertNoJsError, baseUrl, randomString} from './utils.ts';
test('mermaid diagram in issue', async ({page, request}) => {
const repoName = `e2e-mermaid-${randomString(8)}`;
const owner = env.GITEA_TEST_E2E_USER;
await apiCreateRepo(request, {name: repoName});
const body = '```mermaid\nflowchart LR\n Alpha --> Beta\n Beta --> Gamma\n```\n';
const response = await request.post(`${baseUrl()}/api/v1/repos/${owner}/${repoName}/issues`, {
headers: apiHeaders(),
data: {title: 'mermaid test', body},
});
expect(response.ok(), `create issue failed: ${response.status()}`).toBe(true);
const {number} = await response.json();
await page.goto(`/${owner}/${repoName}/issues/${number}`);
const svg = page.frameLocator('iframe.markup-content-iframe').locator('svg');
await expect(svg).toContainText(/Alpha[\s\S]*Beta[\s\S]*Gamma/);
await assertNoJsError(page);
});
@@ -0,0 +1,13 @@
import {env} from 'node:process';
import {test, expect} from '@playwright/test';
import {login, apiCreateRepo, apiDeleteRepo, randomString} from './utils.ts';
test('create a milestone', async ({page}) => {
const repoName = `e2e-milestone-${randomString(8)}`;
await Promise.all([login(page), apiCreateRepo(page.request, {name: repoName})]);
await page.goto(`/${env.GITEA_TEST_E2E_USER}/${repoName}/milestones/new`);
await page.getByPlaceholder('Title').fill('Test Milestone');
await page.getByRole('button', {name: 'Create Milestone'}).click();
await expect(page.locator('.milestone-list')).toContainText('Test Milestone');
await apiDeleteRepo(page.request, env.GITEA_TEST_E2E_USER, repoName);
});
@@ -0,0 +1,13 @@
import {test, expect} from '@playwright/test';
import {login, apiDeleteOrg, randomString} from './utils.ts';
test('create an organization', async ({page}) => {
const orgName = `e2e-org-${randomString(8)}`;
await login(page);
await page.goto('/org/create');
await page.getByLabel('Organization Name').fill(orgName);
await page.getByRole('button', {name: 'Create Organization'}).click();
await expect(page).toHaveURL(new RegExp(`/org/${orgName}`));
// delete via API because of issues related to form-fetch-action
await apiDeleteOrg(page.request, orgName);
});
@@ -0,0 +1,30 @@
import {env} from 'node:process';
import {expect, test} from '@playwright/test';
import {login, apiCreateRepo, apiCreateIssue, apiDeleteRepo, randomString} from './utils.ts';
test('toggle issue reactions', async ({page, request}) => {
const repoName = `e2e-reactions-${randomString(8)}`;
const owner = env.GITEA_TEST_E2E_USER;
await apiCreateRepo(request, {name: repoName});
await Promise.all([
apiCreateIssue(request, owner, repoName, {title: 'Reaction test'}),
login(page),
]);
try {
await page.goto(`/${owner}/${repoName}/issues/1`);
const issueComment = page.locator('.timeline-item.comment.first');
const reactionPicker = issueComment.locator('.select-reaction');
await reactionPicker.click();
await reactionPicker.getByLabel('+1').click();
const reactions = issueComment.getByRole('group', {name: 'Reactions'});
await expect(reactions.getByRole('button', {name: /^\+1:/})).toContainText('1');
await reactions.getByRole('button', {name: /^\+1:/}).click();
await expect(reactions.getByRole('button', {name: /^\+1:/})).toHaveCount(0);
} finally {
await apiDeleteRepo(request, owner, repoName);
}
});
@@ -0,0 +1,11 @@
import {env} from 'node:process';
import {test, expect} from '@playwright/test';
import {apiCreateRepo, apiDeleteRepo, randomString} from './utils.ts';
test('repo readme', async ({page}) => {
const repoName = `e2e-readme-${randomString(8)}`;
await apiCreateRepo(page.request, {name: repoName});
await page.goto(`/${env.GITEA_TEST_E2E_USER}/${repoName}`);
await expect(page.locator('#readme')).toContainText(repoName);
await apiDeleteRepo(page.request, env.GITEA_TEST_E2E_USER, repoName);
});
@@ -0,0 +1,70 @@
import {env} from 'node:process';
import {test, expect} from '@playwright/test';
import {login, logout, apiDeleteUser, randomString} from './utils.ts';
test.beforeEach(async ({page}) => {
await page.goto('/user/sign_up');
});
test('register page has form', async ({page}) => {
await expect(page.getByLabel('Username')).toBeVisible();
await expect(page.getByLabel('Email Address')).toBeVisible();
await expect(page.getByLabel('Password', {exact: true})).toBeVisible();
await expect(page.getByLabel('Confirm Password')).toBeVisible();
await expect(page.getByRole('button', {name: 'Register Account'})).toBeVisible();
});
test('register with empty fields shows error', async ({page}) => {
// HTML5 required attribute prevents submission, so verify the fields are required
await expect(page.locator('input[name="user_name"][required]')).toBeVisible();
await expect(page.locator('input[name="email"][required]')).toBeVisible();
await expect(page.locator('input[name="password"][required]')).toBeVisible();
await expect(page.locator('input[name="retype"][required]')).toBeVisible();
});
test('register with mismatched passwords shows error', async ({page}) => {
await page.getByLabel('Username').fill('e2e-register-mismatch');
await page.getByLabel('Email Address').fill(`e2e-register-mismatch@${env.GITEA_TEST_E2E_DOMAIN}`);
await page.getByLabel('Password', {exact: true}).fill('password123!');
await page.getByLabel('Confirm Password').fill('different123!');
await page.getByRole('button', {name: 'Register Account'}).click();
await expect(page.locator('.ui.negative.message')).toBeVisible();
});
test('register then login', async ({page}) => {
const username = `e2e-register-${randomString(8)}`;
const email = `${username}@${env.GITEA_TEST_E2E_DOMAIN}`;
const password = 'password123!';
await page.getByLabel('Username').fill(username);
await page.getByLabel('Email Address').fill(email);
await page.getByLabel('Password', {exact: true}).fill(password);
await page.getByLabel('Confirm Password').fill(password);
await page.getByRole('button', {name: 'Register Account'}).click();
// After successful registration, should be redirected away from sign_up
await expect(page).not.toHaveURL(/sign_up/);
// Logout then login with the newly created account
await logout(page);
await login(page, username, password);
// delete via API because of issues related to form-fetch-action
await apiDeleteUser(page.request, username);
});
test('register with existing username shows error', async ({page}) => {
await page.getByLabel('Username').fill(env.GITEA_TEST_E2E_USER);
await page.getByLabel('Email Address').fill(`e2e-duplicate@${env.GITEA_TEST_E2E_DOMAIN}`);
await page.getByLabel('Password', {exact: true}).fill('password123!');
await page.getByLabel('Confirm Password').fill('password123!');
await page.getByRole('button', {name: 'Register Account'}).click();
await expect(page.locator('.ui.negative.message')).toBeVisible();
});
test('sign in link exists', async ({page}) => {
const signInLink = page.getByText('Sign in now!');
await expect(signInLink).toBeVisible();
await signInLink.click();
await expect(page).toHaveURL(/\/user\/login$/);
});
@@ -0,0 +1,10 @@
import {test, expect} from '@playwright/test';
import {assertNoJsError} from './utils.ts';
test('relative-time renders without errors', async ({page}) => {
await page.goto('/devtest/relative-time');
const relativeTime = page.getByTestId('relative-time-now');
await expect(relativeTime).toHaveAttribute('data-tooltip-content', /.+/);
await expect(relativeTime).toHaveText('now');
await assertNoJsError(page);
});
@@ -0,0 +1,13 @@
import {env} from 'node:process';
import {test} from '@playwright/test';
import {login, apiDeleteRepo, randomString} from './utils.ts';
test('create a repository', async ({page}) => {
const repoName = `e2e-repo-${randomString(8)}`;
await login(page);
await page.goto('/repo/create');
await page.locator('input[name="repo_name"]').fill(repoName);
await page.getByRole('button', {name: 'Create Repository'}).click();
await page.waitForURL(new RegExp(`/${env.GITEA_TEST_E2E_USER}/${repoName}$`));
await apiDeleteRepo(page.request, env.GITEA_TEST_E2E_USER, repoName);
});
@@ -0,0 +1,20 @@
import {test, expect} from '@playwright/test';
import {loginUser, apiCreateUser, apiDeleteUser, randomString} from './utils.ts';
test('update profile biography', async ({page, request}) => {
const username = `e2e-settings-${randomString(8)}`;
const bio = `e2e-bio-${randomString(8)}`;
await apiCreateUser(request, username);
try {
await loginUser(page, username);
await page.goto('/user/settings');
await page.getByLabel('Biography').fill(bio);
await page.getByRole('button', {name: 'Update Profile'}).click();
await expect(page.getByLabel('Biography')).toHaveValue(bio);
await page.getByLabel('Biography').fill('');
await page.getByRole('button', {name: 'Update Profile'}).click();
await expect(page.getByLabel('Biography')).toHaveValue('');
} finally {
await apiDeleteUser(request, username);
}
});
+138
View File
@@ -0,0 +1,138 @@
import {env} from 'node:process';
import {expect} from '@playwright/test';
import type {APIRequestContext, Locator, Page} from '@playwright/test';
/** Generate a random alphanumeric string. */
export function randomString(length: number): string {
const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let index = 0; index < length; index++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
export const timeoutFactor = Number(env.GITEA_TEST_E2E_TIMEOUT_FACTOR) || 1;
export function baseUrl() {
return env.GITEA_TEST_E2E_URL?.replace(/\/$/g, '');
}
function apiAuthHeader(username: string, password: string) {
return {Authorization: `Basic ${globalThis.btoa(`${username}:${password}`)}`};
}
export function apiHeaders() {
return apiAuthHeader(env.GITEA_TEST_E2E_USER, env.GITEA_TEST_E2E_PASSWORD);
}
async function apiRetry(fn: () => Promise<{ok: () => boolean; status: () => number; text: () => Promise<string>}>, label: string) {
const maxAttempts = 5;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
const response = await fn();
if (response.ok()) return;
if ([500, 502, 503].includes(response.status()) && attempt < maxAttempts - 1) {
const jitter = Math.random() * 500;
await new Promise((resolve) => setTimeout(resolve, 1000 * (attempt + 1) + jitter));
continue;
}
throw new Error(`${label} failed: ${response.status()} ${await response.text()}`);
}
}
export async function apiCreateRepo(requestContext: APIRequestContext, {name, autoInit = true, headers}: {name: string; autoInit?: boolean; headers?: Record<string, string>}) {
await apiRetry(() => requestContext.post(`${baseUrl()}/api/v1/user/repos`, {
headers: headers || apiHeaders(),
data: {name, auto_init: autoInit},
}), 'apiCreateRepo');
}
export async function apiCreateIssue(requestContext: APIRequestContext, owner: string, repo: string, {title, headers}: {title: string; headers?: Record<string, string>}) {
await apiRetry(() => requestContext.post(`${baseUrl()}/api/v1/repos/${owner}/${repo}/issues`, {
headers: headers || apiHeaders(),
data: {title},
}), 'apiCreateIssue');
}
export async function apiStartStopwatch(requestContext: APIRequestContext, owner: string, repo: string, issueIndex: number, {headers}: {headers?: Record<string, string>} = {}) {
await apiRetry(() => requestContext.post(`${baseUrl()}/api/v1/repos/${owner}/${repo}/issues/${issueIndex}/stopwatch/start`, {
headers: headers || apiHeaders(),
}), 'apiStartStopwatch');
}
export async function apiCreateFile(requestContext: APIRequestContext, owner: string, repo: string, filepath: string, content: string) {
await apiRetry(() => requestContext.post(`${baseUrl()}/api/v1/repos/${owner}/${repo}/contents/${filepath}`, {
headers: apiHeaders(),
data: {content: globalThis.btoa(content)},
}), 'apiCreateFile');
}
export async function apiCreateBranch(requestContext: APIRequestContext, owner: string, repo: string, newBranch: string) {
await apiRetry(() => requestContext.post(`${baseUrl()}/api/v1/repos/${owner}/${repo}/branches`, {
headers: apiHeaders(),
data: {new_branch_name: newBranch},
}), 'apiCreateBranch');
}
export async function apiDeleteRepo(requestContext: APIRequestContext, owner: string, name: string) {
await apiRetry(() => requestContext.delete(`${baseUrl()}/api/v1/repos/${owner}/${name}`, {
headers: apiHeaders(),
}), 'apiDeleteRepo');
}
export async function apiDeleteOrg(requestContext: APIRequestContext, name: string) {
await apiRetry(() => requestContext.delete(`${baseUrl()}/api/v1/orgs/${name}`, {
headers: apiHeaders(),
}), 'apiDeleteOrg');
}
/** Password shared by all test users — used for both API user creation and browser login. */
const testUserPassword = 'e2e-password!aA1';
export function apiUserHeaders(username: string) {
return apiAuthHeader(username, testUserPassword);
}
export async function apiCreateUser(requestContext: APIRequestContext, username: string) {
await apiRetry(() => requestContext.post(`${baseUrl()}/api/v1/admin/users`, {
headers: apiHeaders(),
data: {username, password: testUserPassword, email: `${username}@${env.GITEA_TEST_E2E_DOMAIN}`, must_change_password: false},
}), 'apiCreateUser');
}
export async function apiDeleteUser(requestContext: APIRequestContext, username: string) {
await apiRetry(() => requestContext.delete(`${baseUrl()}/api/v1/admin/users/${username}?purge=true`, {
headers: apiHeaders(),
}), 'apiDeleteUser');
}
export async function loginUser(page: Page, username: string) {
return login(page, username, testUserPassword);
}
export async function login(page: Page, username = env.GITEA_TEST_E2E_USER, password = env.GITEA_TEST_E2E_PASSWORD) {
await page.goto('/user/login');
await page.getByLabel('Username or Email Address').fill(username);
await page.getByLabel('Password').fill(password);
await page.getByRole('button', {name: 'Sign In'}).click();
await expect(page.getByRole('link', {name: 'Sign In'})).toBeHidden();
}
export async function assertNoJsError(page: Page) {
await expect(page.locator('.js-global-error')).toHaveCount(0);
}
/* asserts the child has no horizontal inset from its parent — catches padding/border anywhere
* in between regardless of which element declares it */
export async function assertFlushWithParent(child: Locator, parent: Locator) {
const [childBox, parentBox] = await Promise.all([child.boundingBox(), parent.boundingBox()]);
if (!childBox || !parentBox) throw new Error('boundingBox returned null');
expect(childBox.x).toBe(parentBox.x);
expect(childBox.width).toBe(parentBox.width);
}
export async function logout(page: Page) {
await page.context().clearCookies(); // workaround issues related to fomantic dropdown
await page.goto('/');
await expect(page.getByRole('link', {name: 'Sign In'})).toBeVisible();
}
@@ -1,62 +0,0 @@
import {expect} from '@playwright/test';
import {env} from 'node:process';
import type {Browser, Page, WorkerInfo} from '@playwright/test';
const ARTIFACTS_PATH = `tests/e2e/test-artifacts`;
const LOGIN_PASSWORD = 'password';
// log in user and store session info. This should generally be
// run in test.beforeAll(), then the session can be loaded in tests.
export async function login_user(browser: Browser, workerInfo: WorkerInfo, user: string) {
// Set up a new context
const context = await browser.newContext();
const page = await context.newPage();
// Route to login page
// Note: this could probably be done more quickly with a POST
const response = await page.goto('/user/login');
expect(response?.status()).toBe(200); // Status OK
// Fill out form
await page.locator('input[name=user_name]').fill(user);
await page.locator('input[name=password]').fill(LOGIN_PASSWORD);
await page.click('form button.ui.primary.button:visible');
await page.waitForLoadState('networkidle'); // eslint-disable-line playwright/no-networkidle
expect(page.url(), {message: `Failed to login user ${user}`}).toBe(`${workerInfo.project.use.baseURL}/`);
// Save state
await context.storageState({path: `${ARTIFACTS_PATH}/state-${user}-${workerInfo.workerIndex}.json`});
return context;
}
export async function load_logged_in_context(browser: Browser, workerInfo: WorkerInfo, user: string) {
let context;
try {
context = await browser.newContext({storageState: `${ARTIFACTS_PATH}/state-${user}-${workerInfo.workerIndex}.json`});
} catch (err) {
if (err.code === 'ENOENT') {
throw new Error(`Could not find state for '${user}'. Did you call login_user(browser, workerInfo, '${user}') in test.beforeAll()?`);
}
}
return context;
}
export async function save_visual(page: Page) {
// Optionally include visual testing
if (env.VISUAL_TEST) {
await page.waitForLoadState('networkidle'); // eslint-disable-line playwright/no-networkidle
// Mock page/version string
await page.locator('footer div.ui.left').evaluate((node) => node.innerHTML = 'MOCK');
await expect(page).toHaveScreenshot({
fullPage: true,
timeout: 20000,
mask: [
page.locator('.secondary-nav span>img.ui.avatar'),
page.locator('.ui.dropdown.jump.item span>img.ui.avatar'),
],
});
}
}
@@ -1,56 +0,0 @@
// Copyright 2019 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package e2e
import (
"context"
"net"
"net/http"
"net/url"
"testing"
"time"
"code.gitea.io/gitea/modules/setting"
"code.gitea.io/gitea/tests"
"github.com/stretchr/testify/assert"
)
func onGiteaRunTB(t testing.TB, callback func(testing.TB, *url.URL), prepare ...bool) {
if len(prepare) == 0 || prepare[0] {
defer tests.PrepareTestEnv(t, 1)()
}
s := http.Server{
Handler: testE2eWebRoutes,
}
u, err := url.Parse(setting.AppURL)
assert.NoError(t, err)
listener, err := net.Listen("tcp", u.Host)
i := 0
for err != nil && i <= 10 {
time.Sleep(100 * time.Millisecond)
listener, err = net.Listen("tcp", u.Host)
i++
}
assert.NoError(t, err)
u.Host = listener.Addr().String()
defer func() {
ctx, cancel := context.WithTimeout(t.Context(), 2*time.Minute)
s.Shutdown(ctx)
cancel()
}()
go s.Serve(listener)
// Started by config go ssh.Listen(setting.SSH.ListenHost, setting.SSH.ListenPort, setting.SSH.ServerCiphers, setting.SSH.ServerKeyExchanges, setting.SSH.ServerMACs)
callback(t, u)
}
func onGiteaRun(t *testing.T, callback func(*testing.T, *url.URL), prepare ...bool) {
onGiteaRunTB(t, func(t testing.TB, u *url.URL) {
callback(t.(*testing.T), u)
}, prepare...)
}