176 lines
11 KiB
JavaScript
176 lines
11 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'
|
|
|
|
// 执行实际路由守卫与表单脚本;仅替换网络、组件和浏览器路由,所有数据均为隔离样例。
|
|
const fixtures = {}
|
|
globalThis[Symbol.for('identity-shared-ui-test')] = fixtures
|
|
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
|
|
|
|
function stub(key, source) {
|
|
return dataModule(`const fixture = globalThis[Symbol.for('identity-shared-ui-test')][${JSON.stringify(key)}]; ${source}`)
|
|
}
|
|
|
|
async function formModule(view, exports) {
|
|
const key = view
|
|
const fixture = fixtures[key] = {
|
|
auth: { isShared: true, can: () => true }, calls: [], options: { roles: [], depts: [], menus: [] }, selected: []
|
|
}
|
|
const http = stub(key, `
|
|
export const get = async () => fixture.options;
|
|
export const post = async (url, payload) => { fixture.calls.push({ url, payload }); };
|
|
export const reportError = error => { throw error; };
|
|
`)
|
|
const auth = stub(key, 'export const useAuthStore = () => fixture.auth;')
|
|
const group = stub(key, 'export const useGroupStore = () => ({ enabled: true, currentCompanyId: 1, directoryAvailable: true, canStructure: (resource, action) => fixture.auth.can(`auth.${resource}/${action}`) });')
|
|
const router = dataModule('export const refreshAccess = async () => false;')
|
|
const ui = dataModule('export const ElMessage = { success() {}, warning() {} }; export const ElMessageBox = {};')
|
|
const paging = dataModule(`
|
|
import { ref, reactive } from '${vueUrl}';
|
|
export const usePagedList = () => ({ rows: ref([]), total: ref(0), loading: ref(false), query: reactive({}), load() {}, search() {}, reset() {} });
|
|
`)
|
|
const component = dataModule('export default {};')
|
|
const sfc = await readFile(new URL(`../src/views/${view}.vue`, import.meta.url), 'utf8')
|
|
let source = sfc.match(/<script setup lang="ts">([\s\S]*?)<\/script>/)[1]
|
|
source = source.replace("import { computed, onMounted, reactive, ref } from 'vue'", "import { computed, reactive, ref } from 'vue'\nconst onMounted = () => {}")
|
|
const compiled = ts.transpileModule(`${source}\nexport { ${exports.join(', ')} };`, {
|
|
compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 }
|
|
}).outputText
|
|
.replace(/from ['"]vue['"]/g, `from '${vueUrl}'`)
|
|
.replace(/from ['"]element-plus['"]/g, `from '${ui}'`)
|
|
.replace(/from ['"]@element-plus\/icons-vue['"]/g, `from '${component}'`)
|
|
.replace(/import\s*\{[^}]*\}\s*from\s*['"]@element-plus\/icons-vue['"];?/g, '')
|
|
.replace(/from ['"]\.\.\/stores\/auth['"]/g, `from '${auth}'`)
|
|
.replace(/from ['"]\.\.\/stores\/group['"]/g, `from '${group}'`)
|
|
.replace(/from ['"]\.\.\/services\/http['"]/g, `from '${http}'`)
|
|
.replace(/from ['"]\.\.\/router['"]/g, `from '${router}'`)
|
|
.replace(/from ['"]\.\.\/composables\/usePagedList['"]/g, `from '${paging}'`)
|
|
.replace(/from ['"]\.\.\/components\/PageHeader.vue['"]/g, `from '${component}'`)
|
|
return { fixture, module: await import(dataModule(compiled)) }
|
|
}
|
|
|
|
test('共享菜单保存保留原相对路径、组件、权限,且不发送额外源字段', async () => {
|
|
const { fixture, module } = await formModule('Menus', ['form', 'formRef', 'open', 'save', 'pathRules'])
|
|
module.formRef.value = { validate: async () => true, clearValidate() {} }
|
|
const original = {
|
|
id: 9, pid: 0, type: 'M', name: '示例目录', paths: 'legacy/group', component: 'legacy/layout',
|
|
perms: 'legacy/entry', icon: '', sort: 2, is_show: 1, disable: 0, source_secret: 'must-not-send'
|
|
}
|
|
module.open(original)
|
|
await module.save()
|
|
const payload = fixture.calls[0].payload
|
|
assert.equal(payload.paths, original.paths)
|
|
assert.equal(payload.component, original.component)
|
|
assert.equal(payload.perms, original.perms)
|
|
assert.equal('source_secret' in payload, false)
|
|
for (const path of ['legacy/group', 'https://example.invalid/page?q=1']) {
|
|
module.pathRules[0].validator({}, path, (error) => assert.equal(error, undefined))
|
|
}
|
|
fixture.auth.isShared = false
|
|
module.pathRules[0].validator({}, 'legacy/group', (error) => assert.ok(error instanceof Error))
|
|
})
|
|
|
|
test('共享角色保留数据范围与未展示授权,独立角色载荷不增加数据范围', async () => {
|
|
const { fixture, module } = await formModule('Roles', ['formRef', 'treeRef', 'open', 'save'])
|
|
module.formRef.value = { validate: async () => true, clearValidate() {} }
|
|
module.treeRef.value = { setCheckedKeys() {}, getCheckedKeys: () => fixture.selected }
|
|
fixture.options.menus = [{ id: 10, children: [] }]
|
|
fixture.selected = [10]
|
|
const role = { id: 5, name: '示例角色', desc: '', sort: 0, disable: 0, data_scope: 3, menu_id: [10, 99] }
|
|
await module.open(role)
|
|
await module.save()
|
|
assert.equal(fixture.calls[0].payload.data_scope, 3)
|
|
assert.equal('disable' in fixture.calls[0].payload, false)
|
|
assert.deepEqual(fixture.calls[0].payload.menu_id, [10, 99])
|
|
fixture.auth.isShared = false
|
|
fixture.selected = []
|
|
await module.open(role)
|
|
await module.save()
|
|
assert.equal('data_scope' in fixture.calls[1].payload, false)
|
|
assert.equal(fixture.calls[1].payload.disable, 0)
|
|
assert.deepEqual(fixture.calls[1].payload.menu_id, [])
|
|
})
|
|
|
|
test('公司分组及主 GID 不写入医院用户旧载荷,仍完整保留角色部门关联', async () => {
|
|
const { fixture, module } = await formModule('Users', ['formRef', 'open', 'save'])
|
|
module.formRef.value = { validate: async () => true, clearValidate() {} }
|
|
await module.open({ id: 8, account: 'fixture-user', name: '样例', disable: 0, role_id: [2, 3], dept_id: [4], gid: 'gid_private_fixture', company_id: 99 })
|
|
await module.save()
|
|
assert.deepEqual(fixture.calls[0].payload, { id: 8, account: 'fixture-user', name: '样例', password: '', disable: 0, role_id: [2, 3], dept_id: [4] })
|
|
})
|
|
|
|
test('首次改密优先于绑定门禁,受限账号不注册管理页', async () => {
|
|
const key = 'router'
|
|
const fixture = fixtures[key] = {
|
|
auth: { token: 'test-session', user: null }, records: [], guard: null, replaced: [],
|
|
group: { enabled: false, directoryAvailable: true, isGroupAdmin: false }
|
|
}
|
|
const routing = stub(key, `
|
|
export const createWebHistory = () => ({});
|
|
export const createRouter = () => ({
|
|
currentRoute: { value: { name: 'dashboard', path: '/dashboard', meta: {} } },
|
|
addRoute: (parent, record) => {
|
|
fixture.records.push(record);
|
|
return () => { fixture.records = fixture.records.filter(item => item !== record); };
|
|
},
|
|
beforeEach: guard => { fixture.guard = guard; }, afterEach() {},
|
|
resolve: path => ({ name: fixture.records.find(item => item.path === path)?.name || 'not-found' }), replace: async path => { fixture.replaced.push(path); }
|
|
});
|
|
`)
|
|
const auth = stub(key, 'export const useAuthStore = () => fixture.auth;')
|
|
const group = stub(key, 'export const useGroupStore = () => fixture.group;')
|
|
const http = dataModule('export class ApiError extends Error {}')
|
|
const access = dataModule(ts.transpileModule(await readFile(new URL('../src/services/access.ts', import.meta.url), 'utf8'), { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 } }).outputText)
|
|
const source = await readFile(new URL('../src/router/index.ts', import.meta.url), 'utf8')
|
|
const compiled = ts.transpileModule(source, { compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.ES2022 } }).outputText
|
|
.replace(/from ['"]vue-router['"]/, `from '${routing}'`)
|
|
.replace(/from ['"]\.\.\/stores\/auth['"]/, `from '${auth}'`)
|
|
.replace(/from ['"]\.\.\/stores\/group['"]/, `from '${group}'`)
|
|
.replace(/from ['"]\.\.\/services\/http['"]/, `from '${http}'`)
|
|
.replace(/from ['"]\.\.\/services\/access['"]/, `from '${access}'`)
|
|
const module = await import(dataModule(compiled))
|
|
const user = {
|
|
permissions: ['*'], menus: [{ id: 1, type: 'C', paths: '/system/users', component: 'system/users', perms: 'auth.admin/lists', disable: 0 }]
|
|
}
|
|
fixture.auth.user = { ...user, requires_password_change: true, requires_wecom_binding: true }
|
|
module.syncDynamicRoutes(fixture.auth.user)
|
|
assert.equal(fixture.records.length, 0)
|
|
assert.deepEqual(await fixture.guard({ path: '/system/users', name: 'not-found' }), { path: '/profile', replace: true })
|
|
assert.deepEqual(await fixture.guard({ path: '/sso/authorize', name: 'sso-authorize' }), { path: '/profile', replace: true })
|
|
assert.equal(await fixture.guard({ path: '/profile', name: 'profile' }), true)
|
|
fixture.auth.user = { ...user, requires_wecom_binding: true }
|
|
assert.deepEqual(await fixture.guard({ path: '/profile', name: 'profile' }), { path: '/account-required', replace: true })
|
|
assert.deepEqual(await fixture.guard({ path: '/sso/authorize', name: 'sso-authorize' }), { path: '/account-required', replace: true })
|
|
assert.equal(await fixture.guard({ path: '/account-required', name: 'account-required' }), true)
|
|
fixture.auth.user = user
|
|
module.syncDynamicRoutes(user)
|
|
assert.equal(fixture.records[0].path, '/system/users')
|
|
assert.deepEqual(await fixture.guard({ path: '/account-required', name: 'account-required' }), { path: '/dashboard', replace: true })
|
|
fixture.group.enabled = true
|
|
fixture.group.currentCompany = { id: 1, name: '医院公司', is_directory_company: true }
|
|
fixture.group.currentCompanyId = 1
|
|
fixture.group.context = { default_company_id: 1, companies: [fixture.group.currentCompany, { id: 2, name: '新公司' }] }
|
|
const groupMenus = [...user.menus,
|
|
{ id: 2, type: 'C', name: '原部门入口', paths: '/legacy/depts', component: 'system/depts', perms: 'auth.dept/lists', disable: 0 },
|
|
{ id: 3, type: 'C', name: '原菜单入口', paths: '/legacy/menus', component: 'system/menus', perms: 'auth.menu/lists', disable: 0 }
|
|
]
|
|
fixture.auth.user = { ...user, menus: groupMenus }
|
|
module.syncDynamicRoutes(fixture.auth.user)
|
|
const grouped = module.navigationFromMenus(groupMenus)
|
|
assert.deepEqual(grouped.find((item) => item.title === '部门管理').children.map((item) => item.path), ['/system/depts?company_id=1'])
|
|
assert.deepEqual(grouped.find((item) => item.title === '菜单管理').children.map((item) => item.title), ['医院公司'])
|
|
assert.equal(grouped.some((item) => item.path === '/system/users'), true)
|
|
assert.equal(user.menus[0].paths, '/system/users')
|
|
assert.deepEqual(await fixture.guard({ path: '/group/companies', name: 'group-companies', meta: { groupAdmin: true } }), { name: 'forbidden' })
|
|
fixture.group.isGroupAdmin = true
|
|
assert.equal(await fixture.guard({ path: '/group/companies', name: 'group-companies', meta: { groupAdmin: true } }), true)
|
|
fixture.group.directoryAvailable = false
|
|
module.syncDynamicRoutes(fixture.auth.user)
|
|
assert.deepEqual(fixture.records.map((item) => item.path), ['/system/users', '/system/depts', '/system/menus'])
|
|
assert.deepEqual(await fixture.guard({ path: '/system/users', fullPath: '/system/users', name: 'not-found' }), { path: '/system/users', replace: true })
|
|
assert.equal(module.navigationFromMenus(groupMenus).some((item) => item.path === '/system/users'), true)
|
|
assert.equal(module.navigationFromMenus(groupMenus).some((item) => item.title === '部门管理'), true)
|
|
})
|