Commit d79614c2 by 张立顺

test: guard regional live profiles

1 parent c39b7bc6
......@@ -43,6 +43,7 @@
"knowledge:build": "node scripts/knowledge-graph/knowledge-build.mjs",
"knowledge:check": "node scripts/knowledge-graph/knowledge-check.mjs",
"impact": "node scripts/knowledge-graph/query-knowledge-graph.mjs",
"gen:component-index": "npm run knowledge:build"
"gen:component-index": "npm run knowledge:build",
"test:login:ui": "node scripts/run-node-tests.mjs tests/order-lifecycle/ui/loginSmoke.live.test.mjs"
}
}
......@@ -7,6 +7,7 @@ const BASE_URL = 'http://dj.test.glsx.com.cn/rop-dj-car-boutique'
const validEnv = () => ({
RUN_ORDER_E2E: '1',
LIVE_ALLOW_WRITES: '1',
ORDER_E2E_BASE_URL: BASE_URL,
ORDER_E2E_MOBILE: 'runtime-mobile',
ORDER_E2E_CODE: 'runtime-code',
......
/**
* @file Live 订单测试的尽力清理边界;不在结果或诊断中暴露会话信息。
*/
import { ORDER_FLOW_METHODS, waitForOrderStatus } from './orderFlow.mjs'
/**
* 尝试撤销一个测试订单并确认状态。
*
* @param {object} client ROP 客户端。
* @param {object} context 登录上下文。
* @param {string} orderCode 订单号。
* @returns {Promise<{revoked: boolean, alreadyRevoked?: boolean, reason?: string}>} 清理结果。
*/
export async function bestEffortRevoke(client, context, orderCode) {
try {
const response = await client.post(ORDER_FLOW_METHODS.revoke, {
orderCode,
sessionId: context.sessionId,
})
if (Number(response?.code) !== 0) {
const detailResponse = await client.post(ORDER_FLOW_METHODS.detail, {
orderCode,
sessionId: context.sessionId,
})
if (
Number(detailResponse?.code) === 0 &&
Number(detailResponse?.data?.status) === 9
) {
return { revoked: true, alreadyRevoked: true }
}
return {
revoked: false,
reason: `business-code-${response?.code ?? 'missing'}`,
}
}
await waitForOrderStatus({
client,
context,
orderCode,
expectedStatus: 9,
})
return { revoked: true }
} catch {
return { revoked: false, reason: 'request-or-status-check-failed' }
}
}
/**
* 逆序清理全部已跟踪订单;单个失败不会阻断后续订单。
*
* @param {{client: object, context: object, orders?: object[], tracker?: {orders: object[]}, label?: string, onDiagnostic?: Function, testContext?: {diagnostic: Function}}} options 清理依赖和诊断出口。
* @returns {Promise<object[]>} 不含会话字段的逐订单结果。
*/
export async function cleanupTrackedOrders({
client,
context,
orders,
tracker,
label = 'Live cleanup',
onDiagnostic,
testContext,
}) {
const tracked = orders || tracker?.orders || []
const diagnostic = onDiagnostic || ((message) => testContext?.diagnostic?.(message))
const results = []
for (const order of [...tracked].reverse()) {
const cleanup = await bestEffortRevoke(client, context, order.orderCode)
const result = {
orderCode: order.orderCode,
role: order.role,
...cleanup,
}
results.push(result)
if (!cleanup.revoked) {
diagnostic?.(
`${label}: ${JSON.stringify({
orderCode: order.orderCode,
role: order.role,
reason: cleanup.reason,
})}`,
)
}
}
return results
}
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import test from 'node:test'
import { fileURLToPath, pathToFileURL } from 'node:url'
const modulePath = path.join(
path.dirname(fileURLToPath(import.meta.url)),
'liveCleanup.mjs',
)
async function loadCleanup() {
assert.equal(fs.existsSync(modulePath), true, 'Live cleanup helper must exist')
return import(pathToFileURL(modulePath))
}
test('best-effort cleanup attempts every tracked order in reverse order', async () => {
const { cleanupTrackedOrders } = await loadCleanup()
const calls = []
const diagnostics = []
const client = {
async post(method, payload) {
calls.push({ method, orderCode: payload.orderCode })
if (method.endsWith('.revoke') && payload.orderCode === 'ORDER-2') {
throw new Error('fixture revoke failure')
}
if (method.endsWith('.revoke')) return { code: 0 }
return { code: 0, data: { status: 9 } }
},
}
const result = await cleanupTrackedOrders({
client,
context: { sessionId: 'runtime-session' },
orders: [
{ orderCode: 'ORDER-1', role: 'source' },
{ orderCode: 'ORDER-2', role: 'corrected' },
],
label: 'fixture',
onDiagnostic: (message) => diagnostics.push(message),
})
assert.deepEqual(
calls.filter((call) => call.method.endsWith('.revoke')).map((call) => call.orderCode),
['ORDER-2', 'ORDER-1'],
)
assert.equal(result.length, 2)
assert.equal(result.find((item) => item.orderCode === 'ORDER-2').revoked, false)
assert.equal(result.find((item) => item.orderCode === 'ORDER-1').revoked, true)
assert.deepEqual(JSON.parse(diagnostics[0].replace('fixture: ', '')), {
orderCode: 'ORDER-2',
role: 'corrected',
reason: 'request-or-status-check-failed',
})
assert.doesNotMatch(JSON.stringify(result), /runtime-session/)
assert.doesNotMatch(diagnostics.join('\n'), /runtime-session/)
})
......@@ -4,11 +4,10 @@ import { randomUUID } from 'node:crypto'
import { loginAndSelectContext } from './authContext.mjs'
import { buildOrderPayload, buildSyntheticCustomer } from './fixtureBuilders.mjs'
import {
ORDER_FLOW_METHODS,
runCancelableOrderFlow,
runCorrectedOrderFlow,
waitForOrderStatus
runCorrectedOrderFlow
} from './orderFlow.mjs'
import { cleanupTrackedOrders } from './liveCleanup.mjs'
import { runPreflight } from './preflight.mjs'
import { loadE2EConfig } from './testConfig.mjs'
import { loadProjectRopCredentials } from '../support/projectRopCredentials.mjs'
......@@ -43,40 +42,6 @@ const createFixtures = (context, resources, label) => {
}
}
const bestEffortRevoke = async (client, context, orderCode) => {
try {
const response = await client.post(ORDER_FLOW_METHODS.revoke, {
orderCode,
sessionId: context.sessionId
})
if (Number(response?.code) !== 0) {
const detailResponse = await client.post(ORDER_FLOW_METHODS.detail, {
orderCode,
sessionId: context.sessionId
})
if (
Number(detailResponse?.code) === 0 &&
Number(detailResponse?.data?.status) === 9
) {
return { revoked: true, alreadyRevoked: true }
}
return {
revoked: false,
reason: `business-code-${response?.code ?? 'missing'}`
}
}
await waitForOrderStatus({
client,
context,
orderCode,
expectedStatus: 9
})
return { revoked: true }
} catch {
return { revoked: false, reason: 'request-or-status-check-failed' }
}
}
const createOrderTracker = () => {
const orders = []
return {
......@@ -89,27 +54,6 @@ const createOrderTracker = () => {
}
}
const cleanupTrackedOrders = async ({
client,
context,
tracker,
testContext,
label
}) => {
for (const order of [...tracker.orders].reverse()) {
const cleanup = await bestEffortRevoke(client, context, order.orderCode)
if (!cleanup.revoked) {
testContext.diagnostic(
`${label}: ${JSON.stringify({
orderCode: order.orderCode,
role: order.role,
reason: cleanup.reason
})}`
)
}
}
}
test(
'IT-OL-LIVE-001: test environment creates, pays and revokes a shop-payment order',
{ skip: !liveEnabled },
......@@ -153,21 +97,14 @@ test(
})
assert.equal(Number(result.oldOrder.status), 11)
assert.equal(Number(result.correctedOrder.status), 4)
t.diagnostic(
`Residual correction test: ${JSON.stringify({
oldOrderCode: result.oldOrder.orderCode,
correctedOrderCode: result.correctedOrder.orderCode
})}`
)
} catch (error) {
} finally {
await cleanupTrackedOrders({
client,
context,
tracker,
testContext: t,
label: 'Residual failed correction test'
label: 'Residual correction test'
})
throw error
}
}
)
import { assertAllowedE2EEnvironment } from '../support/environmentGuard.mjs'
import {
assertLiveWriteAllowed,
resolveLiveProfile
} from '../liveProfiles.mjs'
const REQUIRED_VARIABLES = [
'RUN_ORDER_E2E',
......@@ -16,6 +20,33 @@ export const FIXED_CONTEXT = Object.freeze({
})
export function loadE2EConfig(env = process.env) {
const profileName = String(env.ORDER_E2E_PROFILE ?? '').trim()
if (profileName) {
const profile = resolveLiveProfile(profileName, env)
assertLiveWriteAllowed(profile, env)
const baseUrl = assertAllowedE2EEnvironment({
baseUrl: profile.baseUrl,
enabled: env.RUN_ORDER_E2E === '1',
allowedBases: [profile.baseUrl]
}).toString()
return Object.freeze({
enabled: true,
profile: profile.name,
baseUrl,
mobile: profile.mobile,
code: profile.code,
yqName: profile.yqName,
storeName: profile.storeName,
sceneName: profile.sceneName,
baseSceneCode: String(env.ORDER_E2E_BASE_SCENE_CODE ?? '').trim(),
constructionImageUrl: String(
env.ORDER_E2E_CONSTRUCTION_IMAGE_URL ?? ''
).trim(),
sceneType: 1,
payType: 2
})
}
const missing = REQUIRED_VARIABLES.filter(name => !String(env[name] ?? '').trim())
if (missing.length) {
throw new Error(`Missing required E2E environment variables: ${missing.join(', ')}`)
......@@ -42,6 +73,11 @@ export function loadE2EConfig(env = process.env) {
)
}
assertLiveWriteAllowed(
{ name: 'regional-test', mode: 'functional' },
env
)
const baseUrl = assertAllowedE2EEnvironment({
baseUrl: env.ORDER_E2E_BASE_URL,
enabled: env.RUN_ORDER_E2E === '1'
......@@ -49,6 +85,7 @@ export function loadE2EConfig(env = process.env) {
return Object.freeze({
enabled: true,
profile: 'regional-test',
baseUrl,
mobile: env.ORDER_E2E_MOBILE,
code: env.ORDER_E2E_CODE,
......
......@@ -45,6 +45,34 @@ describe('order lifecycle environment guard', () => {
assert.equal(result.pathname, '/rop-dj-car-boutique')
})
it('IT-OL-SAFE-005: an explicit exact development allowlist stays strict', () => {
const developmentBase =
'http://dj.dev.glsx.com.cn/rop-dj-car-boutique'
const result = assertAllowedE2EEnvironment({
baseUrl: developmentBase,
enabled: true,
allowedBases: [developmentBase]
})
assert.equal(result.toString(), developmentBase)
for (const variant of [
`${developmentBase}/router`,
`${developmentBase}?source=test`,
`${developmentBase}#fragment`,
'http://name:password@dj.dev.glsx.com.cn/rop-dj-car-boutique'
]) {
assert.throws(
() =>
assertAllowedE2EEnvironment({
baseUrl: variant,
enabled: true,
allowedBases: [developmentBase]
}),
/not allowlisted/
)
}
})
it('IT-OL-SAFE-004: recursive redaction masks sensitive keys without mutation', () => {
const source = {
mobile: 'value-a',
......
/**
* @file 人工触发的 Live 自动化配置。凭证只从环境变量读取,定义中不保存手机号或验证码。
*/
export const LIVE_PROFILE_DEFINITIONS = Object.freeze({
'regional-dev-login': Object.freeze({
environment: 'development',
mode: 'login-only',
baseUrl: 'http://dj.dev.glsx.com.cn/rop-dj-car-boutique',
mobileEnv: 'LIVE_REGIONAL_DEV_MOBILE',
codeEnv: 'LIVE_REGIONAL_DEV_CODE',
}),
'regional-test': Object.freeze({
environment: 'test',
mode: 'functional',
baseUrl: 'http://dj.test.glsx.com.cn/rop-dj-car-boutique',
mobileEnv: 'LIVE_REGIONAL_TEST_MOBILE',
codeEnv: 'LIVE_REGIONAL_TEST_CODE',
yqName: '流程测试园区门店',
storeName: '波波的单店门店',
sceneName: '精品升级',
}),
})
function requiredValue(env, name, missing) {
const value = String(env[name] ?? '').trim()
if (!value) missing.push(name)
return value
}
/**
* 解析一个已批准的 Live 身份;运行时凭据不会进入静态配置。
*
* @param {string} profileName 配置名。
* @param {NodeJS.ProcessEnv|Record<string, string>} env 运行时环境变量。
* @returns {Readonly<object>} 已解析配置。
*/
export function resolveLiveProfile(profileName, env = process.env) {
const normalizedName = String(profileName || '').trim()
if (!normalizedName) throw new Error('Live profile is required')
const definition = LIVE_PROFILE_DEFINITIONS[normalizedName]
if (!definition) throw new Error(`Unknown live profile: ${normalizedName}`)
const missing = []
const mobile = requiredValue(env, definition.mobileEnv, missing)
const code = requiredValue(env, definition.codeEnv, missing)
if (missing.length) {
throw new Error(`Missing Live environment variables: ${missing.join(', ')}`)
}
return Object.freeze({
name: normalizedName,
environment: definition.environment,
mode: definition.mode,
baseUrl: definition.baseUrl,
mobile,
code,
...(definition.yqName ? { yqName: definition.yqName } : {}),
...(definition.storeName ? { storeName: definition.storeName } : {}),
...(definition.sceneName ? { sceneName: definition.sceneName } : {}),
})
}
/**
* 校验功能 profile 和独立写入开关。
*
* @param {object} profile 已解析配置。
* @param {NodeJS.ProcessEnv|Record<string, string>} env 运行时环境变量。
* @returns {true} 校验通过。
*/
export function assertLiveWriteAllowed(profile, env = process.env) {
if (!LIVE_PROFILE_DEFINITIONS[profile?.name]) {
throw new Error('Approved Live profile is required')
}
if (profile.mode !== 'functional') {
throw new Error(`${profile.name} does not allow Live writes`)
}
if (env.LIVE_ALLOW_WRITES !== '1') {
throw new Error('LIVE_ALLOW_WRITES=1 is required for Live write tests')
}
return true
}
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import test from 'node:test'
import { fileURLToPath, pathToFileURL } from 'node:url'
const projectRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
const profilesPath = path.join(projectRoot, 'tests/order-lifecycle/liveProfiles.mjs')
async function loadProfiles() {
assert.equal(fs.existsSync(profilesPath), true, 'live profile resolver must exist')
return import(pathToFileURL(profilesPath))
}
test('resolves the approved development and test profiles from runtime-only credentials', async () => {
const { resolveLiveProfile } = await loadProfiles()
const development = resolveLiveProfile('regional-dev-login', {
LIVE_REGIONAL_DEV_MOBILE: 'runtime-mobile-dev',
LIVE_REGIONAL_DEV_CODE: 'runtime-code-dev',
})
const functional = resolveLiveProfile('regional-test', {
LIVE_REGIONAL_TEST_MOBILE: 'runtime-mobile-test',
LIVE_REGIONAL_TEST_CODE: 'runtime-code-test',
})
assert.deepEqual(development, {
name: 'regional-dev-login',
environment: 'development',
mode: 'login-only',
baseUrl: 'http://dj.dev.glsx.com.cn/rop-dj-car-boutique',
mobile: 'runtime-mobile-dev',
code: 'runtime-code-dev',
})
assert.equal(functional.name, 'regional-test')
assert.equal(functional.environment, 'test')
assert.equal(functional.mode, 'functional')
assert.equal(functional.yqName, '流程测试园区门店')
assert.equal(functional.storeName, '波波的单店门店')
assert.equal(functional.sceneName, '精品升级')
})
test('requires explicit selection and only the declared credential variables', async () => {
const { resolveLiveProfile } = await loadProfiles()
assert.throws(() => resolveLiveProfile('', {}), /profile.*required/i)
assert.throws(() => resolveLiveProfile('unknown', {}), /unknown live profile/i)
assert.throws(
() => resolveLiveProfile('regional-test', {}),
/LIVE_REGIONAL_TEST_MOBILE.*LIVE_REGIONAL_TEST_CODE/,
)
assert.throws(
() =>
resolveLiveProfile('regional-dev-login', {
LIVE_REGIONAL_TEST_MOBILE: 'wrong-mobile',
LIVE_REGIONAL_TEST_CODE: 'wrong-code',
}),
/LIVE_REGIONAL_DEV_MOBILE.*LIVE_REGIONAL_DEV_CODE/,
)
})
test('development is login-only while test writes require an independent gate', async () => {
const { resolveLiveProfile, assertLiveWriteAllowed } = await loadProfiles()
const development = resolveLiveProfile('regional-dev-login', {
LIVE_REGIONAL_DEV_MOBILE: 'runtime-mobile',
LIVE_REGIONAL_DEV_CODE: 'runtime-code',
})
const functional = resolveLiveProfile('regional-test', {
LIVE_REGIONAL_TEST_MOBILE: 'runtime-mobile',
LIVE_REGIONAL_TEST_CODE: 'runtime-code',
})
assert.throws(
() => assertLiveWriteAllowed(development, { LIVE_ALLOW_WRITES: '1' }),
/does not allow Live writes/,
)
assert.throws(() => assertLiveWriteAllowed(functional, {}), /LIVE_ALLOW_WRITES=1/)
assert.equal(
assertLiveWriteAllowed(functional, { LIVE_ALLOW_WRITES: '1' }),
true,
)
})
test('profile metadata never contains credential literals', async () => {
const { LIVE_PROFILE_DEFINITIONS } = await loadProfiles()
const serialized = JSON.stringify(LIVE_PROFILE_DEFINITIONS)
assert.doesNotMatch(serialized, /\b1\d{10}\b/)
assert.doesNotMatch(serialized, /(?:mobile|code)Value/i)
})
test('order E2E accepts only the functional profile and keeps guarded legacy support', async () => {
const { loadE2EConfig } = await import('./e2e/testConfig.mjs')
const profile = loadE2EConfig({
ORDER_E2E_PROFILE: 'regional-test',
LIVE_REGIONAL_TEST_MOBILE: 'runtime-mobile',
LIVE_REGIONAL_TEST_CODE: 'runtime-code',
LIVE_ALLOW_WRITES: '1',
RUN_ORDER_E2E: '1',
})
assert.equal(profile.profile, 'regional-test')
assert.equal(profile.baseUrl, 'http://dj.test.glsx.com.cn/rop-dj-car-boutique')
assert.equal(profile.storeName, '波波的单店门店')
assert.throws(
() =>
loadE2EConfig({
ORDER_E2E_PROFILE: 'regional-dev-login',
LIVE_REGIONAL_DEV_MOBILE: 'runtime-mobile',
LIVE_REGIONAL_DEV_CODE: 'runtime-code',
LIVE_ALLOW_WRITES: '1',
RUN_ORDER_E2E: '1',
}),
/does not allow Live writes/,
)
assert.throws(
() =>
loadE2EConfig({
RUN_ORDER_E2E: '1',
ORDER_E2E_BASE_URL: 'http://dj.test.glsx.com.cn/rop-dj-car-boutique',
ORDER_E2E_MOBILE: 'runtime-mobile',
ORDER_E2E_CODE: 'runtime-code',
ORDER_E2E_YQ_NAME: '流程测试园区门店',
ORDER_E2E_STORE_NAME: '波波的单店门店',
}),
/LIVE_ALLOW_WRITES=1/,
)
})
......@@ -5,7 +5,11 @@ const sensitiveKeyPattern = /mobile|code|session|sign|secret|appKey/i
const notAllowed = () =>
new Error('E2E base URL is not allowlisted for order lifecycle tests')
export function assertAllowedE2EEnvironment({ baseUrl, enabled }) {
export function assertAllowedE2EEnvironment({
baseUrl,
enabled,
allowedBases = [ALLOWED_BASE]
}) {
if (enabled !== true) {
throw new Error('RUN_ORDER_E2E=1 is required for real order lifecycle tests')
}
......@@ -17,15 +21,19 @@ export function assertAllowedE2EEnvironment({ baseUrl, enabled }) {
throw notAllowed()
}
const exactBase =
url.protocol === allowedUrl.protocol &&
url.hostname === allowedUrl.hostname &&
url.port === allowedUrl.port &&
url.pathname === allowedUrl.pathname &&
url.search === '' &&
url.hash === '' &&
url.username === '' &&
url.password === ''
const exactBase = allowedBases.some(base => {
const allowed = base === ALLOWED_BASE ? allowedUrl : new URL(base)
return (
url.protocol === allowed.protocol &&
url.hostname === allowed.hostname &&
url.port === allowed.port &&
url.pathname === allowed.pathname &&
url.search === '' &&
url.hash === '' &&
url.username === '' &&
url.password === ''
)
})
if (!exactBase) {
throw notAllowed()
......
import assert from 'node:assert/strict'
import test from 'node:test'
import automator from 'miniprogram-automator'
import {
loadLoginSmokeConfig,
requireLoginSmokeConfig,
} from './loginSmokeConfig.mjs'
import { openMiniProgram } from './uiLauncher.mjs'
const liveEnabled = loadLoginSmokeConfig().enabled
async function waitForPage(
miniProgram,
predicate,
{ timeoutMs = 30000, intervalMs = 300 } = {},
) {
const deadline = Date.now() + timeoutMs
let lastPath = ''
while (Date.now() < deadline) {
const page = await miniProgram.currentPage()
lastPath = page?.path ?? ''
if (page && predicate(page)) return page
await new Promise((resolve) => setTimeout(resolve, intervalMs))
}
throw new Error(`Timed out waiting for mini program page; last=${lastPath}`)
}
test(
'IT-LOGIN-UI-LIVE-001: development profile logs in and stops at account selection',
{ skip: !liveEnabled, timeout: 120000 },
async () => {
const config = requireLoginSmokeConfig()
let miniProgram
try {
miniProgram = await openMiniProgram(automator, config)
const loginPage = await miniProgram.reLaunch('/pages/wxLogin/wxLogin')
assert.equal(loginPage?.path, 'pages/wxLogin/wxLogin')
await loginPage.setData({ loginType: 1 })
await loginPage.waitFor(300)
const authSetting = await loginPage.$('auth-setting')
const authCheckbox = await authSetting?.$('.choose-box')
assert.ok(authCheckbox, 'privacy agreement checkbox should be rendered')
await authCheckbox.tap()
const inputs = await loginPage.$$('input')
assert.equal(inputs.length, 2)
await inputs[0].input(config.mobile)
await inputs[1].input(config.code)
const loginButton = await loginPage.$('.login_btn')
assert.ok(loginButton, 'mobile login button should be rendered')
await loginButton.tap()
const accountPage = await waitForPage(
miniProgram,
(page) => page.path === 'pages/accountItems/accountItems',
)
const accountData = await accountPage.data()
assert.ok(
Array.isArray(accountData.loginUserInfoList) &&
accountData.loginUserInfoList.length > 0,
'account selection list should be non-empty',
)
} finally {
if (miniProgram) await miniProgram.close()
}
},
)
import { resolveLiveProfile } from '../liveProfiles.mjs'
/**
* 读取登录冒烟的非敏感连接配置;凭据仅在 require 阶段解析。
*
* @param {NodeJS.ProcessEnv|Record<string, string>} env 运行时环境变量。
* @returns {object} 连接配置。
*/
export function loadLoginSmokeConfig(env = process.env) {
return {
enabled: env.RUN_LOGIN_UI_E2E === '1',
profileName: String(env.LOGIN_UI_PROFILE ?? '').trim(),
launchDevTools:
env.ORDER_UI_LAUNCH === '1' || env.RUN_ORDER_UI_LAUNCH === '1',
cliPath: String(env.ORDER_UI_CLI_PATH ?? '').trim(),
projectPath: String(env.ORDER_UI_PROJECT_PATH ?? '').trim() || process.cwd(),
port: Number(String(env.ORDER_UI_PORT ?? '').trim() || 9420),
wsEndpoint:
String(env.ORDER_UI_WS_ENDPOINT ?? '').trim() ||
'ws://127.0.0.1:9420',
}
}
/**
* 校验开发环境登录冒烟配置并按 profile 读取运行时凭据。
*
* @param {NodeJS.ProcessEnv|Record<string, string>} env 运行时环境变量。
* @returns {Readonly<object>} 登录冒烟配置。
*/
export function requireLoginSmokeConfig(env = process.env) {
const config = loadLoginSmokeConfig(env)
if (!config.enabled) {
throw new Error('RUN_LOGIN_UI_E2E=1 is required for login UI smoke')
}
if (config.profileName !== 'regional-dev-login') {
throw new Error('LOGIN_UI_PROFILE=regional-dev-login is required')
}
if (
!Number.isInteger(config.port) ||
config.port < 1024 ||
config.port > 65535
) {
throw new Error('ORDER_UI_PORT must be an integer from 1024 to 65535')
}
let endpoint
try {
endpoint = new URL(config.wsEndpoint)
} catch {
throw new Error('ORDER_UI_WS_ENDPOINT must be a loopback ws endpoint')
}
if (
endpoint.protocol !== 'ws:' ||
!['127.0.0.1', 'localhost', '::1'].includes(endpoint.hostname)
) {
throw new Error('ORDER_UI_WS_ENDPOINT must be a loopback ws endpoint')
}
if (config.launchDevTools && !config.cliPath) {
throw new Error('ORDER_UI_CLI_PATH is required when launching DevTools')
}
const profile = resolveLiveProfile(config.profileName, env)
if (profile.mode !== 'login-only') {
throw new Error(`${profile.name} is not a login-only profile`)
}
return Object.freeze({
...config,
profile: profile.name,
mode: profile.mode,
baseUrl: profile.baseUrl,
mobile: profile.mobile,
code: profile.code,
})
}
import assert from 'node:assert/strict'
import fs from 'node:fs'
import path from 'node:path'
import test from 'node:test'
import { fileURLToPath, pathToFileURL } from 'node:url'
const modulePath = path.join(
path.dirname(fileURLToPath(import.meta.url)),
'loginSmokeConfig.mjs',
)
async function loadConfig() {
assert.equal(fs.existsSync(modulePath), true, 'login smoke config must exist')
return import(pathToFileURL(modulePath))
}
test('login smoke defaults contain connection metadata but no credentials', async () => {
const { loadLoginSmokeConfig } = await loadConfig()
const config = loadLoginSmokeConfig({})
assert.deepEqual(config, {
enabled: false,
profileName: '',
launchDevTools: false,
cliPath: '',
projectPath: process.cwd(),
port: 9420,
wsEndpoint: 'ws://127.0.0.1:9420',
})
})
test('login smoke requires the explicit development login-only profile', async () => {
const { requireLoginSmokeConfig } = await loadConfig()
assert.throws(() => requireLoginSmokeConfig({}), /RUN_LOGIN_UI_E2E/)
assert.throws(
() =>
requireLoginSmokeConfig({
RUN_LOGIN_UI_E2E: '1',
LOGIN_UI_PROFILE: 'regional-test',
LIVE_REGIONAL_TEST_MOBILE: 'runtime-mobile',
LIVE_REGIONAL_TEST_CODE: 'runtime-code',
}),
/regional-dev-login/,
)
})
test('login smoke resolves development credentials only at runtime', async () => {
const { requireLoginSmokeConfig } = await loadConfig()
const config = requireLoginSmokeConfig({
RUN_LOGIN_UI_E2E: '1',
LOGIN_UI_PROFILE: 'regional-dev-login',
LIVE_REGIONAL_DEV_MOBILE: 'runtime-mobile',
LIVE_REGIONAL_DEV_CODE: 'runtime-code',
})
assert.equal(config.profile, 'regional-dev-login')
assert.equal(config.mode, 'login-only')
assert.equal(config.mobile, 'runtime-mobile')
assert.equal(config.code, 'runtime-code')
assert.equal(config.wsEndpoint, 'ws://127.0.0.1:9420')
})
test('login smoke only connects to a valid loopback websocket and port', async () => {
const { requireLoginSmokeConfig } = await loadConfig()
const base = {
RUN_LOGIN_UI_E2E: '1',
LOGIN_UI_PROFILE: 'regional-dev-login',
LIVE_REGIONAL_DEV_MOBILE: 'runtime-mobile',
LIVE_REGIONAL_DEV_CODE: 'runtime-code',
}
assert.throws(
() =>
requireLoginSmokeConfig({
...base,
ORDER_UI_WS_ENDPOINT: 'ws://192.168.1.10:9420',
}),
/loopback/,
)
assert.throws(
() => requireLoginSmokeConfig({ ...base, ORDER_UI_PORT: '80' }),
/1024 to 65535/,
)
})
test('login smoke launch mode requires the existing DevTools launcher fields', async () => {
const { requireLoginSmokeConfig } = await loadConfig()
const base = {
RUN_LOGIN_UI_E2E: '1',
LOGIN_UI_PROFILE: 'regional-dev-login',
LIVE_REGIONAL_DEV_MOBILE: 'runtime-mobile',
LIVE_REGIONAL_DEV_CODE: 'runtime-code',
ORDER_UI_LAUNCH: '1',
}
assert.throws(() => requireLoginSmokeConfig(base), /ORDER_UI_CLI_PATH/)
const config = requireLoginSmokeConfig({
...base,
ORDER_UI_CLI_PATH: 'C:/tools/wechat/cli.bat',
ORDER_UI_PROJECT_PATH: 'C:/workspace/project',
ORDER_UI_PORT: '9527',
})
assert.equal(config.launchDevTools, true)
assert.equal(config.cliPath, 'C:/tools/wechat/cli.bat')
assert.equal(config.projectPath, 'C:/workspace/project')
assert.equal(config.port, 9527)
})
test('login smoke stops after the account list without selecting business context', () => {
const livePath = path.join(
path.dirname(fileURLToPath(import.meta.url)),
'loginSmoke.live.test.mjs',
)
assert.equal(fs.existsSync(livePath), true, 'login smoke Live test must exist')
const source = fs.readFileSync(livePath, 'utf8')
for (const signal of [
"reLaunch('/pages/wxLogin/wxLogin')",
'loginType: 1',
"$('.choose-box')",
"$('.login_btn')",
"page.path === 'pages/accountItems/accountItems'",
'loginUserInfoList',
]) {
assert.ok(source.includes(signal), `missing login-only step: ${signal}`)
}
for (const forbidden of [
"$('.items')",
"$$('.items')",
'pages/merchantList/merchantList',
'pages/sceneIndex/sceneIndex',
'tabWorkOrder/pages/createOrder/createOrder',
]) {
assert.equal(source.includes(forbidden), false, `login smoke must stop before ${forbidden}`)
}
})
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!