mirror of
https://github.com/hanzoai/team.git
synced 2026-09-30 01:57:35 +00:00
E2E/Playwright: Add testcontainers to playwright-lib (#37570)
* add testcontainers to playwright-lib * include retry mechanism for transient failures * - Introduced a new command `testcontainers:up` in package.json to run Playwright tests with Testcontainers. - Created a standalone Playwright configuration file `playwright.testcontainers-up.config.ts` for managing Testcontainers. - Added a no-op test `testcontainers_up.spec.ts` to ensure the Testcontainers stack is up during the test run. - Implemented a global setup script `testcontainers_up_global_setup.ts` to start and stop the Testcontainers stack. - Updated dependencies in package.json, including adding `chalk` for logging. * fix package-lock * fix tsc and restore waiting for all migrations to complete --------- Co-authored-by: Mattermost Build <[email protected]>
This commit is contained in:
committed by
GitHub
co-authored by
Mattermost Build
parent
87f524d0a8
commit
3cda68c5c7
@@ -260,13 +260,22 @@ jobs:
|
||||
worker_index: ${{ fromJSON(needs.prepare-run.outputs.workers-matrix) }}
|
||||
env:
|
||||
COMPOSITE_IDENTITY: ${{ needs.prepare-run.outputs.composite-identity-json }}
|
||||
SERVER: "${{ inputs.server }}"
|
||||
MM_LICENSE: "${{ secrets.MM_LICENSE }}"
|
||||
ENABLED_DOCKER_SERVICES: "${{ inputs.enabled_docker_services }}"
|
||||
TEST: playwright
|
||||
BRANCH: "${{ inputs.branch }}"
|
||||
BUILD_ID: "${{ inputs.build_id }}"
|
||||
CI_BASE_URL: "full-test-${{ matrix.worker_index }}"
|
||||
# testcontainers mode: global setup brings up Postgres, Inbucket, the Mattermost
|
||||
# server, and these services itself. Every worker enables the same fixed set because
|
||||
# dispatch pulls specs from a shared queue, so no worker knows in advance which
|
||||
# service-tagged spec (e.g. @ldap, @saml, @elasticsearch) it will draw.
|
||||
PW_USE_TESTCONTAINERS: "true"
|
||||
PW_TESTCONTAINERS_SERVICES: "openldap,keycloak,elasticsearch,opensearch,minio,azurite"
|
||||
# Keeps the server alive across this worker's per-spec dispatch invocations instead of
|
||||
# tearing down after each — otherwise ci/prepare-playwright's own global-teardown call would
|
||||
# stop the server that ci/dispatch-run needs next. ci/testcontainers-teardown does the final
|
||||
# teardown once the whole queue is done.
|
||||
PW_TESTCONTAINERS_REUSE: "true"
|
||||
steps:
|
||||
- name: ci/checkout-actions
|
||||
# Sparse-checkout just .github/actions from the triggering ref (master)
|
||||
@@ -304,15 +313,9 @@ jobs:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: playwright-browsers-${{ runner.os }}-${{ hashFiles('e2e-tests/playwright/package-lock.json') }}
|
||||
fail-on-cache-miss: true
|
||||
- name: ci/cloud-init
|
||||
working-directory: e2e-tests
|
||||
run: make cloud-init
|
||||
- name: ci/start-server
|
||||
working-directory: e2e-tests
|
||||
run: make start-server
|
||||
# Run the `setup` project so per-spec dispatches can pass --no-deps
|
||||
# and skip plugin-load + server-deployment checks. node_modules,
|
||||
# lib/dist, and chromium are all restored from cache.
|
||||
# Brings up the stack via Testcontainers in `testcontainers` mode (global setup). Also runs the
|
||||
# `setup` project so per-spec dispatches can pass --no-deps and skip plugin-load +
|
||||
# server-deployment checks. node_modules, lib/dist, and chromium are all restored from cache.
|
||||
- name: ci/prepare-playwright
|
||||
working-directory: e2e-tests/playwright
|
||||
run: npx playwright test --project=setup
|
||||
@@ -328,10 +331,14 @@ jobs:
|
||||
gh-job-name: dispatch-run-${{ matrix.worker_index }}
|
||||
playwright-retries: ${{ inputs.playwright_retries }}
|
||||
playwright-project: ${{ inputs.playwright_project }}
|
||||
- name: ci/cloud-teardown
|
||||
# The only step that actually tears down the stack: PW_TESTCONTAINERS_REUSE means every
|
||||
# earlier step (including ci/prepare-playwright's own global-teardown call) just adopts the
|
||||
# already-running server instead of stopping it. Also collects container logs and archives
|
||||
# the boot-env drift history (.env.testcontainers) before removing containers.
|
||||
- name: ci/testcontainers-teardown
|
||||
if: always()
|
||||
working-directory: e2e-tests
|
||||
run: make cloud-teardown
|
||||
working-directory: e2e-tests/playwright
|
||||
run: npm run testcontainers:down
|
||||
- name: ci/upload-debug-artifacts
|
||||
if: always()
|
||||
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
|
||||
|
||||
+5
-3
@@ -8,6 +8,8 @@ This directory contains the E2E testing code for the Mattermost web client.
|
||||
|
||||
Please refer to the [dedicated developer documentation](https://developers.mattermost.com/contribute/more-info/webapp/e2e-testing/) for instructions.
|
||||
|
||||
> **Playwright note:** the instructions below describe the Docker Compose flow Cypress uses (and that Playwright previously used too). Playwright's CI and recommended local setup have since moved to [Testcontainers](https://node.testcontainers.org/) — see `playwright/README.md`'s Server Setup section for details. This Compose flow remains the way to run Cypress, and to run a plain server instance (`TEST=none make`).
|
||||
|
||||
##### For pipeline debugging
|
||||
|
||||
The E2E testing pipeline's scripts depend on the following tools being installed on your system: `docker`, `docker-compose`, `make`, `git`, `jq`, `node`, and some common utilities (`coreutils`, `findutils`, `bash`, `awk`, `sed`, `grep`)
|
||||
@@ -22,7 +24,7 @@ Instructions, detailed:
|
||||
* `ENABLED_DOCKER_SERVICES`: a space-separated list of services to start alongside the server. Default to `postgres inbucket`, for smoke test purposes and for lightweight and faster start-up time. Depending on the test requirement being worked on, you may want to override as needed, as such:
|
||||
- Cypress full tests require all services to be running: `postgres inbucket minio openldap elasticsearch keycloak`.
|
||||
- Cypress smoke tests require only the following: `postgres inbucket`.
|
||||
- Playwright full tests require only the following: `postgres inbucket`.
|
||||
- Playwright no longer runs against this Compose flow in CI (see the note above) — this only matters if you're using it to spin up a plain server instance (`TEST=none make`) for Playwright's `external` mode.
|
||||
* The following variables, will be passed over to the server container: `MM_LICENSE` (no enterprise features will be available if this is unset; required when `SERVER=cloud`), and the exploded `MM_ENV` (a comma-separated list of env var specifications)
|
||||
* The following variables, which will be passed over to the cypress container: `BRANCH`, `BUILD_ID`, `CI_BASE_URL`, `BROWSER`, `AUTOMATION_DASHBOARD_URL` and `AUTOMATION_DASHBOARD_TOKEN`
|
||||
* The `SERVER_IMAGE` variable can also be set if you want to select a custom mattermost-server image. If not specified, the value of the `SERVER_IMAGE_DEFAULT` variable defined in file `.ci/.e2erc` is used.
|
||||
@@ -39,7 +41,7 @@ Instructions, detailed:
|
||||
3. `make`: start and prepare the server, then run the Cypress smoke tests
|
||||
* You can track the progress of the run in the `http://localhost:4000/cycles` dashboard if you launched it locally
|
||||
* For `SERVER=cloud` runs, you'll need to first create a cloud customer against the specified `CWS_URL` service by running `make cloud-init`. The user isn't automatically removed, and may be reused across multiple runs until you run `make cloud-teardown` to delete it.
|
||||
* If you want to run the Playwright tests instead of the Cypress ones, you can run `TEST=playwright make`
|
||||
* If you want to run the Playwright tests instead of the Cypress ones, you can run `TEST=playwright make` — though `playwright/README.md`'s Testcontainers option is now the recommended way to run Playwright locally/in CI
|
||||
* If you just want to run a local server instance, without any further testing, you can run `TEST=none make`
|
||||
* If you're using the automation dashboard, you have the option of sharding the E2E test run: you can launch the `make` command in parallel on different machines (NB: you must use the same `BUILD_ID` and `BRANCH` values that you used for `make generate-test-cycle`) to distribute running the test cases across them. When doing this, you should also set on each machine the `CI_BASE_URL` variable to a value that uniquely identifies the instance where `make` is running.
|
||||
* This script will also parse the local test results, and write a `e2e-tests/${TEST}/results/summary.json` file containing the following keys: `passed`, `failed` and `failed_expected` (the total number of testcases that were run is the sum of these three numbers)
|
||||
@@ -71,4 +73,4 @@ For Cypress:
|
||||
* Your system needs to be setup for Cypress usage, to be able to run this command. Refer to the [E2E testing developer documentation](https://developers.mattermost.com/contribute/more-info/webapp/e2e-testing/) for this.
|
||||
4. The `cypress/results/testPasses.json` file will count, for each of the testfiles, how many times it was run, and how many times each of the testcases contained in it passed. If the attempts and passes numbers do not match, that specific testcase may be flaky.
|
||||
|
||||
For Playwright: WIP
|
||||
For Playwright: not currently supported — Playwright tests are run and re-run individually via `npm run test -- <spec>`, see `playwright/README.md`.
|
||||
|
||||
@@ -14,3 +14,6 @@ test/.eslintcache
|
||||
# build
|
||||
dist
|
||||
*.tsbuildinfo
|
||||
|
||||
# testcontainers ("full" mode) — generated per-run, see docs/testcontainers/testcontainers_plan.md
|
||||
.env.testcontainers
|
||||
|
||||
@@ -91,6 +91,7 @@ npm run show-report
|
||||
- Component abstractions for UI elements
|
||||
- Test utilities and fixtures
|
||||
- Server setup and management functions
|
||||
- Testcontainers orchestration (`lib/src/containers/`) for `testcontainers` mode (see Server Setup below)
|
||||
- Visual testing support
|
||||
|
||||
2. **`specs/` Directory**: Contains the actual test files organized by type:
|
||||
@@ -135,6 +136,11 @@ Tests can be configured through environment variables:
|
||||
- `PW_SLOWMO` - Add delay between actions in ms (default: 0)
|
||||
- `PW_WORKERS` - Number of parallel workers (default: 1)
|
||||
- `PERCY_TOKEN` - Authentication token for Percy visual testing service (required for Percy tests)
|
||||
- `PW_USE_TESTCONTAINERS` - Selects `testcontainers` mode, see Server Setup below (default: false)
|
||||
- `PW_TESTCONTAINERS_SERVICES` - Comma-separated additional services to start, e.g. `minio,openldap` (default: `minio,openldap,keycloak,elasticsearch`; set to an empty string to start none)
|
||||
- `PW_TESTCONTAINERS_REUSE` - Reuse containers across repeated local runs instead of recreating them; tear down explicitly with `npm run testcontainers:down` (default: true)
|
||||
- `SERVER_IMAGE` - Mattermost server image `testcontainers` mode starts (default: `mattermostdevelopment/mattermost-enterprise-edition:master`)
|
||||
- `MM_ENV` - Comma-separated `KEY=VALUE` server config overrides for `testcontainers` mode (default: none)
|
||||
|
||||
## Server Setup
|
||||
|
||||
@@ -146,10 +152,12 @@ Before running tests, a Mattermost server must be available. Two options:
|
||||
cd server && make run
|
||||
```
|
||||
|
||||
2. **Run using Docker** (recommended for testing):
|
||||
2. **Testcontainers** (recommended for testing, and what CI uses) — no separate step needed, Playwright starts and tears down the server + dependencies itself:
|
||||
```bash
|
||||
# Configure environment in e2e-tests/.ci/env
|
||||
cd e2e-tests && TEST=playwright make
|
||||
PW_USE_TESTCONTAINERS=true npm run test
|
||||
# Starts minio,openldap,keycloak,elasticsearch by default; add PW_TESTCONTAINERS_SERVICES=... to change (e.g. add opensearch,azurite, or set to "" to start none)
|
||||
# Containers are reused across runs by default; tear down with `npm run testcontainers:down` (or set PW_TESTCONTAINERS_REUSE=false for a self-cleaning one-off run)
|
||||
# `npm run testcontainers:up` brings the stack up (or confirms an existing one) without running any tests
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
@@ -17,30 +17,27 @@ cd webapp && make run
|
||||
cd server && make run-server
|
||||
```
|
||||
|
||||
**Option 2: Run using Docker (recommended for testing)**
|
||||
**Option 2: Testcontainers (recommended for testing, and what CI uses)**
|
||||
|
||||
No separate terminal or setup step needed — Playwright brings up Postgres, Inbucket, and the Mattermost server itself via [Testcontainers](https://node.testcontainers.org/), then tears them down after the run.
|
||||
|
||||
```bash
|
||||
# 1. Configure environment variables in e2e-tests/.ci/env
|
||||
# Create this file if it doesn't exist
|
||||
# Run with defaults (Postgres, Inbucket, Mattermost server, minio, openldap, keycloak, elasticsearch)
|
||||
PW_USE_TESTCONTAINERS=true npm run test -- login
|
||||
|
||||
# 2. Set the server image (optional)
|
||||
# To use the latest master image:
|
||||
SERVER_IMAGE="mattermostdevelopment/mattermost-enterprise-edition:master"
|
||||
# If not set, it will use the current commit: mattermostdevelopment/mattermost-enterprise-edition:$(git rev-parse --short=7 HEAD)
|
||||
# Note: The image must exist in Docker Hub at https://hub.docker.com/r/mattermostdevelopment/mattermost-enterprise-edition/tags
|
||||
# Change which additional services start, comma-separated (or "" to start none)
|
||||
PW_USE_TESTCONTAINERS=true PW_TESTCONTAINERS_SERVICES=minio,openldap npm run test
|
||||
|
||||
# 3. Add your license if needed
|
||||
MM_LICENSE=<your-license-key>
|
||||
# Pin a specific server image (defaults to mattermostdevelopment/mattermost-enterprise-edition:master)
|
||||
PW_USE_TESTCONTAINERS=true SERVER_IMAGE=mattermostdevelopment/mattermost-enterprise-edition:<tag> npm run test
|
||||
|
||||
# 4. For additional configuration options, see e2e-tests/README.md
|
||||
|
||||
# 5. Run the server and Playwright's smoke tests from the e2e-tests directory
|
||||
cd e2e-tests && TEST=playwright make
|
||||
# Pass arbitrary MM_* config overrides as comma-separated KEY=VALUE pairs
|
||||
PW_USE_TESTCONTAINERS=true MM_ENV=MM_LICENSE=<your-license-key> npm run test
|
||||
```
|
||||
|
||||
This approach uses the server's Docker image to create a consistent testing environment. It automatically configures the server with the necessary settings for Playwright tests and handles dependencies.
|
||||
Containers are reused across invocations by default (`PW_TESTCONTAINERS_REUSE=true`) instead of being recreated every run — tear the stack down explicitly when you're done with `npm run testcontainers:down`. Set `PW_TESTCONTAINERS_REUSE=false` for a one-off run that tears itself down when it finishes. Use `npm run testcontainers:up` to just bring the stack up (or confirm an existing one's still reachable) without running any tests.
|
||||
|
||||
`ENABLED_DOCKER_SERVICES` defaults to the base `postgres inbucket` set (plus the auto-added `playwright` and `webhook-interactions` services). Expand it only when a test needs an extra dependency (for example `minio` for file storage or `openldap` for LDAP).
|
||||
See `lib/README.md` for every available environment variable.
|
||||
|
||||
#### 2. Install dependencies and run the test.
|
||||
|
||||
|
||||
@@ -7,7 +7,14 @@ import eslintPlugin from '@mattermost/eslint-plugin';
|
||||
|
||||
export default [
|
||||
{
|
||||
ignores: ['**/node_modules', '**/dist', '**/playwright-report', '**/test-results', '**/results'],
|
||||
ignores: [
|
||||
'**/node_modules',
|
||||
'**/dist',
|
||||
'**/playwright-report',
|
||||
'**/test-results',
|
||||
'**/results',
|
||||
'lib/src/containers/assets/webhook/tests/**',
|
||||
],
|
||||
},
|
||||
...eslintPlugin.configs.base,
|
||||
{
|
||||
|
||||
@@ -1,21 +1,31 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {baseGlobalSetup, testConfig} from '@mattermost/playwright-lib';
|
||||
import chalk from 'chalk';
|
||||
|
||||
import {baseGlobalSetup, startStack, stopStack, testConfig} from '@mattermost/playwright-lib';
|
||||
|
||||
async function globalSetup() {
|
||||
try {
|
||||
// With PW_USE_TESTCONTAINERS=true, bring up the server + dependencies via Testcontainers
|
||||
// before pinging it. No-op otherwise, when a server is expected to already be running.
|
||||
await startStack();
|
||||
await baseGlobalSetup();
|
||||
} catch (error: unknown) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(error);
|
||||
throw new Error(
|
||||
`Global setup failed.\n\tEnsure the server at ${testConfig.baseURL} is running and accessible.\n\tPlease check the logs for more details.`,
|
||||
);
|
||||
console.error(chalk.cyan('[testcontainers]'), error);
|
||||
// Whatever startStack() managed to bring up (e.g. baseGlobalSetup() failed after the
|
||||
// stack itself came up fine) shouldn't linger just because we're about to throw.
|
||||
await stopStack();
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
const hint = testConfig.useTestContainers
|
||||
? 'Check the container named above and its logs under logs/.'
|
||||
: `Ensure the server at ${testConfig.baseURL} is running and accessible.`;
|
||||
throw new Error(chalk.red(`[testcontainers] Global setup failed: ${message}\n${hint}`));
|
||||
}
|
||||
|
||||
return function () {
|
||||
// placeholder for teardown setup
|
||||
return async function () {
|
||||
await stopStack();
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -139,6 +139,27 @@ All environment variables are optional with sensible defaults.
|
||||
| -------- | ------------------------------------ | ------- |
|
||||
| `CI` | Set automatically in CI environments | N/A |
|
||||
|
||||
#### Testcontainers
|
||||
|
||||
Selects `testcontainers` mode — Playwright brings up the server + dependencies itself via [Testcontainers](https://node.testcontainers.org/) — instead of the `external` mode default, which expects a server already running at `PW_BASE_URL`.
|
||||
|
||||
| Variable | Description | Default |
|
||||
| ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------ |
|
||||
| `PW_USE_TESTCONTAINERS` | Selects `testcontainers` mode | `false` |
|
||||
| `PW_TESTCONTAINERS_SERVICES` | Comma-separated additional services to start (`openldap`, `keycloak`, `elasticsearch`, `opensearch`, `minio`, `azurite`); set to an empty string to start none | `minio,openldap,keycloak,elasticsearch` |
|
||||
| `PW_TESTCONTAINERS_REUSE` | Reuse containers across repeated local runs instead of recreating them; tear down with `npm run testcontainers:down` (requires `testcontainers.reuse.enable=true` in `~/.testcontainers.properties`) | `true` |
|
||||
| `PW_TESTCONTAINERS_CONTAINER_RUNNER` | Set when the Playwright process itself runs inside a Docker container (e.g. CI), to join it to the Testcontainers network | `false` |
|
||||
| `SERVER_IMAGE` | Prebuilt Mattermost server image `testcontainers` mode starts | `mattermostdevelopment/mattermost-enterprise-edition:master` |
|
||||
| `MM_ENV` | Comma-separated `KEY=VALUE` server config overrides, merged over the test baseline | none |
|
||||
| `PW_LDAP_HOST` / `PW_LDAP_PORT` | OpenLDAP host/port (only used when `openldap` is started) | `localhost` / `389` |
|
||||
| `PW_KEYCLOAK_URL` | Keycloak URL (only used when `keycloak` is started) | `http://localhost:8484` |
|
||||
| `PW_ELASTICSEARCH_URL` | Elasticsearch URL (only used when `elasticsearch` is started) | `http://localhost:9200` |
|
||||
| `PW_OPENSEARCH_URL` | OpenSearch URL (only used when `opensearch` is started) | `http://localhost:9201` |
|
||||
| `PW_MINIO_URL` | Minio URL (only used when `minio` is started) | `http://localhost:9000` |
|
||||
| `PW_AZURITE_URL` | Azurite URL (only used when `azurite` is started) | `http://localhost:10000` |
|
||||
|
||||
In `testcontainers` mode, these host/port defaults are never actually used — Testcontainers always assigns its own dynamic port or network alias per run, so a `testcontainers`-mode run can never collide with a same-machine `external`-mode session using the fixed defaults above. Tear a reused stack down explicitly with `npm run testcontainers:down` (from the `playwright/` package).
|
||||
|
||||
## Accessibility Testing
|
||||
|
||||
The library includes built-in accessibility testing using [axe-core](https://github.com/dequelabs/axe-core):
|
||||
|
||||
@@ -44,17 +44,22 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@axe-core/playwright": "4.12.1",
|
||||
"@azure/storage-blob": "12.33.0",
|
||||
"@mattermost/client": "file:../../../webapp/platform/client",
|
||||
"@mattermost/types": "file:../../../webapp/platform/types",
|
||||
"@percy/cli": "1.32.2",
|
||||
"@percy/playwright": "1.1.0",
|
||||
"@testcontainers/postgresql": "12.0.4",
|
||||
"async-wait-until": "2.0.31",
|
||||
"axe-core": "4.12.1",
|
||||
"chalk": "5.6.2",
|
||||
"deepmerge": "4.3.1",
|
||||
"dotenv": "17.4.2",
|
||||
"ldapts": "9.0.0",
|
||||
"luxon": "3.7.2",
|
||||
"mime-types": "3.0.2",
|
||||
"minio": "8.0.7",
|
||||
"testcontainers": "12.0.4",
|
||||
"uuid": "14.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -18,7 +18,10 @@ export default {
|
||||
plugins: [
|
||||
typescript(),
|
||||
copy({
|
||||
targets: [{src: 'src/asset/**/*', dest: 'dist/asset'}], // Copy assets to dist/
|
||||
targets: [
|
||||
{src: 'src/asset/**/*', dest: 'dist/asset'}, // Copy assets to dist/
|
||||
{src: 'src/containers/assets/**/*', dest: 'dist/containers/assets'},
|
||||
],
|
||||
}),
|
||||
],
|
||||
external: [
|
||||
@@ -26,15 +29,22 @@ export default {
|
||||
'@mattermost/client',
|
||||
'@mattermost/types/config',
|
||||
'@axe-core/playwright',
|
||||
'@azure/storage-blob',
|
||||
'@percy/playwright',
|
||||
'@testcontainers/postgresql',
|
||||
'dotenv',
|
||||
'ldapts',
|
||||
'luxon',
|
||||
'minio',
|
||||
'node:child_process',
|
||||
'node:path',
|
||||
'node:fs',
|
||||
'node:fs/promises',
|
||||
'node:os',
|
||||
'node:url',
|
||||
'node:util',
|
||||
'mime-types',
|
||||
'testcontainers',
|
||||
'uuid',
|
||||
'async-wait-until',
|
||||
'chalk',
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
# Copied from server/build/Dockerfile.elasticsearch on 2026-07-19.
|
||||
ARG ELASTICSEARCH_VERSION=9.0.0
|
||||
FROM docker.elastic.co/elasticsearch/elasticsearch:${ELASTICSEARCH_VERSION}
|
||||
|
||||
RUN /usr/share/elasticsearch/bin/elasticsearch-plugin install --batch analysis-icu analysis-nori analysis-kuromoji analysis-smartcn
|
||||
@@ -0,0 +1,5 @@
|
||||
# Copied from server/build/Dockerfile.opensearch on 2026-07-19.
|
||||
ARG OPENSEARCH_VERSION=3.0.0
|
||||
FROM opensearchproject/opensearch:$OPENSEARCH_VERSION
|
||||
|
||||
RUN /usr/share/opensearch/bin/opensearch-plugin install analysis-icu analysis-nori analysis-kuromoji analysis-smartcn
|
||||
@@ -0,0 +1,13 @@
|
||||
# Vendored assets
|
||||
|
||||
These files are copied from `server/build/` in the Mattermost monorepo so that
|
||||
`@mattermost/playwright-lib`'s Testcontainers support is self-contained once published to npm
|
||||
(it can't reach outside its own package at runtime). If the source files change, these copies
|
||||
need to be refreshed manually — they are not symlinked or build-generated.
|
||||
|
||||
| File | Copied from | Date |
|
||||
| ---------------------------- | ------------------------------------------------ | ---------- |
|
||||
| `postgres.conf` | `server/build/docker/postgres.conf` | 2026-07-19 |
|
||||
| `keycloak-realm-export.json` | `server/build/docker/keycloak/realm-export.json` | 2026-07-19 |
|
||||
| `Dockerfile.elasticsearch` | `server/build/Dockerfile.elasticsearch` | 2026-07-19 |
|
||||
| `Dockerfile.opensearch` | `server/build/Dockerfile.opensearch` | 2026-07-19 |
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,9 @@
|
||||
# Copied from server/build/docker/postgres.conf on 2026-07-19.
|
||||
max_connections = 500
|
||||
listen_addresses = '*'
|
||||
fsync = off
|
||||
full_page_writes = off
|
||||
default_text_search_config = 'pg_catalog.english'
|
||||
commit_delay=1000
|
||||
logging_collector=off
|
||||
password_encryption = 'scram-sha-256'
|
||||
@@ -0,0 +1,20 @@
|
||||
# webhook_serve.js, utils/webhook_utils.js, and tests/plugins/post_message_as.js are vendored
|
||||
# copies of e2e-tests/cypress's files of the same name (shared sidecar, also used by Cypress) —
|
||||
# copied on 2026-07-20. Dependencies match e2e-tests/.ci/server.generate.sh's "playwright" Compose
|
||||
# service, just installed at build time instead of on every container start.
|
||||
FROM node:24-alpine
|
||||
|
||||
WORKDIR /webhook
|
||||
|
||||
RUN npm init -y >/dev/null && \
|
||||
npm install [email protected] [email protected] client-oauth2@github:larkox/js-client-oauth2#e24e2eb5dfcbbbb3a59d095e831dbe0012b0ac49
|
||||
|
||||
COPY webhook_serve.js ./webhook_serve.js
|
||||
COPY utils/ ./utils/
|
||||
COPY tests/plugins/post_message_as.js ./tests/plugins/post_message_as.js
|
||||
|
||||
RUN chown -R node:node /webhook
|
||||
USER node
|
||||
|
||||
EXPOSE 3000
|
||||
CMD ["node", "webhook_serve.js"]
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
const axios = require('axios');
|
||||
|
||||
module.exports = async ({sender, message, channelId, rootId, createAt = 0, baseUrl}) => {
|
||||
const loginResponse = await axios({
|
||||
url: `${baseUrl}/api/v4/users/login`,
|
||||
headers: {'X-Requested-With': 'XMLHttpRequest'},
|
||||
method: 'post',
|
||||
data: {login_id: sender.username, password: sender.password},
|
||||
});
|
||||
|
||||
const setCookie = loginResponse.headers['set-cookie'];
|
||||
let cookieString = '';
|
||||
setCookie.forEach((cookie) => {
|
||||
const nameAndValue = cookie.split(';')[0];
|
||||
cookieString += nameAndValue + ';';
|
||||
});
|
||||
|
||||
let response;
|
||||
try {
|
||||
response = await axios({
|
||||
url: `${baseUrl}/api/v4/posts`,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
Cookie: cookieString,
|
||||
},
|
||||
method: 'post',
|
||||
data: {
|
||||
channel_id: channelId,
|
||||
message,
|
||||
type: '',
|
||||
create_at: createAt,
|
||||
root_id: rootId,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
expect(Boolean(err)).to.equal(false);
|
||||
}
|
||||
|
||||
return {status: response.status, data: response.data};
|
||||
};
|
||||
@@ -0,0 +1,837 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
// Helper function to create dialog base structure
|
||||
function createDialog(triggerId, webhookBaseUrl, dialogConfig) {
|
||||
const baseDialog = {
|
||||
trigger_id: triggerId,
|
||||
url: `${webhookBaseUrl}/dialog_submit`,
|
||||
dialog: {
|
||||
callback_id: dialogConfig.callback_id,
|
||||
title: dialogConfig.title,
|
||||
submit_label: dialogConfig.submit_label || 'Submit',
|
||||
notify_on_cancel: true,
|
||||
...dialogConfig.dialog_props,
|
||||
elements: dialogConfig.elements || [],
|
||||
},
|
||||
};
|
||||
|
||||
if (dialogConfig.icon_url) {
|
||||
baseDialog.dialog.icon_url = dialogConfig.icon_url;
|
||||
}
|
||||
|
||||
if (dialogConfig.introduction_text) {
|
||||
baseDialog.dialog.introduction_text = dialogConfig.introduction_text;
|
||||
}
|
||||
|
||||
if (dialogConfig.state) {
|
||||
baseDialog.dialog.state = dialogConfig.state;
|
||||
}
|
||||
|
||||
if (dialogConfig.source_url) {
|
||||
baseDialog.dialog.source_url = dialogConfig.source_url;
|
||||
}
|
||||
|
||||
return baseDialog;
|
||||
}
|
||||
|
||||
// Helper function to create form response structure
|
||||
function createFormResponse(formConfig) {
|
||||
return {
|
||||
callback_id: formConfig.callback_id,
|
||||
title: formConfig.title,
|
||||
submit_label: formConfig.submit_label || 'Submit',
|
||||
notify_on_cancel: true,
|
||||
elements: formConfig.elements || [],
|
||||
...formConfig.form_props,
|
||||
};
|
||||
}
|
||||
|
||||
// Helper function to create common form elements
|
||||
function createElement(type, config) {
|
||||
const baseElement = {
|
||||
display_name: config.display_name,
|
||||
name: config.name,
|
||||
type,
|
||||
optional: config.optional || false,
|
||||
};
|
||||
|
||||
if (config.placeholder) {
|
||||
baseElement.placeholder = config.placeholder;
|
||||
}
|
||||
if (config.help_text) {
|
||||
baseElement.help_text = config.help_text;
|
||||
}
|
||||
if (config.default) {
|
||||
baseElement.default = config.default;
|
||||
}
|
||||
if (config.subtype) {
|
||||
baseElement.subtype = config.subtype;
|
||||
}
|
||||
if (config.min_length) {
|
||||
baseElement.min_length = config.min_length;
|
||||
}
|
||||
if (config.max_length) {
|
||||
baseElement.max_length = config.max_length;
|
||||
}
|
||||
if (config.data_source) {
|
||||
baseElement.data_source = config.data_source;
|
||||
}
|
||||
if (config.options) {
|
||||
baseElement.options = config.options;
|
||||
}
|
||||
if (config.refresh) {
|
||||
baseElement.refresh = config.refresh;
|
||||
}
|
||||
if (config.action_button) {
|
||||
baseElement.action_button = config.action_button;
|
||||
}
|
||||
|
||||
return baseElement;
|
||||
}
|
||||
|
||||
// Standard icon URL
|
||||
const STANDARD_ICON = 'https://mattermost.com/wp-content/uploads/2022/02/icon_WS.png';
|
||||
|
||||
// Dialog configurations
|
||||
const DIALOG_CONFIGS = {
|
||||
full: {
|
||||
callback_id: 'somecallbackid',
|
||||
title: 'Title for Full Dialog Test',
|
||||
icon_url: STANDARD_ICON,
|
||||
elements: [
|
||||
createElement('text', {
|
||||
display_name: 'Display Name',
|
||||
name: 'realname',
|
||||
default: 'default text',
|
||||
placeholder: 'placeholder',
|
||||
help_text: 'This a regular input in an interactive dialog triggered by a test integration.',
|
||||
}),
|
||||
createElement('text', {
|
||||
display_name: 'Email',
|
||||
name: 'someemail',
|
||||
subtype: 'email',
|
||||
placeholder: '[email protected]',
|
||||
help_text: 'This a regular email input in an interactive dialog triggered by a test integration.',
|
||||
}),
|
||||
createElement('text', {display_name: 'Number', name: 'somenumber', subtype: 'number'}),
|
||||
createElement('text', {
|
||||
display_name: 'Password',
|
||||
name: 'somepassword',
|
||||
subtype: 'password',
|
||||
default: 'p@ssW0rd',
|
||||
placeholder: 'placeholder',
|
||||
help_text: 'This a password input in an interactive dialog triggered by a test integration.',
|
||||
optional: true,
|
||||
}),
|
||||
createElement('textarea', {
|
||||
display_name: 'Display Name Long Text Area',
|
||||
name: 'realnametextarea',
|
||||
placeholder: 'placeholder',
|
||||
optional: true,
|
||||
min_length: 5,
|
||||
max_length: 100,
|
||||
}),
|
||||
createElement('select', {
|
||||
display_name: 'User Selector',
|
||||
name: 'someuserselector',
|
||||
placeholder: 'Select a user...',
|
||||
data_source: 'users',
|
||||
}),
|
||||
createElement('select', {
|
||||
display_name: 'Channel Selector',
|
||||
name: 'somechannelselector',
|
||||
placeholder: 'Select a channel...',
|
||||
help_text: 'Choose a channel from the list.',
|
||||
data_source: 'channels',
|
||||
optional: true,
|
||||
}),
|
||||
createElement('select', {
|
||||
display_name: 'Option Selector',
|
||||
name: 'someoptionselector',
|
||||
placeholder: 'Select an option...',
|
||||
options: [
|
||||
{text: 'Option1', value: 'opt1'},
|
||||
{text: 'Option2', value: 'opt2'},
|
||||
{text: 'Option3', value: 'opt3'},
|
||||
],
|
||||
}),
|
||||
createElement('radio', {
|
||||
display_name: 'Radio Option Selector',
|
||||
name: 'someradiooptions',
|
||||
help_text: '',
|
||||
options: [
|
||||
{text: 'Engineering', value: 'engineering'},
|
||||
{text: 'Sales', value: 'sales'},
|
||||
],
|
||||
}),
|
||||
createElement('bool', {
|
||||
display_name: 'Boolean Selector',
|
||||
name: 'boolean_input',
|
||||
placeholder: 'Was this modal helpful?',
|
||||
default: 'True',
|
||||
optional: true,
|
||||
help_text: 'This is the help text',
|
||||
}),
|
||||
],
|
||||
dialog_props: {state: 'somestate'},
|
||||
},
|
||||
|
||||
simple: {
|
||||
callback_id: 'somecallbackid',
|
||||
title: 'Title for Dialog Test without elements',
|
||||
icon_url: STANDARD_ICON,
|
||||
submit_label: 'Submit Test',
|
||||
dialog_props: {state: 'somestate'},
|
||||
},
|
||||
|
||||
userAndChannel: {
|
||||
callback_id: 'somecallbackid',
|
||||
title: 'Title for Dialog Test with user and channel element',
|
||||
icon_url: STANDARD_ICON,
|
||||
submit_label: 'Submit Test',
|
||||
elements: [
|
||||
createElement('select', {
|
||||
display_name: 'User Selector',
|
||||
name: 'someuserselector',
|
||||
placeholder: 'Select a user...',
|
||||
data_source: 'users',
|
||||
}),
|
||||
createElement('select', {
|
||||
display_name: 'Channel Selector',
|
||||
name: 'somechannelselector',
|
||||
placeholder: 'Select a channel...',
|
||||
help_text: 'Choose a channel from the list.',
|
||||
data_source: 'channels',
|
||||
optional: true,
|
||||
}),
|
||||
],
|
||||
dialog_props: {state: 'somestate'},
|
||||
},
|
||||
|
||||
boolean: {
|
||||
callback_id: 'somecallbackid',
|
||||
title: 'Title for Dialog Test with boolean element',
|
||||
icon_url: STANDARD_ICON,
|
||||
submit_label: 'Submit Test',
|
||||
elements: [
|
||||
createElement('bool', {
|
||||
display_name: 'Boolean Selector',
|
||||
name: 'boolean_input',
|
||||
placeholder: 'Was this modal helpful?',
|
||||
default: 'True',
|
||||
optional: true,
|
||||
help_text: 'This is the help text',
|
||||
}),
|
||||
],
|
||||
dialog_props: {state: 'somestate'},
|
||||
},
|
||||
|
||||
fieldRefresh: {
|
||||
callback_id: 'field_refresh_callback',
|
||||
title: 'Field Refresh Demo',
|
||||
introduction_text: 'Enter project name then select type to see different fields',
|
||||
elements: [
|
||||
createElement('text', {
|
||||
display_name: 'Project Name',
|
||||
name: 'project_name',
|
||||
placeholder: 'Enter project name',
|
||||
}),
|
||||
createElement('select', {
|
||||
display_name: 'Project Type',
|
||||
name: 'project_type',
|
||||
refresh: true,
|
||||
placeholder: 'Select project type...',
|
||||
options: [
|
||||
{text: 'Web Application', value: 'web'},
|
||||
{text: 'Mobile App', value: 'mobile'},
|
||||
{text: 'API Service', value: 'api'},
|
||||
],
|
||||
}),
|
||||
],
|
||||
},
|
||||
|
||||
multistepStep1: {
|
||||
callback_id: 'multistep_callback',
|
||||
title: 'Step 1 - Personal Info',
|
||||
introduction_text: 'Multi-step registration - Step 1 of 3',
|
||||
submit_label: 'Next Step',
|
||||
elements: [
|
||||
createElement('text', {
|
||||
display_name: 'First Name',
|
||||
name: 'first_name',
|
||||
placeholder: 'Enter your first name',
|
||||
}),
|
||||
createElement('text', {
|
||||
display_name: 'Email',
|
||||
name: 'email',
|
||||
subtype: 'email',
|
||||
placeholder: 'Enter your email address',
|
||||
}),
|
||||
],
|
||||
dialog_props: {state: 'step1'},
|
||||
},
|
||||
|
||||
multistepStep2: {
|
||||
callback_id: 'multistep_callback',
|
||||
title: 'Step 2 - Work Info',
|
||||
introduction_text: 'Multi-step registration - Step 2 of 3',
|
||||
submit_label: 'Next Step',
|
||||
elements: [
|
||||
createElement('select', {
|
||||
display_name: 'Department',
|
||||
name: 'department',
|
||||
placeholder: 'Select department...',
|
||||
options: [
|
||||
{text: 'Engineering', value: 'engineering'},
|
||||
{text: 'Marketing', value: 'marketing'},
|
||||
{text: 'Sales', value: 'sales'},
|
||||
],
|
||||
}),
|
||||
createElement('radio', {
|
||||
display_name: 'Experience Level',
|
||||
name: 'experience_level',
|
||||
options: [
|
||||
{text: 'Junior', value: 'junior'},
|
||||
{text: 'Mid-level', value: 'mid'},
|
||||
{text: 'Senior', value: 'senior'},
|
||||
],
|
||||
}),
|
||||
],
|
||||
form_props: {state: 'step2'},
|
||||
},
|
||||
|
||||
multistepStep3: {
|
||||
callback_id: 'multistep_callback',
|
||||
title: 'Step 3 - Final Details',
|
||||
introduction_text: 'Multi-step registration - Step 3 of 3',
|
||||
submit_label: 'Complete Registration',
|
||||
elements: [
|
||||
createElement('textarea', {
|
||||
display_name: 'Comments',
|
||||
name: 'comments',
|
||||
placeholder: 'Any additional comments...',
|
||||
optional: true,
|
||||
}),
|
||||
createElement('bool', {display_name: 'Terms & Conditions', name: 'terms_accepted'}),
|
||||
],
|
||||
form_props: {state: 'step3'},
|
||||
},
|
||||
|
||||
actionButtonParent: {
|
||||
callback_id: 'action_button_parent_callback',
|
||||
title: 'Parent Dialog with Action Button',
|
||||
elements: [],
|
||||
},
|
||||
|
||||
actionButtonChild: {
|
||||
callback_id: 'child_callback',
|
||||
title: 'Child Dialog',
|
||||
elements: [
|
||||
createElement('text', {
|
||||
display_name: 'Child Input',
|
||||
name: 'child_input',
|
||||
placeholder: 'Enter value',
|
||||
optional: true,
|
||||
}),
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
// Public API functions
|
||||
function getFullDialog(triggerId, webhookBaseUrl) {
|
||||
return createDialog(triggerId, webhookBaseUrl, DIALOG_CONFIGS.full);
|
||||
}
|
||||
|
||||
function getSimpleDialog(triggerId, webhookBaseUrl) {
|
||||
return createDialog(triggerId, webhookBaseUrl, DIALOG_CONFIGS.simple);
|
||||
}
|
||||
|
||||
function getUserAndChannelDialog(triggerId, webhookBaseUrl) {
|
||||
return createDialog(triggerId, webhookBaseUrl, DIALOG_CONFIGS.userAndChannel);
|
||||
}
|
||||
|
||||
function getBooleanDialog(triggerId, webhookBaseUrl) {
|
||||
return createDialog(triggerId, webhookBaseUrl, DIALOG_CONFIGS.boolean);
|
||||
}
|
||||
|
||||
function getFieldRefreshDialog(triggerId, webhookBaseUrl) {
|
||||
const config = {...DIALOG_CONFIGS.fieldRefresh};
|
||||
config.source_url = `${webhookBaseUrl}/field_refresh_source`;
|
||||
return createDialog(triggerId, webhookBaseUrl, config);
|
||||
}
|
||||
|
||||
function getMultistepStep1Dialog(triggerId, webhookBaseUrl) {
|
||||
return createDialog(triggerId, webhookBaseUrl, DIALOG_CONFIGS.multistepStep1);
|
||||
}
|
||||
|
||||
function getMultistepStep2Dialog(triggerId, webhookBaseUrl) {
|
||||
const config = {...DIALOG_CONFIGS.multistepStep2};
|
||||
config.dialog_props = {url: `${webhookBaseUrl}/dialog_submit`, ...config.form_props};
|
||||
return createFormResponse(config);
|
||||
}
|
||||
|
||||
function getMultistepStep3Dialog(triggerId, webhookBaseUrl) {
|
||||
const config = {...DIALOG_CONFIGS.multistepStep3};
|
||||
config.dialog_props = {url: `${webhookBaseUrl}/dialog_submit`, ...config.form_props};
|
||||
return createFormResponse(config);
|
||||
}
|
||||
|
||||
function getMultiSelectDialog(triggerId, webhookBaseUrl, includeDefaults = false) {
|
||||
return {
|
||||
trigger_id: triggerId,
|
||||
url: `${webhookBaseUrl}/dialog_submit`,
|
||||
dialog: {
|
||||
callback_id: 'somecallbackid',
|
||||
title: 'Title for Dialog Test with multiselect elements',
|
||||
icon_url: 'https://mattermost.com/wp-content/uploads/2022/02/icon_WS.png',
|
||||
submit_label: 'Submit Multiselect Test',
|
||||
notify_on_cancel: true,
|
||||
state: 'somestate',
|
||||
elements: [
|
||||
{
|
||||
display_name: 'Multi Option Selector',
|
||||
name: 'multiselect_options',
|
||||
type: 'select',
|
||||
multiselect: true,
|
||||
default: includeDefaults ? 'opt1,opt3' : '',
|
||||
placeholder: 'Select multiple options...',
|
||||
help_text: 'You can select multiple options from this list.',
|
||||
optional: false,
|
||||
min_length: 0,
|
||||
max_length: 0,
|
||||
data_source: '',
|
||||
options: [
|
||||
{
|
||||
text: 'Engineering',
|
||||
value: 'opt1',
|
||||
},
|
||||
{
|
||||
text: 'Sales',
|
||||
value: 'opt2',
|
||||
},
|
||||
{
|
||||
text: 'Marketing',
|
||||
value: 'opt3',
|
||||
},
|
||||
{
|
||||
text: 'Support',
|
||||
value: 'opt4',
|
||||
},
|
||||
{
|
||||
text: 'Product',
|
||||
value: 'opt5',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
display_name: 'Multi User Selector',
|
||||
name: 'multiselect_users',
|
||||
type: 'select',
|
||||
multiselect: true,
|
||||
default: '',
|
||||
placeholder: 'Select multiple users...',
|
||||
help_text: 'Choose multiple users from the team.',
|
||||
optional: false,
|
||||
min_length: 0,
|
||||
max_length: 0,
|
||||
data_source: 'users',
|
||||
options: null,
|
||||
},
|
||||
{
|
||||
display_name: 'Single Option Selector',
|
||||
name: 'single_select_options',
|
||||
type: 'select',
|
||||
multiselect: false,
|
||||
default: includeDefaults ? 'single2' : '',
|
||||
placeholder: 'Select one option...',
|
||||
help_text: 'This is a regular single-select for comparison.',
|
||||
optional: false,
|
||||
min_length: 0,
|
||||
max_length: 0,
|
||||
data_source: '',
|
||||
options: [
|
||||
{
|
||||
text: 'Single Option 1',
|
||||
value: 'single1',
|
||||
},
|
||||
{
|
||||
text: 'Single Option 2',
|
||||
value: 'single2',
|
||||
},
|
||||
{
|
||||
text: 'Single Option 3',
|
||||
value: 'single3',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function getDynamicSelectDialog(triggerId, webhookBaseUrl) {
|
||||
return {
|
||||
trigger_id: triggerId,
|
||||
url: `${webhookBaseUrl}/dialog_submit`,
|
||||
dialog: {
|
||||
callback_id: 'somecallbackid',
|
||||
title: 'Title for Dialog Test with dynamic select element',
|
||||
icon_url: 'https://mattermost.com/wp-content/uploads/2022/02/icon_WS.png',
|
||||
submit_label: 'Submit Dynamic Select Test',
|
||||
notify_on_cancel: true,
|
||||
state: 'somestate',
|
||||
elements: [
|
||||
{
|
||||
display_name: 'Dynamic Role Selector',
|
||||
name: 'dynamic_role_selector',
|
||||
type: 'select',
|
||||
data_source: 'dynamic',
|
||||
data_source_url: `${webhookBaseUrl}/dynamic_select_source`,
|
||||
default: '',
|
||||
placeholder: 'Search for a role...',
|
||||
help_text: 'Start typing to search for available roles. Options are loaded dynamically.',
|
||||
optional: false,
|
||||
min_length: 0,
|
||||
max_length: 0,
|
||||
},
|
||||
{
|
||||
display_name: 'Optional Dynamic Selector',
|
||||
name: 'optional_dynamic_selector',
|
||||
type: 'select',
|
||||
data_source: 'dynamic',
|
||||
data_source_url: `${webhookBaseUrl}/dynamic_select_source`,
|
||||
default: 'backend_eng',
|
||||
placeholder: 'Search for another role...',
|
||||
help_text: 'This field is optional and has a default value.',
|
||||
optional: true,
|
||||
min_length: 0,
|
||||
max_length: 0,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Basic date field test - MM-T2530A
|
||||
function getBasicDateDialog(triggerId, webhookBaseUrl) {
|
||||
return {
|
||||
trigger_id: triggerId,
|
||||
url: `${webhookBaseUrl}/datetime_dialog_submit`,
|
||||
dialog: {
|
||||
callback_id: 'basic_date_callback',
|
||||
title: 'DateTime Fields Test',
|
||||
icon_url: 'https://mattermost.com/wp-content/uploads/2022/02/icon_WS.png',
|
||||
elements: [
|
||||
{
|
||||
display_name: 'Event Date',
|
||||
name: 'event_date',
|
||||
type: 'date',
|
||||
default: '',
|
||||
placeholder: 'Select a date',
|
||||
help_text: 'Select the date for your event',
|
||||
optional: false,
|
||||
},
|
||||
],
|
||||
submit_label: 'Submit',
|
||||
notify_on_cancel: true,
|
||||
state: 'datetime_state',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Basic datetime field test - MM-T2530B
|
||||
function getBasicDateTimeDialog(triggerId, webhookBaseUrl) {
|
||||
return {
|
||||
trigger_id: triggerId,
|
||||
url: `${webhookBaseUrl}/datetime_dialog_submit`,
|
||||
dialog: {
|
||||
callback_id: 'basic_datetime_callback',
|
||||
title: 'DateTime Fields Test',
|
||||
icon_url: 'https://mattermost.com/wp-content/uploads/2022/02/icon_WS.png',
|
||||
elements: [
|
||||
{
|
||||
display_name: 'Event Date',
|
||||
name: 'event_date',
|
||||
type: 'date',
|
||||
default: '',
|
||||
placeholder: 'Select a date',
|
||||
help_text: 'Select the date for your event',
|
||||
optional: false,
|
||||
},
|
||||
{
|
||||
display_name: 'Meeting Time',
|
||||
name: 'meeting_time',
|
||||
type: 'datetime',
|
||||
default: '',
|
||||
placeholder: 'Select date and time',
|
||||
help_text: 'Select the date and time for your meeting',
|
||||
optional: false,
|
||||
time_interval: 60,
|
||||
},
|
||||
],
|
||||
submit_label: 'Submit',
|
||||
notify_on_cancel: true,
|
||||
state: 'datetime_state',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Date field with min_date constraint - MM-T2530C
|
||||
function getMinDateConstraintDialog(triggerId, webhookBaseUrl) {
|
||||
return {
|
||||
trigger_id: triggerId,
|
||||
url: `${webhookBaseUrl}/datetime_dialog_submit`,
|
||||
dialog: {
|
||||
callback_id: 'mindate_callback',
|
||||
title: 'DateTime Fields Test',
|
||||
icon_url: 'https://mattermost.com/wp-content/uploads/2022/02/icon_WS.png',
|
||||
elements: [
|
||||
{
|
||||
display_name: 'Future Date Only',
|
||||
name: 'future_date',
|
||||
type: 'date',
|
||||
default: '',
|
||||
placeholder: 'Select a future date',
|
||||
help_text: 'Must be today or later',
|
||||
optional: true,
|
||||
min_date: 'today',
|
||||
},
|
||||
],
|
||||
submit_label: 'Submit',
|
||||
notify_on_cancel: true,
|
||||
state: 'datetime_state',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// DateTime field with custom time interval - MM-T2530D
|
||||
function getCustomIntervalDialog(triggerId, webhookBaseUrl) {
|
||||
return {
|
||||
trigger_id: triggerId,
|
||||
url: `${webhookBaseUrl}/datetime_dialog_submit`,
|
||||
dialog: {
|
||||
callback_id: 'interval_callback',
|
||||
title: 'DateTime Fields Test',
|
||||
icon_url: 'https://mattermost.com/wp-content/uploads/2022/02/icon_WS.png',
|
||||
elements: [
|
||||
{
|
||||
display_name: 'Custom Interval Time',
|
||||
name: 'interval_time',
|
||||
type: 'datetime',
|
||||
default: '',
|
||||
placeholder: 'Select time (30min intervals)',
|
||||
help_text: 'Time picker with 30-minute intervals',
|
||||
optional: true,
|
||||
time_interval: 30,
|
||||
},
|
||||
],
|
||||
submit_label: 'Submit',
|
||||
notify_on_cancel: true,
|
||||
state: 'datetime_state',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Relative date values test - MM-T2530F
|
||||
function getRelativeDateDialog(triggerId, webhookBaseUrl) {
|
||||
return {
|
||||
trigger_id: triggerId,
|
||||
url: `${webhookBaseUrl}/datetime_dialog_submit`,
|
||||
dialog: {
|
||||
callback_id: 'relative_callback',
|
||||
title: 'DateTime Fields Test',
|
||||
icon_url: 'https://mattermost.com/wp-content/uploads/2022/02/icon_WS.png',
|
||||
elements: [
|
||||
{
|
||||
display_name: 'Relative Date Example',
|
||||
name: 'relative_date',
|
||||
type: 'date',
|
||||
default: 'today',
|
||||
placeholder: 'Today by default',
|
||||
help_text: 'Defaults to today using relative date',
|
||||
optional: true,
|
||||
},
|
||||
{
|
||||
display_name: 'Relative DateTime Example',
|
||||
name: 'relative_datetime',
|
||||
type: 'datetime',
|
||||
default: '+1d',
|
||||
placeholder: 'Tomorrow by default',
|
||||
help_text: 'Defaults to tomorrow using relative date',
|
||||
optional: true,
|
||||
},
|
||||
],
|
||||
submit_label: 'Submit',
|
||||
notify_on_cancel: true,
|
||||
state: 'datetime_state',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Legacy function for backward compatibility - returns basic datetime dialog
|
||||
function getDateTimeDialog(triggerId, webhookBaseUrl) {
|
||||
return getBasicDateTimeDialog(triggerId, webhookBaseUrl);
|
||||
}
|
||||
|
||||
function getTimezoneManualDialog(triggerId, webhookBaseUrl) {
|
||||
return createDialog(triggerId, webhookBaseUrl, {
|
||||
callback_id: 'timezone_manual',
|
||||
title: 'Timezone & Manual Entry Demo',
|
||||
introduction_text:
|
||||
'**Timezone & Manual Entry Demo**\n\n' +
|
||||
'This dialog demonstrates timezone support and manual time entry features.',
|
||||
elements: [
|
||||
{
|
||||
display_name: 'Your Local Time (Manual Entry)',
|
||||
name: 'local_manual',
|
||||
type: 'datetime',
|
||||
help_text: 'Type any time: 9am, 14:30, 3:45pm - no rounding',
|
||||
datetime_config: {
|
||||
manual_time_entry: true,
|
||||
},
|
||||
optional: true,
|
||||
},
|
||||
{
|
||||
display_name: 'London Office Hours (Dropdown)',
|
||||
name: 'london_dropdown',
|
||||
type: 'datetime',
|
||||
help_text: 'Times shown in GMT - select from 60 min intervals',
|
||||
datetime_config: {
|
||||
location_timezone: 'Europe/London',
|
||||
time_interval: 60,
|
||||
},
|
||||
optional: true,
|
||||
},
|
||||
{
|
||||
display_name: 'London Office Hours (Manual Entry)',
|
||||
name: 'london_manual',
|
||||
type: 'datetime',
|
||||
help_text: 'Type time in GMT: 9am, 14:30, 3:45pm - no rounding',
|
||||
datetime_config: {
|
||||
location_timezone: 'Europe/London',
|
||||
manual_time_entry: true,
|
||||
},
|
||||
optional: true,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
function getFileUploadDialog(triggerId, webhookBaseUrl) {
|
||||
return {
|
||||
trigger_id: triggerId,
|
||||
url: `${webhookBaseUrl}/dialog_submit`,
|
||||
dialog: {
|
||||
callback_id: 'somecallbackid',
|
||||
title: 'Title for Dialog Test with file upload element',
|
||||
icon_url: 'https://mattermost.com/wp-content/uploads/2022/02/icon_WS.png',
|
||||
submit_label: 'Submit File Upload Test',
|
||||
notify_on_cancel: true,
|
||||
state: 'somestate',
|
||||
elements: [
|
||||
{
|
||||
display_name: 'Upload Single Document',
|
||||
name: 'single_document',
|
||||
type: 'file',
|
||||
placeholder: 'Select one document...',
|
||||
help_text: 'Upload a single document (replaces previous selection).',
|
||||
optional: false,
|
||||
},
|
||||
{
|
||||
display_name: 'Upload Multiple Files',
|
||||
name: 'multiple_files',
|
||||
type: 'file',
|
||||
allow_multiple: true,
|
||||
placeholder: 'Select multiple files...',
|
||||
help_text: 'Upload multiple files (can select and add more).',
|
||||
optional: false,
|
||||
},
|
||||
{
|
||||
display_name: 'Description',
|
||||
name: 'description',
|
||||
type: 'textarea',
|
||||
subtype: '',
|
||||
default: '',
|
||||
placeholder: 'Describe the uploaded files...',
|
||||
help_text: 'Provide a description for the uploaded files.',
|
||||
optional: true,
|
||||
min_length: 0,
|
||||
max_length: 500,
|
||||
data_source: '',
|
||||
options: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function getActionButtonParentDialog(triggerId, webhookBaseUrl) {
|
||||
const config = {
|
||||
...DIALOG_CONFIGS.actionButtonParent,
|
||||
elements: [
|
||||
createElement('text', {
|
||||
display_name: 'Your Name',
|
||||
name: 'your_name',
|
||||
placeholder: 'Enter your name',
|
||||
optional: true,
|
||||
}),
|
||||
|
||||
// Two action buttons on the same dialog. Each carries a distinct
|
||||
// context.source so the child dialog can reflect which one was pressed.
|
||||
createElement('action_button', {
|
||||
display_name: 'Open Details',
|
||||
name: 'open_details',
|
||||
action_button: {
|
||||
url: `${webhookBaseUrl}/dialog/open_child`,
|
||||
context: {source: 'Details'},
|
||||
},
|
||||
}),
|
||||
createElement('action_button', {
|
||||
display_name: 'Open Summary',
|
||||
name: 'open_summary',
|
||||
action_button: {
|
||||
url: `${webhookBaseUrl}/dialog/open_child`,
|
||||
context: {source: 'Summary'},
|
||||
},
|
||||
}),
|
||||
],
|
||||
};
|
||||
return createDialog(triggerId, webhookBaseUrl, config);
|
||||
}
|
||||
|
||||
// `source` comes from the pressed action button's context.source and is reflected
|
||||
// in the child dialog's title and introduction text, so a test can verify which
|
||||
// button opened it.
|
||||
function getActionButtonChildDialog(triggerId, webhookBaseUrl, source) {
|
||||
const label = source || 'Unknown';
|
||||
const config = {
|
||||
...DIALOG_CONFIGS.actionButtonChild,
|
||||
title: `${label} Dialog`,
|
||||
introduction_text: `This child dialog was opened from the "${label}" action button.`,
|
||||
};
|
||||
return createDialog(triggerId, webhookBaseUrl, config);
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
getFullDialog,
|
||||
getSimpleDialog,
|
||||
getUserAndChannelDialog,
|
||||
getBooleanDialog,
|
||||
getFieldRefreshDialog,
|
||||
getMultistepStep1Dialog,
|
||||
getMultistepStep2Dialog,
|
||||
getMultistepStep3Dialog,
|
||||
getMultiSelectDialog,
|
||||
getDynamicSelectDialog,
|
||||
getDateTimeDialog,
|
||||
getBasicDateDialog,
|
||||
getBasicDateTimeDialog,
|
||||
getMinDateConstraintDialog,
|
||||
getCustomIntervalDialog,
|
||||
getRelativeDateDialog,
|
||||
getTimezoneManualDialog,
|
||||
getFileUploadDialog,
|
||||
getActionButtonParentDialog,
|
||||
getActionButtonChildDialog,
|
||||
};
|
||||
@@ -0,0 +1,770 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
/* eslint-disable no-console */
|
||||
|
||||
const express = require('express');
|
||||
const axios = require('axios');
|
||||
const ClientOAuth2 = require('client-oauth2');
|
||||
|
||||
const webhookUtils = require('./utils/webhook_utils');
|
||||
const postMessageAs = require('./tests/plugins/post_message_as');
|
||||
|
||||
const port = 3000;
|
||||
|
||||
const server = express();
|
||||
server.use(express.json());
|
||||
server.use(express.urlencoded({extended: true}));
|
||||
|
||||
process.title = process.argv[2];
|
||||
|
||||
server.get('/', ping);
|
||||
server.post('/setup', doSetup);
|
||||
server.post('/message_menus', postMessageMenus);
|
||||
server.post('/dialog_request', onDialogRequest);
|
||||
server.post('/simple_dialog_request', onSimpleDialogRequest);
|
||||
server.post('/user_and_channel_dialog_request', onUserAndChannelDialogRequest);
|
||||
server.post('/dialog_submit', onDialogSubmit);
|
||||
server.post('/boolean_dialog_request', onBooleanDialogRequest);
|
||||
server.post('/multiselect_dialog_request', onMultiSelectDialogRequest);
|
||||
server.post('/dynamic_select_dialog_request', onDynamicSelectDialogRequest);
|
||||
server.post('/file_upload_dialog_request', onFileUploadDialogRequest);
|
||||
server.post('/dynamic_select_source', onDynamicSelectSource);
|
||||
server.post('/dialog/field-refresh', onFieldRefreshDialogRequest);
|
||||
server.post('/dialog/multistep', onMultistepDialogRequest);
|
||||
server.post('/dialog/action_button_request', onActionButtonDialogRequest);
|
||||
server.post('/dialog/open_child', onOpenChildDialog);
|
||||
server.post('/field_refresh_source', onFieldRefreshSource);
|
||||
server.post('/datetime_dialog_request', onDateTimeDialogRequest);
|
||||
server.post('/datetime_dialog_submit', onDateTimeDialogSubmit);
|
||||
server.post('/slack_compatible_message_response', postSlackCompatibleMessageResponse);
|
||||
server.post('/mm_blocks_integration', postMmBlocksIntegration);
|
||||
server.post('/mm_blocks_integration_update', postMmBlocksIntegrationUpdate);
|
||||
server.post('/mm_blocks_integration_static_select', postMmBlocksIntegrationStaticSelect);
|
||||
server.post('/mm_blocks_integration_echo_query', postMmBlocksIntegrationEchoQuery);
|
||||
server.post('/mm_blocks_integration_echo_context', postMmBlocksIntegrationEchoContext);
|
||||
server.post('/send_message_to_channel', postSendMessageToChannel);
|
||||
server.post('/post_outgoing_webhook', postOutgoingWebhook);
|
||||
server.post('/send_oauth_credentials', postSendOauthCredentials);
|
||||
server.get('/start_oauth', getStartOAuth);
|
||||
server.get('/complete_oauth', getCompleteOauth);
|
||||
server.post('/post_oauth_message', postOAuthMessage);
|
||||
|
||||
server.listen(port, (err) => {
|
||||
if (err) {
|
||||
console.error(err);
|
||||
throw err;
|
||||
}
|
||||
console.log(`Webhook test server listening on port ${port}!`);
|
||||
});
|
||||
|
||||
function ping(req, res) {
|
||||
return res.json({
|
||||
message: "I'm alive!",
|
||||
endpoints: [
|
||||
'GET /',
|
||||
'POST /setup',
|
||||
'POST /message_menus',
|
||||
'POST /dialog_request',
|
||||
'POST /simple_dialog_request',
|
||||
'POST /user_and_channel_dialog_request',
|
||||
'POST /dialog_submit',
|
||||
'POST /boolean_dialog_request',
|
||||
'POST /multiselect_dialog_request',
|
||||
'POST /dynamic_select_dialog_request',
|
||||
'POST /file_upload_dialog_request',
|
||||
'POST /dynamic_select_source',
|
||||
'POST /dialog/field-refresh',
|
||||
'POST /dialog/multistep',
|
||||
'POST /dialog/action_button_request',
|
||||
'POST /dialog/open_child',
|
||||
'POST /field_refresh_source',
|
||||
'POST /datetime_dialog_request',
|
||||
'POST /datetime_dialog_submit',
|
||||
'POST /slack_compatible_message_response',
|
||||
'POST /mm_blocks_integration',
|
||||
'POST /mm_blocks_integration_update',
|
||||
'POST /mm_blocks_integration_static_select',
|
||||
'POST /mm_blocks_integration_echo_query',
|
||||
'POST /mm_blocks_integration_echo_context',
|
||||
'POST /send_message_to_channel',
|
||||
'POST /post_outgoing_webhook',
|
||||
'POST /send_oauth_credentials',
|
||||
'GET /start_oauth',
|
||||
'GET /complete_oauth',
|
||||
'POST /post_oauth_message',
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
// Set base URLs and credential to be accessible by any endpoint
|
||||
let baseUrl;
|
||||
let webhookBaseUrl;
|
||||
let adminUsername;
|
||||
let adminPassword;
|
||||
function doSetup(req, res) {
|
||||
baseUrl = req.body.baseUrl;
|
||||
webhookBaseUrl = req.body.webhookBaseUrl;
|
||||
adminUsername = req.body.adminUsername;
|
||||
adminPassword = req.body.adminPassword;
|
||||
|
||||
return res.status(201).send('Successfully setup the new base URLs and credential.');
|
||||
}
|
||||
|
||||
let client;
|
||||
let authedUser;
|
||||
function postSendOauthCredentials(req, res) {
|
||||
const {appID, appSecret} = req.body;
|
||||
client = new ClientOAuth2({
|
||||
clientId: appID,
|
||||
clientSecret: appSecret,
|
||||
authorizationUri: `${baseUrl}/oauth/authorize`,
|
||||
accessTokenUri: `${baseUrl}/oauth/access_token`,
|
||||
redirectUri: `${webhookBaseUrl}/complete_oauth`,
|
||||
});
|
||||
return res.status(200).send('OK');
|
||||
}
|
||||
|
||||
function getStartOAuth(req, res) {
|
||||
return res.redirect(client.code.getUri());
|
||||
}
|
||||
|
||||
function getCompleteOauth(req, res) {
|
||||
client.code
|
||||
.getToken(req.originalUrl)
|
||||
.then((user) => {
|
||||
authedUser = user;
|
||||
return res.status(200).send('OK');
|
||||
})
|
||||
.catch((reason) => {
|
||||
return res.status(reason.status).send(reason);
|
||||
});
|
||||
}
|
||||
|
||||
async function postOAuthMessage(req, res) {
|
||||
const {channelId, message, rootId, createAt} = req.body;
|
||||
const apiUrl = `${baseUrl}/api/v4/posts`;
|
||||
authedUser.sign({
|
||||
method: 'post',
|
||||
url: apiUrl,
|
||||
});
|
||||
try {
|
||||
await axios({
|
||||
url: apiUrl,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Requested-With': 'XMLHttpRequest',
|
||||
Authorization: 'Bearer ' + authedUser.accessToken,
|
||||
},
|
||||
method: 'post',
|
||||
data: {
|
||||
channel_id: channelId,
|
||||
message,
|
||||
type: '',
|
||||
create_at: createAt,
|
||||
root_id: rootId,
|
||||
},
|
||||
});
|
||||
} catch {
|
||||
// Do nothing
|
||||
}
|
||||
return res.status(200).send('OK');
|
||||
}
|
||||
|
||||
function postSlackCompatibleMessageResponse(req, res) {
|
||||
const {spoiler, skipSlackParsing} = req.body.context;
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
return res.json({
|
||||
ephemeral_text: spoiler,
|
||||
skip_slack_parsing: skipSlackParsing,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Mattermost mm_blocks external actions POST the same integration envelope as legacy message buttons.
|
||||
* @see model.PostActionIntegrationResponse
|
||||
*/
|
||||
function postMmBlocksIntegration(req, res) {
|
||||
const userName = req.body && req.body.user_name ? req.body.user_name : 'unknown';
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
return res.status(200).json({
|
||||
ephemeral_text: `Playwright mm_blocks integration OK (user: ${userName}).`,
|
||||
skip_slack_parsing: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a PostActionIntegrationResponse update so the interactive post is edited in-place
|
||||
* (persisted webhook post or ephemeral mm_blocks post).
|
||||
*/
|
||||
function postMmBlocksIntegrationUpdate(req, res) {
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
return res.status(200).json({
|
||||
update: {
|
||||
message: 'E2E mm_blocks post updated (message field).',
|
||||
props: {
|
||||
mm_blocks: [
|
||||
{
|
||||
type: 'text',
|
||||
text: 'PLAYWRIGHT_MM_BLOCKS_UPDATED',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
skip_slack_parsing: true,
|
||||
});
|
||||
}
|
||||
|
||||
/** Echoes URL query parameters Mattermost merged onto the integration request (action query + block query). */
|
||||
function postMmBlocksIntegrationEchoQuery(req, res) {
|
||||
const entries = Object.keys(req.query || {})
|
||||
.sort()
|
||||
.map((k) => `${k}=${String(req.query[k])}`);
|
||||
const summary = entries.join('&');
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
return res.status(200).json({
|
||||
ephemeral_text: `Playwright mm_blocks query OK (${summary})`,
|
||||
skip_slack_parsing: true,
|
||||
});
|
||||
}
|
||||
|
||||
/** Echoes `context.test_marker` from the Mattermost integration POST body for mm_blocks external actions. */
|
||||
function postMmBlocksIntegrationEchoContext(req, res) {
|
||||
const ctx = (req.body && req.body.context) || {};
|
||||
const marker = typeof ctx.test_marker === 'string' ? ctx.test_marker : JSON.stringify(ctx.test_marker ?? null);
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
return res.status(200).json({
|
||||
ephemeral_text: `Playwright mm_blocks context OK (test_marker: ${marker}).`,
|
||||
skip_slack_parsing: true,
|
||||
});
|
||||
}
|
||||
|
||||
/** Echoes `context.selected_option` from the Mattermost integration POST for mm_blocks static_select. */
|
||||
function postMmBlocksIntegrationStaticSelect(req, res) {
|
||||
const selected = req.body && req.body.context && req.body.context.selected_option;
|
||||
const label = typeof selected === 'string' ? selected : JSON.stringify(selected ?? null);
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
return res.status(200).json({
|
||||
ephemeral_text: `Playwright mm_blocks static_select OK (selected_option: ${label}).`,
|
||||
skip_slack_parsing: true,
|
||||
});
|
||||
}
|
||||
|
||||
function postMessageMenus(req, res) {
|
||||
let responseData = {};
|
||||
const {body} = req;
|
||||
if (body && body.context.action === 'do_something') {
|
||||
responseData = {
|
||||
ephemeral_text: `Ephemeral | ${body.type} ${body.data_source} option: ${body.context.selected_option}`,
|
||||
};
|
||||
}
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
return res.json(responseData);
|
||||
}
|
||||
|
||||
async function openDialog(dialog) {
|
||||
// Callers invoke this fire-and-forget (no await/catch), so any rejection here
|
||||
// would become an unhandled rejection and crash the whole webhook process.
|
||||
// Guard against a missing baseUrl (set by /setup) and swallow request errors.
|
||||
if (!baseUrl) {
|
||||
console.error('openDialog called before /setup ran — baseUrl is not set; skipping dialog open');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await axios({
|
||||
method: 'post',
|
||||
url: `${baseUrl}/api/v4/actions/dialogs/open`,
|
||||
data: dialog,
|
||||
});
|
||||
} catch (err) {
|
||||
const status = err.response && err.response.status;
|
||||
const body = err.response && err.response.data;
|
||||
console.error(
|
||||
'openDialog request failed:',
|
||||
status || err.code || err.message,
|
||||
body ? JSON.stringify(body) : '',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function onDialogRequest(req, res) {
|
||||
const {body} = req;
|
||||
if (body.trigger_id) {
|
||||
const dialog = webhookUtils.getFullDialog(body.trigger_id, webhookBaseUrl);
|
||||
openDialog(dialog);
|
||||
}
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
return res.json({text: 'Full dialog triggered via slash command!'});
|
||||
}
|
||||
|
||||
function onSimpleDialogRequest(req, res) {
|
||||
const {body} = req;
|
||||
if (body.trigger_id) {
|
||||
const dialog = webhookUtils.getSimpleDialog(body.trigger_id, webhookBaseUrl);
|
||||
openDialog(dialog);
|
||||
}
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
return res.json({text: 'Simple dialog triggered via slash command!'});
|
||||
}
|
||||
|
||||
function onUserAndChannelDialogRequest(req, res) {
|
||||
const {body} = req;
|
||||
if (body.trigger_id) {
|
||||
const dialog = webhookUtils.getUserAndChannelDialog(body.trigger_id, webhookBaseUrl);
|
||||
openDialog(dialog);
|
||||
}
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
return res.json({text: 'Simple dialog triggered via slash command!'});
|
||||
}
|
||||
|
||||
function onBooleanDialogRequest(req, res) {
|
||||
const {body} = req;
|
||||
if (body.trigger_id) {
|
||||
const dialog = webhookUtils.getBooleanDialog(body.trigger_id, webhookBaseUrl);
|
||||
openDialog(dialog);
|
||||
}
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
return res.json({text: 'Simple dialog triggered via slash command!'});
|
||||
}
|
||||
|
||||
function onMultiSelectDialogRequest(req, res) {
|
||||
const {body} = req;
|
||||
if (body.trigger_id) {
|
||||
// Check URL parameters or body for includeDefaults flag
|
||||
const includeDefaults = req.query.includeDefaults === 'true' || req.query.includeDefaults === true;
|
||||
const dialog = webhookUtils.getMultiSelectDialog(body.trigger_id, webhookBaseUrl, includeDefaults);
|
||||
openDialog(dialog);
|
||||
}
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
return res.json({text: 'Multiselect dialog triggered via slash command!'});
|
||||
}
|
||||
|
||||
function onDynamicSelectDialogRequest(req, res) {
|
||||
const {body} = req;
|
||||
if (body.trigger_id) {
|
||||
const dialog = webhookUtils.getDynamicSelectDialog(body.trigger_id, webhookBaseUrl);
|
||||
openDialog(dialog);
|
||||
}
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
return res.json({text: 'Dynamic select dialog triggered via slash command!'});
|
||||
}
|
||||
|
||||
function onFileUploadDialogRequest(req, res) {
|
||||
const {body} = req;
|
||||
if (body.trigger_id) {
|
||||
const dialog = webhookUtils.getFileUploadDialog(body.trigger_id, webhookBaseUrl);
|
||||
openDialog(dialog);
|
||||
}
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
return res.json({text: 'File upload dialog triggered via slash command!'});
|
||||
}
|
||||
|
||||
function onDynamicSelectSource(req, res) {
|
||||
const {body} = req;
|
||||
|
||||
// Simulate dynamic options based on search text
|
||||
const searchText = (body.submission.query || '').toLowerCase();
|
||||
|
||||
const allOptions = [
|
||||
{text: 'Backend Engineer', value: 'backend_eng'},
|
||||
{text: 'Frontend Engineer', value: 'frontend_eng'},
|
||||
{text: 'Full Stack Engineer', value: 'fullstack_eng'},
|
||||
{text: 'DevOps Engineer', value: 'devops_eng'},
|
||||
{text: 'QA Engineer', value: 'qa_eng'},
|
||||
{text: 'Product Manager', value: 'product_mgr'},
|
||||
{text: 'Engineering Manager', value: 'eng_mgr'},
|
||||
{text: 'Senior Backend Engineer', value: 'sr_backend_eng'},
|
||||
{text: 'Senior Frontend Engineer', value: 'sr_frontend_eng'},
|
||||
{text: 'Principal Engineer', value: 'principal_eng'},
|
||||
{text: 'Staff Engineer', value: 'staff_eng'},
|
||||
{text: 'Technical Lead', value: 'tech_lead'},
|
||||
];
|
||||
|
||||
// Filter options based on search text
|
||||
const filteredOptions = searchText
|
||||
? allOptions.filter(
|
||||
(option) =>
|
||||
option.text.toLowerCase().includes(searchText) || option.value.toLowerCase().includes(searchText),
|
||||
)
|
||||
: allOptions.slice(0, 6); // Limit to first 6 if no search
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
return res.json({
|
||||
items: filteredOptions,
|
||||
});
|
||||
}
|
||||
|
||||
function onDateTimeDialogRequest(req, res) {
|
||||
const {body} = req;
|
||||
if (body.trigger_id) {
|
||||
let dialog;
|
||||
const command = body.text ? body.text.trim() : '';
|
||||
|
||||
// Use focused dialog functions based on command parameter
|
||||
switch (command) {
|
||||
case 'basic':
|
||||
dialog = webhookUtils.getBasicDateDialog(body.trigger_id, webhookBaseUrl);
|
||||
break;
|
||||
case 'mindate':
|
||||
dialog = webhookUtils.getMinDateConstraintDialog(body.trigger_id, webhookBaseUrl);
|
||||
break;
|
||||
case 'interval':
|
||||
dialog = webhookUtils.getCustomIntervalDialog(body.trigger_id, webhookBaseUrl);
|
||||
break;
|
||||
case 'relative':
|
||||
dialog = webhookUtils.getRelativeDateDialog(body.trigger_id, webhookBaseUrl);
|
||||
break;
|
||||
case 'timezone-manual':
|
||||
dialog = webhookUtils.getTimezoneManualDialog(body.trigger_id, webhookBaseUrl);
|
||||
break;
|
||||
default:
|
||||
// Default to basic datetime dialog for backward compatibility
|
||||
dialog = webhookUtils.getBasicDateTimeDialog(body.trigger_id, webhookBaseUrl);
|
||||
break;
|
||||
}
|
||||
console.log('Opening DateTime dialog', dialog.dialog.title);
|
||||
openDialog(dialog);
|
||||
}
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
return res.json({text: 'DateTime dialog triggered via slash command!'});
|
||||
}
|
||||
|
||||
function onDateTimeDialogSubmit(req, res) {
|
||||
console.log('DateTime dialog submit handler called!');
|
||||
const {body} = req;
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
|
||||
// Log the submitted datetime values for debugging
|
||||
console.log('DateTime dialog submission:', JSON.stringify(body, null, 2));
|
||||
|
||||
// Extract datetime values from submission
|
||||
const submission = body.submission || {};
|
||||
const eventDate = submission.event_date;
|
||||
const meetingTime = submission.meeting_time;
|
||||
const relativeDate = submission.relative_date;
|
||||
const relativeDateTime = submission.relative_datetime;
|
||||
|
||||
// Create a success message with the submitted values
|
||||
let message = 'Form submitted successfully! ';
|
||||
if (eventDate || meetingTime || relativeDate || relativeDateTime) {
|
||||
message += 'Submitted values: ';
|
||||
if (eventDate) {
|
||||
message += `Event Date: ${eventDate}, `;
|
||||
}
|
||||
if (meetingTime) {
|
||||
message += `Meeting Time: ${meetingTime}, `;
|
||||
}
|
||||
if (relativeDate) {
|
||||
message += `Relative Date: ${relativeDate}, `;
|
||||
}
|
||||
if (relativeDateTime) {
|
||||
message += `Relative DateTime: ${relativeDateTime}, `;
|
||||
}
|
||||
message = message.slice(0, -2); // Remove trailing comma and space
|
||||
}
|
||||
|
||||
// Send success response that will appear as a post in the channel
|
||||
sendSysadminResponse(message, body.channel_id);
|
||||
return res.json({text: message});
|
||||
}
|
||||
|
||||
function onDialogSubmit(req, res) {
|
||||
const {body} = req;
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
|
||||
let message;
|
||||
if (body.cancelled) {
|
||||
message = 'Dialog cancelled';
|
||||
console.log('[WEBHOOK] Dialog cancelled');
|
||||
sendSysadminResponse(message, body.channel_id);
|
||||
return res.json({text: message});
|
||||
}
|
||||
|
||||
// Check if this is a multistep submission
|
||||
if (body.callback_id === 'multistep_callback') {
|
||||
const currentState = body.state || '';
|
||||
|
||||
// Determine next step based on current state
|
||||
if (currentState === 'step1') {
|
||||
// Move to step 2
|
||||
const nextForm = webhookUtils.getMultistepStep2Dialog(null, webhookBaseUrl);
|
||||
return res.json({
|
||||
type: 'form',
|
||||
form: nextForm,
|
||||
});
|
||||
} else if (currentState === 'step2') {
|
||||
// Move to step 3
|
||||
const nextForm = webhookUtils.getMultistepStep3Dialog(null, webhookBaseUrl);
|
||||
return res.json({
|
||||
type: 'form',
|
||||
form: nextForm,
|
||||
});
|
||||
}
|
||||
|
||||
// Final step - complete the multistep
|
||||
const submission = body.submission || {};
|
||||
message = `Multistep completed successfully! Final step values: ${JSON.stringify(submission, null, 2)}`;
|
||||
sendSysadminResponse(message, body.channel_id);
|
||||
return res.json({text: message});
|
||||
}
|
||||
|
||||
// Check if this is a field refresh dialog submission
|
||||
if (body.callback_id === 'field_refresh_callback') {
|
||||
const submission = body.submission || {};
|
||||
message = `Field refresh dialog submitted successfully! Values: ${JSON.stringify(submission, null, 2)}`;
|
||||
sendSysadminResponse(message, body.channel_id);
|
||||
return res.json({text: message});
|
||||
}
|
||||
|
||||
// Regular dialog submission
|
||||
// Format submission data for the channel message
|
||||
const sanitize = (str) => String(str).replace(/[<>&"']/g, (ch) => `&#${ch.charCodeAt(0)};`);
|
||||
const submissionData = Object.entries(body.submission || {})
|
||||
.map(([key, value]) => `**${sanitize(key)}**: ${sanitize(value)}`)
|
||||
.join('\n');
|
||||
|
||||
message = `Dialog submitted successfully!\n\n**Submission Data:**\n${submissionData}`;
|
||||
|
||||
sendSysadminResponse(message, body.channel_id);
|
||||
return res.json({text: message});
|
||||
}
|
||||
|
||||
/**
|
||||
* @route "POST /send_message_to_channel?type={messageType}&channel_id={channelId}"
|
||||
* @query type - message type of empty string for regular message if not provided (default), "system_message", etc
|
||||
* @query channel_id - channel where to send the message
|
||||
*/
|
||||
function postSendMessageToChannel(req, res) {
|
||||
const channelId = req.query.channel_id;
|
||||
const response = {
|
||||
response_type: 'in_channel',
|
||||
text: 'Extra response 2',
|
||||
channel_id: channelId,
|
||||
extra_responses: [
|
||||
{
|
||||
response_type: 'in_channel',
|
||||
text: 'Hello World',
|
||||
channel_id: channelId,
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
if (req.query.type) {
|
||||
response.type = req.query.type;
|
||||
}
|
||||
|
||||
res.json(response);
|
||||
}
|
||||
|
||||
// Convenient way to send response in a channel by using sysadmin account
|
||||
function sendSysadminResponse(message, channelId) {
|
||||
postMessageAs({
|
||||
sender: {
|
||||
username: adminUsername,
|
||||
password: adminPassword,
|
||||
},
|
||||
message,
|
||||
channelId,
|
||||
baseUrl,
|
||||
});
|
||||
}
|
||||
|
||||
const responseTypes = ['in_channel', 'comment'];
|
||||
|
||||
function getWebhookResponse(body, {responseType, username, iconUrl}) {
|
||||
const payload = Object.entries(body)
|
||||
.map(([key, value]) => `- ${key}: "${value}"`)
|
||||
.join('\n');
|
||||
|
||||
return `
|
||||
\`\`\`
|
||||
#### Outgoing Webhook Payload
|
||||
${payload}
|
||||
#### Webhook override to Mattermost instance
|
||||
- response_type: "${responseType}"
|
||||
- type: ""
|
||||
- username: "${username}"
|
||||
- icon_url: "${iconUrl}"
|
||||
\`\`\`
|
||||
`;
|
||||
}
|
||||
|
||||
/**
|
||||
* @route "POST /post_outgoing_webhook?override_username={username}&override_icon_url={iconUrl}&response_type={comment}"
|
||||
* @query override_username - the user name that overrides the user name defined by the outgoing webhook
|
||||
* @query override_icon_url - the user icon url that overrides the user icon url defined by the outgoing webhook
|
||||
* @query response_type - "in_channel" (default) or "comment"
|
||||
*/
|
||||
function postOutgoingWebhook(req, res) {
|
||||
const {body, query} = req;
|
||||
if (!body) {
|
||||
res.status(404).send({error: 'Invalid data'});
|
||||
}
|
||||
|
||||
const responseType = query.response_type || responseTypes[0];
|
||||
const username = query.override_username || '';
|
||||
const iconUrl = query.override_icon_url || '';
|
||||
|
||||
const response = {
|
||||
text: getWebhookResponse(body, {responseType, username, iconUrl}),
|
||||
username,
|
||||
icon_url: iconUrl,
|
||||
type: '',
|
||||
response_type: responseType,
|
||||
};
|
||||
res.status(200).send(response);
|
||||
}
|
||||
|
||||
function onFieldRefreshDialogRequest(req, res) {
|
||||
const {body} = req;
|
||||
if (body.trigger_id) {
|
||||
const dialog = webhookUtils.getFieldRefreshDialog(body.trigger_id, webhookBaseUrl);
|
||||
openDialog(dialog);
|
||||
}
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
return res.json({text: 'Field refresh dialog triggered via slash command!'});
|
||||
}
|
||||
|
||||
function onMultistepDialogRequest(req, res) {
|
||||
const {body} = req;
|
||||
if (body.trigger_id) {
|
||||
const dialog = webhookUtils.getMultistepStep1Dialog(body.trigger_id, webhookBaseUrl);
|
||||
openDialog(dialog);
|
||||
}
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
return res.json({text: 'Multistep dialog triggered via slash command!'});
|
||||
}
|
||||
|
||||
function onActionButtonDialogRequest(req, res) {
|
||||
const {body} = req;
|
||||
if (body.trigger_id) {
|
||||
const dialog = webhookUtils.getActionButtonParentDialog(body.trigger_id, webhookBaseUrl);
|
||||
openDialog(dialog);
|
||||
}
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
return res.json({text: 'Action button dialog triggered!'});
|
||||
}
|
||||
|
||||
async function onOpenChildDialog(req, res) {
|
||||
const {body} = req;
|
||||
|
||||
// context.source identifies which action button on the parent dialog was
|
||||
// pressed; it is forwarded by the server in the PostActionIntegrationRequest.
|
||||
const source = (body.context && body.context.source) || 'Unknown';
|
||||
console.log('onOpenChildDialog called with trigger_id:', body.trigger_id, 'source:', source);
|
||||
if (body.trigger_id) {
|
||||
const childDialog = webhookUtils.getActionButtonChildDialog(body.trigger_id, webhookBaseUrl, source);
|
||||
|
||||
// Await the dialog open before responding. The server's /execute call
|
||||
// (DoActionRequest) waits for this response, so awaiting here ensures the
|
||||
// child's WS open_dialog event is published before the browser's
|
||||
// executeDialogAction promise resolves — removing the render race in tests.
|
||||
await openDialog(childDialog);
|
||||
}
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
return res.json({});
|
||||
}
|
||||
|
||||
function onFieldRefreshSource(req, res) {
|
||||
const {body} = req;
|
||||
const submission = body.submission || {};
|
||||
const projectType = submission.project_type;
|
||||
const projectName = submission.project_name || '';
|
||||
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
|
||||
// Return updated form based on project type selection
|
||||
const elements = [
|
||||
{
|
||||
display_name: 'Project Name',
|
||||
name: 'project_name',
|
||||
type: 'text',
|
||||
placeholder: 'Enter project name',
|
||||
default: projectName,
|
||||
optional: false,
|
||||
},
|
||||
{
|
||||
display_name: 'Project Type',
|
||||
name: 'project_type',
|
||||
type: 'select',
|
||||
refresh: true,
|
||||
placeholder: 'Select project type...',
|
||||
default: projectType,
|
||||
options: [
|
||||
{text: 'Web Application', value: 'web'},
|
||||
{text: 'Mobile App', value: 'mobile'},
|
||||
{text: 'API Service', value: 'api'},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
// Add different fields based on project type
|
||||
if (projectType === 'web') {
|
||||
elements.push({
|
||||
display_name: 'Framework',
|
||||
name: 'framework',
|
||||
type: 'select',
|
||||
placeholder: 'Select framework...',
|
||||
options: [
|
||||
{text: 'React', value: 'react'},
|
||||
{text: 'Vue', value: 'vue'},
|
||||
{text: 'Angular', value: 'angular'},
|
||||
],
|
||||
});
|
||||
} else if (projectType === 'mobile') {
|
||||
elements.push({
|
||||
display_name: 'Platform',
|
||||
name: 'platform',
|
||||
type: 'select',
|
||||
placeholder: 'Select platform...',
|
||||
options: [
|
||||
{text: 'iOS', value: 'ios'},
|
||||
{text: 'Android', value: 'android'},
|
||||
{text: 'React Native', value: 'react-native'},
|
||||
],
|
||||
});
|
||||
} else if (projectType === 'api') {
|
||||
elements.push({
|
||||
display_name: 'Language',
|
||||
name: 'language',
|
||||
type: 'select',
|
||||
placeholder: 'Select language...',
|
||||
options: [
|
||||
{text: 'Go', value: 'go'},
|
||||
{text: 'Node.js', value: 'nodejs'},
|
||||
{text: 'Python', value: 'python'},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
return res.json({
|
||||
type: 'form',
|
||||
form: {
|
||||
title: 'Field Refresh Demo',
|
||||
introduction_text: 'Enter project name then select type to see different fields',
|
||||
submit_label: 'Submit',
|
||||
elements,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {GenericContainer, Wait} from 'testcontainers';
|
||||
import type {StartedNetwork, StartedTestContainer} from 'testcontainers';
|
||||
|
||||
import {AZURITE_ALIAS, AZURITE_BLOB_PORT, TESTCONTAINERS_LABELS} from './constants';
|
||||
import {AZURITE_IMAGE} from './default_images';
|
||||
import {startWithRetry} from './retry';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
|
||||
// An alternative to Minio for blob storage.
|
||||
export async function startAzuriteContainer(network: StartedNetwork): Promise<StartedTestContainer> {
|
||||
return startWithRetry('azurite', async () => {
|
||||
let builder = new GenericContainer(AZURITE_IMAGE)
|
||||
.withCommand([
|
||||
'azurite-blob',
|
||||
'--blobHost',
|
||||
'0.0.0.0',
|
||||
'--blobPort',
|
||||
String(AZURITE_BLOB_PORT),
|
||||
'--skipApiVersionCheck',
|
||||
])
|
||||
.withExposedPorts(AZURITE_BLOB_PORT)
|
||||
.withNetwork(network)
|
||||
.withNetworkAliases(AZURITE_ALIAS)
|
||||
.withLabels(TESTCONTAINERS_LABELS)
|
||||
.withWaitStrategy(Wait.forListeningPorts());
|
||||
|
||||
if (testConfig.testcontainersReuse) {
|
||||
builder = builder.withReuse();
|
||||
}
|
||||
|
||||
return builder.start();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
// Single source of truth for the fixed values every container/helper needs to agree on.
|
||||
// Kept separate from test_config.ts because these are not overridable — they're either
|
||||
// Testcontainers network aliases (only meaningful inside the Testcontainers network) or
|
||||
// fixed test-only credentials for a throwaway local service.
|
||||
|
||||
export const POSTGRES_ALIAS = 'postgres';
|
||||
export const POSTGRES_PORT = 5432;
|
||||
export const POSTGRES_DB = 'mattermost_test';
|
||||
export const POSTGRES_USER = 'mmuser';
|
||||
export const POSTGRES_PASSWORD = 'mostest';
|
||||
|
||||
export const INBUCKET_ALIAS = 'inbucket';
|
||||
export const INBUCKET_WEB_PORT = 9001;
|
||||
export const INBUCKET_SMTP_PORT = 10025;
|
||||
export const INBUCKET_POP3_PORT = 10110;
|
||||
|
||||
export const MATTERMOST_ALIAS = 'server';
|
||||
export const MATTERMOST_PORT = 8065;
|
||||
|
||||
// Interactive-message/dialog callback sidecar shared with Cypress. Always started, like
|
||||
// postgres/inbucket — not gated behind testcontainersServices.
|
||||
export const WEBHOOK_ALIAS = 'webhook';
|
||||
export const WEBHOOK_PORT = 3000;
|
||||
|
||||
export const OPENLDAP_ALIAS = 'openldap';
|
||||
export const OPENLDAP_PORT = 389;
|
||||
export const OPENLDAP_ADMIN_DN = 'cn=admin,dc=mm,dc=test,dc=com';
|
||||
export const OPENLDAP_ADMIN_PASSWORD = 'mostest';
|
||||
export const OPENLDAP_BASE_DN = 'dc=mm,dc=test,dc=com';
|
||||
|
||||
export const KEYCLOAK_ALIAS = 'keycloak';
|
||||
export const KEYCLOAK_PORT = 8080;
|
||||
export const KEYCLOAK_REALM = 'mattermost';
|
||||
export const KEYCLOAK_ADMIN_USER = 'admin';
|
||||
export const KEYCLOAK_ADMIN_PASSWORD = 'admin';
|
||||
|
||||
export const ELASTICSEARCH_ALIAS = 'elasticsearch';
|
||||
export const ELASTICSEARCH_PORT = 9200;
|
||||
|
||||
export const MINIO_ALIAS = 'minio';
|
||||
export const MINIO_PORT = 9000;
|
||||
export const MINIO_ACCESS_KEY = 'minioaccesskey';
|
||||
export const MINIO_SECRET_KEY = 'miniosecretkey';
|
||||
export const MINIO_BUCKET = 'mattermost-test';
|
||||
|
||||
// Alternative to Minio for blob storage.
|
||||
export const AZURITE_ALIAS = 'azurite';
|
||||
export const AZURITE_BLOB_PORT = 10000;
|
||||
// Azurite's well-known default emulator account — published by Microsoft's own docs, not a secret.
|
||||
export const AZURITE_ACCOUNT_NAME = 'devstoreaccount1';
|
||||
export const AZURITE_ACCOUNT_KEY =
|
||||
'Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==';
|
||||
export const AZURITE_CONTAINER = 'mattermost-test';
|
||||
|
||||
// Alternative to Elasticsearch for search.
|
||||
export const OPENSEARCH_ALIAS = 'opensearch';
|
||||
export const OPENSEARCH_PORT = 9201;
|
||||
export const OPENSEARCH_ADMIN_PASSWORD = 'Test@dmin_123';
|
||||
|
||||
// Applied to every container this module starts, so `npm run testcontainers:down` can find and
|
||||
// remove them from a fresh process — the in-memory `started` state in stack.ts only exists in
|
||||
// the process that created it.
|
||||
export const TESTCONTAINERS_LABEL_KEY = 'mm-playwright-testcontainers';
|
||||
export const TESTCONTAINERS_LABEL_VALUE = 'true';
|
||||
export const TESTCONTAINERS_LABELS = {[TESTCONTAINERS_LABEL_KEY]: TESTCONTAINERS_LABEL_VALUE};
|
||||
@@ -0,0 +1,18 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
// Single place to check and bump every image.
|
||||
// The Mattermost server's default is overridable via the SERVER_IMAGE env var (testConfig.serverImage).
|
||||
export const MATTERMOST_SERVER_IMAGE = 'mattermostdevelopment/mattermost-enterprise-edition:master';
|
||||
export const POSTGRES_IMAGE = 'postgres:14';
|
||||
export const INBUCKET_IMAGE = 'inbucket/inbucket:3.1.1';
|
||||
export const OPENLDAP_IMAGE = 'osixia/openldap:1.4.0';
|
||||
export const KEYCLOAK_IMAGE = 'quay.io/keycloak/keycloak:23.0.7';
|
||||
export const MINIO_IMAGE = 'minio/minio:RELEASE.2024-06-22T05-26-45Z';
|
||||
export const AZURITE_IMAGE = 'mcr.microsoft.com/azure-storage/azurite:3.34.0';
|
||||
// Built from a Dockerfile on top of docker.elastic.co/elasticsearch/elasticsearch, rather than
|
||||
// pulled as a fixed image — so only the version is fixed here.
|
||||
export const ELASTICSEARCH_VERSION = '9.0.0';
|
||||
// Built from a Dockerfile on top of opensearchproject/opensearch, rather than pulled as a fixed
|
||||
// image — so only the version is fixed here.
|
||||
export const OPENSEARCH_VERSION = '3.0.0';
|
||||
@@ -0,0 +1,48 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {GenericContainer, Wait} from 'testcontainers';
|
||||
import type {StartedNetwork, StartedTestContainer} from 'testcontainers';
|
||||
|
||||
import {ELASTICSEARCH_ALIAS, ELASTICSEARCH_PORT, TESTCONTAINERS_LABELS} from './constants';
|
||||
import {ELASTICSEARCH_VERSION as DEFAULT_ELASTICSEARCH_VERSION} from './default_images';
|
||||
import {containerAssetPath} from './paths';
|
||||
import {startWithRetry} from './retry';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
|
||||
// Built from a vendored Dockerfile, not the generic @testcontainers/elasticsearch wrapper — it
|
||||
// installs the CJK analysis plugins (analysis-icu/nori/kuromoji/smartcn) real search tests rely on.
|
||||
export async function startElasticsearchContainer(network: StartedNetwork): Promise<StartedTestContainer> {
|
||||
return startWithRetry('elasticsearch', async () => {
|
||||
// deleteOnExit: false — otherwise the built image bakes in this session's Ryuk id, so Ryuk
|
||||
// reaps the "reused" container the moment this session ends, defeating withReuse() below.
|
||||
const image = await GenericContainer.fromDockerfile(containerAssetPath(), 'Dockerfile.elasticsearch')
|
||||
.withBuildArgs({
|
||||
ELASTICSEARCH_VERSION: process.env.ELASTICSEARCH_VERSION || DEFAULT_ELASTICSEARCH_VERSION,
|
||||
})
|
||||
.build(undefined, {deleteOnExit: false});
|
||||
|
||||
let builder = image
|
||||
.withExposedPorts(ELASTICSEARCH_PORT)
|
||||
.withNetwork(network)
|
||||
.withNetworkAliases(ELASTICSEARCH_ALIAS)
|
||||
.withLabels(TESTCONTAINERS_LABELS)
|
||||
.withEnvironment({
|
||||
'http.host': '0.0.0.0',
|
||||
'http.port': String(ELASTICSEARCH_PORT),
|
||||
'xpack.security.enabled': 'false',
|
||||
'action.destructive_requires_name': 'false',
|
||||
'transport.host': '127.0.0.1',
|
||||
ES_JAVA_OPTS: '-Xms512m -Xmx512m',
|
||||
})
|
||||
.withStartupTimeout(3 * 60_000)
|
||||
.withWaitStrategy(Wait.forHttp('/_cluster/health', ELASTICSEARCH_PORT).forStatusCode(200));
|
||||
|
||||
if (testConfig.testcontainersReuse) {
|
||||
builder = builder.withReuse();
|
||||
}
|
||||
|
||||
return builder.start();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
// Test-oriented MM_* config the Mattermost server container starts with by default,
|
||||
// merged under testConfig.serverEnv (MM_ENV) so callers can still override any of it.
|
||||
export const SERVER_ENV_BASELINE: Record<string, string> = {
|
||||
MM_SERVICEENVIRONMENT: 'test',
|
||||
MM_CLUSTERSETTINGS_READONLYCONFIG: 'false',
|
||||
MM_CONNECTEDWORKSPACESSETTINGS_ENABLEREMOTECLUSTERSERVICE: 'true',
|
||||
MM_CONNECTEDWORKSPACESSETTINGS_ENABLESHAREDWORKSPACES: 'true',
|
||||
MM_LOGSETTINGS_CONSOLELEVEL: 'DEBUG',
|
||||
MM_LOGSETTINGS_ENABLEDIAGNOSTICS: 'false',
|
||||
MM_PLUGINSETTINGS_ENABLEUPLOADS: 'true',
|
||||
MM_SERVICESETTINGS_ALLOWCORSFROM: '*',
|
||||
MM_SERVICESETTINGS_ALLOWEDUNTRUSTEDINTERNALCONNECTIONS: 'keycloak elasticsearch opensearch minio azurite webhook',
|
||||
MM_SERVICESETTINGS_ENABLELOCALMODE: 'true',
|
||||
MM_SERVICESETTINGS_ENABLESECURITYFIXALERT: 'false',
|
||||
MM_SERVICESETTINGS_ENABLETESTING: 'true',
|
||||
// Feature flags this test suite needs on, off by default in the server
|
||||
MM_FEATUREFLAGS_ATTRIBUTEVALUEMASKING: 'true',
|
||||
MM_FEATUREFLAGS_ENABLEREMOTECLUSTERSERVICE: 'true',
|
||||
MM_FEATUREFLAGS_MOVETHREADSENABLED: 'true',
|
||||
MM_FEATUREFLAGS_PERMISSIONPOLICIES: 'true',
|
||||
MM_FEATUREFLAGS_PROPERTYFIELDRANK: 'true',
|
||||
MM_FEATUREFLAGS_TEAMMEMBERSHIPACCESSCONTROL: 'true',
|
||||
MM_FEATUREFLAGS_WYSIWYGEDITOR: 'true',
|
||||
};
|
||||
@@ -0,0 +1,39 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {GenericContainer, Wait} from 'testcontainers';
|
||||
import type {StartedNetwork, StartedTestContainer} from 'testcontainers';
|
||||
|
||||
import {
|
||||
INBUCKET_ALIAS,
|
||||
INBUCKET_POP3_PORT,
|
||||
INBUCKET_SMTP_PORT,
|
||||
INBUCKET_WEB_PORT,
|
||||
TESTCONTAINERS_LABELS,
|
||||
} from './constants';
|
||||
import {INBUCKET_IMAGE} from './default_images';
|
||||
import {startWithRetry} from './retry';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
|
||||
export async function startInbucketContainer(network: StartedNetwork): Promise<StartedTestContainer> {
|
||||
return startWithRetry('inbucket', async () => {
|
||||
let builder = new GenericContainer(INBUCKET_IMAGE)
|
||||
.withExposedPorts(INBUCKET_WEB_PORT, INBUCKET_SMTP_PORT, INBUCKET_POP3_PORT)
|
||||
.withNetwork(network)
|
||||
.withNetworkAliases(INBUCKET_ALIAS)
|
||||
.withLabels(TESTCONTAINERS_LABELS)
|
||||
.withEnvironment({
|
||||
INBUCKET_WEB_ADDR: `0.0.0.0:${INBUCKET_WEB_PORT}`,
|
||||
INBUCKET_POP3_ADDR: `0.0.0.0:${INBUCKET_POP3_PORT}`,
|
||||
INBUCKET_SMTP_ADDR: `0.0.0.0:${INBUCKET_SMTP_PORT}`,
|
||||
})
|
||||
.withWaitStrategy(Wait.forListeningPorts());
|
||||
|
||||
if (testConfig.testcontainersReuse) {
|
||||
builder = builder.withReuse();
|
||||
}
|
||||
|
||||
return builder.start();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
export {startStack, stopStack} from './stack';
|
||||
@@ -0,0 +1,51 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {GenericContainer, Wait} from 'testcontainers';
|
||||
import type {StartedNetwork, StartedTestContainer} from 'testcontainers';
|
||||
|
||||
import {
|
||||
KEYCLOAK_ADMIN_PASSWORD,
|
||||
KEYCLOAK_ADMIN_USER,
|
||||
KEYCLOAK_ALIAS,
|
||||
KEYCLOAK_PORT,
|
||||
TESTCONTAINERS_LABELS,
|
||||
} from './constants';
|
||||
import {KEYCLOAK_IMAGE} from './default_images';
|
||||
import {containerAssetPath} from './paths';
|
||||
import {startWithRetry} from './retry';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
|
||||
export async function startKeycloakContainer(network: StartedNetwork): Promise<StartedTestContainer> {
|
||||
return startWithRetry('keycloak', async () => {
|
||||
let builder = new GenericContainer(KEYCLOAK_IMAGE)
|
||||
.withEntrypoint(['/opt/keycloak/bin/kc.sh'])
|
||||
.withCommand(['start', '--import-realm'])
|
||||
.withExposedPorts(KEYCLOAK_PORT)
|
||||
.withNetwork(network)
|
||||
.withNetworkAliases(KEYCLOAK_ALIAS)
|
||||
.withLabels(TESTCONTAINERS_LABELS)
|
||||
.withEnvironment({
|
||||
KEYCLOAK_ADMIN: KEYCLOAK_ADMIN_USER,
|
||||
KEYCLOAK_ADMIN_PASSWORD,
|
||||
KC_HOSTNAME_STRICT: 'false',
|
||||
KC_HOSTNAME_STRICT_HTTPS: 'false',
|
||||
KC_HTTP_ENABLED: 'true',
|
||||
})
|
||||
.withCopyFilesToContainer([
|
||||
{
|
||||
source: containerAssetPath('keycloak-realm-export.json'),
|
||||
target: '/opt/keycloak/data/import/realm-export.json',
|
||||
},
|
||||
])
|
||||
.withStartupTimeout(3 * 60_000)
|
||||
.withWaitStrategy(Wait.forHttp('/realms/master', KEYCLOAK_PORT).forStatusCode(200));
|
||||
|
||||
if (testConfig.testcontainersReuse) {
|
||||
builder = builder.withReuse();
|
||||
}
|
||||
|
||||
return builder.start();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import chalk from 'chalk';
|
||||
|
||||
const PREFIX = chalk.cyan('[testcontainers]');
|
||||
|
||||
export function logTestcontainers(message: string): void {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`${PREFIX} ${message}`);
|
||||
}
|
||||
|
||||
export function warnTestcontainers(message: string): void {
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn(`${PREFIX} ${message}`);
|
||||
}
|
||||
|
||||
export function errorTestcontainers(message: string): void {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(`${PREFIX} ${message}`);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {GenericContainer, Wait} from 'testcontainers';
|
||||
import type {StartedTestContainer} from 'testcontainers';
|
||||
|
||||
import {
|
||||
INBUCKET_ALIAS,
|
||||
INBUCKET_SMTP_PORT,
|
||||
MATTERMOST_ALIAS,
|
||||
MATTERMOST_PORT,
|
||||
POSTGRES_ALIAS,
|
||||
POSTGRES_DB,
|
||||
POSTGRES_PASSWORD,
|
||||
POSTGRES_PORT,
|
||||
POSTGRES_USER,
|
||||
TESTCONTAINERS_LABELS,
|
||||
} from './constants';
|
||||
import {SERVER_ENV_BASELINE} from './env_baseline';
|
||||
import {startWithRetry} from './retry';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
|
||||
// Env this container computes itself from the stack Testcontainers just built. Must win over any
|
||||
// stray testConfig.serverEnv (MM_ENV) entry and over testConfig.bootEnvOverrides (passed in as
|
||||
// `extraEnv` by restartMattermostContainer()), or a stray key collision there could break the
|
||||
// server's own connectivity. Deliberately does NOT know about any additional service (LDAP/
|
||||
// Keycloak/Elasticsearch/OpenSearch/Minio/Azurite) — those are each spec's own responsibility via
|
||||
// pw.ensure<Service>(), which points the already-running server at them through patchConfig.
|
||||
//
|
||||
// MM_LICENSE (if set) is passed straight through: the server reads it directly at startup
|
||||
// (platform.LoadLicense), so it boots already licensed instead of needing an authenticated upload
|
||||
// call after the fact.
|
||||
function structuralEnv(): Record<string, string> {
|
||||
return {
|
||||
MM_SQLSETTINGS_DRIVERNAME: 'postgres',
|
||||
MM_SQLSETTINGS_DATASOURCE: `postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${POSTGRES_ALIAS}:${POSTGRES_PORT}/${POSTGRES_DB}?sslmode=disable&connect_timeout=10&binary_parameters=yes`,
|
||||
MM_EMAILSETTINGS_SMTPSERVER: INBUCKET_ALIAS,
|
||||
MM_EMAILSETTINGS_SMTPPORT: String(INBUCKET_SMTP_PORT),
|
||||
...(process.env.MM_LICENSE ? {MM_LICENSE: process.env.MM_LICENSE} : {}),
|
||||
// Overrides (not merges) SERVER_ENV_BASELINE's own value for this same key — appends the
|
||||
// network's gateway IP so the SSRF guard also allows fetching from file_server.ts's mock
|
||||
// file server, reachable at that address (see test_config.ts). Only known once the
|
||||
// network is up (testConfig.testcontainersNetworkGatewayIp is set by stack.ts's
|
||||
// startStack() before this container ever starts), so falls back to the baseline's own
|
||||
// value verbatim on the off chance this ever runs without it.
|
||||
MM_SERVICESETTINGS_ALLOWEDUNTRUSTEDINTERNALCONNECTIONS: testConfig.testcontainersNetworkGatewayIp
|
||||
? `${SERVER_ENV_BASELINE.MM_SERVICESETTINGS_ALLOWEDUNTRUSTEDINTERNALCONNECTIONS} ${testConfig.testcontainersNetworkGatewayIp}`
|
||||
: SERVER_ENV_BASELINE.MM_SERVICESETTINGS_ALLOWEDUNTRUSTEDINTERNALCONNECTIONS,
|
||||
};
|
||||
}
|
||||
|
||||
// Readiness requires both the /api/v4/system/ping health check AND the permissions-migration job
|
||||
// scheduler's "All migrations are complete." log line (scheduler.go, jobs/migrations package).
|
||||
// Ping alone isn't enough: MigrationKeyAdvancedPermissionsPhase2 runs as an async job whose
|
||||
// scheduler deliberately delays its first tick 60s after startup — a real window a spec's very
|
||||
// first API call can otherwise land inside, tripping IsPhase2MigrationCompleted() gates with
|
||||
// "required migrations have not yet completed" (confirmed in practice: a permissions-page spec
|
||||
// hit exactly this, with the "Edit Scheme" link stuck disabled, when this wait was dropped).
|
||||
// Requires MM_LOGSETTINGS_CONSOLELEVEL=DEBUG (env_baseline.ts) since the scheduler logs that line
|
||||
// at Debug. Only paid on a genuinely fresh boot — a reused/adopted stack skips this entirely.
|
||||
//
|
||||
// Joins the network by name (withNetworkMode) rather than a StartedNetwork object: also called
|
||||
// from restartMattermostContainer(), which runs in a worker process that never holds the actual
|
||||
// StartedNetwork handle — only the network's name (threaded through testConfig) is available
|
||||
// there.
|
||||
export async function startMattermostContainer(
|
||||
networkName: string,
|
||||
extraEnv: Record<string, string> = {},
|
||||
): Promise<StartedTestContainer> {
|
||||
const env: Record<string, string> = {
|
||||
...SERVER_ENV_BASELINE,
|
||||
...testConfig.serverEnv,
|
||||
...extraEnv,
|
||||
...structuralEnv(),
|
||||
};
|
||||
|
||||
return startWithRetry('server', async () => {
|
||||
let builder = new GenericContainer(testConfig.serverImage)
|
||||
.withPlatform('linux/amd64') // The published server images are amd64-only.
|
||||
.withNetworkMode(networkName)
|
||||
.withNetworkAliases(MATTERMOST_ALIAS)
|
||||
.withLabels(TESTCONTAINERS_LABELS)
|
||||
.withExposedPorts(MATTERMOST_PORT)
|
||||
.withEnvironment(env)
|
||||
.withStartupTimeout(5 * 60_000)
|
||||
.withWaitStrategy(
|
||||
Wait.forAll([
|
||||
Wait.forHttp('/api/v4/system/ping', MATTERMOST_PORT).forStatusCode(200),
|
||||
Wait.forLogMessage(/All migrations are complete\./, 1),
|
||||
]),
|
||||
);
|
||||
|
||||
if (testConfig.testcontainersReuse) {
|
||||
builder = builder.withReuse();
|
||||
}
|
||||
|
||||
return builder.start();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {GenericContainer, Wait} from 'testcontainers';
|
||||
import type {StartedNetwork, StartedTestContainer} from 'testcontainers';
|
||||
|
||||
import {MINIO_ACCESS_KEY, MINIO_ALIAS, MINIO_PORT, MINIO_SECRET_KEY, TESTCONTAINERS_LABELS} from './constants';
|
||||
import {MINIO_IMAGE} from './default_images';
|
||||
import {startWithRetry} from './retry';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
|
||||
export async function startMinioContainer(network: StartedNetwork): Promise<StartedTestContainer> {
|
||||
return startWithRetry('minio', async () => {
|
||||
let builder = new GenericContainer(MINIO_IMAGE)
|
||||
.withCommand(['server', '/data', '--console-address', ':9002'])
|
||||
.withExposedPorts(MINIO_PORT)
|
||||
.withNetwork(network)
|
||||
.withNetworkAliases(MINIO_ALIAS)
|
||||
.withLabels(TESTCONTAINERS_LABELS)
|
||||
.withEnvironment({
|
||||
MINIO_ROOT_USER: MINIO_ACCESS_KEY,
|
||||
MINIO_ROOT_PASSWORD: MINIO_SECRET_KEY,
|
||||
})
|
||||
.withWaitStrategy(Wait.forHttp('/minio/health/live', MINIO_PORT).forStatusCode(200));
|
||||
|
||||
if (testConfig.testcontainersReuse) {
|
||||
builder = builder.withReuse();
|
||||
}
|
||||
|
||||
return builder.start();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {execFile} from 'node:child_process';
|
||||
import {promisify} from 'node:util';
|
||||
|
||||
import {GenericContainer} from 'testcontainers';
|
||||
import type {WaitStrategy} from 'testcontainers';
|
||||
|
||||
import {MATTERMOST_ALIAS, MATTERMOST_PORT, TESTCONTAINERS_LABELS} from './constants';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
const MMCTL_ENTRYPOINT = '/mattermost/bin/mmctl';
|
||||
const MMCTL_CONFIG_DIR = '/tmp/mmctl-xdg';
|
||||
const MMCTL_CREDENTIALS_NAME = 'e2e';
|
||||
|
||||
export type MmctlResult = {
|
||||
exitCode: number;
|
||||
output: string;
|
||||
};
|
||||
|
||||
// Matches the Credentials/CredentialsList shape mmctl reads (server/cmd/mmctl/commands/auth_utils.go).
|
||||
// Written directly instead of via `mmctl auth login`, since that needs a password file and this
|
||||
// image has no shell to create one. AuthMethod "T" treats authToken as a plain bearer token, which
|
||||
// mmctl reads into Client4.AuthToken.
|
||||
function buildCredentialsFileContent(username: string, authToken: string): string {
|
||||
const credentialsList = {
|
||||
[MMCTL_CREDENTIALS_NAME]: {
|
||||
name: MMCTL_CREDENTIALS_NAME,
|
||||
username,
|
||||
authToken,
|
||||
authMethod: 'T',
|
||||
instanceUrl: `http://${MATTERMOST_ALIAS}:${MATTERMOST_PORT}`,
|
||||
active: true,
|
||||
},
|
||||
};
|
||||
return JSON.stringify(credentialsList);
|
||||
}
|
||||
|
||||
async function streamToString(stream: NodeJS.ReadableStream): Promise<string> {
|
||||
const chunks: Buffer[] = [];
|
||||
for await (const chunk of stream) {
|
||||
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
|
||||
}
|
||||
return Buffer.concat(chunks).toString('utf-8');
|
||||
}
|
||||
|
||||
// Wait.forOneShotStartup() throws on any non-zero exit code, but a non-zero exit from mmctl is a
|
||||
// meaningful result to inspect, not a startup failure. This strategy ignores the exit code;
|
||||
// completion is awaited afterward via `docker wait`.
|
||||
class NoOpWaitStrategy implements WaitStrategy {
|
||||
private startupTimeoutMs = 0;
|
||||
|
||||
async waitUntilReady(): Promise<void> {
|
||||
// No-op — completion is awaited by the caller via `docker wait`.
|
||||
}
|
||||
|
||||
withStartupTimeout(startupTimeoutMs: number): this {
|
||||
this.startupTimeoutMs = startupTimeoutMs;
|
||||
return this;
|
||||
}
|
||||
|
||||
isStartupTimeoutSet(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
getStartupTimeout(): number {
|
||||
return this.startupTimeoutMs;
|
||||
}
|
||||
}
|
||||
|
||||
async function waitForExitCode(containerId: string): Promise<number> {
|
||||
// Bounded so a hung mmctl command can't stall cleanup indefinitely.
|
||||
const {stdout} = await execFileAsync('docker', ['wait', containerId], {timeout: 60_000});
|
||||
return parseInt(stdout.trim(), 10);
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a single mmctl command in its own throwaway container built from the server image, acting
|
||||
* as a real remote client rather than the `--local` unix-socket mode used for the server's healthcheck.
|
||||
*
|
||||
* Joins the network by name (withNetworkMode), not via getNetwork() — this runs in the Playwright
|
||||
* worker process, a different OS process from the one that created the network, so getNetwork()'s
|
||||
* in-process cache would create a second, unrelated network instead of finding the real one.
|
||||
*/
|
||||
export async function runMmctl(args: string[], username: string, authToken: string): Promise<MmctlResult> {
|
||||
if (!testConfig.testcontainersNetworkName) {
|
||||
throw new Error(
|
||||
'No Testcontainers network name available (PW_TESTCONTAINERS_NETWORK_NAME) — is PW_USE_TESTCONTAINERS=true?',
|
||||
);
|
||||
}
|
||||
|
||||
const container = await new GenericContainer(testConfig.serverImage)
|
||||
.withPlatform('linux/amd64') // The published server images are amd64-only.
|
||||
.withNetworkMode(testConfig.testcontainersNetworkName)
|
||||
.withLabels(TESTCONTAINERS_LABELS)
|
||||
.withEnvironment({XDG_CONFIG_HOME: MMCTL_CONFIG_DIR})
|
||||
.withCopyContentToContainer([
|
||||
{
|
||||
content: buildCredentialsFileContent(username, authToken),
|
||||
target: `${MMCTL_CONFIG_DIR}/mmctl/config`,
|
||||
},
|
||||
])
|
||||
.withEntrypoint([MMCTL_ENTRYPOINT])
|
||||
.withCommand(args)
|
||||
.withWaitStrategy(new NoOpWaitStrategy())
|
||||
.withStartupTimeout(60_000)
|
||||
.start();
|
||||
|
||||
try {
|
||||
const exitCode = await waitForExitCode(container.getId());
|
||||
const output = await streamToString(await container.logs());
|
||||
return {exitCode, output};
|
||||
} finally {
|
||||
await container.stop({remove: true});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {execFile} from 'node:child_process';
|
||||
import {promisify} from 'node:util';
|
||||
|
||||
import {Network} from 'testcontainers';
|
||||
import type {StartedNetwork} from 'testcontainers';
|
||||
|
||||
import {logTestcontainers, warnTestcontainers} from './log';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
// One bridge network per Playwright invocation, shared by every container it starts. When
|
||||
// Playwright itself runs inside a container, that container also joins this network so it can
|
||||
// reach everything by alias instead of a mapped port.
|
||||
let startedNetwork: StartedNetwork | undefined;
|
||||
|
||||
export async function getNetwork(): Promise<StartedNetwork> {
|
||||
if (!startedNetwork) {
|
||||
logTestcontainers('creating network...');
|
||||
startedNetwork = await new Network().start();
|
||||
logTestcontainers('network created.');
|
||||
}
|
||||
return startedNetwork;
|
||||
}
|
||||
|
||||
/**
|
||||
* The bridge network's gateway IP (e.g. 172.18.0.1) — a real address bound to an interface on the
|
||||
* Docker host itself, so a process listening on 0.0.0.0 on the host is reachable both from the
|
||||
* host directly and from any container on this network, without a network alias or mapped port.
|
||||
* Takes a network id/name rather than a StartedNetwork object so it also works from
|
||||
* reuseExistingStack(), which only has testConfig's network name.
|
||||
*/
|
||||
export async function getNetworkGatewayIp(network: string): Promise<string> {
|
||||
const {stdout} = await execFileAsync('docker', [
|
||||
'network',
|
||||
'inspect',
|
||||
network,
|
||||
'--format',
|
||||
'{{(index .IPAM.Config 0).Gateway}}',
|
||||
]);
|
||||
return stdout.trim();
|
||||
}
|
||||
|
||||
export async function stopNetwork(): Promise<void> {
|
||||
if (!startedNetwork) {
|
||||
return;
|
||||
}
|
||||
|
||||
const network = startedNetwork;
|
||||
startedNetwork = undefined;
|
||||
|
||||
// A container a worker process swapped in via restartMattermostContainer() (a different OS
|
||||
// process, invisible to this one) can still be mid-detach from the network at this exact
|
||||
// moment, which Docker reports as "has active endpoints". Ryuk removes the network anyway
|
||||
// once that settles, so retry briefly rather than surfacing a scary but harmless error.
|
||||
const attempts = 5;
|
||||
for (let attempt = 1; attempt <= attempts; attempt++) {
|
||||
try {
|
||||
await network.stop();
|
||||
return;
|
||||
} catch (error) {
|
||||
if (attempt === attempts) {
|
||||
warnTestcontainers(
|
||||
`could not remove network ${network.getId()} (Ryuk will remove it shortly): ${String(error)}`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 1000));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {GenericContainer, Wait} from 'testcontainers';
|
||||
import type {StartedNetwork, StartedTestContainer} from 'testcontainers';
|
||||
|
||||
import {OPENLDAP_ADMIN_PASSWORD, OPENLDAP_ALIAS, OPENLDAP_PORT, TESTCONTAINERS_LABELS} from './constants';
|
||||
import {OPENLDAP_IMAGE} from './default_images';
|
||||
import {startWithRetry} from './retry';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
|
||||
// osixia/openldap is known to occasionally fail its first boot under load — startWithRetry
|
||||
// retries a bounded number of times rather than letting a flaky first attempt fail the whole run.
|
||||
export async function startOpenldapContainer(network: StartedNetwork): Promise<StartedTestContainer> {
|
||||
return startWithRetry('openldap', async () => {
|
||||
let builder = new GenericContainer(OPENLDAP_IMAGE)
|
||||
.withExposedPorts(OPENLDAP_PORT)
|
||||
.withNetwork(network)
|
||||
.withNetworkAliases(OPENLDAP_ALIAS)
|
||||
.withLabels(TESTCONTAINERS_LABELS)
|
||||
.withEnvironment({
|
||||
LDAP_TLS_VERIFY_CLIENT: 'never',
|
||||
LDAP_ORGANISATION: 'Mattermost Test',
|
||||
LDAP_DOMAIN: 'mm.test.com',
|
||||
LDAP_ADMIN_PASSWORD: OPENLDAP_ADMIN_PASSWORD,
|
||||
})
|
||||
.withStartupTimeout(2 * 60_000)
|
||||
.withWaitStrategy(Wait.forListeningPorts());
|
||||
|
||||
if (testConfig.testcontainersReuse) {
|
||||
builder = builder.withReuse();
|
||||
}
|
||||
|
||||
return builder.start();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {GenericContainer, Wait} from 'testcontainers';
|
||||
import type {StartedNetwork, StartedTestContainer} from 'testcontainers';
|
||||
|
||||
import {OPENSEARCH_ADMIN_PASSWORD, OPENSEARCH_ALIAS, OPENSEARCH_PORT, TESTCONTAINERS_LABELS} from './constants';
|
||||
import {OPENSEARCH_VERSION as DEFAULT_OPENSEARCH_VERSION} from './default_images';
|
||||
import {containerAssetPath} from './paths';
|
||||
import {startWithRetry} from './retry';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
|
||||
// Built from a vendored Dockerfile (installs the same CJK analysis plugins as the
|
||||
// Elasticsearch container) — an alternative to Elasticsearch for search.
|
||||
export async function startOpensearchContainer(network: StartedNetwork): Promise<StartedTestContainer> {
|
||||
return startWithRetry('opensearch', async () => {
|
||||
// deleteOnExit: false — otherwise the built image bakes in this session's Ryuk id, so Ryuk
|
||||
// reaps the "reused" container the moment this session ends, defeating withReuse() below.
|
||||
const image = await GenericContainer.fromDockerfile(containerAssetPath(), 'Dockerfile.opensearch')
|
||||
.withBuildArgs({OPENSEARCH_VERSION: process.env.OPENSEARCH_VERSION || DEFAULT_OPENSEARCH_VERSION})
|
||||
.build(undefined, {deleteOnExit: false});
|
||||
|
||||
let builder = image
|
||||
.withExposedPorts(OPENSEARCH_PORT)
|
||||
.withNetwork(network)
|
||||
.withNetworkAliases(OPENSEARCH_ALIAS)
|
||||
.withLabels(TESTCONTAINERS_LABELS)
|
||||
.withEnvironment({
|
||||
'http.port': String(OPENSEARCH_PORT),
|
||||
'discovery.type': 'single-node',
|
||||
'plugins.security.disabled': 'true',
|
||||
DISABLE_INSTALL_DEMO_CONFIG: 'true',
|
||||
OPENSEARCH_INITIAL_ADMIN_PASSWORD: OPENSEARCH_ADMIN_PASSWORD,
|
||||
OPENSEARCH_JAVA_OPTS: '-Xms512m -Xmx512m',
|
||||
})
|
||||
.withStartupTimeout(3 * 60_000)
|
||||
.withWaitStrategy(Wait.forHttp('/_cluster/health', OPENSEARCH_PORT).forStatusCode(200));
|
||||
|
||||
if (testConfig.testcontainersReuse) {
|
||||
builder = builder.withReuse();
|
||||
}
|
||||
|
||||
return builder.start();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import path from 'node:path';
|
||||
|
||||
// Resolved relative to this module's own location (not the caller's cwd or the monorepo), so it
|
||||
// keeps working once `@mattermost/playwright-lib` is installed as an npm package with no access
|
||||
// to the rest of the repo. `preserveModules` keeps `containers/assets` alongside this file's
|
||||
// compiled output in `dist`, same as `src`.
|
||||
//
|
||||
// `__dirname` rather than `import.meta.url`: despite `"type": "module"`, Playwright loads this
|
||||
// package via `require()`, not `import()` — and Node's require()-of-ESM interop disallows
|
||||
// `import.meta` (throws "Cannot use 'import.meta' outside a module"), while `__dirname` still
|
||||
// resolves since Node wraps the module as CommonJS to support that require() call.
|
||||
const assetsDir = path.join(__dirname, 'assets');
|
||||
|
||||
export function containerAssetPath(...segments: string[]): string {
|
||||
return path.join(assetsDir, ...segments);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {PostgreSqlContainer} from '@testcontainers/postgresql';
|
||||
import type {StartedPostgreSqlContainer} from '@testcontainers/postgresql';
|
||||
import {Wait} from 'testcontainers';
|
||||
import type {StartedNetwork} from 'testcontainers';
|
||||
|
||||
import {POSTGRES_ALIAS, POSTGRES_DB, POSTGRES_PASSWORD, POSTGRES_USER, TESTCONTAINERS_LABELS} from './constants';
|
||||
import {POSTGRES_IMAGE} from './default_images';
|
||||
import {containerAssetPath} from './paths';
|
||||
import {startWithRetry} from './retry';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
|
||||
export async function startPostgresContainer(network: StartedNetwork): Promise<StartedPostgreSqlContainer> {
|
||||
return startWithRetry('postgres', async () => {
|
||||
let builder = new PostgreSqlContainer(POSTGRES_IMAGE)
|
||||
.withDatabase(POSTGRES_DB)
|
||||
.withUsername(POSTGRES_USER)
|
||||
.withPassword(POSTGRES_PASSWORD)
|
||||
.withNetwork(network)
|
||||
.withNetworkAliases(POSTGRES_ALIAS)
|
||||
.withLabels(TESTCONTAINERS_LABELS)
|
||||
.withCopyFilesToContainer([
|
||||
{
|
||||
source: containerAssetPath('postgres.conf'),
|
||||
target: '/etc/postgresql/postgresql.conf',
|
||||
},
|
||||
])
|
||||
.withCommand(['postgres', '-c', 'config_file=/etc/postgresql/postgresql.conf'])
|
||||
.withWaitStrategy(Wait.forLogMessage(/database system is ready to accept connections/, 1));
|
||||
|
||||
if (testConfig.testcontainersReuse) {
|
||||
builder = builder.withReuse();
|
||||
}
|
||||
|
||||
return builder.start();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import type {StartedNetwork, StartedTestContainer} from 'testcontainers';
|
||||
|
||||
import {startAzuriteContainer} from './azurite_container';
|
||||
import {startElasticsearchContainer} from './elasticsearch_container';
|
||||
import {startKeycloakContainer} from './keycloak_container';
|
||||
import {startMinioContainer} from './minio_container';
|
||||
import {startOpenldapContainer} from './openldap_container';
|
||||
import {startOpensearchContainer} from './opensearch_container';
|
||||
|
||||
import type {TestContainersServiceName} from '@/test_config';
|
||||
|
||||
// The single place to extend when a new additional service is needed. `stack.ts` starts these
|
||||
// only for the names in testConfig.testcontainersServices.
|
||||
export const ADDITIONAL_SERVICE_STARTERS: Record<
|
||||
TestContainersServiceName,
|
||||
(network: StartedNetwork) => Promise<StartedTestContainer>
|
||||
> = {
|
||||
openldap: startOpenldapContainer,
|
||||
keycloak: startKeycloakContainer,
|
||||
elasticsearch: startElasticsearchContainer,
|
||||
opensearch: startOpensearchContainer,
|
||||
minio: startMinioContainer,
|
||||
azurite: startAzuriteContainer,
|
||||
};
|
||||
@@ -0,0 +1,38 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {errorTestcontainers} from './log';
|
||||
|
||||
import {duration, wait} from '@/util';
|
||||
|
||||
const DEFAULT_ATTEMPTS = 3;
|
||||
|
||||
// Wraps a container's build+start so transient failures (image pull/build over a flaky network,
|
||||
// occasional first-boot flakiness) get a bounded, backed-off retry instead of failing the whole
|
||||
// run — and so any failure, at any attempt, is unambiguous about which container/image caused it,
|
||||
// rather than surfacing as testcontainers' own generic "Failed to build image"/"Failed to start
|
||||
// container" with no name attached.
|
||||
export async function startWithRetry<T>(
|
||||
label: string,
|
||||
start: () => Promise<T>,
|
||||
attempts = DEFAULT_ATTEMPTS,
|
||||
): Promise<T> {
|
||||
let lastError: unknown;
|
||||
|
||||
for (let attempt = 1; attempt <= attempts; attempt++) {
|
||||
try {
|
||||
return await start();
|
||||
} catch (error) {
|
||||
lastError = error;
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
errorTestcontainers(`"${label}" failed on attempt ${attempt}/${attempts}: ${message}`);
|
||||
if (attempt < attempts) {
|
||||
await wait(duration.two_sec * attempt);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(`Failed to start "${label}" container after ${attempts} attempts: ${String(lastError)}`, {
|
||||
cause: lastError,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,657 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {execFile} from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {promisify} from 'node:util';
|
||||
|
||||
import {test} from '@playwright/test';
|
||||
import type {StartedPostgreSqlContainer} from '@testcontainers/postgresql';
|
||||
import type {StartedNetwork, StartedTestContainer} from 'testcontainers';
|
||||
|
||||
import {
|
||||
AZURITE_ALIAS,
|
||||
AZURITE_BLOB_PORT,
|
||||
ELASTICSEARCH_ALIAS,
|
||||
ELASTICSEARCH_PORT,
|
||||
INBUCKET_ALIAS,
|
||||
INBUCKET_WEB_PORT,
|
||||
KEYCLOAK_ALIAS,
|
||||
KEYCLOAK_PORT,
|
||||
MATTERMOST_ALIAS,
|
||||
MATTERMOST_PORT,
|
||||
MINIO_ALIAS,
|
||||
MINIO_PORT,
|
||||
OPENLDAP_ALIAS,
|
||||
OPENLDAP_PORT,
|
||||
OPENSEARCH_ALIAS,
|
||||
OPENSEARCH_PORT,
|
||||
POSTGRES_ALIAS,
|
||||
POSTGRES_DB,
|
||||
POSTGRES_PASSWORD,
|
||||
POSTGRES_PORT,
|
||||
POSTGRES_USER,
|
||||
WEBHOOK_ALIAS,
|
||||
WEBHOOK_PORT,
|
||||
} from './constants';
|
||||
import {
|
||||
AZURITE_IMAGE,
|
||||
ELASTICSEARCH_VERSION,
|
||||
INBUCKET_IMAGE,
|
||||
KEYCLOAK_IMAGE,
|
||||
MINIO_IMAGE,
|
||||
OPENLDAP_IMAGE,
|
||||
OPENSEARCH_VERSION,
|
||||
POSTGRES_IMAGE,
|
||||
} from './default_images';
|
||||
import {startInbucketContainer} from './inbucket_container';
|
||||
import {logTestcontainers} from './log';
|
||||
import {startMattermostContainer} from './mattermost_container';
|
||||
import {getNetwork, getNetworkGatewayIp, stopNetwork} from './network';
|
||||
import {startPostgresContainer} from './postgres_container';
|
||||
import {ADDITIONAL_SERVICE_STARTERS} from './requirements';
|
||||
import {startWebhookContainer} from './webhook_container';
|
||||
|
||||
import {clearClientCache} from '@/server/client';
|
||||
import {defaultBootEnv, testConfig} from '@/test_config';
|
||||
import type {TestContainersServiceName} from '@/test_config';
|
||||
import {duration} from '@/util';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
const ENV_FILE_PATH = path.resolve(process.cwd(), '.env.testcontainers');
|
||||
const LOG_DIR = path.resolve(process.cwd(), 'logs');
|
||||
|
||||
type StartedStack = {
|
||||
network: StartedNetwork;
|
||||
postgres: StartedPostgreSqlContainer;
|
||||
inbucket: StartedTestContainer;
|
||||
webhook: StartedTestContainer;
|
||||
mattermost: StartedTestContainer;
|
||||
additional: Partial<Record<TestContainersServiceName, StartedTestContainer>>;
|
||||
};
|
||||
|
||||
let started: StartedStack | undefined;
|
||||
// True if this process is running against a stack an EARLIER process created (via
|
||||
// reuseExistingStack()) rather than one it started itself — there are no real Testcontainers
|
||||
// handles to hold in this case, only values .env.testcontainers resolved into testConfig via
|
||||
// dotenv. A reusing process never owns the stack's lifecycle, so stopStack() must leave both
|
||||
// the containers and the env file untouched for whatever other process still needs them.
|
||||
let reused = false;
|
||||
|
||||
/**
|
||||
* Brings up a bridge network, Postgres, Inbucket, the Mattermost server, and whichever
|
||||
* additional services testConfig.testcontainersServices names. No-op if `testcontainers` mode isn't
|
||||
* selected (PW_USE_TESTCONTAINERS unset), already started (repeated calls within the same
|
||||
* process, e.g. a stray double-invocation, are harmless), or already reused. Otherwise first
|
||||
* checks whether an earlier process's stack is still alive and reuses it instead — see
|
||||
* reuseExistingStack().
|
||||
*/
|
||||
export async function startStack(): Promise<void> {
|
||||
if (!testConfig.useTestContainers || started || reused) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (await reuseExistingStack()) {
|
||||
return;
|
||||
}
|
||||
|
||||
// reuseExistingStack() found nothing live to reuse — any bootEnvOverrides read from a stale
|
||||
// .env.testcontainers (e.g. left behind by a manual `docker rm` or a crashed prior process)
|
||||
// no longer describes anything real. Reset to the genuine defaults the container about to be
|
||||
// created will actually boot with, or a later restart could wrongly believe some stale
|
||||
// setting is already active and skip a restart it actually needs.
|
||||
testConfig.bootEnvOverrides = defaultBootEnv();
|
||||
|
||||
const network = await getNetwork();
|
||||
|
||||
if (testConfig.containerRunner) {
|
||||
await joinSelfToNetwork(network.getId());
|
||||
}
|
||||
|
||||
// Stored so a host-side mock file server can be reached from both the browser and containers
|
||||
// on this network (see getNetworkGatewayIp).
|
||||
testConfig.testcontainersNetworkGatewayIp = await getNetworkGatewayIp(network.getId());
|
||||
|
||||
const additionalNames = testConfig.testcontainersServices;
|
||||
|
||||
logTestcontainers(
|
||||
`pulling/starting images: server, postgres, inbucket, webhook${additionalNames.length ? `, ${additionalNames.join(', ')}` : ''}`,
|
||||
);
|
||||
await logServerImageAge(testConfig.serverImage);
|
||||
|
||||
// Tracks every container that actually comes up, independent of whether the group as a whole
|
||||
// (or the mattermost start after it) ultimately succeeds — so a failure partway through still
|
||||
// knows exactly what to tear down instead of leaking whatever already started.
|
||||
const startedContainers: StartedTestContainer[] = [];
|
||||
const trackAndLog = <T extends StartedTestContainer>(name: string, promise: Promise<T>): Promise<T> => {
|
||||
const startedAt = Date.now();
|
||||
|
||||
// The biggest blind spot is the server: its own wait strategy alone can take minutes
|
||||
// (see mattermost_container.ts), during which nothing else prints — so ping every 30s to
|
||||
// make clear the run hasn't stalled.
|
||||
const heartbeat = setInterval(() => {
|
||||
logTestcontainers(`still waiting on ${name} (${elapsedSeconds(startedAt)}s elapsed)...`);
|
||||
}, duration.half_min);
|
||||
|
||||
return promise.then(
|
||||
(container) => {
|
||||
clearInterval(heartbeat);
|
||||
startedContainers.push(container);
|
||||
logTestcontainers(`${name} ready in ${elapsedSeconds(startedAt)}s.`);
|
||||
return container;
|
||||
},
|
||||
(error) => {
|
||||
clearInterval(heartbeat);
|
||||
throw error;
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
try {
|
||||
const [postgres, inbucket, webhook, ...additionalContainers] = await Promise.all([
|
||||
trackAndLog('postgres', startPostgresContainer(network)),
|
||||
trackAndLog('inbucket', startInbucketContainer(network)),
|
||||
trackAndLog('webhook', startWebhookContainer(network)),
|
||||
...additionalNames.map((name) => trackAndLog(name, ADDITIONAL_SERVICE_STARTERS[name](network))),
|
||||
]);
|
||||
|
||||
const additional: Partial<Record<TestContainersServiceName, StartedTestContainer>> = {};
|
||||
additionalNames.forEach((name, index) => {
|
||||
additional[name] = additionalContainers[index];
|
||||
});
|
||||
|
||||
const mattermost = await trackAndLog('server', startMattermostContainer(network.getName()));
|
||||
|
||||
started = {network, postgres, inbucket, webhook, mattermost, additional};
|
||||
} catch (error) {
|
||||
await Promise.allSettled(startedContainers.map((container) => container.stop()));
|
||||
await stopNetwork();
|
||||
throw error;
|
||||
}
|
||||
|
||||
applyResolvedConfig(started);
|
||||
resetEnvFile('initial boot');
|
||||
|
||||
logStackStarted(started);
|
||||
}
|
||||
|
||||
/**
|
||||
* True if .env.testcontainers points at a Mattermost container that's still running — i.e. some
|
||||
* OTHER process already brought up a stack this process should reuse instead of duplicating.
|
||||
* Always a different process (the only channel between them is the env file, not runtime IPC);
|
||||
* covers PW_TESTCONTAINERS_REUSE=true across separate local invocations, and a CI dispatcher that
|
||||
* starts the server once per worker job and runs one spec per process against it.
|
||||
*
|
||||
* Deliberately does not gate on testConfig.testcontainersReuse: that flag governs whether the
|
||||
* OWNING process leaves the stack running on its own exit — a different decision from whether
|
||||
* THIS process should reuse a stack it finds already alive. Reuse always applies once liveness
|
||||
* is confirmed.
|
||||
*/
|
||||
async function reuseExistingStack(): Promise<boolean> {
|
||||
if (!testConfig.mattermostContainerId || !(await isContainerRunning(testConfig.mattermostContainerId))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
reused = true;
|
||||
|
||||
if (testConfig.containerRunner) {
|
||||
await joinSelfToNetwork(testConfig.testcontainersNetworkName);
|
||||
}
|
||||
|
||||
logTestcontainers(
|
||||
'reusing already-running server (with PW_TESTCONTAINERS_REUSE=true), see .env.testcontainers for stack information',
|
||||
);
|
||||
logStackReused();
|
||||
return true;
|
||||
}
|
||||
|
||||
// Same shape of summary as logStackStarted(), but built from testConfig's resolved fields
|
||||
// instead of live StartedTestContainer handles — reusing never gets those (see `reused`'s
|
||||
// declaration above), only whatever an EARLIER process's startStack() persisted to
|
||||
// .env.testcontainers and this process's dotenv.config() read back into testConfig.
|
||||
function logStackReused(): void {
|
||||
const lines: string[] = [
|
||||
` - ${'server'.padEnd(13)} = ${testConfig.baseURL}`,
|
||||
` - ${'postgres'.padEnd(13)} = ${testConfig.postgresUrl}`,
|
||||
` - ${'inbucket'.padEnd(13)} = ${testConfig.smtpURL}`,
|
||||
` - ${'webhook'.padEnd(13)} = ${testConfig.webhookBaseUrl}`,
|
||||
];
|
||||
|
||||
const additionalUrls: Record<TestContainersServiceName, string> = {
|
||||
openldap: `${testConfig.ldapHost}:${testConfig.ldapPort}`,
|
||||
keycloak: testConfig.keycloakUrl,
|
||||
elasticsearch: testConfig.elasticsearchUrl,
|
||||
opensearch: testConfig.opensearchUrl,
|
||||
minio: testConfig.minioUrl,
|
||||
azurite: testConfig.azuriteUrl,
|
||||
};
|
||||
testConfig.testcontainersServices.forEach((name) => {
|
||||
lines.push(` - ${name.padEnd(13)} = ${additionalUrls[name]}`);
|
||||
});
|
||||
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(
|
||||
`Testcontainers (reused, network ${testConfig.testcontainersNetworkName}, tear down with: "npm run testcontainers:down"):\n${lines.join('\n')}\n`,
|
||||
);
|
||||
}
|
||||
|
||||
async function isContainerRunning(containerId: string): Promise<boolean> {
|
||||
try {
|
||||
const {stdout} = await execFileAsync('docker', ['inspect', '-f', '{{.State.Running}}', containerId]);
|
||||
return stdout.trim() === 'true';
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Tears down the stack: always collects logs and removes the generated env file; only actually
|
||||
* stops containers when reuse isn't enabled (PW_TESTCONTAINERS_REUSE=true leaves them running
|
||||
* for the next invocation — local or a CI dispatcher's next spec — to reuse).
|
||||
*
|
||||
* A no-op beyond clearing the local flag when this process reused rather than created the stack:
|
||||
* it never owned the containers or the env file, so it must leave both exactly as it found them
|
||||
* for whichever process (or later dispatch) still depends on them.
|
||||
*/
|
||||
export async function stopStack(options: {force?: boolean} = {}): Promise<void> {
|
||||
if (!testConfig.useTestContainers) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (reused) {
|
||||
reused = false;
|
||||
logTestcontainers('this process reused an existing server — leaving it untouched.');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!started) {
|
||||
return;
|
||||
}
|
||||
|
||||
const stack = started;
|
||||
await collectLogs(stack);
|
||||
|
||||
const shouldStop = options.force || !testConfig.testcontainersReuse;
|
||||
if (shouldStop) {
|
||||
await Promise.allSettled([
|
||||
stack.mattermost.stop(),
|
||||
stack.inbucket.stop(),
|
||||
stack.webhook.stop(),
|
||||
stack.postgres.stop(),
|
||||
...Object.values(stack.additional).map((container) => container?.stop()),
|
||||
]);
|
||||
await stopNetwork();
|
||||
logStackStopped(stack);
|
||||
archiveEnvFile();
|
||||
removeEnvFile();
|
||||
} else {
|
||||
logStackLeftRunning(stack);
|
||||
}
|
||||
|
||||
started = undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* True if every key in `env` already has the given value in testConfig.bootEnvOverrides — i.e.
|
||||
* the currently-running Mattermost container was already booted this way, so a pw.ensure*() can
|
||||
* skip restartMattermostContainer() for these settings.
|
||||
*/
|
||||
export function bootEnvMatches(env: Record<string, string>): boolean {
|
||||
return Object.entries(env).every(([key, value]) => testConfig.bootEnvOverrides[key] === value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the current Mattermost container and starts a fresh one with additional env merged in —
|
||||
* used for settings like FileSettings.DriverName, ElasticsearchSettings.Backend, or
|
||||
* MM_FEATUREFLAGS_* which are never re-read from a running server, so patchConfig alone can't
|
||||
* change them.
|
||||
*
|
||||
* Safe to call from a Playwright worker process, unlike startStack()/stopStack(): it works from
|
||||
* testConfig's container id and network name rather than the in-process StartedStack, since
|
||||
* global setup (which owns that in-process state) and worker processes are different OS
|
||||
* processes.
|
||||
*
|
||||
* `env` is merged into testConfig.bootEnvOverrides (not replaced) so an earlier pw.ensure*()
|
||||
* call's settings survive a later, unrelated one restarting the same container again. The merged
|
||||
* result, new container id, and new baseURL are appended to .env.testcontainers so any other
|
||||
* process picks up the real current state instead of a stale or default one.
|
||||
*
|
||||
* Always performs the restart without checking whether `env` is already active — callers (e.g.
|
||||
* ensureMinio()/ensureAzurite()) own that decision via bootEnvMatches().
|
||||
*/
|
||||
export async function restartMattermostContainer(env: Record<string, string>): Promise<void> {
|
||||
if (!testConfig.useTestContainers) {
|
||||
throw new Error('restartMattermostContainer requires PW_USE_TESTCONTAINERS=true.');
|
||||
}
|
||||
if (!testConfig.mattermostContainerId || !testConfig.testcontainersNetworkName) {
|
||||
throw new Error(
|
||||
'No running Testcontainers stack to restart (missing Mattermost container id or network name).',
|
||||
);
|
||||
}
|
||||
|
||||
extendTimeoutForRestart();
|
||||
|
||||
testConfig.bootEnvOverrides = {...testConfig.bootEnvOverrides, ...env};
|
||||
|
||||
await execFileAsync('docker', ['rm', '-f', testConfig.mattermostContainerId]);
|
||||
|
||||
const mattermost = await startMattermostContainer(
|
||||
testConfig.testcontainersNetworkName,
|
||||
testConfig.bootEnvOverrides,
|
||||
);
|
||||
|
||||
testConfig.baseURL = resolveUrl(mattermost, MATTERMOST_PORT, MATTERMOST_ALIAS);
|
||||
testConfig.mattermostContainerId = mattermost.getId();
|
||||
clearClientCache();
|
||||
|
||||
appendEnvFile(`restart requested by ${describeCurrentTest()} — env ${JSON.stringify(env)}`);
|
||||
|
||||
logTestcontainers(`restarted server with ${JSON.stringify(env)}.`);
|
||||
}
|
||||
|
||||
// Identifies whichever spec/test is currently driving a restart, so .env.testcontainers's history
|
||||
// shows why the server ended up in its current state. restartMattermostContainer() is always
|
||||
// called from inside a running test, so test.info() should resolve; the fallback only guards a
|
||||
// future caller that isn't.
|
||||
function describeCurrentTest(): string {
|
||||
try {
|
||||
const info = test.info();
|
||||
return `${path.relative(process.cwd(), info.file)} > ${info.title}`;
|
||||
} catch {
|
||||
return 'unknown caller (not running inside a test)';
|
||||
}
|
||||
}
|
||||
|
||||
// startMattermostContainer()'s wait strategy blocks on a scheduler log line whose first tick is
|
||||
// deliberately delayed 60s after startup (see that function's comment), so a restart alone can
|
||||
// exceed the suite's default 60s test timeout before the test has done any of its own work.
|
||||
// Playwright's timeout wouldn't cancel the still-in-flight restart, so a timed-out retry can race
|
||||
// it and hit a container mid-swap. Raising (not just extending) the timeout avoids ratcheting it
|
||||
// down if a later restart in the same test calls this again after some budget is already spent.
|
||||
function extendTimeoutForRestart(): void {
|
||||
try {
|
||||
const info = test.info();
|
||||
info.setTimeout(Math.max(info.timeout, duration.four_min));
|
||||
} catch {
|
||||
// Not running inside a test (e.g. called from a script) — nothing to extend.
|
||||
}
|
||||
}
|
||||
|
||||
// containerRunner mode: join the calling `playwright` container to the same network so its own
|
||||
// connections can use aliases too, instead of mapped ports. Relies on Docker setting the
|
||||
// container's hostname to its own container ID by default, and on the `docker` CLI being
|
||||
// present alongside the mounted socket.
|
||||
//
|
||||
// Takes a network name/ID string rather than a StartedNetwork object: reuseExistingStack() only
|
||||
// has testConfig.testcontainersNetworkName (read from .env.testcontainers) to work with, not a
|
||||
// live handle — and the docker CLI resolves either form the same way, so the freshly-created path
|
||||
// below just passes network.getId() instead.
|
||||
async function joinSelfToNetwork(networkId: string): Promise<void> {
|
||||
const selfContainerId = os.hostname();
|
||||
try {
|
||||
await execFileAsync('docker', ['network', 'connect', networkId, selfContainerId]);
|
||||
} catch (error) {
|
||||
// A CI dispatcher running one spec per process reuses the same stack (and this same
|
||||
// runner container) on every invocation, so this join is attempted again every time —
|
||||
// already-connected isn't a failure, it's the expected steady state after the first.
|
||||
if (String(error).includes('already exists in network')) {
|
||||
return;
|
||||
}
|
||||
throw new Error(
|
||||
'containerRunner mode (PW_TESTCONTAINERS_CONTAINER_RUNNER=true) requires the calling container ' +
|
||||
'to join the Testcontainers network, but "docker network connect" failed for container ' +
|
||||
`"${selfContainerId}": ${String(error)}. Ensure /var/run/docker.sock is mounted and the docker ` +
|
||||
'CLI is installed in this image.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function resolveUrl(container: StartedTestContainer, port: number, alias: string): string {
|
||||
if (testConfig.containerRunner) {
|
||||
return `http://${alias}:${port}`;
|
||||
}
|
||||
return `http://${container.getHost()}:${container.getMappedPort(port)}`;
|
||||
}
|
||||
|
||||
function resolveHostAndPort(container: StartedTestContainer, port: number, alias: string): [string, number] {
|
||||
if (testConfig.containerRunner) {
|
||||
return [alias, port];
|
||||
}
|
||||
return [container.getHost(), container.getMappedPort(port)];
|
||||
}
|
||||
|
||||
// Same containerRunner-aware resolution as resolveUrl()/resolveHostAndPort() above: the alias in
|
||||
// containerRunner mode (the test process is on the Testcontainers network), the host-mapped port
|
||||
// otherwise — direct-DB specs are just another client connecting from wherever the test process
|
||||
// runs.
|
||||
function resolvePostgresUrl(postgres: StartedPostgreSqlContainer): string {
|
||||
const [host, port] = resolveHostAndPort(postgres, POSTGRES_PORT, POSTGRES_ALIAS);
|
||||
return `postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${host}:${port}/${POSTGRES_DB}?sslmode=disable&connect_timeout=10&binary_parameters=yes`;
|
||||
}
|
||||
|
||||
type ContainerMetadata = {alias: string; port: number; image: string};
|
||||
|
||||
const ADDITIONAL_CONTAINER_METADATA: Record<TestContainersServiceName, ContainerMetadata> = {
|
||||
openldap: {alias: OPENLDAP_ALIAS, port: OPENLDAP_PORT, image: OPENLDAP_IMAGE},
|
||||
keycloak: {alias: KEYCLOAK_ALIAS, port: KEYCLOAK_PORT, image: KEYCLOAK_IMAGE},
|
||||
elasticsearch: {
|
||||
alias: ELASTICSEARCH_ALIAS,
|
||||
port: ELASTICSEARCH_PORT,
|
||||
image: `built, Elasticsearch ${ELASTICSEARCH_VERSION}`,
|
||||
},
|
||||
opensearch: {alias: OPENSEARCH_ALIAS, port: OPENSEARCH_PORT, image: `built, OpenSearch ${OPENSEARCH_VERSION}`},
|
||||
minio: {alias: MINIO_ALIAS, port: MINIO_PORT, image: MINIO_IMAGE},
|
||||
azurite: {alias: AZURITE_ALIAS, port: AZURITE_BLOB_PORT, image: AZURITE_IMAGE},
|
||||
};
|
||||
|
||||
function containerEntries(stack: StartedStack): Array<[string, StartedTestContainer, ContainerMetadata]> {
|
||||
const base: Array<[string, StartedTestContainer, ContainerMetadata]> = [
|
||||
['server', stack.mattermost, {alias: MATTERMOST_ALIAS, port: MATTERMOST_PORT, image: testConfig.serverImage}],
|
||||
['postgres', stack.postgres, {alias: POSTGRES_ALIAS, port: POSTGRES_PORT, image: POSTGRES_IMAGE}],
|
||||
['inbucket', stack.inbucket, {alias: INBUCKET_ALIAS, port: INBUCKET_WEB_PORT, image: INBUCKET_IMAGE}],
|
||||
['webhook', stack.webhook, {alias: WEBHOOK_ALIAS, port: WEBHOOK_PORT, image: 'built, webhook sidecar'}],
|
||||
];
|
||||
|
||||
const additional = Object.entries(stack.additional)
|
||||
.filter((entry): entry is [TestContainersServiceName, StartedTestContainer] => entry[1] !== undefined)
|
||||
.map((entry): [string, StartedTestContainer, ContainerMetadata] => [
|
||||
entry[0],
|
||||
entry[1],
|
||||
ADDITIONAL_CONTAINER_METADATA[entry[0]],
|
||||
]);
|
||||
|
||||
return [...base, ...additional];
|
||||
}
|
||||
|
||||
function formatContainerLine(name: string, container: StartedTestContainer, metadata: ContainerMetadata): string {
|
||||
const host = `${container.getHost()}:${container.getMappedPort(metadata.port)}`;
|
||||
return ` - ${name.padEnd(13)} = ${metadata.image} (network: ${metadata.alias}:${metadata.port}, host: ${host})`;
|
||||
}
|
||||
|
||||
function elapsedSeconds(startedAt: number): string {
|
||||
return ((Date.now() - startedAt) / 1000).toFixed(1);
|
||||
}
|
||||
|
||||
// `master`/`release-*` tags get rebuilt continuously, so a cached copy can silently go stale;
|
||||
// pinned version tags (e.g. `:11.10.0`) never change, so they're excluded.
|
||||
const MUTABLE_IMAGE_TAG_PATTERN = /:(master|release-.+)$/;
|
||||
|
||||
async function logServerImageAge(image: string): Promise<void> {
|
||||
let created: Date;
|
||||
try {
|
||||
const {stdout} = await execFileAsync('docker', ['image', 'inspect', image, '--format', '{{.Created}}']);
|
||||
created = new Date(stdout.trim());
|
||||
} catch {
|
||||
// Not cached locally — Testcontainers will pull it fresh as part of starting the
|
||||
// container, so whatever comes up is already the latest build. Nothing to warn about.
|
||||
logTestcontainers(`server image "${image}" isn't cached locally yet — will pull the latest build.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const ageHours = (Date.now() - created.getTime()) / (60 * 60 * 1000);
|
||||
const age = ageHours >= 48 ? `${(ageHours / 24).toFixed()}d` : `${ageHours.toFixed()}h`;
|
||||
const looksStale = MUTABLE_IMAGE_TAG_PATTERN.test(image) && ageHours > 24;
|
||||
|
||||
logTestcontainers(
|
||||
`server image "${image}" (built ${created.toISOString()}, ${age} ago).` +
|
||||
(looksStale
|
||||
? ` This is a moving tag and the cached copy may be outdated — run "docker pull ${image}" for the latest build.`
|
||||
: ''),
|
||||
);
|
||||
}
|
||||
|
||||
function logStackStarted(stack: StartedStack): void {
|
||||
const lines = containerEntries(stack).map(([name, container, metadata]) =>
|
||||
formatContainerLine(name, container, metadata),
|
||||
);
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`Testcontainers (network ${stack.network.getId()}):\n${lines.join('\n')}`);
|
||||
}
|
||||
|
||||
function logStackStopped(stack: StartedStack): void {
|
||||
const names = containerEntries(stack).map(([name]) => name);
|
||||
logTestcontainers(`stopped ${names.join(', ')}.`);
|
||||
}
|
||||
|
||||
function logStackLeftRunning(stack: StartedStack): void {
|
||||
const serverUrl = resolveUrl(stack.mattermost, MATTERMOST_PORT, MATTERMOST_ALIAS);
|
||||
logTestcontainers(
|
||||
`left running (PW_TESTCONTAINERS_REUSE=true) — server reachable at ${serverUrl}; may tear down with: "npm run testcontainers:down"`,
|
||||
);
|
||||
}
|
||||
|
||||
// Mutates the testConfig singleton in place so the rest of globalSetup (same process) sees the
|
||||
// real resolved values immediately — the generated env file (resetEnvFile) is what hands these
|
||||
// same values to worker processes.
|
||||
function applyResolvedConfig(stack: StartedStack): void {
|
||||
testConfig.baseURL = resolveUrl(stack.mattermost, MATTERMOST_PORT, MATTERMOST_ALIAS);
|
||||
testConfig.smtpURL = resolveUrl(stack.inbucket, INBUCKET_WEB_PORT, INBUCKET_ALIAS);
|
||||
testConfig.postgresUrl = resolvePostgresUrl(stack.postgres);
|
||||
testConfig.webhookBaseUrl = resolveUrl(stack.webhook, WEBHOOK_PORT, WEBHOOK_ALIAS);
|
||||
testConfig.testcontainersNetworkName = stack.network.getName();
|
||||
testConfig.mattermostContainerId = stack.mattermost.getId();
|
||||
|
||||
if (stack.additional.openldap) {
|
||||
const [host, port] = resolveHostAndPort(stack.additional.openldap, OPENLDAP_PORT, OPENLDAP_ALIAS);
|
||||
testConfig.ldapHost = host;
|
||||
testConfig.ldapPort = port;
|
||||
}
|
||||
if (stack.additional.keycloak) {
|
||||
testConfig.keycloakUrl = resolveUrl(stack.additional.keycloak, KEYCLOAK_PORT, KEYCLOAK_ALIAS);
|
||||
}
|
||||
if (stack.additional.elasticsearch) {
|
||||
testConfig.elasticsearchUrl = resolveUrl(
|
||||
stack.additional.elasticsearch,
|
||||
ELASTICSEARCH_PORT,
|
||||
ELASTICSEARCH_ALIAS,
|
||||
);
|
||||
}
|
||||
if (stack.additional.opensearch) {
|
||||
testConfig.opensearchUrl = resolveUrl(stack.additional.opensearch, OPENSEARCH_PORT, OPENSEARCH_ALIAS);
|
||||
}
|
||||
if (stack.additional.minio) {
|
||||
testConfig.minioUrl = resolveUrl(stack.additional.minio, MINIO_PORT, MINIO_ALIAS);
|
||||
}
|
||||
if (stack.additional.azurite) {
|
||||
testConfig.azuriteUrl = resolveUrl(stack.additional.azurite, AZURITE_BLOB_PORT, AZURITE_ALIAS);
|
||||
}
|
||||
}
|
||||
|
||||
// One block per write: a human-readable `# [timestamp] label` comment line (dotenv ignores
|
||||
// `#`-led lines) followed by the current resolved KEY=VALUE state, including bootEnvOverrides
|
||||
// JSON-encoded and single-quoted so its embedded double quotes/braces survive dotenv's parser.
|
||||
function envFileLines(label: string): string[] {
|
||||
return [
|
||||
`# [${new Date().toISOString()}] ${label}`,
|
||||
`PW_BASE_URL=${testConfig.baseURL}`,
|
||||
`PW_SMTP_URL=${testConfig.smtpURL}`,
|
||||
`PW_POSTGRES_URL=${testConfig.postgresUrl}`,
|
||||
`PW_WEBHOOK_BASE_URL=${testConfig.webhookBaseUrl}`,
|
||||
`PW_TESTCONTAINERS_NETWORK_GATEWAY_IP=${testConfig.testcontainersNetworkGatewayIp}`,
|
||||
`PW_LDAP_HOST=${testConfig.ldapHost}`,
|
||||
`PW_LDAP_PORT=${testConfig.ldapPort}`,
|
||||
`PW_KEYCLOAK_URL=${testConfig.keycloakUrl}`,
|
||||
`PW_ELASTICSEARCH_URL=${testConfig.elasticsearchUrl}`,
|
||||
`PW_OPENSEARCH_URL=${testConfig.opensearchUrl}`,
|
||||
`PW_MINIO_URL=${testConfig.minioUrl}`,
|
||||
`PW_AZURITE_URL=${testConfig.azuriteUrl}`,
|
||||
`PW_TESTCONTAINERS_NETWORK_NAME=${testConfig.testcontainersNetworkName}`,
|
||||
`PW_TESTCONTAINERS_MATTERMOST_CONTAINER_ID=${testConfig.mattermostContainerId}`,
|
||||
`PW_TESTCONTAINERS_BOOT_ENV='${JSON.stringify(testConfig.bootEnvOverrides)}'`,
|
||||
'',
|
||||
];
|
||||
}
|
||||
|
||||
// (Re)creates .env.testcontainers from scratch — only called once, when a brand new stack boots,
|
||||
// so a leftover file from an earlier (now-dead) stack never bleeds into this one.
|
||||
function resetEnvFile(label: string): void {
|
||||
fs.writeFileSync(ENV_FILE_PATH, envFileLines(label).join('\n') + '\n', 'utf-8');
|
||||
}
|
||||
|
||||
/**
|
||||
* Appends a new snapshot block instead of overwriting — dotenv resolves the correct current value
|
||||
* per key when a fresh process parses the file (later occurrences win), while the file as a whole
|
||||
* becomes a chronological log of every restart: which spec/test triggered it, what env diff was
|
||||
* requested, and the full resolved state right after. That's what's needed to investigate
|
||||
* server-state drift after the fact, since in the CI dispatch model no single process ever sees
|
||||
* the whole picture on its own.
|
||||
*/
|
||||
function appendEnvFile(label: string): void {
|
||||
fs.appendFileSync(ENV_FILE_PATH, envFileLines(label).join('\n') + '\n', 'utf-8');
|
||||
}
|
||||
|
||||
// Preserves the full restart history as a debug artifact before it's deleted — logs/ is already
|
||||
// what CI's upload-debug-artifacts step picks up, so this needs no separate wiring.
|
||||
function archiveEnvFile(): void {
|
||||
if (!fs.existsSync(ENV_FILE_PATH)) {
|
||||
return;
|
||||
}
|
||||
fs.mkdirSync(LOG_DIR, {recursive: true});
|
||||
fs.copyFileSync(ENV_FILE_PATH, path.join(LOG_DIR, 'testcontainers_env_history.log'));
|
||||
}
|
||||
|
||||
function removeEnvFile(): void {
|
||||
if (fs.existsSync(ENV_FILE_PATH)) {
|
||||
fs.rmSync(ENV_FILE_PATH);
|
||||
}
|
||||
}
|
||||
|
||||
async function collectLogs(stack: StartedStack): Promise<void> {
|
||||
fs.mkdirSync(LOG_DIR, {recursive: true});
|
||||
|
||||
const targets: Array<[string, StartedTestContainer]> = [
|
||||
['mattermost', stack.mattermost],
|
||||
['postgres', stack.postgres],
|
||||
['inbucket', stack.inbucket],
|
||||
['webhook', stack.webhook],
|
||||
...Object.entries(stack.additional).filter(
|
||||
(entry): entry is [string, StartedTestContainer] => entry[1] !== undefined,
|
||||
),
|
||||
];
|
||||
|
||||
await Promise.allSettled(
|
||||
targets.map(async ([name, container]) => {
|
||||
const logStream = await container.logs();
|
||||
const outFile = fs.createWriteStream(path.join(LOG_DIR, `${name}.log`));
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
logStream.pipe(outFile);
|
||||
// Don't let a stalled log stream hold up teardown indefinitely.
|
||||
const timer = setTimeout(() => {
|
||||
outFile.end();
|
||||
resolve();
|
||||
}, 10_000);
|
||||
logStream.on('end', () => {
|
||||
clearTimeout(timer);
|
||||
resolve();
|
||||
});
|
||||
logStream.on('error', (error) => {
|
||||
clearTimeout(timer);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {GenericContainer, Wait} from 'testcontainers';
|
||||
import type {StartedNetwork, StartedTestContainer} from 'testcontainers';
|
||||
|
||||
import {TESTCONTAINERS_LABELS, WEBHOOK_ALIAS, WEBHOOK_PORT} from './constants';
|
||||
import {containerAssetPath} from './paths';
|
||||
import {startWithRetry} from './retry';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
|
||||
// Vendored from e2e-tests/cypress/webhook_serve.js — the interactive-message/dialog callback
|
||||
// sidecar tests point PW_WEBHOOK_BASE_URL at. Always started, unlike the other optional services,
|
||||
// since testConfig.webhookBaseUrl defaults to localhost:3000 outside Testcontainers mode too.
|
||||
export async function startWebhookContainer(network: StartedNetwork): Promise<StartedTestContainer> {
|
||||
return startWithRetry('webhook', async () => {
|
||||
// deleteOnExit: false — otherwise the built image bakes in this session's Ryuk id, so Ryuk
|
||||
// reaps the "reused" container the moment this session ends, defeating withReuse() below.
|
||||
const image = await GenericContainer.fromDockerfile(containerAssetPath('webhook'), 'Dockerfile.webhook').build(
|
||||
undefined,
|
||||
{deleteOnExit: false},
|
||||
);
|
||||
|
||||
let builder = image
|
||||
.withExposedPorts(WEBHOOK_PORT)
|
||||
.withNetwork(network)
|
||||
.withNetworkAliases(WEBHOOK_ALIAS)
|
||||
.withLabels(TESTCONTAINERS_LABELS)
|
||||
.withWaitStrategy(Wait.forHttp('/', WEBHOOK_PORT).forStatusCode(200));
|
||||
|
||||
if (testConfig.testcontainersReuse) {
|
||||
builder = builder.withReuse();
|
||||
}
|
||||
|
||||
return builder.start();
|
||||
});
|
||||
}
|
||||
@@ -6,6 +6,8 @@ import path from 'node:path';
|
||||
|
||||
import {test} from './test_fixture';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
|
||||
/**
|
||||
* Starts a server that serves files from ./asset. When run from the monorepo, this will serve files from
|
||||
* e2e-tests/playwright/asset.
|
||||
@@ -48,7 +50,7 @@ export function setupFileServer(): Promise<string> {
|
||||
fileServer.once('message', (message: {type?: string; port?: number}) => {
|
||||
if (message?.type === 'listening' && message.port) {
|
||||
clearTimeout(timeout);
|
||||
resolve(`http://localhost:${message.port}`);
|
||||
resolve(`http://${fileServerHost()}:${message.port}`);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -60,3 +62,11 @@ export function setupFileServer(): Promise<string> {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// localhost isn't reachable from inside the Mattermost container in `testcontainers` mode (it resolves to
|
||||
// the container's own loopback, not the host's). testcontainersNetworkGatewayIp is reachable
|
||||
// from both the container and the host-side browser, so it works as a single URL for both — this
|
||||
// server binds to 0.0.0.0, not just loopback, to accept the former.
|
||||
function fileServerHost(): string {
|
||||
return testConfig.useTestContainers ? testConfig.testcontainersNetworkGatewayIp : 'localhost';
|
||||
}
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
|
||||
export {test, expect, PlaywrightExtended} from './test_fixture';
|
||||
export type {ExtendedFixtures} from './test_fixture';
|
||||
export {testConfig} from './test_config';
|
||||
export {testConfig, TESTCONTAINERS_SERVICE_NAMES} from './test_config';
|
||||
export type {TestContainersServiceName} from './test_config';
|
||||
export {baseGlobalSetup} from './global_setup';
|
||||
export {TestBrowser} from './browser_context';
|
||||
export {getBlobFromAsset, getFileFromAsset} from './file';
|
||||
@@ -22,8 +23,33 @@ export {
|
||||
isWebhookTestServerReachable,
|
||||
setupWebhookTestServer,
|
||||
PlaywrightClient4,
|
||||
generateLdapUser,
|
||||
createLdapUser,
|
||||
updateLdapUser,
|
||||
deleteLdapUser,
|
||||
ldapServerConfig,
|
||||
ensureOpenldap,
|
||||
createKeycloakUser,
|
||||
deleteKeycloakUser,
|
||||
listMinioObjectKeys,
|
||||
ensureMinio,
|
||||
samlServerConfig,
|
||||
ensureKeycloak,
|
||||
elasticsearchServerConfig,
|
||||
opensearchServerConfig,
|
||||
ensureElasticsearch,
|
||||
ensureOpensearch,
|
||||
ensureAzurite,
|
||||
listAzuriteBlobNames,
|
||||
ensureLocalFile,
|
||||
ensurePostgresSearch,
|
||||
ensureFeatureFlag,
|
||||
runMmctl,
|
||||
ensureMmctl,
|
||||
} from './server';
|
||||
export type {InbucketEmail} from './server';
|
||||
export type {InbucketEmail, LdapUser, KeycloakUser, MmctlResult} from './server';
|
||||
|
||||
export {startStack, stopStack} from './containers';
|
||||
|
||||
export {
|
||||
ChannelsPage,
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {BlobServiceClient, StorageSharedKeyCredential} from '@azure/storage-blob';
|
||||
import {test} from '@playwright/test';
|
||||
|
||||
import {
|
||||
AZURITE_ACCOUNT_KEY,
|
||||
AZURITE_ACCOUNT_NAME,
|
||||
AZURITE_ALIAS,
|
||||
AZURITE_BLOB_PORT,
|
||||
AZURITE_CONTAINER,
|
||||
} from '../containers/constants';
|
||||
import {bootEnvMatches, restartMattermostContainer} from '../containers/stack';
|
||||
|
||||
import {uploadProbeImage} from './filestore';
|
||||
import {getAdminClient} from './init';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
|
||||
function getBlobServiceClient(): BlobServiceClient {
|
||||
const credential = new StorageSharedKeyCredential(AZURITE_ACCOUNT_NAME, AZURITE_ACCOUNT_KEY);
|
||||
return new BlobServiceClient(`${testConfig.azuriteUrl}/${AZURITE_ACCOUNT_NAME}`, credential);
|
||||
}
|
||||
|
||||
// Only used internally by ensureAzurite() — not a spec-facing entry point.
|
||||
async function ensureAzuriteContainer(container: string = AZURITE_CONTAINER): Promise<void> {
|
||||
const client = getBlobServiceClient().getContainerClient(container);
|
||||
const exists = await client.exists();
|
||||
if (!exists) {
|
||||
await client.create();
|
||||
}
|
||||
}
|
||||
|
||||
/** Lists every blob name in the container, to confirm the server actually wrote to Azurite. */
|
||||
export async function listAzuriteBlobNames(container: string = AZURITE_CONTAINER): Promise<string[]> {
|
||||
const client = getBlobServiceClient().getContainerClient(container);
|
||||
const names: string[] = [];
|
||||
for await (const blob of client.listBlobsFlat()) {
|
||||
names.push(blob.name);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
// FileSettings' backend is chosen once when the Mattermost process boots and never re-read from a
|
||||
// running server's config, so pointing the server at Azurite can only happen via the env vars the
|
||||
// container starts with — always via the network alias, since the server itself always runs
|
||||
// inside the Testcontainers network. AzureEndpoint under the "custom" cloud is the full service
|
||||
// URL (path-style, account name included), unlike the vhost-style URLs real Azure uses.
|
||||
function azuriteServerEnv(): Record<string, string> {
|
||||
return {
|
||||
MM_FILESETTINGS_DRIVERNAME: 'azureblob',
|
||||
MM_FILESETTINGS_AZURESTORAGEACCOUNT: AZURITE_ACCOUNT_NAME,
|
||||
MM_FILESETTINGS_AZUREAUTHMODE: 'shared_key',
|
||||
MM_FILESETTINGS_AZUREACCESSKEY: AZURITE_ACCOUNT_KEY,
|
||||
MM_FILESETTINGS_AZURECONTAINER: AZURITE_CONTAINER,
|
||||
MM_FILESETTINGS_AZURECLOUD: 'custom',
|
||||
MM_FILESETTINGS_AZUREENDPOINT: `http://${AZURITE_ALIAS}:${AZURITE_BLOB_PORT}/${AZURITE_ACCOUNT_NAME}`,
|
||||
MM_FILESETTINGS_AZURESSL: 'false',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks Azurite was started this run, restarts the server onto it if it isn't already the active
|
||||
* file storage backend, and confirms a real upload actually lands in Azurite — skipping the test
|
||||
* otherwise, instead of failing on an unmet precondition.
|
||||
*/
|
||||
export async function ensureAzurite(): Promise<void> {
|
||||
if (!testConfig.testcontainersServices.includes('azurite')) {
|
||||
test.skip(true, 'Skipping test - azurite not started (set PW_TESTCONTAINERS_SERVICES=azurite)');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await ensureAzuriteContainer();
|
||||
const env = azuriteServerEnv();
|
||||
if (!bootEnvMatches(env)) {
|
||||
await restartMattermostContainer(env);
|
||||
}
|
||||
|
||||
const {adminClient, adminUser} = await getAdminClient();
|
||||
await uploadProbeImage(adminClient, adminUser);
|
||||
|
||||
const blobNames = await listAzuriteBlobNames();
|
||||
if (blobNames.length === 0) {
|
||||
throw new Error(
|
||||
'Azurite container is still empty after a real upload — the server is not actually using ' +
|
||||
'Azurite as its file backend.',
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
test.skip(true, `Skipping test - Azurite connection test failed: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,17 @@ import {testConfig} from '@/test_config';
|
||||
// Variable to hold cache
|
||||
const clients: Record<string, ClientCache> = {};
|
||||
|
||||
/**
|
||||
* Drops every cached client, so the next makeClient()/getAdminClient() call logs in again instead
|
||||
* of reusing a session pointed at a Mattermost container that no longer exists — needed after
|
||||
* restartMattermostContainer() swaps in a fresh container (new base URL, new session).
|
||||
*/
|
||||
export function clearClientCache(): void {
|
||||
for (const key of Object.keys(clients)) {
|
||||
delete clients[key];
|
||||
}
|
||||
}
|
||||
|
||||
export async function makeClient(
|
||||
userRequest?: UserRequest,
|
||||
opts: {useCache?: boolean; skipLog?: boolean} = {useCache: true, skipLog: false},
|
||||
|
||||
@@ -79,7 +79,12 @@ const onPremServerConfig = (): Partial<TestAdminConfig> => {
|
||||
},
|
||||
},
|
||||
ServiceSettings: {
|
||||
SiteURL: testConfig.baseURL,
|
||||
// SiteURL is the server's own view of itself (e.g. for building plugin callback
|
||||
// URLs), so it must use an address the server can reach itself with. In `testcontainers` mode
|
||||
// testConfig.baseURL is a host-mapped port the server's own container can't reach;
|
||||
// internalBaseURL is the Docker network alias there, and the same as baseURL in
|
||||
// `external` mode — correct in both cases.
|
||||
SiteURL: testConfig.internalBaseURL,
|
||||
EnableOnboardingFlow: false,
|
||||
EnableSecurityFixAlert: false,
|
||||
GiphySdkKey: 's0glxvzVg9azvPipKxcPLpXV0q1x1fVP',
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {test} from '@playwright/test';
|
||||
import type {AdminConfig} from '@mattermost/types/config';
|
||||
|
||||
import {ELASTICSEARCH_ALIAS, ELASTICSEARCH_PORT} from '../containers/constants';
|
||||
import {bootEnvMatches, restartMattermostContainer} from '../containers/stack';
|
||||
|
||||
import {getAdminClient} from './init';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
|
||||
// The Mattermost server always connects to Elasticsearch itself (indexing/search requests), so it
|
||||
// needs the Testcontainers network alias, not a host-mapped address.
|
||||
export function elasticsearchServerConfig(): Partial<AdminConfig['ElasticsearchSettings']> {
|
||||
return {
|
||||
ConnectionURL: `http://${ELASTICSEARCH_ALIAS}:${ELASTICSEARCH_PORT}`,
|
||||
EnableIndexing: true,
|
||||
EnableSearching: true,
|
||||
EnableAutocomplete: true,
|
||||
Sniff: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks Elasticsearch was started this run, restarts the server onto it if the Elasticsearch Go
|
||||
* client isn't already the registered search engine, and confirms the server can actually reach
|
||||
* it — skipping the test otherwise, instead of failing on an unmet precondition. Backend picks
|
||||
* which of two Go implementations (Elasticsearch vs OpenSearch client) the server registers — a
|
||||
* factory invoked once at startup, never re-invoked by the config-change watcher — so switching it
|
||||
* needs a restart, unlike the rest of ElasticsearchSettings, which the watcher does pick up live.
|
||||
*/
|
||||
export async function ensureElasticsearch(): Promise<void> {
|
||||
if (!testConfig.testcontainersServices.includes('elasticsearch')) {
|
||||
test.skip(true, 'Skipping test - elasticsearch not started (set PW_TESTCONTAINERS_SERVICES=elasticsearch)');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const env = {MM_ELASTICSEARCHSETTINGS_BACKEND: 'elasticsearch'};
|
||||
if (!bootEnvMatches(env)) {
|
||||
await restartMattermostContainer(env);
|
||||
}
|
||||
|
||||
const {adminClient} = await getAdminClient();
|
||||
await adminClient.patchConfig({ElasticsearchSettings: elasticsearchServerConfig()});
|
||||
await adminClient.testElasticsearch();
|
||||
} catch (error) {
|
||||
test.skip(true, `Skipping test - Elasticsearch connection test failed: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
@@ -47,6 +47,12 @@ export async function getRecentEmail(
|
||||
throw new Error(`Timed out waiting for email to ${recipient}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts a link matching `pathname` from the email body and rewrites its origin to
|
||||
* testConfig.baseURL. Links come back carrying ServiceSettings.SiteURL's origin, which in
|
||||
* `testcontainers` mode is the Docker network alias the server uses to reach itself — not reachable from this
|
||||
* test process or its browser.
|
||||
*/
|
||||
export function extractEmailLink(email: InbucketEmail, pathname: string): string {
|
||||
const escapedPathname = pathname.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const link = email.body.text.match(new RegExp(`https?://[^\\s<>"')]+${escapedPathname}[^\\s<>"')]+`))?.[0];
|
||||
@@ -55,7 +61,13 @@ export function extractEmailLink(email: InbucketEmail, pathname: string): string
|
||||
throw new Error(`Email to ${email.to.join(', ')} does not contain a link for ${pathname}`);
|
||||
}
|
||||
|
||||
return link.replaceAll('&', '&');
|
||||
const unescaped = link.replaceAll('&', '&');
|
||||
const rewritten = new URL(unescaped);
|
||||
const reachable = new URL(testConfig.baseURL);
|
||||
rewritten.protocol = reachable.protocol;
|
||||
rewritten.host = reachable.host;
|
||||
|
||||
return rewritten.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {test} from '@playwright/test';
|
||||
|
||||
import {bootEnvMatches, restartMattermostContainer} from '../containers/stack';
|
||||
|
||||
import {getAdminClient} from './init';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
|
||||
/**
|
||||
* Restarts the server with the given feature flag set to `value` if it isn't already, and
|
||||
* confirms the running server actually reports that value — skipping the test otherwise, instead
|
||||
* of failing on an unmet precondition.
|
||||
*
|
||||
* FeatureFlags can't be changed via patchConfig on a running server at all: with no Split key
|
||||
* configured (this test setup never sets one), the config store's readOnlyFF handling reverts any
|
||||
* FeatureFlags patch back to its prior value before it's even persisted
|
||||
* (server/config/store.go's Set()/Load()), so only a boot-time MM_FEATUREFLAGS_* env var actually
|
||||
* takes effect.
|
||||
*/
|
||||
export async function ensureFeatureFlag(flagName: string, value: boolean): Promise<void> {
|
||||
if (!testConfig.useTestContainers) {
|
||||
test.skip(true, 'Skipping test - feature flag restart requires PW_USE_TESTCONTAINERS=true');
|
||||
return;
|
||||
}
|
||||
|
||||
const envKey = `MM_FEATUREFLAGS_${flagName.toUpperCase()}`;
|
||||
const envValue = String(value);
|
||||
|
||||
try {
|
||||
const env = {[envKey]: envValue};
|
||||
if (!bootEnvMatches(env)) {
|
||||
await restartMattermostContainer(env);
|
||||
}
|
||||
|
||||
const {adminClient} = await getAdminClient();
|
||||
const config = await adminClient.getConfig();
|
||||
const actual = config.FeatureFlags?.[flagName];
|
||||
if (String(actual) !== envValue) {
|
||||
throw new Error(`Feature flag "${flagName}" is "${String(actual)}" after restart, expected "${envValue}".`);
|
||||
}
|
||||
} catch (error) {
|
||||
test.skip(true, `Skipping test - feature flag "${flagName}" check failed: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {test} from '@playwright/test';
|
||||
import type {Client4} from '@mattermost/client';
|
||||
import type {UserProfile} from '@mattermost/types/users';
|
||||
|
||||
import {bootEnvMatches, restartMattermostContainer} from '../containers/stack';
|
||||
|
||||
import {getAdminClient} from './init';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
|
||||
// A 1x1 transparent PNG, just to exercise a real write through the server's file backend.
|
||||
const PROBE_IMAGE_BASE64_PNG =
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=';
|
||||
|
||||
/** Uploads a throwaway profile image, exercising the server's real, live file backend. */
|
||||
export async function uploadProbeImage(adminClient: Client4, adminUser: UserProfile | null): Promise<void> {
|
||||
if (!adminUser) {
|
||||
throw new Error('No admin user available to probe a real upload with.');
|
||||
}
|
||||
const probeImage = new File([Buffer.from(PROBE_IMAGE_BASE64_PNG, 'base64')], 'probe.png', {type: 'image/png'});
|
||||
await adminClient.uploadProfileImage(adminUser.id, probeImage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Restarts the server onto local disk storage if it isn't already there, and confirms a real
|
||||
* upload actually works — skipping the test otherwise, instead of failing on an unmet
|
||||
* precondition. The counterpart to ensureMinio()/ensureAzurite() for specs that specifically need
|
||||
* local storage active (e.g. after another spec in the same run switched it away).
|
||||
*/
|
||||
export async function ensureLocalFile(): Promise<void> {
|
||||
if (!testConfig.useTestContainers) {
|
||||
test.skip(true, 'Skipping test - local file storage restart requires PW_USE_TESTCONTAINERS=true');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const env = {MM_FILESETTINGS_DRIVERNAME: 'local'};
|
||||
if (!bootEnvMatches(env)) {
|
||||
await restartMattermostContainer(env);
|
||||
}
|
||||
|
||||
const {adminClient, adminUser} = await getAdminClient();
|
||||
await uploadProbeImage(adminClient, adminUser);
|
||||
} catch (error) {
|
||||
test.skip(true, `Skipping test - local file storage check failed: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
@@ -38,3 +38,23 @@ export {
|
||||
} from './abac_helpers';
|
||||
export {installAndEnablePlugin, isPluginActive, getPluginStatus} from './plugin';
|
||||
export {isWebhookTestServerReachable, setupWebhookTestServer} from './webhook_server';
|
||||
export {
|
||||
generateLdapUser,
|
||||
createLdapUser,
|
||||
updateLdapUser,
|
||||
deleteLdapUser,
|
||||
ldapServerConfig,
|
||||
ensureOpenldap,
|
||||
} from './openldap';
|
||||
export type {LdapUser} from './openldap';
|
||||
export {createKeycloakUser, deleteKeycloakUser, samlServerConfig, ensureKeycloak} from './keycloak';
|
||||
export type {KeycloakUser} from './keycloak';
|
||||
export {listMinioObjectKeys, ensureMinio} from './minio';
|
||||
export {elasticsearchServerConfig, ensureElasticsearch} from './elasticsearch';
|
||||
export {opensearchServerConfig, ensureOpensearch} from './opensearch';
|
||||
export {ensureAzurite, listAzuriteBlobNames} from './azurite';
|
||||
export {ensureLocalFile} from './filestore';
|
||||
export {ensurePostgresSearch} from './postgres_search';
|
||||
export {ensureFeatureFlag} from './feature_flags';
|
||||
export {runMmctl, ensureMmctl} from './mmctl';
|
||||
export type {MmctlResult} from './mmctl';
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {test} from '@playwright/test';
|
||||
import type {Client4} from '@mattermost/client';
|
||||
import type {AdminConfig} from '@mattermost/types/config';
|
||||
|
||||
import {
|
||||
KEYCLOAK_ADMIN_PASSWORD,
|
||||
KEYCLOAK_ADMIN_USER,
|
||||
KEYCLOAK_ALIAS,
|
||||
KEYCLOAK_PORT,
|
||||
KEYCLOAK_REALM,
|
||||
} from '../containers/constants';
|
||||
|
||||
import {getAdminClient} from './init';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
|
||||
export type KeycloakUser = {
|
||||
username: string;
|
||||
email: string;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
password: string;
|
||||
};
|
||||
|
||||
async function getAdminToken(): Promise<string> {
|
||||
const response = await fetch(`${testConfig.keycloakUrl}/realms/master/protocol/openid-connect/token`, {
|
||||
method: 'POST',
|
||||
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
|
||||
body: new URLSearchParams({
|
||||
grant_type: 'password',
|
||||
client_id: 'admin-cli',
|
||||
username: KEYCLOAK_ADMIN_USER,
|
||||
password: KEYCLOAK_ADMIN_PASSWORD,
|
||||
}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to get Keycloak admin token: ${response.status} ${await response.text()}`);
|
||||
}
|
||||
|
||||
const body = (await response.json()) as {access_token: string};
|
||||
return body.access_token;
|
||||
}
|
||||
|
||||
/** Creates the user in Keycloak and returns its Keycloak user id. */
|
||||
export async function createKeycloakUser(user: KeycloakUser): Promise<string> {
|
||||
const token = await getAdminToken();
|
||||
const response = await fetch(`${testConfig.keycloakUrl}/admin/realms/${KEYCLOAK_REALM}/users`, {
|
||||
method: 'POST',
|
||||
headers: {Authorization: `Bearer ${token}`, 'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({
|
||||
username: user.username,
|
||||
email: user.email,
|
||||
firstName: user.firstName,
|
||||
lastName: user.lastName,
|
||||
enabled: true,
|
||||
credentials: [{type: 'password', value: user.password, temporary: false}],
|
||||
}),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to create Keycloak user: ${response.status} ${await response.text()}`);
|
||||
}
|
||||
|
||||
const location = response.headers.get('Location');
|
||||
const userId = location?.split('/').pop();
|
||||
if (!userId) {
|
||||
throw new Error('Keycloak user creation response had no Location header to read the new user id from.');
|
||||
}
|
||||
return userId;
|
||||
}
|
||||
|
||||
export async function deleteKeycloakUser(userId: string): Promise<void> {
|
||||
const token = await getAdminToken();
|
||||
const response = await fetch(`${testConfig.keycloakUrl}/admin/realms/${KEYCLOAK_REALM}/users/${userId}`, {
|
||||
method: 'DELETE',
|
||||
headers: {Authorization: `Bearer ${token}`},
|
||||
});
|
||||
if (!response.ok && response.status !== 404) {
|
||||
throw new Error(`Failed to delete Keycloak user: ${response.status} ${await response.text()}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Matches the SAML client's clientId in keycloak-realm-export.json.
|
||||
const SAML_SERVICE_PROVIDER_ID = 'mattermost';
|
||||
|
||||
// The Mattermost server fetches this URL itself (via POST /saml/metadatafromidp), so it must be
|
||||
// reachable from inside the Testcontainers network — unlike the IdpURL/IdpDescriptorURL below,
|
||||
// which the browser follows directly and so must be reachable from the host instead. Only the
|
||||
// certificate from this response is used; its embedded URLs reflect the alias host, not the one
|
||||
// the browser needs.
|
||||
function keycloakSamlDescriptorUrl(): string {
|
||||
return `http://${KEYCLOAK_ALIAS}:${KEYCLOAK_PORT}/realms/${KEYCLOAK_REALM}/protocol/saml/descriptor`;
|
||||
}
|
||||
|
||||
// The metadata response's certificate is the raw base64 DER content straight out of the SAML
|
||||
// metadata XML's <X509Certificate> element — no PEM armor — but IdpCertificateFile parsing
|
||||
// requires a proper PEM block.
|
||||
function toPemCertificate(base64Der: string): string {
|
||||
const lines = base64Der.replace(/\s+/g, '').match(/.{1,64}/g) ?? [];
|
||||
return `-----BEGIN CERTIFICATE-----\n${lines.join('\n')}\n-----END CERTIFICATE-----\n`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches Keycloak's SAML IdP certificate (via the server's own metadata-from-IdP call) and
|
||||
* uploads it, then returns a `SamlSettings` patch pointing the server at Keycloak's SAML IdP and
|
||||
* the users `createKeycloakUser` creates.
|
||||
*/
|
||||
export async function samlServerConfig(adminClient: Client4): Promise<Partial<AdminConfig['SamlSettings']>> {
|
||||
const metadata = await adminClient.getSamlMetadataFromIdp(keycloakSamlDescriptorUrl());
|
||||
const certificate = toPemCertificate(metadata.idp_public_certificate);
|
||||
await adminClient.uploadIdpSamlCertificate(new File([certificate], 'idp-certificate.crt'));
|
||||
|
||||
return {
|
||||
Enable: true,
|
||||
Verify: true,
|
||||
Encrypt: false,
|
||||
SignRequest: false,
|
||||
IdpURL: `${testConfig.keycloakUrl}/realms/${KEYCLOAK_REALM}/protocol/saml`,
|
||||
IdpDescriptorURL: `${testConfig.keycloakUrl}/realms/${KEYCLOAK_REALM}`,
|
||||
ServiceProviderIdentifier: SAML_SERVICE_PROVIDER_ID,
|
||||
AssertionConsumerServiceURL: `${testConfig.baseURL}/login/sso/saml`,
|
||||
IdAttribute: 'id',
|
||||
EmailAttribute: 'email',
|
||||
UsernameAttribute: 'username',
|
||||
FirstNameAttribute: 'givenName',
|
||||
LastNameAttribute: 'surname',
|
||||
LoginButtonText: 'Keycloak SAML',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks Keycloak was started this run, points the server's SAML settings at it (fetching its IdP
|
||||
* metadata/certificate along the way), and skips the test if either step fails, instead of
|
||||
* failing on an unmet precondition.
|
||||
*/
|
||||
export async function ensureKeycloak(): Promise<void> {
|
||||
if (!testConfig.testcontainersServices.includes('keycloak')) {
|
||||
test.skip(true, 'Skipping test - keycloak not started (set PW_TESTCONTAINERS_SERVICES=keycloak)');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const {adminClient} = await getAdminClient();
|
||||
const config = await samlServerConfig(adminClient);
|
||||
await adminClient.patchConfig({SamlSettings: config});
|
||||
} catch (error) {
|
||||
test.skip(true, `Skipping test - Keycloak SAML setup failed: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {Client as MinioClient} from 'minio';
|
||||
import {test} from '@playwright/test';
|
||||
|
||||
import {MINIO_ACCESS_KEY, MINIO_ALIAS, MINIO_BUCKET, MINIO_PORT, MINIO_SECRET_KEY} from '../containers/constants';
|
||||
import {bootEnvMatches, restartMattermostContainer} from '../containers/stack';
|
||||
|
||||
import {uploadProbeImage} from './filestore';
|
||||
import {getAdminClient} from './init';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
|
||||
function getMinioClient(): MinioClient {
|
||||
const url = new URL(testConfig.minioUrl);
|
||||
return new MinioClient({
|
||||
endPoint: url.hostname,
|
||||
port: Number(url.port),
|
||||
useSSL: url.protocol === 'https:',
|
||||
accessKey: MINIO_ACCESS_KEY,
|
||||
secretKey: MINIO_SECRET_KEY,
|
||||
});
|
||||
}
|
||||
|
||||
// Only used internally by ensureMinio() — not a spec-facing entry point.
|
||||
async function ensureMinioBucket(bucket: string = MINIO_BUCKET): Promise<void> {
|
||||
const client = getMinioClient();
|
||||
const exists = await client.bucketExists(bucket);
|
||||
if (!exists) {
|
||||
await client.makeBucket(bucket);
|
||||
}
|
||||
}
|
||||
|
||||
/** Lists every object key in the bucket, to confirm the server actually wrote to Minio. */
|
||||
export async function listMinioObjectKeys(bucket: string = MINIO_BUCKET): Promise<string[]> {
|
||||
const client = getMinioClient();
|
||||
const keys: string[] = [];
|
||||
for await (const item of client.listObjectsV2(bucket, '', true)) {
|
||||
if (item.name) {
|
||||
keys.push(item.name);
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
// FileSettings' backend is chosen once when the Mattermost process boots and never re-read from a
|
||||
// running server's config, so pointing the server at Minio can only happen via the env vars the
|
||||
// container starts with — always via the network alias, since the server itself always runs
|
||||
// inside the Testcontainers network.
|
||||
function minioServerEnv(): Record<string, string> {
|
||||
return {
|
||||
MM_FILESETTINGS_DRIVERNAME: 'amazons3',
|
||||
MM_FILESETTINGS_AMAZONS3ENDPOINT: `${MINIO_ALIAS}:${MINIO_PORT}`,
|
||||
MM_FILESETTINGS_AMAZONS3ACCESSKEYID: MINIO_ACCESS_KEY,
|
||||
MM_FILESETTINGS_AMAZONS3SECRETACCESSKEY: MINIO_SECRET_KEY,
|
||||
MM_FILESETTINGS_AMAZONS3BUCKET: MINIO_BUCKET,
|
||||
MM_FILESETTINGS_AMAZONS3SSL: 'false',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks Minio was started this run, restarts the server onto it if it isn't already the active
|
||||
* file storage backend, and confirms a real upload actually lands in Minio — skipping the test
|
||||
* otherwise, instead of failing on an unmet precondition.
|
||||
*/
|
||||
export async function ensureMinio(): Promise<void> {
|
||||
if (!testConfig.testcontainersServices.includes('minio')) {
|
||||
test.skip(true, 'Skipping test - minio not started (set PW_TESTCONTAINERS_SERVICES=minio)');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await ensureMinioBucket();
|
||||
const env = minioServerEnv();
|
||||
if (!bootEnvMatches(env)) {
|
||||
await restartMattermostContainer(env);
|
||||
}
|
||||
|
||||
const {adminClient, adminUser} = await getAdminClient();
|
||||
await uploadProbeImage(adminClient, adminUser);
|
||||
|
||||
const objectKeys = await listMinioObjectKeys();
|
||||
if (objectKeys.length === 0) {
|
||||
throw new Error(
|
||||
'Minio bucket is still empty after a real upload — the server is not actually using Minio ' +
|
||||
'as its file backend.',
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
test.skip(true, `Skipping test - Minio connection test failed: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {test} from '@playwright/test';
|
||||
|
||||
import {runMmctl as runMmctlContainer} from '../containers/mmctl_container';
|
||||
import type {MmctlResult} from '../containers/mmctl_container';
|
||||
|
||||
import {getAdminClient} from './init';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
|
||||
export type {MmctlResult};
|
||||
|
||||
/**
|
||||
* Runs an mmctl command as a real remote client: a separate container built from the same server
|
||||
* image, authenticated with the current admin session, reaching the server over the
|
||||
* Testcontainers network rather than the `--local` unix socket the server's own container uses.
|
||||
*/
|
||||
export async function runMmctl(args: string[]): Promise<MmctlResult> {
|
||||
const {adminClient, adminUser} = await getAdminClient();
|
||||
if (!adminUser) {
|
||||
throw new Error('No admin user available to authenticate mmctl with.');
|
||||
}
|
||||
return runMmctlContainer(args, adminUser.username, adminClient.getToken());
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks full (Testcontainers) mode is active and a real remote mmctl invocation actually reaches
|
||||
* the server — skipping the test otherwise, instead of failing on an unmet precondition.
|
||||
*/
|
||||
export async function ensureMmctl(): Promise<void> {
|
||||
if (!testConfig.useTestContainers) {
|
||||
test.skip(true, 'Skipping test - remote mmctl container requires PW_USE_TESTCONTAINERS=true');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const result = await runMmctl(['version']);
|
||||
if (result.exitCode !== 0) {
|
||||
throw new Error(`mmctl exited with code ${result.exitCode}: ${result.output}`);
|
||||
}
|
||||
} catch (error) {
|
||||
test.skip(true, `Skipping test - mmctl connectivity check failed: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {AlreadyExistsError, Attribute, Change, Client} from 'ldapts';
|
||||
import {test} from '@playwright/test';
|
||||
import type {AdminConfig} from '@mattermost/types/config';
|
||||
|
||||
import {
|
||||
OPENLDAP_ADMIN_DN,
|
||||
OPENLDAP_ADMIN_PASSWORD,
|
||||
OPENLDAP_ALIAS,
|
||||
OPENLDAP_BASE_DN,
|
||||
OPENLDAP_PORT,
|
||||
} from '../containers/constants';
|
||||
|
||||
import {getAdminClient} from './init';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
import {getRandomId} from '@/util';
|
||||
|
||||
// Typed in-process LDAP client — avoids depending on external ldapadd/ldapmodify binaries.
|
||||
|
||||
export type LdapUser = {
|
||||
username: string;
|
||||
password: string;
|
||||
email: string;
|
||||
firstname: string;
|
||||
lastname: string;
|
||||
};
|
||||
|
||||
const ORG_UNIT = 'e2etest';
|
||||
const ORG_UNIT_DN = `ou=${ORG_UNIT},${OPENLDAP_BASE_DN}`;
|
||||
|
||||
export function generateLdapUser(prefix = 'ldap'): LdapUser {
|
||||
const randomId = getRandomId();
|
||||
const username = `${prefix}user${randomId}`;
|
||||
return {
|
||||
username,
|
||||
password: 'Password1',
|
||||
email: `${username}@mmtest.com`,
|
||||
firstname: `Firstname-${randomId}`,
|
||||
lastname: `Lastname-${randomId}`,
|
||||
};
|
||||
}
|
||||
|
||||
async function withAdminClient<T>(fn: (client: Client) => Promise<T>): Promise<T> {
|
||||
const client = new Client({url: `ldap://${testConfig.ldapHost}:${testConfig.ldapPort}`});
|
||||
try {
|
||||
await client.bind(OPENLDAP_ADMIN_DN, OPENLDAP_ADMIN_PASSWORD);
|
||||
return await fn(client);
|
||||
} finally {
|
||||
await client.unbind();
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureOrgUnit(client: Client): Promise<void> {
|
||||
try {
|
||||
await client.add(ORG_UNIT_DN, {objectClass: 'organizationalUnit', ou: ORG_UNIT});
|
||||
} catch (error) {
|
||||
if (!(error instanceof AlreadyExistsError)) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Creates the user (and the shared org unit, if it doesn't exist yet) and returns it. */
|
||||
export async function createLdapUser(user: LdapUser = generateLdapUser()): Promise<LdapUser> {
|
||||
await withAdminClient(async (client) => {
|
||||
await ensureOrgUnit(client);
|
||||
await client.add(`uid=${user.username},${ORG_UNIT_DN}`, {
|
||||
objectClass: 'inetOrgPerson',
|
||||
cn: user.firstname,
|
||||
sn: user.lastname,
|
||||
uid: user.username,
|
||||
mail: user.email,
|
||||
userPassword: user.password,
|
||||
});
|
||||
});
|
||||
return user;
|
||||
}
|
||||
|
||||
export async function updateLdapUser(username: string, changes: Partial<Omit<LdapUser, 'username'>>): Promise<void> {
|
||||
await withAdminClient(async (client) => {
|
||||
const dn = `uid=${username},${ORG_UNIT_DN}`;
|
||||
const attributeByType: Array<[string, string | undefined]> = [
|
||||
['cn', changes.firstname],
|
||||
['sn', changes.lastname],
|
||||
['mail', changes.email],
|
||||
['userPassword', changes.password],
|
||||
];
|
||||
|
||||
const modifications = attributeByType
|
||||
.filter((entry): entry is [string, string] => entry[1] !== undefined)
|
||||
.map(
|
||||
([type, value]) =>
|
||||
new Change({operation: 'replace', modification: new Attribute({type, values: [value]})}),
|
||||
);
|
||||
|
||||
if (modifications.length > 0) {
|
||||
await client.modify(dn, modifications);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteLdapUser(username: string): Promise<void> {
|
||||
await withAdminClient(async (client) => {
|
||||
await client.del(`uid=${username},${ORG_UNIT_DN}`);
|
||||
});
|
||||
}
|
||||
|
||||
// In `testcontainers` mode the Mattermost server is itself a container on the Testcontainers network, so it
|
||||
// must reach OpenLDAP via its network alias — unlike testConfig.ldapHost/ldapPort, which resolve to
|
||||
// a host-mapped address for this module's own ldapts client (a separate, non-containerized process).
|
||||
function ldapServerAddress(): [string, number] {
|
||||
return testConfig.useTestContainers ? [OPENLDAP_ALIAS, OPENLDAP_PORT] : [testConfig.ldapHost, testConfig.ldapPort];
|
||||
}
|
||||
|
||||
/** `LdapSettings` patch pointing the server at the OpenLDAP container and the users this module creates. */
|
||||
export function ldapServerConfig(): Partial<AdminConfig['LdapSettings']> {
|
||||
const [ldapServer, ldapPort] = ldapServerAddress();
|
||||
return {
|
||||
Enable: true,
|
||||
LdapServer: ldapServer,
|
||||
LdapPort: ldapPort,
|
||||
BaseDN: ORG_UNIT_DN,
|
||||
BindUsername: OPENLDAP_ADMIN_DN,
|
||||
BindPassword: OPENLDAP_ADMIN_PASSWORD,
|
||||
UserFilter: '(objectClass=inetOrgPerson)',
|
||||
IdAttribute: 'uid',
|
||||
LoginIdAttribute: 'uid',
|
||||
UsernameAttribute: 'uid',
|
||||
EmailAttribute: 'mail',
|
||||
FirstNameAttribute: 'cn',
|
||||
LastNameAttribute: 'sn',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks OpenLDAP was started this run, points the server at it, and confirms the server can
|
||||
* actually reach it — skipping the test otherwise, instead of failing on an unmet precondition.
|
||||
*/
|
||||
export async function ensureOpenldap(): Promise<void> {
|
||||
if (!testConfig.testcontainersServices.includes('openldap')) {
|
||||
test.skip(true, 'Skipping test - openldap not started (set PW_TESTCONTAINERS_SERVICES=openldap)');
|
||||
return;
|
||||
}
|
||||
|
||||
const {adminClient} = await getAdminClient();
|
||||
await adminClient.patchConfig({LdapSettings: ldapServerConfig()});
|
||||
|
||||
// testLdap() searches under BaseDN and requires at least one matching user to succeed, so
|
||||
// probe with a throwaway user rather than depending on whatever the spec creates afterward.
|
||||
const probeUser = generateLdapUser('ensureprobe');
|
||||
try {
|
||||
await createLdapUser(probeUser);
|
||||
await adminClient.testLdap();
|
||||
} catch (error) {
|
||||
test.skip(true, `Skipping test - LDAP connection test failed: ${String(error)}`);
|
||||
} finally {
|
||||
await deleteLdapUser(probeUser.username).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {test} from '@playwright/test';
|
||||
import type {AdminConfig} from '@mattermost/types/config';
|
||||
|
||||
import {OPENSEARCH_ADMIN_PASSWORD, OPENSEARCH_ALIAS, OPENSEARCH_PORT} from '../containers/constants';
|
||||
import {bootEnvMatches, restartMattermostContainer} from '../containers/stack';
|
||||
|
||||
import {getAdminClient} from './init';
|
||||
|
||||
import {testConfig} from '@/test_config';
|
||||
|
||||
// The Mattermost server always connects to OpenSearch itself (indexing/search requests), so it
|
||||
// needs the Testcontainers network alias, not a host-mapped address.
|
||||
export function opensearchServerConfig(): Partial<AdminConfig['ElasticsearchSettings']> {
|
||||
return {
|
||||
ConnectionURL: `http://${OPENSEARCH_ALIAS}:${OPENSEARCH_PORT}`,
|
||||
Username: 'admin',
|
||||
Password: OPENSEARCH_ADMIN_PASSWORD,
|
||||
EnableIndexing: true,
|
||||
EnableSearching: true,
|
||||
EnableAutocomplete: true,
|
||||
Sniff: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks OpenSearch was started this run, restarts the server onto it if the OpenSearch Go client
|
||||
* isn't already the registered search engine, and confirms the server can actually reach it —
|
||||
* skipping the test otherwise, instead of failing on an unmet precondition. Backend picks which of
|
||||
* two Go implementations (Elasticsearch vs OpenSearch client) the server registers — a factory
|
||||
* invoked once at startup, never re-invoked by the config-change watcher — so switching it needs a
|
||||
* restart, unlike the rest of ElasticsearchSettings, which the watcher does pick up live.
|
||||
*/
|
||||
export async function ensureOpensearch(): Promise<void> {
|
||||
if (!testConfig.testcontainersServices.includes('opensearch')) {
|
||||
test.skip(true, 'Skipping test - opensearch not started (set PW_TESTCONTAINERS_SERVICES=opensearch)');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const env = {MM_ELASTICSEARCHSETTINGS_BACKEND: 'opensearch'};
|
||||
if (!bootEnvMatches(env)) {
|
||||
await restartMattermostContainer(env);
|
||||
}
|
||||
|
||||
const {adminClient} = await getAdminClient();
|
||||
await adminClient.patchConfig({ElasticsearchSettings: opensearchServerConfig()});
|
||||
await adminClient.testElasticsearch();
|
||||
} catch (error) {
|
||||
test.skip(true, `Skipping test - OpenSearch connection test failed: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {test} from '@playwright/test';
|
||||
|
||||
import {getAdminClient} from './init';
|
||||
|
||||
/**
|
||||
* Disables Elasticsearch/OpenSearch indexing/searching so search falls back to the database —
|
||||
* skipping the test otherwise, instead of failing on an unmet precondition. The counterpart to
|
||||
* ensureElasticsearch()/ensureOpensearch() for specs that specifically need database-backed search
|
||||
* active (e.g. after another spec in the same run switched it away).
|
||||
*
|
||||
* No restart involved, unlike most other ensure*() functions: which search engine (if any) is
|
||||
* active is decided at runtime from these enable flags, not from the boot-time Backend setting, so
|
||||
* disabling them here is enough to make the server fall through to Postgres-backed search.
|
||||
*/
|
||||
export async function ensurePostgresSearch(): Promise<void> {
|
||||
try {
|
||||
const {adminClient} = await getAdminClient();
|
||||
await adminClient.patchConfig({
|
||||
ElasticsearchSettings: {EnableIndexing: false, EnableSearching: false, EnableAutocomplete: false},
|
||||
});
|
||||
} catch (error) {
|
||||
test.skip(true, `Skipping test - database search check failed: ${String(error)}`);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,28 @@
|
||||
|
||||
import * as dotenv from 'dotenv';
|
||||
|
||||
import {MATTERMOST_ALIAS, MATTERMOST_PORT, WEBHOOK_ALIAS, WEBHOOK_PORT} from './containers/constants';
|
||||
import {MATTERMOST_SERVER_IMAGE} from './containers/default_images';
|
||||
import {SERVER_ENV_BASELINE} from './containers/env_baseline';
|
||||
|
||||
dotenv.config({quiet: true});
|
||||
dotenv.config({path: '.env.testcontainers', quiet: true, override: true});
|
||||
|
||||
// The set of additional services `testcontainers` mode knows how to start.
|
||||
// Single source of truth for `requirements.ts` and for validating PW_TESTCONTAINERS_SERVICES.
|
||||
export const TESTCONTAINERS_SERVICE_NAMES = [
|
||||
'openldap',
|
||||
'keycloak',
|
||||
'elasticsearch',
|
||||
'opensearch',
|
||||
'minio',
|
||||
'azurite',
|
||||
] as const;
|
||||
export type TestContainersServiceName = (typeof TESTCONTAINERS_SERVICE_NAMES)[number];
|
||||
|
||||
// Started whenever PW_TESTCONTAINERS_SERVICES is unset
|
||||
// opensearch and azurite are opt-in only
|
||||
const DEFAULT_TESTCONTAINERS_SERVICES: TestContainersServiceName[] = ['minio', 'openldap', 'keycloak', 'elasticsearch'];
|
||||
|
||||
// All process.env should be defined here
|
||||
export class TestConfig {
|
||||
@@ -24,9 +45,85 @@ export class TestConfig {
|
||||
snapshotEnabled: boolean;
|
||||
percyEnabled: boolean;
|
||||
smtpURL: string;
|
||||
/**
|
||||
* Postgres connection string for specs needing direct DB access to bypass API-level
|
||||
* validation. In `testcontainers` mode the default port is a placeholder — startStack() overwrites
|
||||
* it with the actual Testcontainers-assigned host-mapped port once the container is up.
|
||||
*/
|
||||
postgresUrl: string;
|
||||
|
||||
/** Base URL of the Cypress/Playwright webhook sidecar (`e2e-tests/cypress`: `npm run start:webhook`). */
|
||||
webhookBaseUrl: string;
|
||||
/**
|
||||
* How OTHER containers (not the test process) reach Mattermost — used when a URL is embedded
|
||||
* in a request body the server itself later dereferences (e.g. a webhook callback URL). In
|
||||
* `external` mode this equals baseURL. In `testcontainers` mode it's the fixed Docker network alias,
|
||||
* since a container can't reach another container's host-mapped port via `localhost`.
|
||||
*/
|
||||
internalBaseURL: string;
|
||||
/** Same distinction as internalBaseURL, for the webhook sidecar's own address. */
|
||||
webhookInternalUrl: string;
|
||||
/**
|
||||
* Gateway IP (e.g. 172.18.0.1) of the Testcontainers bridge network in `testcontainers` mode — an
|
||||
* address on the Docker host itself, reachable both from the browser and from inside the
|
||||
* Mattermost container, so a single mock file server URL works for both without a network
|
||||
* alias or mapped port. Empty in `external` mode, where plain localhost already works for
|
||||
* both since neither runs in a container.
|
||||
*/
|
||||
testcontainersNetworkGatewayIp: string;
|
||||
|
||||
// Testcontainers (`testcontainers` mode)
|
||||
|
||||
/** Selects `testcontainers` mode (Testcontainers manages the server + dependencies) over `external` mode (default). */
|
||||
useTestContainers: boolean;
|
||||
/** Prebuilt Mattermost server image `testcontainers` mode starts. Same env var Compose-based CI already uses. */
|
||||
serverImage: string;
|
||||
/** Arbitrary MM_* config overrides merged over the test-oriented baseline, comma-separated KEY=VALUE pairs. */
|
||||
serverEnv: Record<string, string>;
|
||||
/**
|
||||
* Which additional services `testcontainers` mode starts, validated against
|
||||
* `TESTCONTAINERS_SERVICE_NAMES`. Defaults to `DEFAULT_TESTCONTAINERS_SERVICES` when
|
||||
* PW_TESTCONTAINERS_SERVICES is unset; set it to an empty string to start none.
|
||||
*/
|
||||
testcontainersServices: TestContainersServiceName[];
|
||||
/** Reuse containers across repeated local `testcontainers`-mode runs instead of recreating them every time. */
|
||||
testcontainersReuse: boolean;
|
||||
/** Playwright itself runs inside a container (e.g. CI); join it to the Testcontainers network instead of using mapped ports. */
|
||||
containerRunner: boolean;
|
||||
/**
|
||||
* Name of the Docker network the stack runs on. getNetwork()'s in-process cache only helps
|
||||
* within the process that called startStack() (global setup) — worker processes need this to
|
||||
* join a container (e.g. the mmctl runner) to that same network instead of creating their own.
|
||||
*/
|
||||
testcontainersNetworkName: string;
|
||||
/**
|
||||
* ID of the currently-running Mattermost container. Global setup and worker processes are
|
||||
* separate OS processes — this is how a worker's restartMattermostContainer() (e.g. to switch
|
||||
* file storage backends) finds the container to replace without an in-process object handle.
|
||||
*/
|
||||
mattermostContainerId: string;
|
||||
/**
|
||||
* The full set of env vars the current Mattermost container actually booted with — baseline
|
||||
* plus every boot-time-only setting a pw.ensure*() has switched via
|
||||
* restartMattermostContainer() so far. Each ensure*() checks this before restarting, so it
|
||||
* only restarts when something actually needs to change, and restartMattermostContainer()
|
||||
* merges into this record rather than replacing it, so a restart for one setting doesn't
|
||||
* undo another restart's change.
|
||||
*
|
||||
* Persisted to .env.testcontainers and read back rather than recomputed, because a container
|
||||
* can outlive the process that booted it (e.g. reused across specs in CI) — a later process
|
||||
* must see the server's actual current state, not assume defaults.
|
||||
*/
|
||||
bootEnvOverrides: Record<string, string>;
|
||||
|
||||
/** Used in every mode; defaults match the fixed ports the Testcontainers stack publishes. */
|
||||
ldapHost: string;
|
||||
ldapPort: number;
|
||||
keycloakUrl: string;
|
||||
elasticsearchUrl: string;
|
||||
opensearchUrl: string;
|
||||
minioUrl: string;
|
||||
azuriteUrl: string;
|
||||
|
||||
constructor() {
|
||||
// Server
|
||||
@@ -54,7 +151,42 @@ export class TestConfig {
|
||||
this.percyEnabled = parseBool(process.env.PW_PERCY_ENABLE, false);
|
||||
// Email
|
||||
this.smtpURL = process.env.PW_SMTP_URL || 'http://localhost:9001';
|
||||
this.postgresUrl =
|
||||
process.env.PW_POSTGRES_URL ||
|
||||
'postgres://mmuser:mostest@localhost:5432/mattermost_test?sslmode=disable&connect_timeout=10&binary_parameters=yes';
|
||||
this.webhookBaseUrl = process.env.PW_WEBHOOK_BASE_URL || 'http://localhost:3000';
|
||||
|
||||
// Testcontainers
|
||||
this.useTestContainers = parseBool(process.env.PW_USE_TESTCONTAINERS, false);
|
||||
// Fixed Docker network aliases, not derived from any started container object — stable
|
||||
// across a restartMattermostContainer() call, unlike baseURL's host-mapped port.
|
||||
this.internalBaseURL = this.useTestContainers ? `http://${MATTERMOST_ALIAS}:${MATTERMOST_PORT}` : this.baseURL;
|
||||
this.webhookInternalUrl = this.useTestContainers
|
||||
? `http://${WEBHOOK_ALIAS}:${WEBHOOK_PORT}`
|
||||
: this.webhookBaseUrl;
|
||||
this.testcontainersNetworkGatewayIp = process.env.PW_TESTCONTAINERS_NETWORK_GATEWAY_IP || '';
|
||||
this.serverImage = process.env.SERVER_IMAGE || MATTERMOST_SERVER_IMAGE;
|
||||
this.serverEnv = parseKeyValueList(process.env.MM_ENV);
|
||||
this.testcontainersServices = parseTestContainersServices(process.env.PW_TESTCONTAINERS_SERVICES);
|
||||
// Defaults to true so a local Ctrl+C (or just finishing a run) doesn't throw away the
|
||||
// stack you were likely about to inspect — tear down explicitly with `npm run testcontainers:down`.
|
||||
this.testcontainersReuse = parseBool(process.env.PW_TESTCONTAINERS_REUSE, true);
|
||||
this.containerRunner = parseBool(process.env.PW_TESTCONTAINERS_CONTAINER_RUNNER, false);
|
||||
this.testcontainersNetworkName = process.env.PW_TESTCONTAINERS_NETWORK_NAME || '';
|
||||
this.mattermostContainerId = process.env.PW_TESTCONTAINERS_MATTERMOST_CONTAINER_ID || '';
|
||||
// Prefer a previously-persisted boot env, since it reflects the container's actual
|
||||
// current state; only compute the default when it's genuinely absent (first boot). A
|
||||
// stale file pointing at a container that's no longer running is detected and reset
|
||||
// elsewhere, before a fresh container starts.
|
||||
this.bootEnvOverrides =
|
||||
parsePersistedBootEnv(process.env.PW_TESTCONTAINERS_BOOT_ENV) ?? computeDefaultBootEnv(this.serverEnv);
|
||||
this.ldapHost = process.env.PW_LDAP_HOST || 'localhost';
|
||||
this.ldapPort = parseNumber(process.env.PW_LDAP_PORT, 389);
|
||||
this.keycloakUrl = process.env.PW_KEYCLOAK_URL || 'http://localhost:8484';
|
||||
this.elasticsearchUrl = process.env.PW_ELASTICSEARCH_URL || 'http://localhost:9200';
|
||||
this.opensearchUrl = process.env.PW_OPENSEARCH_URL || 'http://localhost:9201';
|
||||
this.minioUrl = process.env.PW_MINIO_URL || 'http://localhost:9000';
|
||||
this.azuriteUrl = process.env.PW_AZURITE_URL || 'http://localhost:10000';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -68,3 +200,75 @@ function parseBool(actualValue: string | undefined, defaultValue: boolean) {
|
||||
function parseNumber(actualValue: string | undefined, defaultValue: number) {
|
||||
return actualValue ? parseInt(actualValue, 10) : defaultValue;
|
||||
}
|
||||
|
||||
function parseKeyValueList(actualValue: string | undefined): Record<string, string> {
|
||||
if (!actualValue) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const result: Record<string, string> = {};
|
||||
for (const entry of actualValue
|
||||
.split(',')
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean)) {
|
||||
const separatorIndex = entry.indexOf('=');
|
||||
if (separatorIndex === -1) {
|
||||
throw new Error(`Invalid MM_ENV entry "${entry}" — expected KEY=VALUE.`);
|
||||
}
|
||||
result[entry.slice(0, separatorIndex)] = entry.slice(separatorIndex + 1);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Mirrors startMattermostContainer()'s actual default boot env: baseline plus MM_ENV overrides
|
||||
// (same precedence), plus the two settings it never sets itself, so the server falls back to
|
||||
// its own defaults for those.
|
||||
function computeDefaultBootEnv(serverEnv: Record<string, string>): Record<string, string> {
|
||||
return {
|
||||
...SERVER_ENV_BASELINE,
|
||||
MM_FILESETTINGS_DRIVERNAME: 'local',
|
||||
MM_ELASTICSEARCHSETTINGS_BACKEND: 'elasticsearch',
|
||||
...serverEnv,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Boot env a genuinely fresh container starts with. Used to reset bootEnvOverrides when a
|
||||
* persisted boot env turns out to reference a container that's no longer running.
|
||||
*/
|
||||
export function defaultBootEnv(): Record<string, string> {
|
||||
return computeDefaultBootEnv(testConfig.serverEnv);
|
||||
}
|
||||
|
||||
function parsePersistedBootEnv(actualValue: string | undefined): Record<string, string> | undefined {
|
||||
if (!actualValue) {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
return JSON.parse(actualValue);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function parseTestContainersServices(actualValue: string | undefined): TestContainersServiceName[] {
|
||||
if (actualValue === undefined) {
|
||||
return DEFAULT_TESTCONTAINERS_SERVICES;
|
||||
}
|
||||
|
||||
// An explicit empty string is a deliberate opt-out (e.g. a spec that wants only the core
|
||||
// stack), distinct from not setting the var at all.
|
||||
if (!actualValue) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const requested = actualValue.split(',').filter(Boolean);
|
||||
const unknown = requested.filter((name) => !(TESTCONTAINERS_SERVICE_NAMES as readonly string[]).includes(name));
|
||||
if (unknown.length > 0) {
|
||||
throw new Error(
|
||||
`Unknown PW_TESTCONTAINERS_SERVICES entr${unknown.length > 1 ? 'ies' : 'y'}: ${unknown.join(', ')}. ` +
|
||||
`Valid services are: ${TESTCONTAINERS_SERVICE_NAMES.join(', ')}.`,
|
||||
);
|
||||
}
|
||||
return requested as TestContainersServiceName[];
|
||||
}
|
||||
|
||||
@@ -20,6 +20,8 @@ import {
|
||||
import {getBlobFromAsset, getFileFromAsset} from './file';
|
||||
import {
|
||||
configureAIBridgeMock,
|
||||
createKeycloakUser,
|
||||
createLdapUser,
|
||||
createMockAIAgent,
|
||||
createNewUserProfile,
|
||||
createNewTeam,
|
||||
@@ -28,11 +30,23 @@ import {
|
||||
createRandomTeam,
|
||||
createRandomUser,
|
||||
createUserWithAttributes,
|
||||
deleteKeycloakUser,
|
||||
deleteLdapUser,
|
||||
enableAIBridgeTestMode,
|
||||
listMinioObjectKeys,
|
||||
ensureMinio,
|
||||
ensureAzurite,
|
||||
listAzuriteBlobNames,
|
||||
ensureLocalFile,
|
||||
ensurePostgresSearch,
|
||||
ensureFeatureFlag,
|
||||
generateLdapUser,
|
||||
getAIBridgeMock,
|
||||
getAdminClient,
|
||||
initSetup,
|
||||
isOutsideRemoteUserHour,
|
||||
ldapServerConfig,
|
||||
ensureOpenldap,
|
||||
makeClient,
|
||||
mergeWithOnPremServerConfig,
|
||||
recapCompletion,
|
||||
@@ -40,6 +54,15 @@ import {
|
||||
rewriteCompletion,
|
||||
installAndEnablePlugin,
|
||||
isPluginActive,
|
||||
samlServerConfig,
|
||||
ensureKeycloak,
|
||||
elasticsearchServerConfig,
|
||||
opensearchServerConfig,
|
||||
ensureElasticsearch,
|
||||
ensureOpensearch,
|
||||
runMmctl,
|
||||
ensureMmctl,
|
||||
updateLdapUser,
|
||||
} from './server';
|
||||
import {
|
||||
toBeFocusedWithFocusVisible,
|
||||
@@ -74,7 +97,6 @@ type AxeBuilderOptions = {
|
||||
};
|
||||
|
||||
export const test = base.extend<ExtendedFixtures>({
|
||||
// eslint-disable-next-line no-empty-pattern
|
||||
axe: async ({}, use) => {
|
||||
const ab = new AxeBuilderExtended();
|
||||
await use(ab);
|
||||
@@ -118,6 +140,31 @@ export class PlaywrightExtended {
|
||||
readonly installAndEnablePlugin;
|
||||
readonly isPluginActive;
|
||||
|
||||
// ./server/openldap, ./server/keycloak, ./server/elasticsearch, ./server/opensearch, ./server/minio
|
||||
readonly generateLdapUser;
|
||||
readonly createLdapUser;
|
||||
readonly updateLdapUser;
|
||||
readonly deleteLdapUser;
|
||||
readonly ldapServerConfig;
|
||||
readonly ensureOpenldap;
|
||||
readonly createKeycloakUser;
|
||||
readonly deleteKeycloakUser;
|
||||
readonly samlServerConfig;
|
||||
readonly ensureKeycloak;
|
||||
readonly elasticsearchServerConfig;
|
||||
readonly opensearchServerConfig;
|
||||
readonly ensureElasticsearch;
|
||||
readonly ensureOpensearch;
|
||||
readonly listMinioObjectKeys;
|
||||
readonly ensureMinio;
|
||||
readonly ensureAzurite;
|
||||
readonly ensureLocalFile;
|
||||
readonly ensurePostgresSearch;
|
||||
readonly ensureFeatureFlag;
|
||||
readonly listAzuriteBlobNames;
|
||||
readonly runMmctl;
|
||||
readonly ensureMmctl;
|
||||
|
||||
// ./test_action
|
||||
readonly toBeFocusedWithFocusVisible;
|
||||
readonly hideDynamicChannelsContent;
|
||||
@@ -193,6 +240,31 @@ export class PlaywrightExtended {
|
||||
this.installAndEnablePlugin = installAndEnablePlugin;
|
||||
this.isPluginActive = isPluginActive;
|
||||
|
||||
// ./server/openldap, ./server/keycloak, ./server/elasticsearch, ./server/opensearch, ./server/minio
|
||||
this.generateLdapUser = generateLdapUser;
|
||||
this.createLdapUser = createLdapUser;
|
||||
this.updateLdapUser = updateLdapUser;
|
||||
this.deleteLdapUser = deleteLdapUser;
|
||||
this.ldapServerConfig = ldapServerConfig;
|
||||
this.ensureOpenldap = ensureOpenldap;
|
||||
this.createKeycloakUser = createKeycloakUser;
|
||||
this.deleteKeycloakUser = deleteKeycloakUser;
|
||||
this.samlServerConfig = samlServerConfig;
|
||||
this.ensureKeycloak = ensureKeycloak;
|
||||
this.elasticsearchServerConfig = elasticsearchServerConfig;
|
||||
this.opensearchServerConfig = opensearchServerConfig;
|
||||
this.ensureElasticsearch = ensureElasticsearch;
|
||||
this.ensureOpensearch = ensureOpensearch;
|
||||
this.listMinioObjectKeys = listMinioObjectKeys;
|
||||
this.ensureMinio = ensureMinio;
|
||||
this.ensureAzurite = ensureAzurite;
|
||||
this.ensureLocalFile = ensureLocalFile;
|
||||
this.ensurePostgresSearch = ensurePostgresSearch;
|
||||
this.ensureFeatureFlag = ensureFeatureFlag;
|
||||
this.listAzuriteBlobNames = listAzuriteBlobNames;
|
||||
this.runMmctl = runMmctl;
|
||||
this.ensureMmctl = ensureMmctl;
|
||||
|
||||
// ./test_action
|
||||
this.toBeFocusedWithFocusVisible = toBeFocusedWithFocusVisible;
|
||||
this.hideDynamicChannelsContent = hideDynamicChannelsContent;
|
||||
|
||||
@@ -16,6 +16,7 @@ export default class LoginPage {
|
||||
readonly loginInput;
|
||||
readonly loginPlaceholder;
|
||||
readonly loginWithAdLdapPlaceholder;
|
||||
readonly samlLoginButton;
|
||||
readonly passwordInput;
|
||||
readonly passwordToggleButton;
|
||||
readonly signInButton;
|
||||
@@ -34,7 +35,8 @@ export default class LoginPage {
|
||||
this.bodyCard = page.getByTestId('login-body-card');
|
||||
this.loginInput = page.locator('#input_loginId');
|
||||
this.loginPlaceholder = page.getByPlaceholder('Email or Username');
|
||||
this.loginWithAdLdapPlaceholder = page.getByPlaceholder('Email, Username or AD/LDAP Username');
|
||||
this.loginWithAdLdapPlaceholder = page.getByRole('textbox', {name: 'Email, Username or AD/LDAP Username'});
|
||||
this.samlLoginButton = page.locator('#saml');
|
||||
this.passwordInput = page.locator('#input_password-input');
|
||||
this.passwordToggleButton = page.locator('#password_toggle');
|
||||
this.signInButton = page.getByRole('button', {name: 'Log in'});
|
||||
|
||||
@@ -100,7 +100,9 @@ const server = createServer((req, res) => {
|
||||
});
|
||||
});
|
||||
|
||||
server.listen(PORT, '127.0.0.1', () => {
|
||||
// Bind to all interfaces, not just loopback, so the Mattermost server container can reach this
|
||||
// over the Docker network in `testcontainers` mode.
|
||||
server.listen(PORT, () => {
|
||||
const address = server.address();
|
||||
const actualPort = typeof address === 'object' && address ? address.port : PORT;
|
||||
console.log(`File server serving ${ASSET_DIR} on port ${actualPort}!`);
|
||||
|
||||
Generated
+2562
-241
File diff suppressed because it is too large
Load Diff
@@ -21,6 +21,9 @@
|
||||
"test:visual-update-snapshots": "npm run build && cross-env PW_SNAPSHOT_ENABLE=true playwright test specs/visual --grep @visual --update-snapshots",
|
||||
"test:update-snapshots": "npm run build && cross-env PW_SNAPSHOT_ENABLE=true playwright test --project=chrome --grep @snapshots --update-snapshots --update-source-method=overwrite",
|
||||
"test:slomo": "npm run build && cross-env PW_SNAPSHOT_ENABLE=true PW_SLOWMO=1000 playwright test",
|
||||
"test:full": "npm run build && cross-env PW_USE_TESTCONTAINERS=true PW_SNAPSHOT_ENABLE=true playwright test",
|
||||
"testcontainers:up": "npm run build && cross-env PW_USE_TESTCONTAINERS=true playwright test --config=playwright.testcontainers-up.config.ts",
|
||||
"testcontainers:down": "node script/testcontainers_down.mjs",
|
||||
"percy:docker": "npm run build && cross-env PW_PERCY_ENABLE=true PERCY_BROWSER_EXECUTABLE='/ms-playwright/chromium-1169/chrome-linux/chrome' percy exec -- playwright test specs/visual --grep @visual --project=chrome --project=ipad",
|
||||
"codegen": "npm run build && cross-env playwright codegen $PW_BASE_URL",
|
||||
"playwright-ui": "npm run build && cross-env playwright test --ui",
|
||||
@@ -39,16 +42,25 @@
|
||||
"@types/luxon": "3.7.2",
|
||||
"@types/pg": "8.20.0",
|
||||
"@typescript-eslint/eslint-plugin": "8.62.0",
|
||||
"chalk": "5.6.2",
|
||||
"cross-env": "10.1.0",
|
||||
"dayjs": "1.11.21",
|
||||
"eslint": "9.39.4",
|
||||
"eslint-import-resolver-typescript": "4.4.5",
|
||||
"globals": "17.7.0",
|
||||
"glob": "13.0.6",
|
||||
"globals": "17.7.0",
|
||||
"luxon": "3.7.2",
|
||||
"pg": "8.22.0",
|
||||
"prettier": "3.9.1",
|
||||
"typescript": "6.0.3",
|
||||
"zod": "4.4.3"
|
||||
},
|
||||
"allowScripts": {
|
||||
"[email protected]": true,
|
||||
"[email protected]": true,
|
||||
"[email protected]": true,
|
||||
"[email protected]": true,
|
||||
"@percy/[email protected]": true,
|
||||
"[email protected]": true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {defineConfig} from '@playwright/test';
|
||||
|
||||
// Standalone config for `npm run testcontainers:up`: brings up (or reuses) the Testcontainers
|
||||
// stack via its own global setup — deliberately not the real suite's global_setup.ts, so the
|
||||
// server comes up fresh and untouched by baseGlobalSetup()'s admin/sysadmin bootstrap. Runs a
|
||||
// single no-op test so Playwright has something to execute global setup/teardown around, without
|
||||
// pulling in the main playwright.config.ts's projects/browsers or touching its `specs` testDir.
|
||||
export default defineConfig({
|
||||
globalSetup: './script/testcontainers_up_global_setup.ts',
|
||||
testDir: './script',
|
||||
testMatch: /testcontainers_up\.spec\.ts/,
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
// Reused containers are deliberately left running after a Playwright process exits, so there's no
|
||||
// in-process teardown to call from a fresh invocation of this script — it finds and removes them
|
||||
// directly via Docker, by the label every container this project starts carries.
|
||||
//
|
||||
// Also doubles as CI's final teardown step: with PW_TESTCONTAINERS_REUSE, the stack stays up
|
||||
// across every per-spec test invocation in a job, so none of them ever run the real (non-adopted)
|
||||
// teardown path that collects container logs or archives the boot-env drift history. This script
|
||||
// does both before removing anything, so `ci/upload-debug-artifacts` still picks them up.
|
||||
|
||||
import {execSync} from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const LABEL_FILTER = 'label=mm-playwright-testcontainers=true';
|
||||
const LOG_DIR = path.resolve(process.cwd(), 'logs');
|
||||
const ENV_FILE_PATH = path.resolve(process.cwd(), '.env.testcontainers');
|
||||
|
||||
function run(command) {
|
||||
try {
|
||||
return execSync(command, {encoding: 'utf-8'}).trim();
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
// Reads the last-written PW_TESTCONTAINERS_NETWORK_NAME= line from .env.testcontainers before
|
||||
// it's archived/removed, so this run's network can be removed by name instead of via a host-wide
|
||||
// `docker network prune`. Entries are appended on each write, so the last match is current.
|
||||
function readTestcontainersNetworkName() {
|
||||
if (!fs.existsSync(ENV_FILE_PATH)) {
|
||||
return undefined;
|
||||
}
|
||||
const matches = [...fs.readFileSync(ENV_FILE_PATH, 'utf-8').matchAll(/^PW_TESTCONTAINERS_NETWORK_NAME=(.*)$/gm)];
|
||||
return matches.at(-1)?.[1]?.trim() || undefined;
|
||||
}
|
||||
|
||||
// Archives, then removes, .env.testcontainers — a stale copy left behind would seed the next
|
||||
// fresh boot's config overrides from a container that no longer exists, wrongly convincing a
|
||||
// later pw.ensure*() call that some old setting is already active.
|
||||
function archiveEnvFile() {
|
||||
if (!fs.existsSync(ENV_FILE_PATH)) {
|
||||
return;
|
||||
}
|
||||
fs.mkdirSync(LOG_DIR, {recursive: true});
|
||||
fs.copyFileSync(ENV_FILE_PATH, path.join(LOG_DIR, 'testcontainers_env_history.log'));
|
||||
fs.rmSync(ENV_FILE_PATH);
|
||||
}
|
||||
|
||||
function collectLogs(containerIds) {
|
||||
fs.mkdirSync(LOG_DIR, {recursive: true});
|
||||
for (const id of containerIds) {
|
||||
const image = run(`docker inspect -f "{{.Config.Image}}" ${id}`) || id;
|
||||
const safeName = image.replace(/[^a-zA-Z0-9_.-]/g, '_');
|
||||
const outPath = path.join(LOG_DIR, `${safeName}-${id.slice(0, 12)}.log`);
|
||||
try {
|
||||
execSync(`docker logs "${id}" > "${outPath}" 2>&1`);
|
||||
} catch {
|
||||
// Best-effort — a container that's already gone or never logged anything shouldn't
|
||||
// block teardown.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const containerIds = run(`docker ps -aq --filter "${LABEL_FILTER}"`).split('\n').filter(Boolean);
|
||||
|
||||
const networkName = readTestcontainersNetworkName();
|
||||
archiveEnvFile();
|
||||
|
||||
if (containerIds.length === 0) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log('No Testcontainers-managed containers found (nothing to remove).');
|
||||
} else {
|
||||
collectLogs(containerIds);
|
||||
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`Removing ${containerIds.length} Testcontainers-managed container(s): ${containerIds.join(', ')}`);
|
||||
execSync(`docker rm -f ${containerIds.join(' ')}`, {stdio: 'inherit'});
|
||||
|
||||
if (networkName) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`Removing Testcontainers-managed network: ${networkName}`);
|
||||
run(`docker network rm ${networkName}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {test} from '@playwright/test';
|
||||
|
||||
// No-op: playwright.testcontainers-up.config.ts's globalSetup (the same global_setup.ts the real
|
||||
// suite uses) already brought the stack up, or reused one already running. This test exists only
|
||||
// because Playwright's global setup/teardown fire around an actual test run, not standalone.
|
||||
test('testcontainers stack is up', () => {});
|
||||
@@ -0,0 +1,27 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import chalk from 'chalk';
|
||||
|
||||
import {startStack, stopStack} from '@mattermost/playwright-lib';
|
||||
|
||||
// Deliberately skips baseGlobalSetup() (admin user bootstrap, sysadmin setup, plugin config):
|
||||
// `npm run testcontainers:up` is for bringing up a fresh, untouched server for poking around or
|
||||
// for a later `npm run test` to reuse — not for preparing it as if a real suite were about to run.
|
||||
async function globalSetup() {
|
||||
try {
|
||||
await startStack();
|
||||
} catch (error: unknown) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.error(chalk.cyan('[testcontainers]'), error);
|
||||
await stopStack();
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
throw new Error(chalk.red(`[testcontainers] stack failed to start: ${message}`));
|
||||
}
|
||||
|
||||
return async function () {
|
||||
await stopStack();
|
||||
};
|
||||
}
|
||||
|
||||
export default globalSetup;
|
||||
+18
-18
@@ -63,7 +63,7 @@ test.describe('Interactive mm_blocks (ephemeral post)', () => {
|
||||
);
|
||||
|
||||
await setupWebhookTestServer(request, {
|
||||
mattermostBaseUrl: testConfig.baseURL,
|
||||
mattermostBaseUrl: testConfig.internalBaseURL,
|
||||
adminUsername: testConfig.adminUsername,
|
||||
adminPassword: testConfig.adminPassword,
|
||||
});
|
||||
@@ -89,7 +89,7 @@ test.describe('Interactive mm_blocks (ephemeral post)', () => {
|
||||
});
|
||||
|
||||
const ephemeralMarker = `E2E mm_blocks ephemeral action ${pw.random.id()}`;
|
||||
const integrationUrl = `${testConfig.webhookBaseUrl}/mm_blocks_integration`;
|
||||
const integrationUrl = `${testConfig.webhookInternalUrl}/mm_blocks_integration`;
|
||||
|
||||
await adminClient.createPostEphemeral(user.id, {
|
||||
channel_id: townSquare.id,
|
||||
@@ -153,7 +153,7 @@ test.describe('Interactive mm_blocks (ephemeral post)', () => {
|
||||
);
|
||||
|
||||
await setupWebhookTestServer(request, {
|
||||
mattermostBaseUrl: testConfig.baseURL,
|
||||
mattermostBaseUrl: testConfig.internalBaseURL,
|
||||
adminUsername: testConfig.adminUsername,
|
||||
adminPassword: testConfig.adminPassword,
|
||||
});
|
||||
@@ -177,7 +177,7 @@ test.describe('Interactive mm_blocks (ephemeral post)', () => {
|
||||
});
|
||||
|
||||
const ephemeralMarker = `E2E mm_blocks ephemeral update ${pw.random.id()}`;
|
||||
const integrationUrl = `${testConfig.webhookBaseUrl}/mm_blocks_integration_update`;
|
||||
const integrationUrl = `${testConfig.webhookInternalUrl}/mm_blocks_integration_update`;
|
||||
|
||||
await adminClient.createPostEphemeral(user.id, {
|
||||
channel_id: townSquare.id,
|
||||
@@ -238,7 +238,7 @@ test.describe('Interactive mm_blocks (ephemeral post)', () => {
|
||||
);
|
||||
|
||||
await setupWebhookTestServer(request, {
|
||||
mattermostBaseUrl: testConfig.baseURL,
|
||||
mattermostBaseUrl: testConfig.internalBaseURL,
|
||||
adminUsername: testConfig.adminUsername,
|
||||
adminPassword: testConfig.adminPassword,
|
||||
});
|
||||
@@ -264,7 +264,7 @@ test.describe('Interactive mm_blocks (ephemeral post)', () => {
|
||||
|
||||
const overrideAuthorName = 'Playwright mm_blocks eph override';
|
||||
const ephemeralMarker = `E2E mm_blocks ephemeral override ${pw.random.id()}`;
|
||||
const integrationUrl = `${testConfig.webhookBaseUrl}/mm_blocks_integration_update`;
|
||||
const integrationUrl = `${testConfig.webhookInternalUrl}/mm_blocks_integration_update`;
|
||||
|
||||
await adminClient.createPostEphemeral(user.id, {
|
||||
channel_id: townSquare.id,
|
||||
@@ -331,7 +331,7 @@ test.describe('Interactive mm_blocks (ephemeral post)', () => {
|
||||
);
|
||||
|
||||
await setupWebhookTestServer(request, {
|
||||
mattermostBaseUrl: testConfig.baseURL,
|
||||
mattermostBaseUrl: testConfig.internalBaseURL,
|
||||
adminUsername: testConfig.adminUsername,
|
||||
adminPassword: testConfig.adminPassword,
|
||||
});
|
||||
@@ -355,7 +355,7 @@ test.describe('Interactive mm_blocks (ephemeral post)', () => {
|
||||
});
|
||||
|
||||
const ephemeralMarker = `E2E mm_blocks eph query merge ${pw.random.id()}`;
|
||||
const integrationUrl = `${testConfig.webhookBaseUrl}/mm_blocks_integration_echo_query`;
|
||||
const integrationUrl = `${testConfig.webhookInternalUrl}/mm_blocks_integration_echo_query`;
|
||||
|
||||
await adminClient.createPostEphemeral(user.id, {
|
||||
channel_id: townSquare.id,
|
||||
@@ -418,7 +418,7 @@ test.describe('Interactive mm_blocks (ephemeral post)', () => {
|
||||
);
|
||||
|
||||
await setupWebhookTestServer(request, {
|
||||
mattermostBaseUrl: testConfig.baseURL,
|
||||
mattermostBaseUrl: testConfig.internalBaseURL,
|
||||
adminUsername: testConfig.adminUsername,
|
||||
adminPassword: testConfig.adminPassword,
|
||||
});
|
||||
@@ -442,7 +442,7 @@ test.describe('Interactive mm_blocks (ephemeral post)', () => {
|
||||
});
|
||||
|
||||
const ephemeralMarker = `E2E mm_blocks eph query override ${pw.random.id()}`;
|
||||
const integrationUrl = `${testConfig.webhookBaseUrl}/mm_blocks_integration_echo_query`;
|
||||
const integrationUrl = `${testConfig.webhookInternalUrl}/mm_blocks_integration_echo_query`;
|
||||
|
||||
await adminClient.createPostEphemeral(user.id, {
|
||||
channel_id: townSquare.id,
|
||||
@@ -501,7 +501,7 @@ test.describe('Interactive mm_blocks (ephemeral post)', () => {
|
||||
);
|
||||
|
||||
await setupWebhookTestServer(request, {
|
||||
mattermostBaseUrl: testConfig.baseURL,
|
||||
mattermostBaseUrl: testConfig.internalBaseURL,
|
||||
adminUsername: testConfig.adminUsername,
|
||||
adminPassword: testConfig.adminPassword,
|
||||
});
|
||||
@@ -525,7 +525,7 @@ test.describe('Interactive mm_blocks (ephemeral post)', () => {
|
||||
});
|
||||
|
||||
const ephemeralMarker = `E2E mm_blocks eph static_select query ${pw.random.id()}`;
|
||||
const integrationUrl = `${testConfig.webhookBaseUrl}/mm_blocks_integration_echo_query`;
|
||||
const integrationUrl = `${testConfig.webhookInternalUrl}/mm_blocks_integration_echo_query`;
|
||||
|
||||
await adminClient.createPostEphemeral(user.id, {
|
||||
channel_id: townSquare.id,
|
||||
@@ -596,7 +596,7 @@ test.describe('Interactive mm_blocks (ephemeral post)', () => {
|
||||
);
|
||||
|
||||
await setupWebhookTestServer(request, {
|
||||
mattermostBaseUrl: testConfig.baseURL,
|
||||
mattermostBaseUrl: testConfig.internalBaseURL,
|
||||
adminUsername: testConfig.adminUsername,
|
||||
adminPassword: testConfig.adminPassword,
|
||||
});
|
||||
@@ -620,7 +620,7 @@ test.describe('Interactive mm_blocks (ephemeral post)', () => {
|
||||
});
|
||||
|
||||
const ephemeralMarker = `E2E mm_blocks eph static_select users ${pw.random.id()}`;
|
||||
const integrationUrl = `${testConfig.webhookBaseUrl}/mm_blocks_integration_static_select`;
|
||||
const integrationUrl = `${testConfig.webhookInternalUrl}/mm_blocks_integration_static_select`;
|
||||
|
||||
await adminClient.createPostEphemeral(user.id, {
|
||||
channel_id: townSquare.id,
|
||||
@@ -690,7 +690,7 @@ test.describe('Interactive mm_blocks (ephemeral post)', () => {
|
||||
);
|
||||
|
||||
await setupWebhookTestServer(request, {
|
||||
mattermostBaseUrl: testConfig.baseURL,
|
||||
mattermostBaseUrl: testConfig.internalBaseURL,
|
||||
adminUsername: testConfig.adminUsername,
|
||||
adminPassword: testConfig.adminPassword,
|
||||
});
|
||||
@@ -714,7 +714,7 @@ test.describe('Interactive mm_blocks (ephemeral post)', () => {
|
||||
});
|
||||
|
||||
const ephemeralMarker = `E2E mm_blocks eph static_select channels ${pw.random.id()}`;
|
||||
const integrationUrl = `${testConfig.webhookBaseUrl}/mm_blocks_integration_static_select`;
|
||||
const integrationUrl = `${testConfig.webhookInternalUrl}/mm_blocks_integration_static_select`;
|
||||
|
||||
await adminClient.createPostEphemeral(user.id, {
|
||||
channel_id: townSquare.id,
|
||||
@@ -783,7 +783,7 @@ test.describe('Interactive mm_blocks (ephemeral post)', () => {
|
||||
);
|
||||
|
||||
await setupWebhookTestServer(request, {
|
||||
mattermostBaseUrl: testConfig.baseURL,
|
||||
mattermostBaseUrl: testConfig.internalBaseURL,
|
||||
adminUsername: testConfig.adminUsername,
|
||||
adminPassword: testConfig.adminPassword,
|
||||
});
|
||||
@@ -808,7 +808,7 @@ test.describe('Interactive mm_blocks (ephemeral post)', () => {
|
||||
|
||||
const contextMarker = `ctx_${pw.random.id()}`;
|
||||
const ephemeralMarker = `E2E mm_blocks eph action_context ${pw.random.id()}`;
|
||||
const integrationUrl = `${testConfig.webhookBaseUrl}/mm_blocks_integration_echo_context`;
|
||||
const integrationUrl = `${testConfig.webhookInternalUrl}/mm_blocks_integration_echo_context`;
|
||||
|
||||
await adminClient.createPostEphemeral(user.id, {
|
||||
channel_id: townSquare.id,
|
||||
|
||||
+20
-20
@@ -237,7 +237,7 @@ test.describe('Interactive mm_blocks (incoming webhook)', () => {
|
||||
);
|
||||
|
||||
await setupWebhookTestServer(request, {
|
||||
mattermostBaseUrl: testConfig.baseURL,
|
||||
mattermostBaseUrl: testConfig.internalBaseURL,
|
||||
adminUsername: testConfig.adminUsername,
|
||||
adminPassword: testConfig.adminPassword,
|
||||
});
|
||||
@@ -255,7 +255,7 @@ test.describe('Interactive mm_blocks (incoming webhook)', () => {
|
||||
display_name: 'Playwright mm_blocks integration',
|
||||
});
|
||||
|
||||
const integrationUrl = `${testConfig.webhookBaseUrl}/mm_blocks_integration`;
|
||||
const integrationUrl = `${testConfig.webhookInternalUrl}/mm_blocks_integration`;
|
||||
|
||||
await postIncomingWebhook(webhook.id, {
|
||||
text: 'E2E mm_blocks external integration',
|
||||
@@ -317,7 +317,7 @@ test.describe('Interactive mm_blocks (incoming webhook)', () => {
|
||||
);
|
||||
|
||||
await setupWebhookTestServer(request, {
|
||||
mattermostBaseUrl: testConfig.baseURL,
|
||||
mattermostBaseUrl: testConfig.internalBaseURL,
|
||||
adminUsername: testConfig.adminUsername,
|
||||
adminPassword: testConfig.adminPassword,
|
||||
});
|
||||
@@ -335,7 +335,7 @@ test.describe('Interactive mm_blocks (incoming webhook)', () => {
|
||||
display_name: 'Playwright mm_blocks update',
|
||||
});
|
||||
|
||||
const integrationUrl = `${testConfig.webhookBaseUrl}/mm_blocks_integration_update`;
|
||||
const integrationUrl = `${testConfig.webhookInternalUrl}/mm_blocks_integration_update`;
|
||||
|
||||
await postIncomingWebhook(webhook.id, {
|
||||
text: 'E2E mm_blocks before apply update',
|
||||
@@ -385,7 +385,7 @@ test.describe('Interactive mm_blocks (incoming webhook)', () => {
|
||||
);
|
||||
|
||||
await setupWebhookTestServer(request, {
|
||||
mattermostBaseUrl: testConfig.baseURL,
|
||||
mattermostBaseUrl: testConfig.internalBaseURL,
|
||||
adminUsername: testConfig.adminUsername,
|
||||
adminPassword: testConfig.adminPassword,
|
||||
});
|
||||
@@ -406,7 +406,7 @@ test.describe('Interactive mm_blocks (incoming webhook)', () => {
|
||||
|
||||
const overrideAuthorName = 'Playwright mm_blocks override';
|
||||
const marker = `E2E mm_blocks override author ${pw.random.id()}`;
|
||||
const integrationUrl = `${testConfig.webhookBaseUrl}/mm_blocks_integration_update`;
|
||||
const integrationUrl = `${testConfig.webhookInternalUrl}/mm_blocks_integration_update`;
|
||||
|
||||
await postIncomingWebhook(webhook.id, {
|
||||
username: overrideAuthorName,
|
||||
@@ -466,7 +466,7 @@ test.describe('Interactive mm_blocks (incoming webhook)', () => {
|
||||
);
|
||||
|
||||
await setupWebhookTestServer(request, {
|
||||
mattermostBaseUrl: testConfig.baseURL,
|
||||
mattermostBaseUrl: testConfig.internalBaseURL,
|
||||
adminUsername: testConfig.adminUsername,
|
||||
adminPassword: testConfig.adminPassword,
|
||||
});
|
||||
@@ -484,7 +484,7 @@ test.describe('Interactive mm_blocks (incoming webhook)', () => {
|
||||
display_name: 'Playwright mm_blocks static_select',
|
||||
});
|
||||
|
||||
const integrationUrl = `${testConfig.webhookBaseUrl}/mm_blocks_integration_static_select`;
|
||||
const integrationUrl = `${testConfig.webhookInternalUrl}/mm_blocks_integration_static_select`;
|
||||
const marker = `E2E mm_blocks static_select ${pw.random.id()}`;
|
||||
|
||||
await postIncomingWebhook(webhook.id, {
|
||||
@@ -561,7 +561,7 @@ test.describe('Interactive mm_blocks (incoming webhook)', () => {
|
||||
);
|
||||
|
||||
await setupWebhookTestServer(request, {
|
||||
mattermostBaseUrl: testConfig.baseURL,
|
||||
mattermostBaseUrl: testConfig.internalBaseURL,
|
||||
adminUsername: testConfig.adminUsername,
|
||||
adminPassword: testConfig.adminPassword,
|
||||
});
|
||||
@@ -579,7 +579,7 @@ test.describe('Interactive mm_blocks (incoming webhook)', () => {
|
||||
display_name: 'Playwright mm_blocks static_select users',
|
||||
});
|
||||
|
||||
const integrationUrl = `${testConfig.webhookBaseUrl}/mm_blocks_integration_static_select`;
|
||||
const integrationUrl = `${testConfig.webhookInternalUrl}/mm_blocks_integration_static_select`;
|
||||
const marker = `E2E mm_blocks static_select users ${pw.random.id()}`;
|
||||
|
||||
await postIncomingWebhook(webhook.id, {
|
||||
@@ -655,7 +655,7 @@ test.describe('Interactive mm_blocks (incoming webhook)', () => {
|
||||
);
|
||||
|
||||
await setupWebhookTestServer(request, {
|
||||
mattermostBaseUrl: testConfig.baseURL,
|
||||
mattermostBaseUrl: testConfig.internalBaseURL,
|
||||
adminUsername: testConfig.adminUsername,
|
||||
adminPassword: testConfig.adminPassword,
|
||||
});
|
||||
@@ -673,7 +673,7 @@ test.describe('Interactive mm_blocks (incoming webhook)', () => {
|
||||
display_name: 'Playwright mm_blocks static_select channels',
|
||||
});
|
||||
|
||||
const integrationUrl = `${testConfig.webhookBaseUrl}/mm_blocks_integration_static_select`;
|
||||
const integrationUrl = `${testConfig.webhookInternalUrl}/mm_blocks_integration_static_select`;
|
||||
const marker = `E2E mm_blocks static_select channels ${pw.random.id()}`;
|
||||
|
||||
await postIncomingWebhook(webhook.id, {
|
||||
@@ -748,7 +748,7 @@ test.describe('Interactive mm_blocks (incoming webhook)', () => {
|
||||
);
|
||||
|
||||
await setupWebhookTestServer(request, {
|
||||
mattermostBaseUrl: testConfig.baseURL,
|
||||
mattermostBaseUrl: testConfig.internalBaseURL,
|
||||
adminUsername: testConfig.adminUsername,
|
||||
adminPassword: testConfig.adminPassword,
|
||||
});
|
||||
@@ -767,7 +767,7 @@ test.describe('Interactive mm_blocks (incoming webhook)', () => {
|
||||
});
|
||||
|
||||
const contextMarker = `ctx_${pw.random.id()}`;
|
||||
const integrationUrl = `${testConfig.webhookBaseUrl}/mm_blocks_integration_echo_context`;
|
||||
const integrationUrl = `${testConfig.webhookInternalUrl}/mm_blocks_integration_echo_context`;
|
||||
const marker = `E2E mm_blocks action_context ${pw.random.id()}`;
|
||||
|
||||
await postIncomingWebhook(webhook.id, {
|
||||
@@ -888,7 +888,7 @@ test.describe('Interactive mm_blocks (incoming webhook)', () => {
|
||||
);
|
||||
|
||||
await setupWebhookTestServer(request, {
|
||||
mattermostBaseUrl: testConfig.baseURL,
|
||||
mattermostBaseUrl: testConfig.internalBaseURL,
|
||||
adminUsername: testConfig.adminUsername,
|
||||
adminPassword: testConfig.adminPassword,
|
||||
});
|
||||
@@ -906,7 +906,7 @@ test.describe('Interactive mm_blocks (incoming webhook)', () => {
|
||||
display_name: 'Playwright mm_blocks button query',
|
||||
});
|
||||
|
||||
const integrationUrl = `${testConfig.webhookBaseUrl}/mm_blocks_integration_echo_query`;
|
||||
const integrationUrl = `${testConfig.webhookInternalUrl}/mm_blocks_integration_echo_query`;
|
||||
const marker = `E2E mm_blocks button query ${pw.random.id()}`;
|
||||
|
||||
await postIncomingWebhook(webhook.id, {
|
||||
@@ -974,7 +974,7 @@ test.describe('Interactive mm_blocks (incoming webhook)', () => {
|
||||
);
|
||||
|
||||
await setupWebhookTestServer(request, {
|
||||
mattermostBaseUrl: testConfig.baseURL,
|
||||
mattermostBaseUrl: testConfig.internalBaseURL,
|
||||
adminUsername: testConfig.adminUsername,
|
||||
adminPassword: testConfig.adminPassword,
|
||||
});
|
||||
@@ -992,7 +992,7 @@ test.describe('Interactive mm_blocks (incoming webhook)', () => {
|
||||
display_name: 'Playwright mm_blocks query override',
|
||||
});
|
||||
|
||||
const integrationUrl = `${testConfig.webhookBaseUrl}/mm_blocks_integration_echo_query`;
|
||||
const integrationUrl = `${testConfig.webhookInternalUrl}/mm_blocks_integration_echo_query`;
|
||||
const marker = `E2E mm_blocks query override ${pw.random.id()}`;
|
||||
|
||||
await postIncomingWebhook(webhook.id, {
|
||||
@@ -1049,7 +1049,7 @@ test.describe('Interactive mm_blocks (incoming webhook)', () => {
|
||||
);
|
||||
|
||||
await setupWebhookTestServer(request, {
|
||||
mattermostBaseUrl: testConfig.baseURL,
|
||||
mattermostBaseUrl: testConfig.internalBaseURL,
|
||||
adminUsername: testConfig.adminUsername,
|
||||
adminPassword: testConfig.adminPassword,
|
||||
});
|
||||
@@ -1067,7 +1067,7 @@ test.describe('Interactive mm_blocks (incoming webhook)', () => {
|
||||
display_name: 'Playwright mm_blocks select query',
|
||||
});
|
||||
|
||||
const integrationUrl = `${testConfig.webhookBaseUrl}/mm_blocks_integration_echo_query`;
|
||||
const integrationUrl = `${testConfig.webhookInternalUrl}/mm_blocks_integration_echo_query`;
|
||||
const marker = `E2E mm_blocks static_select query ${pw.random.id()}`;
|
||||
|
||||
await postIncomingWebhook(webhook.id, {
|
||||
|
||||
@@ -36,12 +36,15 @@ test.describe('Post height', () => {
|
||||
type: 'O',
|
||||
});
|
||||
|
||||
// # Enable SVG rendering and let the server fetch metadata from the local mock file server
|
||||
// # Enable SVG rendering and let the server fetch metadata from the mock file server.
|
||||
// AllowedUntrustedInternalConnections only takes effect in `external` mode here — in
|
||||
// `testcontainers` mode it's fixed at boot via an env var, and a PatchConfig on an env-controlled
|
||||
// field is accepted but has no real effect.
|
||||
await adminClient.patchConfig({
|
||||
ServiceSettings: {
|
||||
EnableSVGs: true,
|
||||
EnableLinkPreviews: true,
|
||||
AllowedUntrustedInternalConnections: 'localhost 127.0.0.1',
|
||||
AllowedUntrustedInternalConnections: `localhost 127.0.0.1 ${new URL(fileServerUrl).hostname}`,
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
+13
-3
@@ -1,7 +1,15 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {expect, test, enableABAC, getAdminClient, TestBrowser, getRandomId} from '@mattermost/playwright-lib';
|
||||
import {
|
||||
expect,
|
||||
test,
|
||||
enableABAC,
|
||||
getAdminClient,
|
||||
TestBrowser,
|
||||
getRandomId,
|
||||
testConfig,
|
||||
} from '@mattermost/playwright-lib';
|
||||
|
||||
import type {CustomProfileAttribute} from '../../../channels/custom_profile_attributes/helpers';
|
||||
import {setupCustomProfileAttributeFields} from '../../../channels/custom_profile_attributes/helpers';
|
||||
@@ -350,8 +358,10 @@ test.describe('ABAC Permission Policies - BOR and Permalink', () => {
|
||||
// # Retrieve the post ID and construct the permalink URL
|
||||
const postsResult = await adminClient.getPosts(channelId, 0, 1);
|
||||
const postId = postsResult.order[0];
|
||||
const serverUrl = adminClient.getBaseRoute().replace('/api/v4', '');
|
||||
const permalinkUrl = `${serverUrl}/${team.name}/pl/${postId}`;
|
||||
// Use testConfig.internalBaseURL, not adminClient's host-mapped route — the server itself
|
||||
// must recognize this URL as its own SiteURL to embed it via an internal permalink lookup,
|
||||
// instead of trying (and, in `testcontainers` mode, failing) to fetch it back over HTTP as a link.
|
||||
const permalinkUrl = `${testConfig.internalBaseURL}/${team.name}/pl/${postId}`;
|
||||
|
||||
// # Admin posts the permalink in the same channel (creates an embedded preview)
|
||||
await adminChannelsPage.centerView.postCreate.postMessage(permalinkUrl);
|
||||
|
||||
+5
-10
@@ -14,22 +14,17 @@
|
||||
* Helpers use a one-shot `pg.Client` so we don't keep a connection pool open
|
||||
* for the lifetime of the test run, and use parameterized queries throughout.
|
||||
*
|
||||
* DB URL resolution order:
|
||||
* 1. MM_TEST_DB_URL env var
|
||||
* 2. default: postgres://mmuser:mostest@localhost/mattermost_test?sslmode=disable
|
||||
* Connects via testConfig.postgresUrl, which resolves to the fixed localhost:5432 default in
|
||||
* `external` mode (docker-compose's mapped port), or the Testcontainers-assigned host port in
|
||||
* `testcontainers` mode.
|
||||
*/
|
||||
|
||||
import {Client} from 'pg';
|
||||
|
||||
const DEFAULT_DB_URL =
|
||||
'postgres://mmuser:mostest@localhost:5432/mattermost_test?sslmode=disable&connect_timeout=10&binary_parameters=yes';
|
||||
|
||||
function resolveDbUrl(): string {
|
||||
return process.env.MM_TEST_DB_URL ?? DEFAULT_DB_URL;
|
||||
}
|
||||
import {testConfig} from '@mattermost/playwright-lib';
|
||||
|
||||
async function runQuery<T = unknown>(sql: string, params: unknown[] = []): Promise<T[]> {
|
||||
const client = new Client({connectionString: resolveDbUrl()});
|
||||
const client = new Client({connectionString: testConfig.postgresUrl});
|
||||
await client.connect();
|
||||
try {
|
||||
const result = await client.query(sql, params);
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {expect, test} from '@mattermost/playwright-lib';
|
||||
|
||||
/**
|
||||
* @objective Verify a FeatureFlags entry can be switched via a server restart, since FeatureFlags
|
||||
* are never re-read from a running server's config store and only take effect through a boot-time
|
||||
* MM_FEATUREFLAGS_* env var.
|
||||
*
|
||||
* @precondition
|
||||
* Full (Testcontainers) mode, so the server can be restarted with a different feature flag env var.
|
||||
*/
|
||||
test('flips a feature flag by restarting the server with it set', async ({pw}) => {
|
||||
// Ensure prerequisites
|
||||
await pw.ensureFeatureFlag('TestBoolFeature', true);
|
||||
|
||||
const {adminClient} = await pw.getAdminClient();
|
||||
const config = await adminClient.getConfig();
|
||||
|
||||
expect(String(config.FeatureFlags?.TestBoolFeature)).toBe('true');
|
||||
});
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {test} from '@mattermost/playwright-lib';
|
||||
|
||||
import {uploadAndVerifyFile} from './file_storage_helpers';
|
||||
|
||||
/**
|
||||
* @objective Verify a file uploaded while FileSettings is configured for Azure Blob storage
|
||||
* (against Azurite) can be uploaded and downloaded back through Mattermost.
|
||||
*
|
||||
* @precondition
|
||||
* An Azurite instance reachable at the configured FileSettings.AzureEndpoint.
|
||||
*/
|
||||
test('uploads and retrieves a file backed by Azure Blob storage', async ({pw}) => {
|
||||
// Ensure prerequisites
|
||||
await pw.ensureAzurite();
|
||||
|
||||
const {userClient, team} = await pw.initSetup();
|
||||
|
||||
await uploadAndVerifyFile(userClient, team.id, () => pw.listAzuriteBlobNames());
|
||||
});
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import type {Client4} from '@mattermost/client';
|
||||
|
||||
import {expect, getFileFromAsset, getRandomId} from '@mattermost/playwright-lib';
|
||||
|
||||
/**
|
||||
* Uploads the shared test asset to the given team's town-square channel and downloads it back
|
||||
* through Mattermost, asserting the round-tripped bytes match exactly. When `listObjectKeys` is
|
||||
* provided (Minio/Azurite), also asserts the object landed in the backend's own listing —
|
||||
* local storage has no such listing to check.
|
||||
*/
|
||||
export async function uploadAndVerifyFile(
|
||||
userClient: Client4,
|
||||
teamId: string,
|
||||
listObjectKeys?: () => Promise<string[]>,
|
||||
): Promise<void> {
|
||||
const townSquare = await userClient.getChannelByName(teamId, 'town-square');
|
||||
const filename = 'mattermost-icon_128x128.png';
|
||||
const file = getFileFromAsset(filename);
|
||||
|
||||
const formData = new FormData();
|
||||
formData.set('channel_id', townSquare.id);
|
||||
formData.set('client_ids', getRandomId());
|
||||
formData.set('files', file, filename);
|
||||
|
||||
const objectKeysBeforeUpload = listObjectKeys ? await listObjectKeys() : undefined;
|
||||
|
||||
const uploadResponse = await userClient.uploadFile(formData);
|
||||
const fileId = uploadResponse.file_infos[0].id;
|
||||
|
||||
if (listObjectKeys) {
|
||||
const objectKeysAfterUpload = await listObjectKeys();
|
||||
const newObjectKeys = objectKeysAfterUpload.filter((key) => !objectKeysBeforeUpload?.includes(key));
|
||||
expect(newObjectKeys.length).toBeGreaterThan(0);
|
||||
}
|
||||
|
||||
const downloadResponse = await fetch(userClient.getFileUrl(fileId, 0), {
|
||||
headers: {Authorization: `Bearer ${userClient.getToken()}`},
|
||||
});
|
||||
expect(downloadResponse.ok).toBe(true);
|
||||
|
||||
const downloadedBytes = Buffer.from(await downloadResponse.arrayBuffer());
|
||||
const originalBytes = Buffer.from(await file.arrayBuffer());
|
||||
expect(downloadedBytes.equals(originalBytes)).toBe(true);
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {test} from '@mattermost/playwright-lib';
|
||||
|
||||
import {uploadAndVerifyFile} from './file_storage_helpers';
|
||||
|
||||
/**
|
||||
* @objective Verify a file uploaded while FileSettings is configured for local disk storage (the
|
||||
* default) can be uploaded and downloaded back through Mattermost. Untagged, unlike the Minio/
|
||||
* Azurite specs: local is already every core test's default backend, so ensureLocalFile() here is
|
||||
* a no-op check rather than a disruptive restart, and this can run alongside normal core tests.
|
||||
*
|
||||
* @precondition
|
||||
* None beyond the default server config.
|
||||
*/
|
||||
test('uploads and retrieves a file backed by local disk storage', async ({pw}) => {
|
||||
// Ensure prerequisites
|
||||
await pw.ensureLocalFile();
|
||||
|
||||
const {userClient, team} = await pw.initSetup();
|
||||
|
||||
await uploadAndVerifyFile(userClient, team.id);
|
||||
});
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {test} from '@mattermost/playwright-lib';
|
||||
|
||||
import {uploadAndVerifyFile} from './file_storage_helpers';
|
||||
|
||||
/**
|
||||
* @objective Verify a file uploaded while FileSettings is configured for Minio S3-compatible
|
||||
* storage is actually written to the Minio bucket and can be downloaded back through Mattermost.
|
||||
*
|
||||
* @precondition
|
||||
* A Minio instance reachable at the configured FileSettings.AmazonS3Endpoint.
|
||||
*/
|
||||
test('uploads and retrieves a file backed by Minio S3 storage', async ({pw}) => {
|
||||
// Ensure prerequisites
|
||||
await pw.ensureMinio();
|
||||
|
||||
const {userClient, team} = await pw.initSetup();
|
||||
|
||||
await uploadAndVerifyFile(userClient, team.id, () => pw.listMinioObjectKeys());
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {expect, test} from '@mattermost/playwright-lib';
|
||||
|
||||
/**
|
||||
* @objective Verify a user who only exists in the directory (never created in Mattermost) can
|
||||
* authenticate through the standard login form once LDAP authentication is enabled, and that the
|
||||
* server provisions their account via LDAP on first login rather than local auth.
|
||||
*
|
||||
* @precondition
|
||||
* An LDAP directory reachable at the configured LdapSettings.LdapServer/LdapPort.
|
||||
*/
|
||||
test('logs in a directory-only user through the standard login form', {tag: '@ldap'}, async ({pw}) => {
|
||||
// Ensure prerequisites
|
||||
await pw.ensureLicense();
|
||||
await pw.skipIfNoLicense();
|
||||
await pw.ensureOpenldap();
|
||||
|
||||
const {adminClient} = await pw.getAdminClient();
|
||||
const ldapUser = pw.generateLdapUser();
|
||||
await pw.createLdapUser(ldapUser);
|
||||
|
||||
try {
|
||||
// # Log in through the real login form with the directory-only user's credentials
|
||||
await pw.hasSeenLandingPage();
|
||||
await pw.loginPage.goto();
|
||||
await pw.loginPage.toBeVisible();
|
||||
|
||||
// * Verify the login form reflects LDAP being enabled
|
||||
await expect(pw.loginPage.loginWithAdLdapPlaceholder).toBeVisible();
|
||||
|
||||
await pw.loginPage.loginInput.fill(ldapUser.username);
|
||||
await pw.loginPage.passwordInput.fill(ldapUser.password);
|
||||
await pw.loginPage.signInButton.click();
|
||||
|
||||
// * Verify the login succeeded
|
||||
await expect(pw.loginPage.page).not.toHaveURL(/\/login/);
|
||||
|
||||
// * Verify the server provisioned the account via LDAP, with the directory's attributes
|
||||
const provisionedUser = await adminClient.getUserByUsername(ldapUser.username);
|
||||
expect(provisionedUser.auth_service).toBe('ldap');
|
||||
expect(provisionedUser.email).toBe(ldapUser.email);
|
||||
} finally {
|
||||
await pw.deleteLdapUser(ldapUser.username);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {expect, test, getRandomId, newTestPassword} from '@mattermost/playwright-lib';
|
||||
|
||||
/**
|
||||
* @objective Verify mmctl — the same binary bundled in the server image — can administer the
|
||||
* real test server as a remote client, run from a separate container instance built from that
|
||||
* same image rather than the server's own container's `--local` unix socket.
|
||||
*
|
||||
* @precondition
|
||||
* Full (Testcontainers) mode, so a Docker network and the server image are available to build a
|
||||
* second, independent mmctl container instance from.
|
||||
*/
|
||||
test('creates a user through a remote mmctl container instance', {tag: '@mmctl'}, async ({pw}) => {
|
||||
await pw.ensureMmctl();
|
||||
|
||||
const {adminClient} = await pw.getAdminClient();
|
||||
|
||||
const randomId = getRandomId();
|
||||
const username = `mmctluser${randomId}`;
|
||||
const email = `${username}@mmtest.com`;
|
||||
|
||||
// # Create a user via mmctl running in a separate remote container instance
|
||||
const result = await pw.runMmctl([
|
||||
'user',
|
||||
'create',
|
||||
'--username',
|
||||
username,
|
||||
'--email',
|
||||
email,
|
||||
'--password',
|
||||
newTestPassword(),
|
||||
]);
|
||||
|
||||
// * Verify the mmctl command succeeded
|
||||
expect(result.exitCode, result.output).toBe(0);
|
||||
|
||||
// * Verify the user was actually created on the real server
|
||||
const createdUser = await adminClient.getUserByUsername(username);
|
||||
expect(createdUser.email).toBe(email);
|
||||
});
|
||||
|
||||
/**
|
||||
* @objective Verify the remote mmctl container reports the same version as the server, since
|
||||
* both come from the same image — a sanity check that the "different container/instance, same
|
||||
* image" setup is actually using the image it claims to.
|
||||
*
|
||||
* @precondition
|
||||
* Full (Testcontainers) mode, so a Docker network and the server image are available to build a
|
||||
* second, independent mmctl container instance from.
|
||||
*/
|
||||
test('reports the same version as the server it is bundled with', {tag: '@mmctl'}, async ({pw}) => {
|
||||
await pw.ensureMmctl();
|
||||
|
||||
const {adminClient} = await pw.getAdminClient();
|
||||
const serverConfig = await adminClient.getClientConfig();
|
||||
|
||||
// # Query the version reported by the remote mmctl container instance
|
||||
const result = await pw.runMmctl(['version', '--json']);
|
||||
expect(result.exitCode, result.output).toBe(0);
|
||||
|
||||
// * Verify the remote mmctl reports the same version as the server it's bundled with
|
||||
const [mmctlVersionInfo] = JSON.parse(result.output);
|
||||
expect(mmctlVersionInfo.Version).toBe(serverConfig.Version);
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {expect, test} from '@mattermost/playwright-lib';
|
||||
import {expect, test, testConfig} from '@mattermost/playwright-lib';
|
||||
|
||||
test('should be able to enable mobile security settings when licensed', async ({pw}) => {
|
||||
const {adminUser, adminClient} = await pw.initSetup();
|
||||
@@ -379,7 +379,7 @@ test('should configure new IntuneSettings with SAML auth provider', async ({pw})
|
||||
}
|
||||
|
||||
// # Set server URL for fetch calls
|
||||
const serverUrl = process.env.MM_SERVER_URL || 'http://localhost:8065';
|
||||
const serverUrl = testConfig.baseURL;
|
||||
|
||||
// # Upload a valid SAML IdP certificate using fetch
|
||||
const idpCert =
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {expect, test, getRandomId} from '@mattermost/playwright-lib';
|
||||
|
||||
/**
|
||||
* @objective Verify a user who only exists in Keycloak (never created in Mattermost) can
|
||||
* authenticate through SAML SSO once SAML authentication is enabled, and that the server
|
||||
* provisions their account via SAML on first login rather than local auth.
|
||||
*
|
||||
* @precondition
|
||||
* A Keycloak realm reachable at the configured SamlSettings.IdpURL, with a SAML client matching
|
||||
* ServiceProviderIdentifier.
|
||||
*/
|
||||
test('logs in a directory-only user through Keycloak SAML SSO', {tag: '@saml'}, async ({pw}) => {
|
||||
// Ensure prerequisites
|
||||
await pw.ensureLicense();
|
||||
await pw.skipIfNoLicense();
|
||||
await pw.ensureKeycloak();
|
||||
|
||||
const {adminClient} = await pw.getAdminClient();
|
||||
|
||||
const randomId = getRandomId();
|
||||
const keycloakUser = {
|
||||
username: `samluser${randomId}`,
|
||||
email: `samluser${randomId}@mmtest.com`,
|
||||
firstName: `Firstname-${randomId}`,
|
||||
lastName: `Lastname-${randomId}`,
|
||||
password: 'Password1',
|
||||
};
|
||||
|
||||
const keycloakUserId = await pw.createKeycloakUser(keycloakUser);
|
||||
|
||||
try {
|
||||
// # Log in through the SAML SSO button, which redirects to Keycloak's hosted login form
|
||||
await pw.hasSeenLandingPage();
|
||||
await pw.loginPage.goto();
|
||||
await pw.loginPage.toBeVisible();
|
||||
|
||||
// * Verify the login form reflects SAML being enabled
|
||||
await expect(pw.loginPage.samlLoginButton).toBeVisible();
|
||||
await pw.loginPage.samlLoginButton.click();
|
||||
|
||||
// Keycloak's own hosted login form.
|
||||
await pw.loginPage.page.locator('#username').fill(keycloakUser.username);
|
||||
await pw.loginPage.page.locator('#password').fill(keycloakUser.password);
|
||||
await pw.loginPage.page.locator('#kc-login').click();
|
||||
|
||||
// * Verify the login succeeded
|
||||
await expect(pw.loginPage.page).not.toHaveURL(/\/login/);
|
||||
|
||||
// * Verify the server provisioned the account via SAML, with Keycloak's attributes
|
||||
const provisionedUser = await adminClient.getUserByUsername(keycloakUser.username);
|
||||
expect(provisionedUser.auth_service).toBe('saml');
|
||||
expect(provisionedUser.email).toBe(keycloakUser.email);
|
||||
} finally {
|
||||
await pw.deleteKeycloakUser(keycloakUserId);
|
||||
}
|
||||
});
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {test} from '@mattermost/playwright-lib';
|
||||
|
||||
import {postAndFindMessage} from './search_helpers';
|
||||
|
||||
/**
|
||||
* @objective Verify a message posted while Elasticsearch indexing/searching is enabled can be
|
||||
* found through the search API, confirming the server is actually querying Elasticsearch rather
|
||||
* than silently falling back to database search.
|
||||
*
|
||||
* @precondition
|
||||
* An Elasticsearch cluster reachable at the configured ElasticsearchSettings.ConnectionURL, and a
|
||||
* server license that includes Elasticsearch.
|
||||
*/
|
||||
test('finds a newly posted message through Elasticsearch search', {tag: '@elasticsearch'}, async ({pw}) => {
|
||||
// Ensure prerequisites
|
||||
await pw.ensureLicense();
|
||||
await pw.skipIfNoLicense();
|
||||
await pw.ensureElasticsearch();
|
||||
|
||||
const {adminClient, userClient, team} = await pw.initSetup();
|
||||
await adminClient.purgeElasticsearchIndexes();
|
||||
|
||||
// # Post a message with a unique term, then search for it via the search API
|
||||
// * Verify the search API returns exactly the post containing the unique term
|
||||
await postAndFindMessage(pw, userClient, team.id);
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {test} from '@mattermost/playwright-lib';
|
||||
|
||||
import {postAndFindMessage} from './search_helpers';
|
||||
|
||||
/**
|
||||
* @objective Verify a message posted while OpenSearch indexing/searching is enabled can be found
|
||||
* through the search API, confirming the server is actually querying OpenSearch rather than
|
||||
* silently falling back to database search.
|
||||
*
|
||||
* @precondition
|
||||
* An OpenSearch cluster reachable at the configured ElasticsearchSettings.ConnectionURL, with
|
||||
* Backend set to "opensearch", and a server license that includes Elasticsearch.
|
||||
*/
|
||||
test('finds a newly posted message through OpenSearch search', {tag: '@opensearch'}, async ({pw}) => {
|
||||
// Ensure prerequisites
|
||||
await pw.ensureLicense();
|
||||
await pw.skipIfNoLicense();
|
||||
await pw.ensureOpensearch();
|
||||
|
||||
const {adminClient, userClient, team} = await pw.initSetup();
|
||||
await adminClient.purgeElasticsearchIndexes();
|
||||
|
||||
// # Post a message with a unique term, then search for it via the search API
|
||||
// * Verify the search API returns exactly the post containing the unique term
|
||||
await postAndFindMessage(pw, userClient, team.id);
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {test} from '@mattermost/playwright-lib';
|
||||
|
||||
import {postAndFindMessage} from './search_helpers';
|
||||
|
||||
/**
|
||||
* @objective Verify a message posted while Elasticsearch/OpenSearch indexing and searching are
|
||||
* disabled can still be found through the search API, confirming the server falls back to
|
||||
* database search.
|
||||
*
|
||||
* @precondition
|
||||
* None beyond a running server — this is the default search mode.
|
||||
*/
|
||||
test('finds a newly posted message through database search', async ({pw}) => {
|
||||
// Ensure prerequisites
|
||||
await pw.ensurePostgresSearch();
|
||||
|
||||
const {userClient, team} = await pw.initSetup();
|
||||
|
||||
await postAndFindMessage(pw, userClient, team.id);
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import type {Client4} from '@mattermost/client';
|
||||
|
||||
import {expect, getRandomId} from '@mattermost/playwright-lib';
|
||||
import type {PlaywrightExtended} from '@mattermost/playwright-lib';
|
||||
|
||||
/**
|
||||
* Posts a message with a unique term, polls the search API until it's indexed, then asserts it's
|
||||
* the single result returned — the common flow across the Elasticsearch/OpenSearch/database search
|
||||
* specs, which otherwise differ only in prerequisite setup (ensure*, plus index purge).
|
||||
*/
|
||||
export async function postAndFindMessage(pw: PlaywrightExtended, userClient: Client4, teamId: string): Promise<void> {
|
||||
const townSquare = await userClient.getChannelByName(teamId, 'town-square');
|
||||
const uniqueTerm = `searchterm${getRandomId()}`;
|
||||
await userClient.createPost({channel_id: townSquare.id, message: `hello ${uniqueTerm}`});
|
||||
|
||||
await pw.waitUntil(
|
||||
async () => {
|
||||
const results = await userClient.searchPosts(teamId, uniqueTerm, false);
|
||||
return results.order.length > 0;
|
||||
},
|
||||
{timeout: 15000, intervalBetweenAttempts: 1000},
|
||||
);
|
||||
|
||||
const results = await userClient.searchPosts(teamId, uniqueTerm, false);
|
||||
expect(results.order).toHaveLength(1);
|
||||
expect(results.posts[results.order[0]].message).toContain(uniqueTerm);
|
||||
}
|
||||
Reference in New Issue
Block a user