mattermost-mobile-upstream/detox/e2e/support/server_api/system.ts
yasser khan a5d81c6b24
ci(e2e): port E2E CI stack to release-2.43 to unblock merges (#10004)
* chore(e2e): Fix e2e artifact upload path for CMT workflow (#9955)

* chore(e2e): Fix e2e artifact upload path for CMT workflow

* test(e2e): Replace MM-T placeholder test keys with real Zephyr Scale IDs

- Classification Banner (18 tests): MM-T6196–MM-T6205, MM-T6206–MM-T6208, MM-T6209–MM-T6213
- mm_blocks (incoming webhook + ephemeral): MM-T6214–MM-T6240 (27 tests)
- Fixes TM4J test-case linking by ensuring all test titles use real MM-T#### keys
- Tightens getTM4JTestCases filter regex from /(MM-T)\w+/ to /MM-T\d+/ to prevent
  crashes when non-numeric MM-T placeholders slip through before Zephyr linkage


- Scan all Xcode_*.app directories and filter for major version >= 26 to
  future-proof against Xcode 30+ releases (current glob pattern maxes at 29)
- Extract version from directory name, validate major >= 26, sort and select highest
- Add least-privilege job-level permissions (contents: read) to build jobs
  (build-ios-simulator, build-android-apk, build-android-apk-maestro) to scope
  actions/checkout and actions/upload-artifact access

* fix: apply CodeRabbit review feedback

Require Xcode 26.1+ for iOS prepare, standardize E2E titles to MM-TXXXX_N,
and bound Zephyr test-case id matching to complete identifiers.


* fix(e2e): Grant actions:write on CMT build jobs for artifact upload

Job-level contents:read alone strips upload-artifact permission; match
e2e-detox-pr.yml so ios/android/maestro builds can publish artifacts.

* feat(e2e): Integrate TSIO reporting (#9925)


Retire legacy maestro per-platform contexts from cancel-e2e-runs and
document the canonical PR, master, and CMT status context mapping.
Wire Detox + Maestro (PR/main/CMT) into Test System IO with a single
commit status (e2e/mobile; CMT uses e2e/compatibility-matrix-testing)
and groups mobile-pr / mobile-main / cmt-mobile.

Upload shard results with correct framework labels, merge Jest shards
into TSIO Detox shape, stub missing/dead shards as failures, and post
channel summaries after status settles. Matterwick MASTER is treated as
MAIN for mobile-main routing.

Also harden report/fail paths, stage Maestro screenshots per flow for
TSIO galleries, fix a few Detox setup/testID issues, and skip known
platform flakes so the pipeline stays actionable while TSIO lands.

* ci(e2e): per-job TSIO report groups, commit statuses, and webhook sidecar (#9969)

* ci(e2e): per-job TSIO report groups and commit statuses

E2E jobs previously shared a single `e2e/mobile` commit status backed by one
TSIO report group, so concurrent platform legs raced to finalize the group and
clobbered each other's results. Give each Detox/Maestro job its own report
group (`mobile-<flow>-<job>`, total_reports_expected=1) and its own commit
status context (`detox-ios`, `detox-android`, `detox-ipad`, `maestro-ios`,
`maestro-android`); CMT reports per shard plus an umbrella context.

Channel notifications move to a single rollup step so N platform legs no
longer spam the webhook, and the five-server topology is dispatched with
explicit per-platform inputs that still resolve to the existing SITE_*_URL
contract consumed by the test config.

Also adds the webhook sidecar launcher, Android emulator CI prep, and TSIO
screenshot path linking that keeps folder basenames matching Jest full names.

The new detox type-check job surfaced pre-existing broken import paths in
maestro/fixtures/calls_seed.ts, which pointed at detox/detox/e2e; corrected so
the guard passes on its own first run.

Note: the CMT matrix now reads per-platform server URLs (`ios_site_1_url`,
`android_site_1_url`, `site_3_url`) instead of a single `url`, which needs the
matching Matterwick dispatch change to land alongside this.

Co-authored-by: Cursor <cursoragent@cursor.com>

* ci(e2e): aggregate CMT channel rollup from TSIO and wire notify secrets

The CMT umbrella posted a placeholder summary built from CI job outcomes
(passed:0, failed:0|1, reports:[]), so the release channel message carried no
per-leg detail. It now runs the same tsio-channel-notify-rollup.js path as
PR/main: cmt-identity emits a per-shard TSIO config map and the rollup polls
every shard group, so counts and per-leg rows come from TSIO. The rollup job
also needs id-token: write to mint its OIDC token.

Webhook secrets used by the per-job TSIO finalize steps were referenced but
never declared in the templates' workflow_call.secrets, so GitHub resolved them
to empty strings and channel notify silently no-opped. Declare them in the
iOS/Android/Maestro templates and forward them from e2e-detox.yml and the CMT
callers. The Maestro PR path worked only because its callers use
secrets: inherit.

Also from review:
- split-tests.js emitted two matrix jobs at parallelism=1 when mm_blocks specs
  were present; merge into one shard instead of exceeding the requested count.
- Move the Android ARTIFACT_RUN_ID emptiness check ahead of download-artifact,
  which consumes it and otherwise fails with an opaque API error.
- resolve-tsio-job-config.sh now reuses webhookBucketForReportName instead of
  re-deriving the bucket prefix with a looser startsWith check.

Co-authored-by: Cursor <cursoragent@cursor.com>

* ci(e2e): add local preflight for CI PRs

The webhook-secret and OIDC-permission gaps in this branch were invisible
locally and in a green CI run — the affected steps exit 0 and just skip the
notify or commit status. Add a script engineers can run before opening a PR that
touches .github/ or detox/utils:

  cd detox && npm run preflight:ci        # :ci-fast skips lint + tsc

It runs actionlint (which flags secrets not declared in a callee's
workflow_call.secrets), scans for exit-code capture broken by a trailing
backslash, asserts every job running a TSIO OIDC script declares
id-token: write, then runs the detox/utils tests and npm run check. actionlint
and the CodeRabbit CLI are optional and skipped with an install hint when absent.

Co-authored-by: Cursor <cursoragent@cursor.com>

* ci(e2e): use mktemp for preflight logs

Fixed /tmp log paths can be pre-created as symlinks, so the preflight
script would truncate whatever they point at (CWE-377). Create both logs
with mktemp and drop them on exit.

Co-authored-by: Cursor <cursoragent@cursor.com>

* ci(e2e): address review feedback on TSIO statuses and sidecar

A cancelled E2E run reached no conclusion, so posting `success` on its
commit statuses let a PR merge on a check that never ran. Cancelled runs
now post `pending`; `success` is reserved for the one deliberate bypass,
the E2E/Override label.

Commit-status contexts move into the `e2e-test/*` namespace to match the
mattermost monorepo, with the prefix owned by build-tsio-job-config.js and
mirrored in the cancel action's context list. Legacy unprefixed and `e2e/*`
contexts are dropped rather than carried forward.

The `preflight:ci` script and its OIDC-permission checker duplicated what
actionlint, the unit tests and `npm run check` already do, so they are
removed and detox/CLAUDE.md documents the underlying failure modes and the
commands to catch them instead.

cloudflared and the TSIO CLI are pinned to known-good releases rather than
`latest`, and detox/README.md now documents the webhook sidecar: when a
tunnel is needed, the WEBHOOK_PUBLIC_BASE_URL / CLOUDFLARED_TUNNEL_TOKEN
precedence, and why quick tunnels report callbacks as unreachable.

Co-authored-by: Cursor <cursoragent@cursor.com>

* ci(e2e): detect upstream cancellation and surface status reset failures

generate-report runs with always(), so job.status stays "success" when an
upstream job is cancelled and TSIO was published as a real failure. Read the
generate-specs/e2e-* needs results so a cancelled run is reported as such.

In cancel-e2e-runs, only reset the E2E commit statuses for runs that were
actually stopped — a run we failed to cancel keeps publishing its own results.
Aggregate createCommitStatus failures across every context and fail the action
afterwards instead of silently warning, so a stale check cannot go unnoticed.

---------

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(e2e): Quarantine proven flakes and harden Detox harness (#9971)

* ci(e2e): make E2E/Override waive checks instead of cancelling runs (#9975)

* ci(e2e): make E2E/Override waive checks instead of cancelling runs

E2E/Override previously cancelled in-flight E2E runs and posted success on
their commit statuses. Cancelling destroys the very signal the maintainer
might still want, and reporting success for a run that never finished
attributes a conclusion to work that never happened.

Override now means one thing only: the required e2e-test/* contexts go green
so the PR can merge. Runs keep going and keep reporting to TSIO.

- Add .github/actions/e2e-override-status to post success (or pending) on all
  five required e2e-test/* contexts for a SHA.
- Label manager posts success on `labeled` and pending on `unlabeled`, so
  removing the escape hatch re-blocks the PR instead of leaving a stale waiver
  on the head SHA. It comments the runs it left running rather than killing
  them, and drops to `actions: read` now that it never cancels.
- tsio-report-status re-reads the PR labels before posting a failure. Because
  runs are no longer cancelled, a result landing after the override was applied
  would otherwise re-red a check the maintainer deliberately bypassed. The
  lookup fails closed so an unreadable label list cannot turn a real failure
  green, and the step itself no longer fails under override.
- Guard e2e-cancel-on-label-removal: stripping E2E/Run* is exactly what the
  Honor E2E/Override step does, so without this the indirect unlabeled event
  would cancel the runs the redesign is meant to preserve.
- e2e-detox-pr posts the success itself when the policy skips E2E, since every
  downstream job is skipped and a skipped job leaves the required contexts
  absent, blocking the merge forever.
- cancel-e2e-runs drops status_state: a cancelled run has no conclusion to
  report, so it always resets to pending.
- Thread `issues: read` through the reusable workflow callers so finalize can
  read the labels; a reusable workflow cannot escalate past its caller.

Co-authored-by: Cursor <cursoragent@cursor.com>

* ci(e2e): derive required E2E contexts from one definition

The override and cancel actions each carried their own copy of the five
required e2e-test/* contexts, kept aligned with build-tsio-job-config.js by
comment alone. A job renamed in PR_MAIN_JOBS would silently leave the actions
waiving or resetting a context that no longer exists, so a PR either cannot
merge or merges while a real context still blocks it.

Export E2E_STATUS_CONTEXTS from detox/utils/build-tsio-job-config.js, derived
from PR_MAIN_JOBS, and require it from both composite actions. github-script
resolves relative requires against the workspace, and every call site already
checks out the repo before using the action.

Also set persist-credentials: false on the e2e-label-manager checkout, matching
the other checkout steps.

Co-authored-by: Cursor <cursoragent@cursor.com>

* ci(e2e): drop the cancel action for native concurrency, keep GitHub calls in Actions

Review feedback from @saturninoabril.

Superseding an in-flight E2E run is what GitHub's `concurrency` already does, so
`e2e-detox-pr.yml` now declares `concurrency: e2e-<ref>` with `cancel-in-progress`
instead of cancelling from a step inside the run that supersedes it. The older run
is cancelled the moment the new dispatch is created rather than once a runner picks
up the first job.

That removes the only two remaining callers of `.github/actions/cancel-e2e-runs`,
along with the commit statuses it forced to `pending` on cancel — a cancelled run
has no conclusion to report, so the state is left to GitHub. Forcing a commit status
is now reserved for real test results and the override waiver. The action is deleted.

`e2e-cancel-on-label-removal.yml` goes with it: with `E2E/Run` on its way out and
override no longer cancelling, removing the label to stop a run has no remaining
practical case, and dropping the workflow also removes the back-door cancel guard
it needed.

The `E2E/Override` lookup moves out of `tsio-report-status.js` into a new
`.github/actions/e2e-override-label` composite action, which the finalize steps
call and pass in via `--e2e-override`. Talking to GitHub stays in the Actions
layer and the reporter is left deciding on its inputs.

Co-authored-by: Cursor <cursoragent@cursor.com>

* ci(e2e): paginate PR label lookups for E2E/Override

Co-authored-by: Cursor <cursoragent@cursor.com>

* ci(e2e): re-post E2E/Override success on new commits

Override success is SHA-scoped: it is posted only on the head SHA at
label-apply time (e2e-label-manager 'labeled' path) and when Matterwick
dispatches e2e-detox-pr.yml (post-e2e-override-status). On a push after
E2E/Override is applied, refresh-e2e-run-label strips the run labels and
returns — Matterwick is not dispatched, so the new head SHA gets no
e2e-test/* statuses. With those checks Required, the new commit is
blocked until the label is re-toggled.

Carry the override onto the new commit: refresh-e2e-run-label now emits
an e2e_override output, and when it is set a gated checkout +
e2e-override-status step re-posts success on the new head SHA. Reuses
the existing e2e-override-status action (same 5 required e2e-test/*
contexts, same 'E2E bypassed' description), so it is idempotent with the
labeled path. Adds statuses: write / contents: read to the job.

Note: refresh-e2e-run-label is gated on base.ref == 'main', so stacked
PRs (base != main) are not covered; non-main-base already posts success
at dispatch time.

---------

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-04 16:50:34 +05:30

511 lines
18 KiB
TypeScript

// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import path from 'path';
import {timeouts, wait} from '@support/utils';
import jestExpect from 'expect';
import client from './client';
import {apiUploadFile, getResponseFromError} from './common';
// ****************************************************************
// System
// See https://api.mattermost.com/#tag/system
//
/* eslint-disable no-console */
// Exported API function should have the following:
// - documented using JSDoc
// - meaningful description
// - match the referenced API endpoints
// - parameter/s defined by `@param`
// - return value defined by `@return`
// ****************************************************************
/**
* Check system health.
* @param {string} baseUrl - the base server URL
*/
export const apiCheckSystemHealth = async (baseUrl: string): Promise<any> => {
const result = await apiPingServerStatus(baseUrl);
// apiPingServerStatus returns {data} on success, {error, status} on failure.
// Guard against the error path so callers get a descriptive error, not a TypeError.
if (!result || result.error || !result.data) {
const detail = result?.error
? JSON.stringify(result.error)
: 'No response from server';
throw new Error(`apiCheckSystemHealth: server at "${baseUrl}" is not healthy. ${detail}`);
}
const {data} = result;
jestExpect(data.status).toEqual('OK');
jestExpect(data.database_status).toEqual('OK');
jestExpect(data.filestore_status).toEqual('OK');
};
/**
* Send a test email.
* See https://api.mattermost.com/#operation/TestEmail
* @param {string} baseUrl - the base server URL
* @return {Object} returns response on success or {error, status} on error
*/
export const apiEmailTest = async (baseUrl: string): Promise<any> => {
try {
return await client.post(`${baseUrl}/api/v4/email/test`);
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Get client license.
* See https://api.mattermost.com/#operation/GetClientLicense
* @param {string} baseUrl - the base server URL
* @return {Object} returns {license} on success or {error, status} on error
*/
export const apiGetClientLicense = async (baseUrl: string): Promise<any> => {
try {
const response = await client.get(`${baseUrl}/api/v4/license/client?format=old`);
return {license: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Get client config (old format), same shape as the mobile app uses for About.
* @param {string} baseUrl - the base server URL
* @return {Object} returns {config} on success or {error, status} on failure
*/
export const apiGetClientConfigOld = async (baseUrl: string): Promise<any> => {
try {
const response = await client.get(`${baseUrl}/api/v4/config/client?format=old`);
return {config: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Wait for a client configuration flag to reach the expected value.
* @param {string} baseUrl - the base server URL
* @param {string} flagKey - client configuration key
* @param {string} expectedValue - expected client configuration value
* @param {Object} options - polling attempts and interval
* @return {boolean} true when the expected value is observed
*/
export const waitForClientConfigFlag = async (
baseUrl: string,
flagKey: string,
expectedValue: string,
options: {maxAttempts?: number; pollMs?: number} = {},
): Promise<boolean> => {
const maxAttempts = options.maxAttempts ?? 60;
const pollMs = options.pollMs ?? timeouts.ONE_SEC;
for (let attempt = 0; attempt < maxAttempts; attempt++) {
// eslint-disable-next-line no-await-in-loop -- client config propagation is asynchronous
const {config} = await apiGetClientConfigOld(baseUrl);
if (config?.[flagKey] === expectedValue) {
return true;
}
if (attempt < maxAttempts - 1) {
// eslint-disable-next-line no-await-in-loop
await wait(pollMs);
}
}
return false;
};
/**
* Get configuration.
* See https://api.mattermost.com/#operation/GetConfig
* @param {string} baseUrl - the base server URL
* @return {Object} returns {config} on success or {error, status} on error
*/
export const apiGetConfig = async (baseUrl: string): Promise<any> => {
try {
const response = await client.get(`${baseUrl}/api/v4/config`);
return {config: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Update server configuration.
* See https://api.mattermost.com/#operation/UpdateConfig
* @param {string} baseUrl - the base server URL
* @param {Object} newConfig - partial configuration object to merge with current config
* @return {Object} returns {config} on success or {error, status} on error
*/
export const apiUpdateConfig = async (baseUrl: string, newConfig: any): Promise<any> => {
try {
// Use config/patch endpoint for partial updates — no need to GET+merge+PUT the full config
const response = await client.put(`${baseUrl}/api/v4/config/patch`, newConfig);
return {config: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Replace server configuration with a complete config object.
* @param {string} baseUrl - the base server URL
* @param {Object} config - complete server configuration
* @return {Object} returns {config} on success or {error, status} on error
*/
export const apiReplaceConfig = async (baseUrl: string, config: any): Promise<any> => {
try {
const response = await client.put(`${baseUrl}/api/v4/config`, config);
return {config: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Patch server configuration (partial update; server merges with current config).
* See https://api.mattermost.com/#operation/PatchConfig
* @param {string} baseUrl - the base server URL
* @param {Object} patchConfig - partial configuration object (same struct keys as server Config)
* @return {Object} returns {config} on success or {error, status} on error
*/
export const apiPatchConfig = async (baseUrl: string, patchConfig: any): Promise<any> => {
try {
const response = await client.put(`${baseUrl}/api/v4/config/patch`, patchConfig);
return {config: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Get remote clusters (connected workspaces).
* See https://api.mattermost.com/#tag/remote_cluster
* Requires system admin. Use before tests that need "no connected workspaces" (e.g. TC-MOB-03).
* @param {string} baseUrl - the base server URL
* @param {Object} options - optional query (only_confirmed, etc.)
* @return {Object} returns {remotes: Array<{remote_id: string, ...}>} on success or {error, status} on error
*/
export const apiGetRemoteClusters = async (
baseUrl: string,
options: {onlyConfirmed?: boolean; excludePlugins?: boolean} = {},
): Promise<{remotes?: Array<{remote_id: string}>; error?: {message: string}; status?: number}> => {
try {
const params = new URLSearchParams();
if (options.onlyConfirmed !== undefined) {
params.set('only_confirmed', String(options.onlyConfirmed));
}
if (options.excludePlugins !== undefined) {
params.set('exclude_plugins', String(options.excludePlugins));
}
const qs = params.toString() ? `?${params.toString()}` : '';
const response = await client.get(`${baseUrl}/api/v4/remotecluster${qs}`);
return {remotes: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Delete a remote cluster.
* See https://api.mattermost.com/#tag/remote_cluster
* Requires system admin.
* @param {string} baseUrl - the base server URL
* @param {string} remoteId - the remote cluster id
* @return {Object} returns on success or {error, status} on error
*/
export const apiDeleteRemoteCluster = async (
baseUrl: string,
remoteId: string,
): Promise<{error?: {message: string}; status?: number}> => {
try {
await client.delete(`${baseUrl}/api/v4/remotecluster/${encodeURIComponent(remoteId)}`);
return {};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Delete all remote clusters on the server.
* Call as admin (e.g. after User.apiAdminLogin) so tests can assert "No connected workspaces" (e.g. TC-MOB-03).
* @param {string} baseUrl - the base server URL
*/
export const apiDeleteAllRemoteClusters = async (baseUrl: string): Promise<void> => {
const result = await apiGetRemoteClusters(baseUrl, {});
if (result.error || !result.remotes) {
return;
}
for (const r of result.remotes) {
// eslint-disable-next-line no-await-in-loop
await apiDeleteRemoteCluster(baseUrl, r.remote_id);
}
};
/**
* Create a remote cluster (connected workspace). Requires system admin.
* See https://api.mattermost.com/#tag/remote_cluster
*/
export const apiCreateRemoteCluster = async (
baseUrl: string,
payload: {
name: string;
display_name: string;
default_team_id: string;
password: string;
},
): Promise<Record<string, unknown> & {error?: {message: string}; status?: number}> => {
try {
const response = await client.post(`${baseUrl}/api/v4/remotecluster`, payload);
return response.data ?? {};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Ensures at least one confirmed remote cluster exists (matches web e2e ensureConfirmedRemote).
* Enables remote cluster service when creating. Call as admin after EnableSharedChannels is on.
*/
export const apiEnsureAtLeastOneConfirmedRemoteCluster = async (baseUrl: string, teamId: string): Promise<void> => {
const confirmed = await apiGetRemoteClusters(baseUrl, {
onlyConfirmed: true,
excludePlugins: true,
});
const list = Array.isArray(confirmed.remotes) ? confirmed.remotes : [];
if (list.length > 0) {
return;
}
await apiPatchConfig(baseUrl, {
ConnectedWorkspacesSettings: {
EnableRemoteClusterService: true,
},
});
const suffix = `${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
const result = await apiCreateRemoteCluster(baseUrl, {
name: `e2e-remote-${suffix}`,
display_name: `E2E Remote ${suffix}`,
default_team_id: teamId,
password: `e2e-remote-pwd-${suffix}`,
});
if (result.error) {
throw new Error(`apiCreateRemoteCluster failed: ${result.error.message ?? 'unknown error'}`);
}
};
/**
* Deletes all remotes then creates exactly one (known name/display_name for e2e taps by text or id).
* Requires admin session.
*/
export const apiEnsureSingleRemoteCluster = async (
baseUrl: string,
teamId: string,
remote: {name: string; display_name: string; password: string},
): Promise<void> => {
await apiDeleteAllRemoteClusters(baseUrl);
await apiPatchConfig(baseUrl, {
ConnectedWorkspacesSettings: {
EnableRemoteClusterService: true,
},
});
const result = await apiCreateRemoteCluster(baseUrl, {
name: remote.name,
display_name: remote.display_name,
default_team_id: teamId,
password: remote.password,
});
if (result.error) {
throw new Error(`apiEnsureSingleRemoteCluster failed: ${result.error.message ?? 'unknown error'}`);
}
};
/**
* Check that plugin uploads are enabled, fail if not.
* @param {string} baseUrl - the base server URL
* @return {Promise<void>} throws error if plugin uploads are disabled
*/
export const shouldHavePluginUploadEnabled = async (baseUrl: string): Promise<void> => {
const {config} = await apiGetConfig(baseUrl);
const isUploadEnabled = config.PluginSettings.EnableUploads;
if (!isUploadEnabled) {
throw new Error('Plugin uploads must be enabled for this test to run. Set PluginSettings.EnableUploads=true');
}
jestExpect(isUploadEnabled).toEqual(true);
};
/**
* Ping server status.
* See https://api.mattermost.com/#operation/GetPing
* @param {string} baseUrl - the base server URL
* @return {Object} returns {data} on success or {error, status} on error
*/
export const apiPingServerStatus = async (baseUrl: string): Promise<any> => {
try {
const response = await client.get(`${baseUrl}/api/v4/system/ping?get_server_status=true`);
return {data: response.data};
} catch (err) {
return getResponseFromError(err);
}
};
/**
* Require server license to successfully continue.
* @param {string} baseUrl - the base server URL
* @return {Object} returns {license} on success or fail when no license
*/
export const apiRequireLicense = async (baseUrl: string): Promise<any> => {
const {license} = await getClientLicense(baseUrl);
if (license.IsLicensed !== 'true') {
console.error('Server has no Enterprise license.');
}
jestExpect(license.IsLicensed).toEqual('true');
return {license};
};
/**
* Require server license with specific feature to successfully continue.
* @param {string} baseUrl - the base server URL
* @param {string} key - feature, e.g. LDAP
* @return {Object} returns {license} on success or fail when no license or no license to specific feature.
*/
export const apiRequireLicenseForFeature = async (baseUrl: string, key = ''): Promise<any> => {
const {license} = await getClientLicense(baseUrl);
if (license.IsLicensed !== 'true') {
console.error('Server has no Enterprise license.');
}
jestExpect(license.IsLicensed).toEqual('true');
let hasLicenseKey = false;
for (const [k, v] of Object.entries(license)) {
if (k === key && v === 'true') {
hasLicenseKey = true;
break;
}
}
if (!hasLicenseKey) {
console.error(`Server has no license for "${key}" feature.`);
}
jestExpect(hasLicenseKey).toEqual(true);
return {license};
};
/**
* Require SMTP server to be running.
* @param {string} baseUrl - the base server URL
*/
export const apiRequireSMTPServer = async (baseUrl: string) => {
const {status} = await apiEmailTest(baseUrl);
jestExpect(status).toEqual(200);
};
/**
* Upload server license with file expected at "/detox/e2e/support/fixtures/mattermost-license.txt"
* See https://api.mattermost.com/#operation/UploadLicenseFile
* @param {string} baseUrl - the base server URL
* @return {Object} returns response on success or {error, status} on error
*/
export const apiUploadLicense = async (baseUrl: string): Promise<any> => {
const absFilePath = path.resolve(__dirname, '../../support/fixtures/mattermost-license.txt');
return apiUploadFile('license', absFilePath, {url: `${baseUrl}/api/v4/license`, method: 'POST'});
};
// DISABLED: Do not request trial license in tests — tests should run with Free edition only.
// Keeping code commented out as reference; remove this function if trial licensing is never needed.
// /**
// * Request a trial Enterprise license from the Mattermost license server.
// * See https://api.mattermost.com/#operation/RequestTrialLicense
// * @param {string} baseUrl - the base server URL
// * @return {Object} returns response on success or {error, status} on error
// */
// export const apiRequestTrialLicense = async (baseUrl: string): Promise<any> => {
// try {
// const response = await client.post(`${baseUrl}/api/v4/trial-license`, {
// users: 1000,
// terms_accepted: true,
// receive_emails_accepted: true,
// contact_name: 'E2E Test',
// contact_email: 'admin@example.mattermost.com',
// company_name: 'Mattermost E2E',
// company_country: 'US',
// company_size: 'ONE_TO_50',
// });
// return {data: response.data};
// } catch (err) {
// return getResponseFromError(err);
// }
// };
/**
* Get client license.
* If no license, try to upload a license file first.
* Does NOT request trial license — tests run with Free edition features only.
* @param {string} baseUrl - the base server URL
* @return {Object} returns {license} on success or the unlicensed state
*/
export const getClientLicense = async (baseUrl: string): Promise<any> => {
const licenseResponse = await apiGetClientLicense(baseUrl);
if (licenseResponse.error) {
return licenseResponse;
}
const {license} = licenseResponse;
if (license?.IsLicensed === 'true') {
return {license};
}
// Try uploading a license file first (e.g. from fixtures)
const uploadResponse = await apiUploadLicense(baseUrl);
if (!uploadResponse.error) {
const out = await apiGetClientLicense(baseUrl);
if (out.license?.IsLicensed === 'true') {
return {license: out.license};
}
}
// Do not request trial license — tests should work with Free edition only
return {license};
};
export const System = {
apiCheckSystemHealth,
apiCreateRemoteCluster,
apiDeleteAllRemoteClusters,
apiEnsureSingleRemoteCluster,
apiDeleteRemoteCluster,
apiEnsureAtLeastOneConfirmedRemoteCluster,
apiEmailTest,
apiGetClientConfigOld,
apiGetClientLicense,
apiGetConfig,
apiGetRemoteClusters,
apiPatchConfig,
apiPingServerStatus,
apiReplaceConfig,
waitForClientConfigFlag,
// apiRequestTrialLicense, // DISABLED: Do not request trial license in tests
apiRequireLicense,
apiRequireLicenseForFeature,
apiRequireSMTPServer,
apiUpdateConfig,
apiUploadLicense,
getClientLicense,
shouldHavePluginUploadEnabled,
};
export default System;