snapshot of https://github.com/mattermost/mattermost.git (master, 2026-09-16; blobs > 131072B omitted)
Some checks failed
Server CI / Postgres (shard 0) (push) Has been skipped
Server CI / Postgres (shard 3) (push) Has been skipped
BuildEnv Docker Image / build-image (push) Failing after 4s
BuildEnv Docker Image / build-image-fips (push) Failing after 4s
Migration Review & Release Notes / Generate migration review & release notes (push) Failing after 3s
Server CI / Build Environment (push) Failing after 3s
Server CI / Postgres (shard 1) (push) Has been skipped
Tools CI / check-style (mattermost-govet) (push) Failing after 4s
Server CI / Postgres (shard 2) (push) Has been skipped
Tools CI / check-style (mmgotool) (push) Failing after 3s
Server CI / Elasticsearch v8 Compatibility (push) Has been skipped
Server CI / OpenSearch v2 Compatibility (push) Has been skipped
Server CI / Postgres FIPS (shard 0) (push) Has been skipped
Tools CI / Test (mattermost-govet) (push) Failing after 3s
Server CI / Postgres FIPS (shard 1) (push) Has been skipped
Server CI / Postgres FIPS (shard 2) (push) Has been skipped
Tools CI / Test (mmgotool) (push) Failing after 3s
Server CI / Postgres FIPS (shard 3) (push) Has been skipped
Server CI / Run mmctl tests (push) Has been skipped
Server CI / Run mmctl tests (FIPS) (push) Has been skipped
Server CI / Merge Postgres Test Results (push) Has been skipped
Server CI / Merge Postgres FIPS Test Results (push) Has been skipped
Server CI / Check backport migrations (push) Has been skipped
Server CI / Check generated files (push) Has been skipped
Server CI / check-style (push) Has been skipped
Server CI / Vet API (push) Has been skipped
Server CI / Build mattermost server app (push) Has been skipped
Server CI / Server CI Complete (push) Failing after 2s
Server CI / Server CI Artifacts (push) Has been skipped
Server CI / Sentry Upload (push) Has been skipped
Server CI / Server CI Report (push) Failing after 5m1s
Server CI Nightly Race / Race Detector (push) Has been skipped
CodeQL / Analyze (go) (push) Has been cancelled
CodeQL / Analyze (javascript) (push) Has been cancelled
Webapp CI Cache Warm / Warm Webapp node_modules Cache (push) Has been cancelled
E2E CI Cache Warm / Warm E2E npm Registry Cache (push) Has been cancelled
API / build (push) Has been cancelled
Web App CI / check-types (push) Has been cancelled
Web App CI / check-lint (push) Has been cancelled
Web App CI / check-i18n (push) Has been cancelled
Web App CI / check-external-links (push) Has been cancelled
Web App CI / test (platform) (push) Has been cancelled
Web App CI / test (mattermost-redux) (push) Has been cancelled
Web App CI / test (channels shard 1/4) (push) Has been cancelled
Web App CI / test (channels shard 2/4) (push) Has been cancelled
Web App CI / test (channels shard 3/4) (push) Has been cancelled
Web App CI / test (channels shard 4/4) (push) Has been cancelled
Web App CI / upload-coverage (push) Has been cancelled
Web App CI / build (push) Has been cancelled
YAML Lint / yamllint (push) Has been cancelled
Push mirrored docker images / cd/Push mirrored docker images (push) Has been cancelled
docs-cd / Build and deploy docs (push) Has been cancelled
Docs CI / build (push) Has been cancelled
E2E Cache Warm: Cypress deps / Warm Cypress deps cache (push) Has been cancelled
Scorecards supply-chain security / Scorecard analysis (push) Has been cancelled
Server CI Weekly / Postgres FIPS (push) Has been skipped
Server CI Weekly / Run mmctl tests (FIPS) (push) Has been skipped
Server CI Weekly / Postgres with binary parameters (push) Has been skipped
Server CI Weekly / Build Environment (push) Failing after 1s
Server CI Nightly Race / Build Environment (push) Failing after 1s
Server CI Cache Warm / Warm Go Module and Build Cache (push) Failing after 1s
Some checks failed
Server CI / Postgres (shard 0) (push) Has been skipped
Server CI / Postgres (shard 3) (push) Has been skipped
BuildEnv Docker Image / build-image (push) Failing after 4s
BuildEnv Docker Image / build-image-fips (push) Failing after 4s
Migration Review & Release Notes / Generate migration review & release notes (push) Failing after 3s
Server CI / Build Environment (push) Failing after 3s
Server CI / Postgres (shard 1) (push) Has been skipped
Tools CI / check-style (mattermost-govet) (push) Failing after 4s
Server CI / Postgres (shard 2) (push) Has been skipped
Tools CI / check-style (mmgotool) (push) Failing after 3s
Server CI / Elasticsearch v8 Compatibility (push) Has been skipped
Server CI / OpenSearch v2 Compatibility (push) Has been skipped
Server CI / Postgres FIPS (shard 0) (push) Has been skipped
Tools CI / Test (mattermost-govet) (push) Failing after 3s
Server CI / Postgres FIPS (shard 1) (push) Has been skipped
Server CI / Postgres FIPS (shard 2) (push) Has been skipped
Tools CI / Test (mmgotool) (push) Failing after 3s
Server CI / Postgres FIPS (shard 3) (push) Has been skipped
Server CI / Run mmctl tests (push) Has been skipped
Server CI / Run mmctl tests (FIPS) (push) Has been skipped
Server CI / Merge Postgres Test Results (push) Has been skipped
Server CI / Merge Postgres FIPS Test Results (push) Has been skipped
Server CI / Check backport migrations (push) Has been skipped
Server CI / Check generated files (push) Has been skipped
Server CI / check-style (push) Has been skipped
Server CI / Vet API (push) Has been skipped
Server CI / Build mattermost server app (push) Has been skipped
Server CI / Server CI Complete (push) Failing after 2s
Server CI / Server CI Artifacts (push) Has been skipped
Server CI / Sentry Upload (push) Has been skipped
Server CI / Server CI Report (push) Failing after 5m1s
Server CI Nightly Race / Race Detector (push) Has been skipped
CodeQL / Analyze (go) (push) Has been cancelled
CodeQL / Analyze (javascript) (push) Has been cancelled
Webapp CI Cache Warm / Warm Webapp node_modules Cache (push) Has been cancelled
E2E CI Cache Warm / Warm E2E npm Registry Cache (push) Has been cancelled
API / build (push) Has been cancelled
Web App CI / check-types (push) Has been cancelled
Web App CI / check-lint (push) Has been cancelled
Web App CI / check-i18n (push) Has been cancelled
Web App CI / check-external-links (push) Has been cancelled
Web App CI / test (platform) (push) Has been cancelled
Web App CI / test (mattermost-redux) (push) Has been cancelled
Web App CI / test (channels shard 1/4) (push) Has been cancelled
Web App CI / test (channels shard 2/4) (push) Has been cancelled
Web App CI / test (channels shard 3/4) (push) Has been cancelled
Web App CI / test (channels shard 4/4) (push) Has been cancelled
Web App CI / upload-coverage (push) Has been cancelled
Web App CI / build (push) Has been cancelled
YAML Lint / yamllint (push) Has been cancelled
Push mirrored docker images / cd/Push mirrored docker images (push) Has been cancelled
docs-cd / Build and deploy docs (push) Has been cancelled
Docs CI / build (push) Has been cancelled
E2E Cache Warm: Cypress deps / Warm Cypress deps cache (push) Has been cancelled
Scorecards supply-chain security / Scorecard analysis (push) Has been cancelled
Server CI Weekly / Postgres FIPS (push) Has been skipped
Server CI Weekly / Run mmctl tests (FIPS) (push) Has been skipped
Server CI Weekly / Postgres with binary parameters (push) Has been skipped
Server CI Weekly / Build Environment (push) Failing after 1s
Server CI Nightly Race / Build Environment (push) Failing after 1s
Server CI Cache Warm / Warm Go Module and Build Cache (push) Failing after 1s
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,268 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import type {SystemConsolePage} from '@mattermost/playwright-lib';
|
||||
import {
|
||||
enableAutotranslationConfig,
|
||||
disableAutotranslationConfig,
|
||||
hasAutotranslationLicense,
|
||||
expect,
|
||||
test,
|
||||
} from '@mattermost/playwright-lib';
|
||||
|
||||
test(
|
||||
'permission exists; Channel Administrators have Manage Channel Auto Translation ON',
|
||||
{
|
||||
tag: ['@autotranslation', '@permissions'],
|
||||
},
|
||||
async ({pw}) => {
|
||||
const {adminUser, adminClient} = await pw.initSetup();
|
||||
|
||||
const license = await adminClient.getClientLicenseOld();
|
||||
test.skip(
|
||||
!hasAutotranslationLicense(license.SkuShortName),
|
||||
'Skipping test - server does not have Entry or Advanced license',
|
||||
);
|
||||
|
||||
const {systemConsolePage} = await pw.testBrowser.login(adminUser);
|
||||
await systemConsolePage.goto();
|
||||
await systemConsolePage.toBeVisible();
|
||||
|
||||
await gotoSystemSchemePage(systemConsolePage);
|
||||
|
||||
const scheme = systemConsolePage.permissionsSystemScheme;
|
||||
await scheme.toBeVisible();
|
||||
|
||||
await scheme.expectManageChannelAutoTranslationChecked(scheme.channelAdministratorsSection);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'System Administrators have Manage Channel Auto Translation ON',
|
||||
{
|
||||
tag: ['@autotranslation', '@permissions'],
|
||||
},
|
||||
async ({pw}) => {
|
||||
const {adminUser, adminClient} = await pw.initSetup();
|
||||
|
||||
const license = await adminClient.getClientLicenseOld();
|
||||
test.skip(
|
||||
!hasAutotranslationLicense(license.SkuShortName),
|
||||
'Skipping test - server does not have Entry or Advanced license',
|
||||
);
|
||||
|
||||
const {systemConsolePage} = await pw.testBrowser.login(adminUser);
|
||||
await systemConsolePage.goto();
|
||||
await systemConsolePage.toBeVisible();
|
||||
|
||||
await gotoSystemSchemePage(systemConsolePage);
|
||||
|
||||
const scheme = systemConsolePage.permissionsSystemScheme;
|
||||
await scheme.toBeVisible();
|
||||
|
||||
await scheme.expectManageChannelAutoTranslationChecked(scheme.systemAdministratorsSection);
|
||||
},
|
||||
);
|
||||
|
||||
test.describe('autotranslation configuration tests', () => {
|
||||
test(
|
||||
'DM menu follows effective RestrictDMAndGM client config',
|
||||
{
|
||||
tag: ['@autotranslation', '@permissions'],
|
||||
},
|
||||
async ({pw}) => {
|
||||
const {adminClient, user, team} = await pw.initSetup();
|
||||
|
||||
const license = await adminClient.getClientLicenseOld();
|
||||
test.skip(
|
||||
!hasAutotranslationLicense(license.SkuShortName),
|
||||
'Skipping test - server does not have Entry or Advanced license',
|
||||
);
|
||||
|
||||
const originalConfig = await adminClient.getConfig();
|
||||
|
||||
try {
|
||||
await enableAutotranslationConfig(adminClient, {
|
||||
mockBaseUrl: process.env.TRANSLATION_SERVICE_URL || 'http://localhost:3010',
|
||||
targetLanguages: ['en', 'es'],
|
||||
});
|
||||
await expect.poll(async () => (await adminClient.getClientConfig()).EnableAutoTranslation).toBe('true');
|
||||
const restrictDMAndGM = (await adminClient.getClientConfig()).RestrictDMAndGMAutotranslation;
|
||||
const shouldShowEditHeader = restrictDMAndGM === 'true';
|
||||
|
||||
const peerData = await pw.random.user('dm-peer');
|
||||
const peerUser = await adminClient.createUser(peerData, '', '');
|
||||
await adminClient.addToTeam(team.id, peerUser.id);
|
||||
await adminClient.createDirectChannel([user.id, peerUser.id]);
|
||||
|
||||
const {channelsPage} = await pw.testBrowser.login(user);
|
||||
await channelsPage.goto(team.name, `@${peerUser.username}`);
|
||||
await channelsPage.toBeVisible();
|
||||
|
||||
await channelsPage.centerView.header.openChannelMenu();
|
||||
if (shouldShowEditHeader) {
|
||||
await expect(channelsPage.page.getByRole('menuitem', {name: 'Edit Header'})).toBeVisible();
|
||||
await expect(channelsPage.page.getByRole('menuitem', {name: 'Channel Settings'})).toHaveCount(0);
|
||||
} else {
|
||||
await expect(channelsPage.page.getByRole('menuitem', {name: 'Channel Settings'})).toBeVisible();
|
||||
await expect(channelsPage.page.getByRole('menuitem', {name: 'Edit Header'})).toHaveCount(0);
|
||||
}
|
||||
} finally {
|
||||
await adminClient.updateConfig(originalConfig as any);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'DM menu shows Edit Header when RestrictDMAndGM is enabled',
|
||||
{
|
||||
tag: ['@autotranslation', '@permissions'],
|
||||
},
|
||||
async ({pw}) => {
|
||||
const {adminClient, user, team} = await pw.initSetup();
|
||||
|
||||
const license = await adminClient.getClientLicenseOld();
|
||||
test.skip(
|
||||
!hasAutotranslationLicense(license.SkuShortName),
|
||||
'Skipping test - server does not have Entry or Advanced license',
|
||||
);
|
||||
|
||||
const originalConfig = await adminClient.getConfig();
|
||||
|
||||
try {
|
||||
await enableAutotranslationConfig(adminClient, {
|
||||
mockBaseUrl: process.env.TRANSLATION_SERVICE_URL || 'http://localhost:3010',
|
||||
targetLanguages: ['en', 'es'],
|
||||
});
|
||||
const configAfterEnable = (await adminClient.getConfig()) as any;
|
||||
await adminClient.updateConfig({
|
||||
...configAfterEnable,
|
||||
AutoTranslationSettings: {
|
||||
...configAfterEnable.AutoTranslationSettings,
|
||||
RestrictDMAndGM: true,
|
||||
},
|
||||
} as any);
|
||||
|
||||
await expect
|
||||
.poll(
|
||||
async () => ((await adminClient.getConfig()) as any)?.AutoTranslationSettings?.RestrictDMAndGM,
|
||||
)
|
||||
.toBe(true);
|
||||
await expect.poll(async () => (await adminClient.getClientConfig()).EnableAutoTranslation).toBe('true');
|
||||
await expect
|
||||
.poll(async () => (await adminClient.getClientConfig()).RestrictDMAndGMAutotranslation)
|
||||
.toBe('true');
|
||||
|
||||
const peerData = await pw.random.user('dm-peer-restricted');
|
||||
const peerUser = await adminClient.createUser(peerData, '', '');
|
||||
await adminClient.addToTeam(team.id, peerUser.id);
|
||||
await adminClient.createDirectChannel([user.id, peerUser.id]);
|
||||
|
||||
const {channelsPage} = await pw.testBrowser.login(user);
|
||||
await channelsPage.goto(team.name, `@${peerUser.username}`);
|
||||
await channelsPage.toBeVisible();
|
||||
|
||||
await channelsPage.centerView.header.openChannelMenu();
|
||||
await expect(channelsPage.page.getByRole('menuitem', {name: 'Edit Header'})).toBeVisible();
|
||||
await expect(channelsPage.page.getByRole('menuitem', {name: 'Channel Settings'})).toHaveCount(0);
|
||||
} finally {
|
||||
await adminClient.updateConfig(originalConfig as any);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'DM header saves from Channel Settings',
|
||||
{
|
||||
tag: ['@autotranslation', '@permissions'],
|
||||
},
|
||||
async ({pw}) => {
|
||||
const {adminClient, user, team} = await pw.initSetup();
|
||||
|
||||
const license = await adminClient.getClientLicenseOld();
|
||||
test.skip(
|
||||
!hasAutotranslationLicense(license.SkuShortName),
|
||||
'Skipping test - server does not have Entry or Advanced license',
|
||||
);
|
||||
|
||||
await enableAutotranslationConfig(adminClient, {
|
||||
mockBaseUrl: process.env.TRANSLATION_SERVICE_URL || 'http://localhost:3010',
|
||||
targetLanguages: ['en', 'es'],
|
||||
});
|
||||
|
||||
const otherUserData = await pw.random.user('dm-peer');
|
||||
const otherUser = await adminClient.createUser(otherUserData, '', '');
|
||||
await adminClient.addToTeam(team.id, otherUser.id);
|
||||
const dmChannel = await adminClient.createDirectChannel([user.id, otherUser.id]);
|
||||
|
||||
const {channelsPage} = await pw.testBrowser.login(user);
|
||||
await channelsPage.goto(team.name, `@${otherUser.username}`);
|
||||
await channelsPage.toBeVisible();
|
||||
|
||||
const channelSettingsModal = await channelsPage.openChannelSettings();
|
||||
await channelSettingsModal.toBeVisible();
|
||||
|
||||
const newHeader = `DM header ${pw.random.id()}`;
|
||||
await channelsPage.page.getByTestId('channel_settings_header_textbox').fill(newHeader);
|
||||
await channelsPage.page.getByRole('button', {name: 'Save'}).click();
|
||||
await channelSettingsModal.close();
|
||||
|
||||
await expect.poll(async () => (await adminClient.getChannel(dmChannel.id)).header).toBe(newHeader);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'user without permission cannot enable autotranslation at channel level',
|
||||
{
|
||||
tag: ['@autotranslation', '@permissions'],
|
||||
},
|
||||
async ({pw}) => {
|
||||
const {adminClient, user, team} = await pw.initSetup();
|
||||
|
||||
const license = await adminClient.getClientLicenseOld();
|
||||
test.skip(
|
||||
!hasAutotranslationLicense(license.SkuShortName),
|
||||
'Skipping test - server does not have Entry or Advanced license',
|
||||
);
|
||||
|
||||
// Enable autotranslation
|
||||
await enableAutotranslationConfig(adminClient, {
|
||||
mockBaseUrl: process.env.TRANSLATION_SERVICE_URL || 'http://localhost:3010',
|
||||
targetLanguages: ['en', 'es'],
|
||||
});
|
||||
|
||||
const channelName = `autotranslation-perm-${pw.random.id()}`;
|
||||
const created = await adminClient.createChannel({
|
||||
team_id: team.id,
|
||||
name: channelName,
|
||||
display_name: 'Permission Test Channel',
|
||||
type: 'O',
|
||||
});
|
||||
await adminClient.addToChannel(user.id, created.id);
|
||||
|
||||
const {channelsPage} = await pw.testBrowser.login(user);
|
||||
await channelsPage.goto(team.name, channelName);
|
||||
await channelsPage.toBeVisible();
|
||||
|
||||
const channelSettingsModal = await channelsPage.openChannelSettings();
|
||||
const configTabVisible = await channelSettingsModal.configurationTab.isVisible();
|
||||
if (configTabVisible) {
|
||||
const configurationTab = await channelSettingsModal.openConfigurationTab();
|
||||
await expect(
|
||||
configurationTab.container.getByTestId('channelTranslationToggle-button'),
|
||||
).not.toBeVisible();
|
||||
}
|
||||
|
||||
// Restore autotranslation to disabled via patchConfig (race-safe)
|
||||
await disableAutotranslationConfig(adminClient);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
async function gotoSystemSchemePage(systemConsolePage: SystemConsolePage) {
|
||||
await systemConsolePage.sidebar.userManagement.permissions.click();
|
||||
await systemConsolePage.page.waitForURL(/\/admin_console\/user_management\/permissions/);
|
||||
|
||||
await systemConsolePage.page.getByRole('link', {name: 'Edit Scheme'}).click();
|
||||
await systemConsolePage.page.waitForURL(/\/admin_console\/user_management\/permissions\/system_scheme/);
|
||||
}
|
||||
@@ -0,0 +1,516 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {
|
||||
ChannelsPost,
|
||||
disableAutotranslationConfig,
|
||||
enableAutotranslationConfig,
|
||||
enableChannelAutotranslation,
|
||||
getAdminClient,
|
||||
hasAutotranslationLicense,
|
||||
setUserChannelAutotranslation,
|
||||
expect,
|
||||
test,
|
||||
setMockSourceLanguage,
|
||||
} from '@mattermost/playwright-lib';
|
||||
|
||||
// Autotranslation tests involve real UI interactions with plugin state and can run
|
||||
// longer than the default 60 s in loaded CI. Set per-test timeout to 2 minutes.
|
||||
test.beforeEach(async () => {
|
||||
test.setTimeout(120000);
|
||||
});
|
||||
|
||||
// Disable AutoTranslationSettings at end of file so leftover state cannot leak
|
||||
// into other suites. Individual tests enable the feature via
|
||||
// enableAutotranslationConfig() as needed.
|
||||
test.afterAll(async () => {
|
||||
try {
|
||||
const {adminClient} = await getAdminClient({skipLog: true});
|
||||
await disableAutotranslationConfig(adminClient);
|
||||
} catch {
|
||||
// Best-effort cleanup.
|
||||
}
|
||||
});
|
||||
test(
|
||||
'translated message has indicator; click opens Show Translation modal',
|
||||
{
|
||||
tag: ['@autotranslation'],
|
||||
},
|
||||
async ({pw}) => {
|
||||
const {adminClient, user, userClient, team} = await pw.initSetup();
|
||||
|
||||
const license = await adminClient.getClientLicenseOld();
|
||||
test.skip(
|
||||
!hasAutotranslationLicense(license.SkuShortName),
|
||||
'Skipping test - server does not have Entry or Advanced license',
|
||||
);
|
||||
const translationUrl = process.env.TRANSLATION_SERVICE_URL || 'http://localhost:3010';
|
||||
await enableAutotranslationConfig(adminClient, {
|
||||
mockBaseUrl: translationUrl,
|
||||
targetLanguages: ['en', 'es'],
|
||||
});
|
||||
|
||||
const channelName = `autotranslation-modal-${pw.random.id()}`;
|
||||
const created = await adminClient.createChannel({
|
||||
team_id: team.id,
|
||||
name: channelName,
|
||||
display_name: 'Show Translation Modal Test',
|
||||
type: 'O',
|
||||
});
|
||||
await enableChannelAutotranslation(adminClient, created.id);
|
||||
await adminClient.addToChannel(user.id, created.id);
|
||||
await setUserChannelAutotranslation(userClient, created.id, true);
|
||||
|
||||
// Re-apply config immediately before posting so the server translates this message.
|
||||
// A concurrent initSetup() can reset AutoTranslationSettings.Enable to false.
|
||||
await enableAutotranslationConfig(adminClient, {
|
||||
mockBaseUrl: translationUrl,
|
||||
targetLanguages: ['en', 'es'],
|
||||
});
|
||||
// Confirm Enable=true before posting — translation happens at creation time,
|
||||
// so the config must be confirmed before posts are submitted.
|
||||
await pw.waitUntil(async () => {
|
||||
const cfg = await adminClient.getConfig();
|
||||
return (cfg as any).AutoTranslationSettings?.Enable === true;
|
||||
});
|
||||
// Verify the mock translation service is reachable before attempting to use it.
|
||||
try {
|
||||
await fetch(translationUrl, {signal: AbortSignal.timeout(3000)});
|
||||
} catch {
|
||||
test.skip(
|
||||
true,
|
||||
`Mock translation service not reachable at ${translationUrl}. ` +
|
||||
'Start the service or set TRANSLATION_SERVICE_URL to run this test.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Set Spanish source so the mock returns source='es', triggering es→en translation.
|
||||
await setMockSourceLanguage(translationUrl, 'es');
|
||||
|
||||
const poster = await pw.random.user('poster');
|
||||
const createdPoster = await adminClient.createUser(poster, '', '');
|
||||
await adminClient.addToTeam(team.id, createdPoster.id);
|
||||
await adminClient.addToChannel(createdPoster.id, created.id);
|
||||
const {client: posterClient} = await pw.makeClient({
|
||||
username: poster.username,
|
||||
password: poster.password,
|
||||
});
|
||||
if (!posterClient) {
|
||||
throw new Error('Failed to create poster client');
|
||||
}
|
||||
|
||||
// Create a second poster to show translation indicator (only visible with multiple users)
|
||||
const poster2 = await pw.random.user('poster2');
|
||||
const createdPoster2 = await adminClient.createUser(poster2, '', '');
|
||||
await adminClient.addToTeam(team.id, createdPoster2.id);
|
||||
await adminClient.addToChannel(createdPoster2.id, created.id);
|
||||
const {client: posterClient2} = await pw.makeClient({
|
||||
username: poster2.username,
|
||||
password: poster2.password,
|
||||
});
|
||||
if (!posterClient2) {
|
||||
throw new Error('Failed to create second poster client');
|
||||
}
|
||||
|
||||
// Post Spanish message that's long enough for reliable detection
|
||||
await posterClient.createPost({
|
||||
channel_id: created.id,
|
||||
message: 'Este es un texto para la modal de traducción automática que debe ser lo suficientemente largo',
|
||||
user_id: createdPoster.id,
|
||||
});
|
||||
// Second user posts a message so the first user's translation indicator appears
|
||||
await posterClient2.createPost({
|
||||
channel_id: created.id,
|
||||
message: 'Segundo usuario con mensaje más largo para mejor detección de idioma',
|
||||
user_id: createdPoster2.id,
|
||||
});
|
||||
|
||||
const {channelsPage, page} = await pw.testBrowser.login(user);
|
||||
await channelsPage.goto(team.name, channelName);
|
||||
await channelsPage.toBeVisible();
|
||||
|
||||
// Re-apply config + reload to counter concurrent initSetup() resets.
|
||||
await enableAutotranslationConfig(adminClient, {mockBaseUrl: translationUrl, targetLanguages: ['en', 'es']});
|
||||
await pw.waitUntil(async () => {
|
||||
const cfg = await adminClient.getConfig();
|
||||
return (cfg as any).AutoTranslationSettings?.Enable === true;
|
||||
});
|
||||
await channelsPage.page.reload();
|
||||
await channelsPage.toBeVisible();
|
||||
// Post-reload re-apply: a concurrent initSetup() may have reset
|
||||
// Enable during the ~500ms reload window.
|
||||
await enableAutotranslationConfig(adminClient, {mockBaseUrl: translationUrl, targetLanguages: ['en', 'es']});
|
||||
await pw.waitUntil(async () => {
|
||||
const cfg = await adminClient.getConfig();
|
||||
return (cfg as any).AutoTranslationSettings?.Enable === true;
|
||||
});
|
||||
|
||||
// * Wait for post by searching for the Spanish original (mock appends "[translated to en]", no real translation)
|
||||
const modalPost = channelsPage.centerView.container
|
||||
.locator('[id^="post_"]')
|
||||
.filter({hasText: 'Este es un texto para la modal de traducción automática'});
|
||||
await expect(modalPost).toBeVisible({timeout: 15000});
|
||||
|
||||
// * Check for translation button - if it exists, click it and verify modal
|
||||
const translationButton = modalPost.getByRole('button', {name: 'This post has been translated'});
|
||||
const hasTranslationButton = (await translationButton.count()) > 0;
|
||||
|
||||
// Translation button should be present - test expects translation to happen
|
||||
if (!hasTranslationButton) {
|
||||
throw new Error(
|
||||
'Translation button not found on post. Expected autotranslation to produce a translated message indicator.',
|
||||
);
|
||||
}
|
||||
|
||||
// Translation happened - verify the modal opens
|
||||
await translationButton.click();
|
||||
const showTranslationDialog = page.getByRole('dialog').filter({hasText: 'Show Translation'});
|
||||
await expect(showTranslationDialog).toBeVisible();
|
||||
await expect(showTranslationDialog.getByText('ORIGINAL')).toBeVisible();
|
||||
await expect(showTranslationDialog.getByText('AUTO-TRANSLATED')).toBeVisible();
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'message actions include Show translation',
|
||||
{
|
||||
tag: ['@autotranslation'],
|
||||
},
|
||||
async ({pw}) => {
|
||||
const {adminClient, user, userClient, team} = await pw.initSetup();
|
||||
|
||||
const license = await adminClient.getClientLicenseOld();
|
||||
test.skip(
|
||||
!hasAutotranslationLicense(license.SkuShortName),
|
||||
'Skipping test - server does not have Entry or Advanced license',
|
||||
);
|
||||
const translationUrl = process.env.TRANSLATION_SERVICE_URL || 'http://localhost:3010';
|
||||
await enableAutotranslationConfig(adminClient, {
|
||||
mockBaseUrl: translationUrl,
|
||||
targetLanguages: ['en', 'es'],
|
||||
});
|
||||
|
||||
const channelName = `autotranslation-dotmenu-${pw.random.id()}`;
|
||||
const created = await adminClient.createChannel({
|
||||
team_id: team.id,
|
||||
name: channelName,
|
||||
display_name: 'Dot Menu Show Translation Test',
|
||||
type: 'O',
|
||||
});
|
||||
await enableChannelAutotranslation(adminClient, created.id);
|
||||
await adminClient.addToChannel(user.id, created.id);
|
||||
await setUserChannelAutotranslation(userClient, created.id, true);
|
||||
|
||||
const poster = await pw.random.user('poster');
|
||||
const createdPoster = await adminClient.createUser(poster, '', '');
|
||||
await adminClient.addToTeam(team.id, createdPoster.id);
|
||||
await adminClient.addToChannel(createdPoster.id, created.id);
|
||||
const {client: posterClient} = await pw.makeClient({
|
||||
username: poster.username,
|
||||
password: poster.password,
|
||||
});
|
||||
if (!posterClient) {
|
||||
throw new Error('Failed to create poster client');
|
||||
}
|
||||
|
||||
// Create a second poster to show translation indicator (only visible with multiple users)
|
||||
const poster2 = await pw.random.user('poster2');
|
||||
const createdPoster2 = await adminClient.createUser(poster2, '', '');
|
||||
await adminClient.addToTeam(team.id, createdPoster2.id);
|
||||
await adminClient.addToChannel(createdPoster2.id, created.id);
|
||||
const {client: posterClient2} = await pw.makeClient({
|
||||
username: poster2.username,
|
||||
password: poster2.password,
|
||||
});
|
||||
if (!posterClient2) {
|
||||
throw new Error('Failed to create second poster client');
|
||||
}
|
||||
|
||||
// Re-apply config immediately before posting so the server translates this message.
|
||||
// A concurrent initSetup() can reset AutoTranslationSettings.Enable to false.
|
||||
await enableAutotranslationConfig(adminClient, {mockBaseUrl: translationUrl, targetLanguages: ['en', 'es']});
|
||||
// Confirm Enable=true before posting — translation happens at creation time,
|
||||
// so the config must be confirmed before posts are submitted.
|
||||
await pw.waitUntil(async () => {
|
||||
const cfg = await adminClient.getConfig();
|
||||
return (cfg as any).AutoTranslationSettings?.Enable === true;
|
||||
});
|
||||
// Verify the mock translation service is reachable before attempting to use it.
|
||||
// setMockSourceLanguage() swallows connection errors internally, so we probe the
|
||||
// service directly. If it is not running, skip rather than fail — the service is
|
||||
// an external dependency started by CI but not typically present in local runs.
|
||||
try {
|
||||
await fetch(translationUrl, {signal: AbortSignal.timeout(3000)});
|
||||
} catch {
|
||||
test.skip(
|
||||
true,
|
||||
`Mock translation service not reachable at ${translationUrl}. ` +
|
||||
'Start the service or set TRANSLATION_SERVICE_URL to run this test.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Set Spanish source so the mock returns source='es', triggering es→en translation.
|
||||
await setMockSourceLanguage(translationUrl, 'es');
|
||||
// Post Spanish message that's long enough for reliable detection.
|
||||
await posterClient.createPost({
|
||||
channel_id: created.id,
|
||||
message: 'Este mensaje es para probar el menú de acciones con la opción de mostrar traducción automática',
|
||||
user_id: createdPoster.id,
|
||||
});
|
||||
// Second post ensures the first post's translation indicator is rendered
|
||||
// (the UI only renders it for posts that are not the last in the channel).
|
||||
await posterClient2.createPost({
|
||||
channel_id: created.id,
|
||||
message: 'Segundo usuario con mensaje más largo para mejor detección de idioma',
|
||||
user_id: createdPoster2.id,
|
||||
});
|
||||
|
||||
const {channelsPage, page} = await pw.testBrowser.login(user);
|
||||
await channelsPage.goto(team.name, channelName);
|
||||
await channelsPage.toBeVisible();
|
||||
|
||||
// Pre-reload re-apply: ensure Enable=true before the page loads so the client
|
||||
// fetches posts with translations active.
|
||||
await enableAutotranslationConfig(adminClient, {mockBaseUrl: translationUrl, targetLanguages: ['en', 'es']});
|
||||
await pw.waitUntil(async () => {
|
||||
const cfg = await adminClient.getConfig();
|
||||
return (cfg as any).AutoTranslationSettings?.Enable === true;
|
||||
});
|
||||
await channelsPage.page.reload();
|
||||
await channelsPage.toBeVisible();
|
||||
// Post-reload re-apply: a concurrent initSetup() on another shard may have reset
|
||||
// Enable during the ~500ms reload window. Re-confirm before badge check.
|
||||
await enableAutotranslationConfig(adminClient, {mockBaseUrl: translationUrl, targetLanguages: ['en', 'es']});
|
||||
await pw.waitUntil(async () => {
|
||||
const cfg = await adminClient.getConfig();
|
||||
return (cfg as any).AutoTranslationSettings?.Enable === true;
|
||||
});
|
||||
|
||||
// * Wait for the channel-level autotranslation badge — confirms the feature is active.
|
||||
await expect(channelsPage.centerView.autotranslationBadge).toBeVisible({timeout: 15000});
|
||||
|
||||
// * Wait for the translated target post to appear.
|
||||
// The mock appends "[translated to en]" to the original Spanish text, confirming
|
||||
// translation.state==='ready' so that "Show translation" will be in the dot menu.
|
||||
const messagePost = channelsPage.centerView.container
|
||||
.getByTestId('postView')
|
||||
.filter({hasText: 'Este mensaje es para probar el menú de acciones'});
|
||||
await expect(messagePost.getByText(/\[translated to en\]/i)).toBeVisible({timeout: 15000});
|
||||
|
||||
// * Open dot menu using the established hover → wait → click pattern
|
||||
const post = new ChannelsPost(messagePost);
|
||||
await post.hover();
|
||||
await post.postMenu.toBeVisible();
|
||||
await post.postMenu.dotMenuButton.click();
|
||||
|
||||
// Move mouse away so it doesn't hover over Remind and trigger its submenu.
|
||||
// The submenu's MUI portal sets aria-hidden on the main menu, breaking getByRole.
|
||||
await page.mouse.move(0, 0);
|
||||
await channelsPage.postDotMenu.toBeVisible();
|
||||
|
||||
// * Verify the "Show translation" menu item is present
|
||||
await expect(channelsPage.postDotMenu.showTranslationMenuItem).toBeVisible({timeout: 10000});
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'any user can disable and enable again autotranslation for themselves in a channel',
|
||||
{
|
||||
tag: ['@autotranslation'],
|
||||
},
|
||||
async ({pw}) => {
|
||||
const {adminClient, user, userClient, team} = await pw.initSetup();
|
||||
|
||||
const license = await adminClient.getClientLicenseOld();
|
||||
test.skip(
|
||||
!hasAutotranslationLicense(license.SkuShortName),
|
||||
'Skipping test - server does not have Entry or Advanced license',
|
||||
);
|
||||
const translationUrl = process.env.TRANSLATION_SERVICE_URL || 'http://localhost:3010';
|
||||
await enableAutotranslationConfig(adminClient, {
|
||||
mockBaseUrl: translationUrl,
|
||||
targetLanguages: ['en', 'es'],
|
||||
});
|
||||
|
||||
const channelName = `autotranslation-toggle-${pw.random.id()}`;
|
||||
const created = await adminClient.createChannel({
|
||||
team_id: team.id,
|
||||
name: channelName,
|
||||
display_name: 'Autotranslation Toggle Test',
|
||||
type: 'O',
|
||||
});
|
||||
await enableChannelAutotranslation(adminClient, created.id);
|
||||
await adminClient.addToChannel(user.id, created.id);
|
||||
await setUserChannelAutotranslation(userClient, created.id, true);
|
||||
|
||||
const {channelsPage, page} = await pw.testBrowser.login(user);
|
||||
await channelsPage.goto(team.name, channelName);
|
||||
await channelsPage.toBeVisible();
|
||||
|
||||
// Defeat concurrent initSetup() config resets: re-apply on every poll iteration until badge appears.
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
await enableAutotranslationConfig(adminClient, {
|
||||
mockBaseUrl: translationUrl,
|
||||
targetLanguages: ['en', 'es'],
|
||||
});
|
||||
return channelsPage.centerView.autotranslationBadge.isVisible();
|
||||
},
|
||||
{timeout: 45000, intervals: [2000]},
|
||||
)
|
||||
.toBeTruthy();
|
||||
|
||||
await channelsPage.centerView.header.openChannelMenu();
|
||||
await page.getByRole('menuitem', {name: 'Disable autotranslation'}).click();
|
||||
await page.getByRole('button', {name: 'Turn off auto-translation'}).click();
|
||||
|
||||
await expect(channelsPage.centerView.autotranslationBadge).not.toBeVisible();
|
||||
|
||||
// Re-apply config before opening menu to ensure "Enable autotranslation" option is present.
|
||||
await enableAutotranslationConfig(adminClient, {mockBaseUrl: translationUrl, targetLanguages: ['en', 'es']});
|
||||
await channelsPage.centerView.header.openChannelMenu();
|
||||
await page.getByRole('menuitem', {name: 'Enable autotranslation'}).click();
|
||||
|
||||
// Poll with config re-apply until badge reappears.
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
await enableAutotranslationConfig(adminClient, {
|
||||
mockBaseUrl: translationUrl,
|
||||
targetLanguages: ['en', 'es'],
|
||||
});
|
||||
return channelsPage.centerView.autotranslationBadge.isVisible();
|
||||
},
|
||||
{timeout: 45000, intervals: [2000]},
|
||||
)
|
||||
.toBeTruthy();
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'autotranslation badge is only visible on translated channels',
|
||||
{
|
||||
tag: ['@autotranslation'],
|
||||
},
|
||||
async ({pw}) => {
|
||||
const {adminClient, user, userClient, team} = await pw.initSetup();
|
||||
|
||||
const license = await adminClient.getClientLicenseOld();
|
||||
test.skip(
|
||||
!hasAutotranslationLicense(license.SkuShortName),
|
||||
'Skipping test - server does not have Entry or Advanced license',
|
||||
);
|
||||
const translationUrl = process.env.TRANSLATION_SERVICE_URL || 'http://localhost:3010';
|
||||
await enableAutotranslationConfig(adminClient, {
|
||||
mockBaseUrl: translationUrl,
|
||||
targetLanguages: ['en', 'es'],
|
||||
});
|
||||
|
||||
const translatedChannelName = `autotranslation-badge-${pw.random.id()}`;
|
||||
const translatedChannel = await adminClient.createChannel({
|
||||
team_id: team.id,
|
||||
name: translatedChannelName,
|
||||
display_name: 'Translated Channel',
|
||||
type: 'O',
|
||||
});
|
||||
await enableChannelAutotranslation(adminClient, translatedChannel.id);
|
||||
await adminClient.addToChannel(user.id, translatedChannel.id);
|
||||
await setUserChannelAutotranslation(userClient, translatedChannel.id, true);
|
||||
|
||||
const noTranslationChannelName = `no-translation-${pw.random.id()}`;
|
||||
const noTranslationChannel = await adminClient.createChannel({
|
||||
team_id: team.id,
|
||||
name: noTranslationChannelName,
|
||||
display_name: 'No Translation Channel',
|
||||
type: 'O',
|
||||
});
|
||||
await adminClient.addToChannel(user.id, noTranslationChannel.id);
|
||||
|
||||
const {channelsPage} = await pw.testBrowser.login(user);
|
||||
|
||||
await channelsPage.goto(team.name, translatedChannelName);
|
||||
await channelsPage.toBeVisible();
|
||||
|
||||
// Re-apply config + reload to counter concurrent initSetup() resets.
|
||||
await enableAutotranslationConfig(adminClient, {mockBaseUrl: translationUrl, targetLanguages: ['en', 'es']});
|
||||
await pw.waitUntil(async () => {
|
||||
const cfg = await adminClient.getConfig();
|
||||
return (cfg as any).AutoTranslationSettings?.Enable === true;
|
||||
});
|
||||
await channelsPage.page.reload();
|
||||
// Post-reload re-apply: firing the CONFIG_CHANGED WebSocket event during page load
|
||||
// rather than after prevents it from disrupting the badge render.
|
||||
await enableAutotranslationConfig(adminClient, {mockBaseUrl: translationUrl, targetLanguages: ['en', 'es']});
|
||||
await pw.waitUntil(async () => {
|
||||
const cfg = await adminClient.getConfig();
|
||||
return (cfg as any).AutoTranslationSettings?.Enable === true;
|
||||
});
|
||||
await channelsPage.toBeVisible();
|
||||
|
||||
await expect(channelsPage.centerView.autotranslationBadge).toBeVisible({timeout: 15000});
|
||||
|
||||
await channelsPage.goto(team.name, noTranslationChannelName);
|
||||
await channelsPage.toBeVisible();
|
||||
await expect(channelsPage.centerView.autotranslationBadge).not.toBeVisible();
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'unsupported language does not show channel badge and shows message in channel header menu',
|
||||
{
|
||||
tag: ['@autotranslation'],
|
||||
},
|
||||
async ({pw}) => {
|
||||
const {adminClient, user, userClient, team} = await pw.initSetup();
|
||||
|
||||
const license = await adminClient.getClientLicenseOld();
|
||||
test.skip(
|
||||
!hasAutotranslationLicense(license.SkuShortName),
|
||||
'Skipping test - server does not have Entry or Advanced license',
|
||||
);
|
||||
const translationUrl = process.env.TRANSLATION_SERVICE_URL || 'http://localhost:3010';
|
||||
await enableAutotranslationConfig(adminClient, {
|
||||
mockBaseUrl: translationUrl,
|
||||
targetLanguages: ['en', 'es'],
|
||||
});
|
||||
|
||||
const channelName = `autotranslation-unsupported-${pw.random.id()}`;
|
||||
const created = await adminClient.createChannel({
|
||||
team_id: team.id,
|
||||
name: channelName,
|
||||
display_name: 'Unsupported Language Test',
|
||||
type: 'O',
|
||||
});
|
||||
await enableChannelAutotranslation(adminClient, created.id);
|
||||
await adminClient.addToChannel(user.id, created.id);
|
||||
|
||||
await userClient.patchMe({locale: 'fr'});
|
||||
|
||||
const {channelsPage, page} = await pw.testBrowser.login(user);
|
||||
await channelsPage.goto(team.name, channelName);
|
||||
await channelsPage.toBeVisible();
|
||||
|
||||
// Re-apply config + reload to ensure the browser reads the latest AutoTranslationSettings.
|
||||
// The badge should still be absent (French locale is not in targetLanguages), but the
|
||||
// server config must be active so the channel header menu shows the "unsupported" notice.
|
||||
await enableAutotranslationConfig(adminClient, {mockBaseUrl: translationUrl, targetLanguages: ['en', 'es']});
|
||||
await pw.waitUntil(async () => {
|
||||
const cfg = await adminClient.getConfig();
|
||||
return (cfg as any).AutoTranslationSettings?.Enable === true;
|
||||
});
|
||||
await channelsPage.page.reload();
|
||||
await channelsPage.toBeVisible();
|
||||
|
||||
await expect(channelsPage.centerView.autotranslationBadge).not.toBeVisible({timeout: 30000});
|
||||
|
||||
await channelsPage.centerView.header.openChannelMenu();
|
||||
const channelMenu = page
|
||||
.getByRole('menu')
|
||||
.filter({has: page.getByRole('menuitem', {name: /Auto-translation|Channel Settings/})});
|
||||
await expect(channelMenu.getByText('Auto-translation', {exact: true})).toBeVisible({timeout: 30000});
|
||||
await expect(channelMenu.getByText('Your language is not supported')).toBeVisible({timeout: 30000});
|
||||
const autotranslationItem = page.getByRole('menuitem', {name: /Auto-translation/});
|
||||
await expect(autotranslationItem).toBeDisabled();
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,508 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import {
|
||||
disableAutotranslationConfig,
|
||||
enableAutotranslationConfig,
|
||||
enableChannelAutotranslation,
|
||||
getAdminClient,
|
||||
hasAutotranslationLicense,
|
||||
setUserChannelAutotranslation,
|
||||
expect,
|
||||
test,
|
||||
setMockSourceLanguage,
|
||||
} from '@mattermost/playwright-lib';
|
||||
|
||||
// Autotranslation tests involve real UI interactions with plugin state and can run
|
||||
// longer than the default 60 s in loaded CI. Set per-test timeout to 2 minutes.
|
||||
test.beforeEach(async () => {
|
||||
test.setTimeout(120000);
|
||||
});
|
||||
|
||||
// Disable AutoTranslationSettings at end of file so leftover state cannot leak
|
||||
// into other suites. Individual tests enable the feature via
|
||||
// enableAutotranslationConfig() as needed.
|
||||
test.afterAll(async () => {
|
||||
try {
|
||||
const {adminClient} = await getAdminClient({skipLog: true});
|
||||
await disableAutotranslationConfig(adminClient);
|
||||
} catch {
|
||||
// Best-effort cleanup.
|
||||
}
|
||||
});
|
||||
test.fixme(
|
||||
'auto-translation is ON by default for new channel members',
|
||||
{
|
||||
tag: ['@autotranslation'],
|
||||
},
|
||||
async ({pw}) => {
|
||||
const {adminClient, user, team} = await pw.initSetup();
|
||||
|
||||
const license = await adminClient.getClientLicenseOld();
|
||||
test.skip(
|
||||
!hasAutotranslationLicense(license.SkuShortName),
|
||||
'Skipping test - server does not have Entry or Advanced license',
|
||||
);
|
||||
const translationUrl = process.env.TRANSLATION_SERVICE_URL || 'http://localhost:3010';
|
||||
await enableAutotranslationConfig(adminClient, {
|
||||
mockBaseUrl: translationUrl,
|
||||
targetLanguages: ['en', 'es'],
|
||||
});
|
||||
|
||||
const channelName = `autotranslation-default-on-${pw.random.id()}`;
|
||||
const created = await adminClient.createChannel({
|
||||
team_id: team.id,
|
||||
name: channelName,
|
||||
display_name: 'Default On Test',
|
||||
type: 'O',
|
||||
});
|
||||
await enableChannelAutotranslation(adminClient, created.id);
|
||||
|
||||
const poster = await pw.random.user('poster');
|
||||
const createdPoster = await adminClient.createUser(poster, '', '');
|
||||
await adminClient.addToTeam(team.id, createdPoster.id);
|
||||
await adminClient.addToChannel(createdPoster.id, created.id);
|
||||
const {client: posterClient} = await pw.makeClient({
|
||||
username: poster.username,
|
||||
password: poster.password,
|
||||
});
|
||||
if (!posterClient) {
|
||||
throw new Error('Failed to create poster client');
|
||||
}
|
||||
|
||||
// Re-apply config immediately before the post so the server translates it.
|
||||
await enableAutotranslationConfig(adminClient, {mockBaseUrl: translationUrl, targetLanguages: ['en', 'es']});
|
||||
// Set Spanish source to ensure translation happens for new member
|
||||
await setMockSourceLanguage(translationUrl, 'es');
|
||||
await posterClient.createPost({
|
||||
channel_id: created.id,
|
||||
message: 'Hola para nuevo miembro',
|
||||
user_id: createdPoster.id,
|
||||
});
|
||||
|
||||
await adminClient.addToChannel(user.id, created.id);
|
||||
const {channelsPage} = await pw.testBrowser.login(user);
|
||||
await channelsPage.goto(team.name, channelName);
|
||||
await channelsPage.toBeVisible();
|
||||
|
||||
// Re-apply config + reload so the badge and translated text reflect the latest server config.
|
||||
await enableAutotranslationConfig(adminClient, {mockBaseUrl: translationUrl, targetLanguages: ['en', 'es']});
|
||||
await pw.waitUntil(async () => {
|
||||
const cfg = await adminClient.getConfig();
|
||||
return (cfg as any).AutoTranslationSettings?.Enable === true;
|
||||
});
|
||||
await channelsPage.page.reload();
|
||||
await channelsPage.toBeVisible();
|
||||
|
||||
// * Verify translation badge is visible (indicates autotranslation is ON by default)
|
||||
await expect(channelsPage.centerView.autotranslationBadge).toBeVisible({timeout: 15000});
|
||||
|
||||
// * Verify post appeared with translation (mock server appends "[translated to en]" to original)
|
||||
await expect(
|
||||
channelsPage.centerView.container
|
||||
.locator('[id^="post_"]')
|
||||
.getByText('Hola para nuevo miembro [translated to en]', {exact: false}),
|
||||
).toBeVisible();
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'opting out shows ephemeral message to user',
|
||||
{
|
||||
tag: ['@autotranslation'],
|
||||
},
|
||||
async ({pw}) => {
|
||||
const {adminClient, user, userClient, team} = await pw.initSetup();
|
||||
|
||||
const license = await adminClient.getClientLicenseOld();
|
||||
test.skip(
|
||||
!hasAutotranslationLicense(license.SkuShortName),
|
||||
'Skipping test - server does not have Entry or Advanced license',
|
||||
);
|
||||
const translationUrl = process.env.TRANSLATION_SERVICE_URL || 'http://localhost:3010';
|
||||
await enableAutotranslationConfig(adminClient, {
|
||||
mockBaseUrl: translationUrl,
|
||||
targetLanguages: ['en', 'es'],
|
||||
});
|
||||
|
||||
const channelName = `autotranslation-ephemeral-${pw.random.id()}`;
|
||||
const created = await adminClient.createChannel({
|
||||
team_id: team.id,
|
||||
name: channelName,
|
||||
display_name: 'Ephemeral Test',
|
||||
type: 'O',
|
||||
});
|
||||
await enableChannelAutotranslation(adminClient, created.id);
|
||||
await adminClient.addToChannel(user.id, created.id);
|
||||
await setUserChannelAutotranslation(userClient, created.id, true);
|
||||
|
||||
const {channelsPage, page} = await pw.testBrowser.login(user);
|
||||
await channelsPage.goto(team.name, channelName);
|
||||
await channelsPage.toBeVisible();
|
||||
|
||||
// Re-apply config + reload so the badge reflects the latest AutoTranslationSettings.
|
||||
// A concurrent initSetup() → updateConfig(defaultConfig) resets Enable to false,
|
||||
// preventing the badge from appearing and the "Disable autotranslation" menu item
|
||||
// from being shown.
|
||||
await enableAutotranslationConfig(adminClient, {mockBaseUrl: translationUrl, targetLanguages: ['en', 'es']});
|
||||
await pw.waitUntil(async () => {
|
||||
const cfg = await adminClient.getConfig();
|
||||
return (cfg as any).AutoTranslationSettings?.Enable === true;
|
||||
});
|
||||
await channelsPage.page.reload();
|
||||
await channelsPage.toBeVisible();
|
||||
|
||||
// Wait for autotranslation state to be reflected in the header before opening the menu,
|
||||
// so that the "Disable autotranslation" menu item is present when the menu opens.
|
||||
await expect(channelsPage.centerView.autotranslationBadge).toBeVisible({timeout: 15000});
|
||||
|
||||
await channelsPage.centerView.header.openChannelMenu();
|
||||
await page.getByRole('menuitem', {name: 'Disable autotranslation'}).click();
|
||||
await page.getByRole('button', {name: 'Turn off auto-translation'}).click();
|
||||
|
||||
await expect(
|
||||
channelsPage.centerView.container.locator('p').getByText(/You disabled Auto-translation for this channel/i),
|
||||
).toBeVisible();
|
||||
},
|
||||
);
|
||||
|
||||
test.fixme(
|
||||
'disabling for self reverts translated messages to original',
|
||||
{
|
||||
tag: ['@autotranslation'],
|
||||
},
|
||||
async ({pw}) => {
|
||||
const {adminClient, user, userClient, team} = await pw.initSetup();
|
||||
|
||||
const license = await adminClient.getClientLicenseOld();
|
||||
test.skip(
|
||||
!hasAutotranslationLicense(license.SkuShortName),
|
||||
'Skipping test - server does not have Entry or Advanced license',
|
||||
);
|
||||
const translationUrl = process.env.TRANSLATION_SERVICE_URL || 'http://localhost:3010';
|
||||
await enableAutotranslationConfig(adminClient, {
|
||||
mockBaseUrl: translationUrl,
|
||||
targetLanguages: ['en', 'es'],
|
||||
});
|
||||
|
||||
const channelName = `autotranslation-revert-${pw.random.id()}`;
|
||||
const created = await adminClient.createChannel({
|
||||
team_id: team.id,
|
||||
name: channelName,
|
||||
display_name: 'Revert Test',
|
||||
type: 'O',
|
||||
});
|
||||
await enableChannelAutotranslation(adminClient, created.id);
|
||||
await adminClient.addToChannel(user.id, created.id);
|
||||
await setUserChannelAutotranslation(userClient, created.id, true);
|
||||
|
||||
const poster = await pw.random.user('poster');
|
||||
const createdPoster = await adminClient.createUser(poster, '', '');
|
||||
await adminClient.addToTeam(team.id, createdPoster.id);
|
||||
await adminClient.addToChannel(createdPoster.id, created.id);
|
||||
const {client: posterClient} = await pw.makeClient({
|
||||
username: poster.username,
|
||||
password: poster.password,
|
||||
});
|
||||
if (!posterClient) {
|
||||
throw new Error('Failed to create poster client');
|
||||
}
|
||||
|
||||
const originalText = 'Solo texto original';
|
||||
// Re-apply config immediately before posting so the server translates this message.
|
||||
await enableAutotranslationConfig(adminClient, {mockBaseUrl: translationUrl, targetLanguages: ['en', 'es']});
|
||||
// Set Spanish to ensure translation
|
||||
await setMockSourceLanguage(translationUrl, 'es');
|
||||
await posterClient.createPost({
|
||||
channel_id: created.id,
|
||||
message: originalText,
|
||||
user_id: createdPoster.id,
|
||||
});
|
||||
|
||||
const {channelsPage, page} = await pw.testBrowser.login(user);
|
||||
await channelsPage.goto(team.name, channelName);
|
||||
await channelsPage.toBeVisible();
|
||||
|
||||
// Re-apply config + reload so the browser reads the latest AutoTranslationSettings.
|
||||
// A concurrent initSetup() on another shard may have disabled autotranslation between
|
||||
// the initial enableAutotranslationConfig call (before posting) and login.
|
||||
await enableAutotranslationConfig(adminClient, {mockBaseUrl: translationUrl, targetLanguages: ['en', 'es']});
|
||||
await pw.waitUntil(async () => {
|
||||
const cfg = await adminClient.getConfig();
|
||||
return (cfg as any).AutoTranslationSettings?.Enable === true;
|
||||
});
|
||||
await channelsPage.page.reload();
|
||||
await channelsPage.toBeVisible();
|
||||
|
||||
// * Verify post with translated text appears before disabling.
|
||||
// Mock server appends "[translated to en]" to the original text. Translation
|
||||
// is asynchronous and can lag several seconds in CI; use expect.poll to retry
|
||||
// reliably rather than a fixed 15 s one-shot timeout.
|
||||
const translatedText = 'Solo texto original [translated to en]';
|
||||
const spanishPost = channelsPage.centerView.container
|
||||
.locator('[id^="post_"]')
|
||||
.filter({hasText: translatedText});
|
||||
await expect
|
||||
.poll(async () => spanishPost.isVisible(), {
|
||||
timeout: 60000,
|
||||
intervals: [500, 1500, 3000, 5000],
|
||||
})
|
||||
.toBe(true);
|
||||
|
||||
await channelsPage.centerView.header.openChannelMenu();
|
||||
await page.getByRole('menuitem', {name: 'Disable autotranslation'}).click();
|
||||
await page.getByRole('button', {name: 'Turn off auto-translation'}).click();
|
||||
|
||||
// * After disabling, wait for page to update and verify original text is shown
|
||||
// Find the post containing the original text (skip system messages)
|
||||
const userPost = channelsPage.centerView.container
|
||||
.locator('[id^="post_"]')
|
||||
.filter({has: page.locator('.post__body').filter({hasText: originalText})});
|
||||
await expect(userPost).toBeVisible({timeout: 15000});
|
||||
await expect(userPost).toContainText(originalText);
|
||||
|
||||
// * Verify translation indicator is no longer present
|
||||
await expect(userPost.getByRole('button', {name: 'This post has been translated'})).not.toBeVisible();
|
||||
},
|
||||
);
|
||||
|
||||
test.fixme(
|
||||
'messages only translate when source differs from user language',
|
||||
{
|
||||
tag: ['@autotranslation'],
|
||||
},
|
||||
async ({pw}) => {
|
||||
const {adminClient, user, userClient, team} = await pw.initSetup();
|
||||
|
||||
const license = await adminClient.getClientLicenseOld();
|
||||
test.skip(
|
||||
!hasAutotranslationLicense(license.SkuShortName),
|
||||
'Skipping test - server does not have Entry or Advanced license',
|
||||
);
|
||||
const translationUrl = process.env.TRANSLATION_SERVICE_URL || 'http://localhost:3010';
|
||||
await enableAutotranslationConfig(adminClient, {
|
||||
mockBaseUrl: translationUrl,
|
||||
targetLanguages: ['en', 'es'],
|
||||
});
|
||||
|
||||
const channelName = `autotranslation-lang-${pw.random.id()}`;
|
||||
const created = await adminClient.createChannel({
|
||||
team_id: team.id,
|
||||
name: channelName,
|
||||
display_name: 'Language Rules Test',
|
||||
type: 'O',
|
||||
});
|
||||
await enableChannelAutotranslation(adminClient, created.id);
|
||||
await adminClient.addToChannel(user.id, created.id);
|
||||
await setUserChannelAutotranslation(userClient, created.id, true);
|
||||
|
||||
const poster = await pw.random.user('poster');
|
||||
const createdPoster = await adminClient.createUser(poster, '', '');
|
||||
await adminClient.addToTeam(team.id, createdPoster.id);
|
||||
await adminClient.addToChannel(createdPoster.id, created.id);
|
||||
const {client: posterClient} = await pw.makeClient({
|
||||
username: poster.username,
|
||||
password: poster.password,
|
||||
});
|
||||
if (!posterClient) {
|
||||
throw new Error('Failed to create poster client');
|
||||
}
|
||||
|
||||
// Create a second poster to test translation indicators (only show with multiple users)
|
||||
const poster2 = await pw.random.user('poster2');
|
||||
const createdPoster2 = await adminClient.createUser(poster2, '', '');
|
||||
await adminClient.addToTeam(team.id, createdPoster2.id);
|
||||
await adminClient.addToChannel(createdPoster2.id, created.id);
|
||||
const {client: posterClient2} = await pw.makeClient({
|
||||
username: poster2.username,
|
||||
password: poster2.password,
|
||||
});
|
||||
if (!posterClient2) {
|
||||
throw new Error('Failed to create second poster client');
|
||||
}
|
||||
|
||||
// Re-apply config immediately before posting so the server translates these messages.
|
||||
await enableAutotranslationConfig(adminClient, {mockBaseUrl: translationUrl, targetLanguages: ['en', 'es']});
|
||||
// Set source language for mock/real server before creating posts
|
||||
// For mock: controls which language is detected; for real: auto-detection is used
|
||||
// Post Spanish first so it gets the translation indicator (first message from posterClient)
|
||||
await setMockSourceLanguage(translationUrl, 'es');
|
||||
await posterClient.createPost({
|
||||
channel_id: created.id,
|
||||
message: 'Solo español',
|
||||
user_id: createdPoster.id,
|
||||
});
|
||||
// English message won't be translated
|
||||
await setMockSourceLanguage(translationUrl, 'en');
|
||||
await posterClient.createPost({
|
||||
channel_id: created.id,
|
||||
message: 'English only',
|
||||
user_id: createdPoster.id,
|
||||
});
|
||||
// Second user posts translated message (translation indicators only show with multiple users)
|
||||
await posterClient2.createPost({
|
||||
channel_id: created.id,
|
||||
message: 'Hola desde segundo usuario',
|
||||
user_id: createdPoster2.id,
|
||||
});
|
||||
|
||||
const {channelsPage} = await pw.testBrowser.login(user);
|
||||
await channelsPage.goto(team.name, channelName);
|
||||
await channelsPage.toBeVisible();
|
||||
|
||||
// * Verify both posts appear
|
||||
// Mock server produces "<original> [translated to en]", not real translations.
|
||||
// Translation is async — use expect.poll to ride out mock-service latency in CI.
|
||||
await expect(channelsPage.centerView.container.locator('[id^="post_"]').getByText('English only')).toBeVisible({
|
||||
timeout: 15000,
|
||||
});
|
||||
const translatedSpanishLocator = channelsPage.centerView.container
|
||||
.locator('[id^="post_"]')
|
||||
.getByText('Solo español [translated to en]', {exact: false});
|
||||
await expect
|
||||
.poll(async () => translatedSpanishLocator.isVisible(), {
|
||||
timeout: 45000,
|
||||
intervals: [500, 1500, 3000, 5000],
|
||||
})
|
||||
.toBe(true);
|
||||
|
||||
// * Verify both messages are present
|
||||
const spanishPost = channelsPage.centerView.container
|
||||
.locator('[id^="post_"]')
|
||||
.filter({hasText: 'Solo español [translated to en]'});
|
||||
await expect(spanishPost).toBeVisible({timeout: 30000});
|
||||
|
||||
// * Verify English message is present and unchanged
|
||||
const englishPost = channelsPage.centerView.container
|
||||
.locator('[id^="post_"]')
|
||||
.filter({hasText: 'English only'});
|
||||
await expect(englishPost).toBeVisible();
|
||||
},
|
||||
);
|
||||
|
||||
test.fixme(
|
||||
'message indicator only on actually translated message',
|
||||
{
|
||||
tag: ['@autotranslation'],
|
||||
},
|
||||
async ({pw}) => {
|
||||
test.setTimeout(120000);
|
||||
const {adminClient, user, userClient, team} = await pw.initSetup();
|
||||
|
||||
const license = await adminClient.getClientLicenseOld();
|
||||
test.skip(
|
||||
!hasAutotranslationLicense(license.SkuShortName),
|
||||
'Skipping test - server does not have Entry or Advanced license',
|
||||
);
|
||||
const translationUrl = process.env.TRANSLATION_SERVICE_URL || 'http://localhost:3010';
|
||||
await enableAutotranslationConfig(adminClient, {
|
||||
mockBaseUrl: translationUrl,
|
||||
targetLanguages: ['en', 'es'],
|
||||
});
|
||||
|
||||
const channelName = `autotranslation-indicator-${pw.random.id()}`;
|
||||
const created = await adminClient.createChannel({
|
||||
team_id: team.id,
|
||||
name: channelName,
|
||||
display_name: 'Indicator Test',
|
||||
type: 'O',
|
||||
});
|
||||
await enableChannelAutotranslation(adminClient, created.id);
|
||||
await adminClient.addToChannel(user.id, created.id);
|
||||
await setUserChannelAutotranslation(userClient, created.id, true);
|
||||
|
||||
const poster = await pw.random.user('poster');
|
||||
const createdPoster = await adminClient.createUser(poster, '', '');
|
||||
await adminClient.addToTeam(team.id, createdPoster.id);
|
||||
await adminClient.addToChannel(createdPoster.id, created.id);
|
||||
const {client: posterClient} = await pw.makeClient({
|
||||
username: poster.username,
|
||||
password: poster.password,
|
||||
});
|
||||
if (!posterClient) {
|
||||
throw new Error('Failed to create poster client');
|
||||
}
|
||||
|
||||
// Create a second poster to test translation indicators (only show with multiple users)
|
||||
const poster2 = await pw.random.user('poster2');
|
||||
const createdPoster2 = await adminClient.createUser(poster2, '', '');
|
||||
await adminClient.addToTeam(team.id, createdPoster2.id);
|
||||
await adminClient.addToChannel(createdPoster2.id, created.id);
|
||||
const {client: posterClient2} = await pw.makeClient({
|
||||
username: poster2.username,
|
||||
password: poster2.password,
|
||||
});
|
||||
if (!posterClient2) {
|
||||
throw new Error('Failed to create second poster client');
|
||||
}
|
||||
|
||||
// Re-apply config immediately before posting so the server translates these messages.
|
||||
await enableAutotranslationConfig(adminClient, {mockBaseUrl: translationUrl, targetLanguages: ['en', 'es']});
|
||||
|
||||
// Post the English-only message FIRST so the mock's source-language state is reset
|
||||
// before any setMockSourceLanguage calls. The server processes translation
|
||||
// asynchronously: if setMockSourceLanguage('en') is called right after a post the
|
||||
// mock's detected language can be overridden before the server's detect request
|
||||
// arrives, silently preventing translation of the Spanish message.
|
||||
// By posting 'English only' first (no source override — mock auto-detects English
|
||||
// and skips translation because source == target), we then safely set 'es' and
|
||||
// post the Spanish message without any subsequent race-prone source switch.
|
||||
await posterClient.createPost({
|
||||
channel_id: created.id,
|
||||
message: 'English only',
|
||||
user_id: createdPoster.id,
|
||||
});
|
||||
|
||||
// Set Spanish source so the mock translates the next post.
|
||||
await setMockSourceLanguage(translationUrl, 'es');
|
||||
await posterClient.createPost({
|
||||
channel_id: created.id,
|
||||
message: 'Solo español',
|
||||
user_id: createdPoster.id,
|
||||
});
|
||||
// Second user posts translated message (translation indicators only show with multiple users)
|
||||
await posterClient2.createPost({
|
||||
channel_id: created.id,
|
||||
message: 'Otro mensaje en español',
|
||||
user_id: createdPoster2.id,
|
||||
});
|
||||
|
||||
await enableAutotranslationConfig(adminClient, {
|
||||
mockBaseUrl: translationUrl,
|
||||
targetLanguages: ['en', 'es'],
|
||||
});
|
||||
await pw.waitUntil(async () => {
|
||||
const cfg = await adminClient.getConfig();
|
||||
return (cfg as any).AutoTranslationSettings?.Enable === true;
|
||||
});
|
||||
|
||||
const {channelsPage} = await pw.testBrowser.login(user);
|
||||
await channelsPage.goto(team.name, channelName);
|
||||
await channelsPage.toBeVisible();
|
||||
await channelsPage.centerView.container.waitFor({state: 'visible', timeout: 30000});
|
||||
|
||||
// * Verify translated Spanish post is present
|
||||
// Mock server produces "<original> [translated to en]"
|
||||
const translatedPost = channelsPage.centerView.container
|
||||
.locator('[id^="post_"]')
|
||||
.filter({hasText: 'Solo español [translated to en]'});
|
||||
await expect
|
||||
.poll(async () => translatedPost.isVisible(), {
|
||||
timeout: 90000,
|
||||
intervals: [500, 1500, 3000, 5000],
|
||||
})
|
||||
.toBe(true);
|
||||
|
||||
// * Verify the English post is present and unchanged (not translated)
|
||||
const notTranslatedPost = channelsPage.centerView.container
|
||||
.locator('[id^="post_"]')
|
||||
.filter({hasText: 'English only'})
|
||||
.filter({hasNotText: '[translated to en]'});
|
||||
await expect
|
||||
.poll(async () => notTranslatedPost.isVisible(), {
|
||||
timeout: 60000,
|
||||
intervals: [500, 1500, 3000],
|
||||
})
|
||||
.toBe(true);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,303 @@
|
||||
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
|
||||
// See LICENSE.txt for license information.
|
||||
|
||||
import type {Page, Route} from '@playwright/test';
|
||||
|
||||
interface MockTranslateRequest {
|
||||
q?: string;
|
||||
text?: string;
|
||||
source?: string;
|
||||
target?: string;
|
||||
}
|
||||
|
||||
interface MockTranslateResponse {
|
||||
translatedText: string;
|
||||
detectedLanguage: {language: string; confidence: number};
|
||||
}
|
||||
|
||||
/**
|
||||
* Tracks the source language for mock translation responses
|
||||
* Used to simulate language detection behavior
|
||||
*/
|
||||
let mockSourceLanguage = 'es';
|
||||
|
||||
/**
|
||||
* Simple language detection from text content
|
||||
* Simulates how real LibreTranslate detects language from actual message text
|
||||
*/
|
||||
function detectLanguageFromText(text: string): string {
|
||||
if (!text) {
|
||||
return mockSourceLanguage;
|
||||
}
|
||||
|
||||
const lowerText = text.toLowerCase();
|
||||
|
||||
// Spanish patterns
|
||||
const spanishIndicators = [
|
||||
'el ',
|
||||
'la ',
|
||||
'de ',
|
||||
'que ',
|
||||
'para ',
|
||||
'con ',
|
||||
'una ',
|
||||
'este ',
|
||||
'está',
|
||||
'muy',
|
||||
'en ',
|
||||
'aquí',
|
||||
'gracias',
|
||||
'hola',
|
||||
'adiós',
|
||||
];
|
||||
const spanishMatches = spanishIndicators.filter((indicator) => lowerText.includes(indicator)).length;
|
||||
|
||||
// English patterns
|
||||
const englishIndicators = [
|
||||
'the ',
|
||||
'and ',
|
||||
'is ',
|
||||
'to ',
|
||||
'of ',
|
||||
'that ',
|
||||
'this ',
|
||||
'for ',
|
||||
'with ',
|
||||
'hello',
|
||||
'thanks',
|
||||
'please',
|
||||
'translation',
|
||||
];
|
||||
const englishMatches = englishIndicators.filter((indicator) => lowerText.includes(indicator)).length;
|
||||
|
||||
// French patterns
|
||||
const frenchIndicators = [
|
||||
'le ',
|
||||
'la ',
|
||||
'de ',
|
||||
'est ',
|
||||
'que ',
|
||||
'pour ',
|
||||
'avec ',
|
||||
'un ',
|
||||
'une ',
|
||||
'ça',
|
||||
'bonjour',
|
||||
'merci',
|
||||
];
|
||||
const frenchMatches = frenchIndicators.filter((indicator) => lowerText.includes(indicator)).length;
|
||||
|
||||
// Return the language with most matches
|
||||
if (spanishMatches > englishMatches && spanishMatches > frenchMatches) {
|
||||
return 'es';
|
||||
}
|
||||
if (englishMatches > frenchMatches) {
|
||||
return 'en';
|
||||
}
|
||||
if (frenchMatches > 0) {
|
||||
return 'fr';
|
||||
}
|
||||
|
||||
// Default to configured mock language
|
||||
return mockSourceLanguage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the source language that the mock will detect
|
||||
* Useful for testing language detection and filtering logic
|
||||
*/
|
||||
export function setMockSourceLanguage(language: string): void {
|
||||
mockSourceLanguage = language;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current mock source language
|
||||
*/
|
||||
export function getMockSourceLanguage(): string {
|
||||
return mockSourceLanguage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset mock source language to default
|
||||
*/
|
||||
export function resetMockSourceLanguage(): void {
|
||||
mockSourceLanguage = 'es';
|
||||
}
|
||||
|
||||
/**
|
||||
* Mock the autotranslation API route using Playwright's route interception.
|
||||
* This replaces the need for an external mock server.
|
||||
*
|
||||
* Returns a `Disposable` to remove the mock routes. Use with `await using`
|
||||
* for automatic cleanup or call `.dispose()` manually:
|
||||
*
|
||||
* ```ts
|
||||
* await using mock = await mockAutotranslationRoute(page);
|
||||
* ```
|
||||
*
|
||||
* @param page - Playwright Page object
|
||||
* @param options - Optional configuration
|
||||
* @param options.sourceLanguage - Initial detected source language (default: 'es')
|
||||
* @param options.supportedLanguages - List of supported target languages (default: ['en', 'es', 'fr', 'de'])
|
||||
*/
|
||||
export async function mockAutotranslationRoute(
|
||||
page: Page,
|
||||
options?: {
|
||||
sourceLanguage?: string;
|
||||
supportedLanguages?: string[];
|
||||
},
|
||||
): Promise<{dispose(): Promise<void>; [Symbol.asyncDispose](): Promise<void>}> {
|
||||
// Reset mockSourceLanguage to avoid state leakage between tests
|
||||
mockSourceLanguage = options?.sourceLanguage || 'es';
|
||||
|
||||
const supportedLanguages = options?.supportedLanguages || ['en', 'es', 'fr', 'de'];
|
||||
|
||||
// Named handler so it can be passed to page.unroute() for cleanup
|
||||
const translateHandler = async (route: Route): Promise<void> => {
|
||||
const request = route.request();
|
||||
const method = request.method();
|
||||
|
||||
if (method === 'POST') {
|
||||
let postData: MockTranslateRequest;
|
||||
try {
|
||||
postData = (await request.postDataJSON()) as MockTranslateRequest;
|
||||
} catch {
|
||||
// If POST data is not JSON, try to parse as form-encoded data
|
||||
const postDataBuffer = request.postData();
|
||||
if (!postDataBuffer) {
|
||||
await route.abort('failed');
|
||||
return;
|
||||
}
|
||||
// Parse form-encoded data (application/x-www-form-urlencoded)
|
||||
const formData = new URLSearchParams(postDataBuffer.toString());
|
||||
postData = {
|
||||
q: formData.get('q') || undefined,
|
||||
text: formData.get('text') || undefined,
|
||||
source: formData.get('source') || undefined,
|
||||
target: formData.get('target') || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
const textToTranslate = postData.q || postData.text || '';
|
||||
// When source is empty or "auto", detect language from text (simulates real LibreTranslate)
|
||||
// Otherwise use the provided source language
|
||||
const sourceLanguage =
|
||||
postData.source && postData.source !== 'auto'
|
||||
? postData.source
|
||||
: detectLanguageFromText(textToTranslate);
|
||||
const targetLanguage = postData.target || 'en';
|
||||
|
||||
// Validate target language is supported
|
||||
if (!supportedLanguages.includes(targetLanguage)) {
|
||||
await route.fulfill({
|
||||
status: 400,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
error: `Target language '${targetLanguage}' is not supported`,
|
||||
}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Mock response: only "translate" if source differs from target
|
||||
let translatedText = textToTranslate;
|
||||
const shouldTranslate = sourceLanguage !== targetLanguage;
|
||||
|
||||
if (shouldTranslate) {
|
||||
// Prepend language code to simulate translation
|
||||
translatedText = `[${targetLanguage}] ${textToTranslate}`;
|
||||
}
|
||||
|
||||
const response: MockTranslateResponse = {
|
||||
translatedText,
|
||||
detectedLanguage: {
|
||||
language: sourceLanguage,
|
||||
confidence: 0.95,
|
||||
},
|
||||
};
|
||||
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(response),
|
||||
});
|
||||
} else if (method === 'GET') {
|
||||
// Handle GET requests (e.g., /translate?q=hello&source=es&target=en)
|
||||
const url = new URL(request.url());
|
||||
const textToTranslate = url.searchParams.get('q') || '';
|
||||
const sourceParam = url.searchParams.get('source');
|
||||
// When source is empty or "auto", detect language from text (simulates real LibreTranslate)
|
||||
const sourceLanguage =
|
||||
sourceParam && sourceParam !== 'auto' ? sourceParam : detectLanguageFromText(textToTranslate);
|
||||
const targetLanguage = url.searchParams.get('target') || 'en';
|
||||
|
||||
if (!supportedLanguages.includes(targetLanguage)) {
|
||||
await route.fulfill({
|
||||
status: 400,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
error: `Target language '${targetLanguage}' is not supported`,
|
||||
}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let translatedText = textToTranslate;
|
||||
const shouldTranslate = sourceLanguage !== targetLanguage;
|
||||
|
||||
if (shouldTranslate) {
|
||||
translatedText = `[${targetLanguage}] ${textToTranslate}`;
|
||||
}
|
||||
|
||||
const response: MockTranslateResponse = {
|
||||
translatedText,
|
||||
detectedLanguage: {
|
||||
language: sourceLanguage,
|
||||
confidence: 0.95,
|
||||
},
|
||||
};
|
||||
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(response),
|
||||
});
|
||||
} else {
|
||||
await route.abort('failed');
|
||||
}
|
||||
};
|
||||
|
||||
// Named handler so it can be passed to page.unroute() for cleanup
|
||||
const detectHandler = async (route: Route): Promise<void> => {
|
||||
// Language detection is mocked to always return the configured source language
|
||||
// regardless of the input text
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
result: [
|
||||
{
|
||||
language: mockSourceLanguage,
|
||||
confidence: 0.95,
|
||||
},
|
||||
],
|
||||
detectedLanguage: {language: mockSourceLanguage, confidence: 0.95},
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
// Mock LibreTranslate API endpoints
|
||||
await page.route('**/api/translate', translateHandler);
|
||||
await page.route('**/api/detect', detectHandler);
|
||||
|
||||
return {
|
||||
async dispose() {
|
||||
await page.unroute('**/api/translate', translateHandler);
|
||||
await page.unroute('**/api/detect', detectHandler);
|
||||
},
|
||||
async [Symbol.asyncDispose]() {
|
||||
await page.unroute('**/api/translate', translateHandler);
|
||||
await page.unroute('**/api/detect', detectHandler);
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user