240 lines
12 KiB
JavaScript
240 lines
12 KiB
JavaScript
import assert from 'node:assert/strict'
|
|
import { readFile } from 'node:fs/promises'
|
|
import test from 'node:test'
|
|
import ts from '../node_modules/typescript/lib/typescript.js'
|
|
|
|
// 执行实际 SFC、HTTP 处理和全局退出回调;网络、凭据和浏览器均使用隔离样例。
|
|
const fixtures = {}
|
|
globalThis[Symbol.for('identity-account-sync-test')] = fixtures
|
|
let sequence = 0
|
|
const dataModule = source => `data:text/javascript;base64,${Buffer.from(source).toString('base64')}`
|
|
const vueUrl = new URL('../node_modules/vue/index.mjs', import.meta.url).href
|
|
const component = dataModule('export default {};')
|
|
|
|
async function compileFile(path, imports, suffix = '', sfc = false) {
|
|
const content = await readFile(new URL(path, import.meta.url), 'utf8')
|
|
const source = sfc ? content.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1] : content
|
|
const compiled = ts.transpileModule(`${source}\n${suffix}`, {
|
|
compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 }
|
|
}).outputText
|
|
.replace(/^import ['"][^'"]+\.css['"];?\s*$/gm, '')
|
|
.replace(/from (['"])([^'"]+)\1/g, (match, _quote, name) => {
|
|
assert.ok(imports[name], `没有隔离的依赖:${name}`)
|
|
return `from '${imports[name]}'`
|
|
})
|
|
return dataModule(compiled)
|
|
}
|
|
|
|
async function loadView(view) {
|
|
const key = `${view}-${++sequence}`
|
|
const fixture = fixtures[key] = {
|
|
token: 'isolated-session', calls: [], events: [], options: { roles: [], depts: [], menus: [] }, selected: [],
|
|
refreshCalls: 0, loads: 0, resetRoutes: 0, replaced: [], revoked: false,
|
|
auth: { isShared: true, user: { id: 71 }, requiresPasswordChange: false, can: () => true },
|
|
clearCount: 0
|
|
}
|
|
fixture.auth.clear = () => {
|
|
fixture.clearCount++
|
|
fixture.token = ''
|
|
fixture.auth.user = null
|
|
}
|
|
fixture.request = async config => {
|
|
if (config.method === 'POST') {
|
|
fixture.calls.push({ url: config.url, payload: structuredClone(config.data) })
|
|
await fixture.onPost?.(config)
|
|
return { data: { code: 1, data: {} } }
|
|
}
|
|
if (config.url === '/auth/options') return { data: { code: 1, data: fixture.options } }
|
|
if (fixture.revoked) throw { isolatedAxiosError: true, response: { status: 401, data: { msg: '隔离会话已失效' } } }
|
|
return { data: { code: 1, data: {} } }
|
|
}
|
|
const stub = source => dataModule(`const fixture = globalThis[Symbol.for('identity-account-sync-test')][${JSON.stringify(key)}]; ${source}`)
|
|
const ui = stub(`
|
|
export default {};
|
|
export const ElMessage = Object.fromEntries(['success', 'warning', 'error', 'info'].map(type => [type, message => fixture.events.push({ type, message })]));
|
|
export const ElMessageBox = { confirm: async () => {} };
|
|
`)
|
|
const auth = stub('export const useAuthStore = () => fixture.auth;')
|
|
const group = stub('export const useGroupStore = () => ({ enabled: true });')
|
|
const axios = stub(`
|
|
export default {
|
|
create: () => ({ request: config => fixture.request(config) }),
|
|
isAxiosError: error => error?.isolatedAxiosError === true
|
|
};
|
|
`)
|
|
const http = await compileFile('../src/services/http.ts', {
|
|
axios, 'element-plus': ui, './token': stub('export const readToken = () => fixture.token;')
|
|
})
|
|
const httpModule = await import(http)
|
|
const router = stub(`
|
|
export const refreshAccess = async () => { fixture.refreshCalls++; return fixture.onRefresh ? fixture.onRefresh() : false; };
|
|
export const resetDynamicRoutes = () => { fixture.resetRoutes++; };
|
|
export default { replace: async path => { fixture.replaced.push(path); await fixture.onReplace?.(); } };
|
|
`)
|
|
const appVue = dataModule('export const createApp = () => ({ use() {}, mount() {} });')
|
|
const main = await compileFile('../src/main.ts', {
|
|
vue: appVue, pinia: dataModule('export const createPinia = () => ({});'),
|
|
'element-plus': ui, 'element-plus/es/locale/lang/zh-cn': component, './App.vue': component,
|
|
'./router': router, './stores/auth': auth, './services/http': http
|
|
})
|
|
await import(main)
|
|
const paging = stub(`
|
|
import { ref, reactive } from '${vueUrl}';
|
|
export const usePagedList = () => ({
|
|
rows: ref([]), total: ref(0), loading: ref(false), query: reactive({ page_no: 1 }),
|
|
load: async () => { fixture.loads++; await fixture.onLoad?.(); }, search() {}, reset() {}
|
|
});
|
|
`)
|
|
const exports = view === 'Profile' ? ['form', 'formRef', 'saving', 'submit']
|
|
: ['form', 'formRef', 'saving', 'visible', 'open', 'save', 'remove', ...(view === 'Roles' ? ['treeRef'] : [])]
|
|
const moduleUrl = await compileFile(`../src/views/${view}.vue`, {
|
|
vue: vueUrl, 'element-plus': ui, '../stores/auth': auth, '../stores/group': group,
|
|
'../router': router, '../services/http': http, '../composables/usePagedList': paging,
|
|
'../components/PageHeader.vue': component, '../components/CompanyScope.vue': component
|
|
}, `export { ${exports.join(', ')} };`, true)
|
|
const module = await import(moduleUrl)
|
|
module.formRef.value = { validate: async () => true, clearValidate() {} }
|
|
if (module.treeRef) module.treeRef.value = { setCheckedKeys() {}, getCheckedKeys: () => fixture.selected }
|
|
return { fixture, module, http: httpModule }
|
|
}
|
|
|
|
const user = { id: 8, account: 'isolated-user', name: '隔离样例', disable: 0, role_id: [2, 3], dept_id: [4] }
|
|
const role = { id: 5, name: '隔离角色', desc: '', sort: 0, disable: 0, data_scope: 3, menu_id: [10, 99] }
|
|
const deferred = () => {
|
|
let resolve
|
|
const promise = new Promise(accept => { resolve = accept })
|
|
return { promise, resolve }
|
|
}
|
|
|
|
test('用户编辑直接提交医院账号,空密码保持不变且不携带集团字段', async () => {
|
|
const { fixture, module } = await loadView('Users')
|
|
await module.open({ ...user, gid: 'isolated-gid', company_id: 999, source_secret: 'isolated-extra' })
|
|
await module.save()
|
|
assert.deepEqual(fixture.calls, [{ url: '/auth.admin/edit', payload: { ...user, password: '' } }])
|
|
assert.equal(fixture.refreshCalls, 1)
|
|
assert.equal(fixture.events[0].message, '用户已更新')
|
|
})
|
|
|
|
test('管理员重置密码直接随医院账号保存,成功后清空输入值', async () => {
|
|
const { fixture, module } = await loadView('Users')
|
|
await module.open(user)
|
|
module.form.password = 'isolated-new-password'
|
|
await module.save()
|
|
assert.equal(fixture.calls[0].payload.password, 'isolated-new-password')
|
|
assert.equal(module.form.password, '')
|
|
assert.equal(module.visible.value, false)
|
|
})
|
|
|
|
for (const view of ['Users', 'Roles']) {
|
|
test(`${view} 保存当前权限后真实 HTTP 401 清会话并退出,不追加保存失败提示`, async () => {
|
|
const { fixture, module, http } = await loadView(view)
|
|
if (view === 'Users') await module.open({ ...user, id: fixture.auth.user.id })
|
|
else await module.open(role)
|
|
fixture.revoked = true
|
|
fixture.onRefresh = async () => { await http.get('/auth.admin/mySelf'); return true }
|
|
await module.save()
|
|
assert.equal(fixture.calls.length, 1)
|
|
assert.equal(fixture.clearCount, 1)
|
|
assert.equal(fixture.token, '')
|
|
assert.equal(fixture.resetRoutes, 1)
|
|
assert.deepEqual(fixture.replaced, [{ name: 'login', query: { reason: 'expired' } }])
|
|
assert.equal(fixture.loads, 0)
|
|
assert.deepEqual(fixture.events.map(item => item.type), ['success', 'warning'])
|
|
assert.equal(fixture.events[1].message, '登录已失效,请重新登录')
|
|
assert.equal(module.saving.value, false)
|
|
})
|
|
|
|
test(`${view} 保存后网络刷新故障仍明确说明已保存`, async () => {
|
|
const { fixture, module } = await loadView(view)
|
|
await module.open(view === 'Users' ? user : role)
|
|
fixture.onRefresh = async () => { throw new Error('isolated-refresh-error') }
|
|
await module.save()
|
|
assert.deepEqual(fixture.events.map(item => item.type), ['success', 'warning'])
|
|
assert.equal(fixture.events[1].message, '变更已保存,权限或列表刷新未完成,请重新登录后查看')
|
|
assert.equal(module.visible.value, false)
|
|
assert.equal(module.saving.value, false)
|
|
})
|
|
|
|
test(`${view} 保存中重复点击与再次打开表单不会产生第二次写入`, async () => {
|
|
const { fixture, module } = await loadView(view)
|
|
await module.open(view === 'Users' ? user : role)
|
|
const blocked = deferred()
|
|
const started = deferred()
|
|
fixture.onPost = () => { started.resolve(); return blocked.promise }
|
|
const first = module.save()
|
|
await started.promise
|
|
await module.save()
|
|
await module.open({ id: 999, account: 'other', name: '另一个样例' })
|
|
assert.equal(fixture.calls.length, 1)
|
|
assert.equal(module.form.id, view === 'Users' ? user.id : role.id)
|
|
blocked.resolve()
|
|
await first
|
|
assert.equal(module.saving.value, false)
|
|
})
|
|
}
|
|
|
|
test('共享角色保留未展示授权和原数据范围,直接提交医院角色', async () => {
|
|
const { fixture, module } = await loadView('Roles')
|
|
fixture.options.menus = [{ id: 10, children: [] }]
|
|
fixture.selected = [10, 10]
|
|
await module.open({ ...role, gid: 'isolated-extra', company_id: 999 })
|
|
await module.save()
|
|
assert.deepEqual(fixture.calls, [{
|
|
url: '/auth.role/edit', payload: { id: 5, name: '隔离角色', desc: '', sort: 0, data_scope: 3, menu_id: [10, 99] }
|
|
}])
|
|
})
|
|
|
|
test('root 账号仍受保护,当前账号也不能删除', async () => {
|
|
const { fixture, module } = await loadView('Users')
|
|
await module.open({ ...user, is_root: 1 })
|
|
await module.remove({ ...user, is_root: 1 })
|
|
await module.remove({ ...user, id: fixture.auth.user.id })
|
|
assert.equal(module.visible.value, false)
|
|
assert.equal(fixture.calls.length, 0)
|
|
assert.equal(fixture.events[0].type, 'info')
|
|
})
|
|
|
|
test('个人改密成功后清会话、清密码并退出,重复提交仅写入一次', async () => {
|
|
const { fixture, module } = await loadView('Profile')
|
|
Object.assign(module.form, { old_password: 'isolated-old', password: 'isolated-new', password_confirm: 'isolated-new' })
|
|
const blocked = deferred()
|
|
const started = deferred()
|
|
fixture.onPost = () => { started.resolve(); return blocked.promise }
|
|
const first = module.submit()
|
|
await started.promise
|
|
await module.submit()
|
|
blocked.resolve()
|
|
await first
|
|
assert.deepEqual(fixture.calls, [{ url: '/auth.admin/password', payload: { old_password: 'isolated-old', password: 'isolated-new', password_confirm: 'isolated-new' } }])
|
|
assert.deepEqual(module.form, { old_password: '', password: '', password_confirm: '' })
|
|
assert.equal(fixture.clearCount, 1)
|
|
assert.equal(fixture.resetRoutes, 1)
|
|
assert.deepEqual(fixture.replaced, ['/login'])
|
|
assert.match(fixture.events[0].message, /医院与集团登录密码已修改/)
|
|
})
|
|
|
|
test('首次改密仍只提交新密码字段,登录页跳转失败不会误报改密失败', async () => {
|
|
const { fixture, module } = await loadView('Profile')
|
|
fixture.auth.requiresPasswordChange = true
|
|
Object.assign(module.form, { old_password: 'must-not-send', password: 'isolated-new', password_confirm: 'isolated-new' })
|
|
fixture.onReplace = async () => { throw new Error('isolated-route-error') }
|
|
await module.submit()
|
|
assert.deepEqual(fixture.calls[0].payload, { password: 'isolated-new', password_confirm: 'isolated-new' })
|
|
assert.equal(fixture.clearCount, 1)
|
|
assert.deepEqual(fixture.events.map(item => item.type), ['success', 'warning'])
|
|
assert.match(fixture.events[1].message, /^密码已修改/)
|
|
})
|
|
|
|
test('写入失败不会清输入、关闭编辑框或提示保存成功', async () => {
|
|
const { fixture, module } = await loadView('Users')
|
|
await module.open(user)
|
|
module.form.password = 'isolated-new'
|
|
fixture.onPost = async () => { throw new Error('isolated-write-error') }
|
|
await module.save()
|
|
assert.equal(module.visible.value, true)
|
|
assert.equal(module.form.password, 'isolated-new')
|
|
assert.equal(fixture.refreshCalls, 0)
|
|
assert.deepEqual(fixture.events.map(item => item.type), ['error'])
|
|
assert.equal(module.saving.value, false)
|
|
})
|