test(36-04): add Vitest unit and component tests covering all 7 scope picker backstops

This commit is contained in:
Jakub Zych
2026-11-24 20:08:24 +01:00
parent 782f4dc19d
commit 2661e0f363
5 changed files with 1072 additions and 0 deletions

View File

@@ -0,0 +1,204 @@
// Component tests for ScopeAccessControl.vue (Phase 36 backstop #7 + tier controls).
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { enableAutoUnmount, mount } from '@vue/test-utils'
import type { AdminAPITokenScope } from '../../src/api/types'
import { setBundle } from '../../src/app/i18n'
import ScopeAccessControl from '../../src/components/scopes/ScopeAccessControl.vue'
import { langFixture } from '../fixtures/typed'
import { resetState } from '../helpers'
const strings = {
'backend::lang.api_tokens.access_level': { other: 'Access level' },
'backend::lang.api_tokens.tier_full': { other: 'Full access' },
'backend::lang.api_tokens.tier_read_only': { other: 'Read-only' },
'backend::lang.api_tokens.tier_custom': { other: 'Custom' },
'backend::lang.api_tokens.read_only': { other: 'Read-only' },
'backend::lang.api_tokens.scope_customize': { other: 'Customize scopes…' },
'backend::lang.api_tokens.scope_summary_empty': { other: 'No scopes selected yet. Choose at least one scope to continue.' },
'backend::lang.api_tokens.scope_more': { other: '+:count more' },
'backend::lang.api_tokens.scope_count': { one: ':count scope', other: ':count scopes' },
'backend::lang.api_tokens.scope_write_count': { one: ':count write scope', other: ':count write scopes' },
'backend::lang.api_tokens.scope_plugin_count': { one: ':count plugin', other: ':count plugins' },
'backend::lang.api_tokens.scope_summary_line': { other: ':scopes across :plugins' },
'backend::lang.api_tokens.scope_summary_admin_read_plus': { other: 'Read-only admin + :scopes across :plugins' },
}
function makeScope(overrides: Partial<AdminAPITokenScope> & Pick<AdminAPITokenScope, 'name'>): AdminAPITokenScope {
return {
label: overrides.name,
description: `Description for ${overrides.name}`,
read_only: overrides.name.endsWith(':read'),
known: true,
plugin_id: 'acme.demo',
group: 'Demo',
...overrides,
}
}
const STAR = makeScope({ name: '*', label: 'Full access', read_only: false, plugin_id: '', group: '' })
const ADMIN_READ = makeScope({ name: 'admin:read', label: 'Read-only admin', read_only: true, plugin_id: '', group: '' })
beforeEach(() => {
resetState()
setBundle({ ...langFixture.data, ...strings }, 'en')
})
afterEach(() => {
document.body.innerHTML = ''
})
enableAutoUnmount(afterEach)
describe('ScopeAccessControl.vue', () => {
it('renders 3-tier RadioGroupRoot, omits missing tiers, and hides RadioGroupRoot when <= 1 tier', () => {
const blog = makeScope({ name: 'blog', label: 'Blog', read_only: false, plugin_id: 'acme.blog', group: 'Blog' })
const allThree = mount(ScopeAccessControl, {
props: {
catalog: [STAR, ADMIN_READ, blog],
availableTiers: ['full', 'read_only', 'custom'],
tier: 'read_only',
custom: { adminRead: false, scopes: new Set<string>() },
idPrefix: 'test-3',
},
attachTo: document.body,
})
expect(allThree.findAll('[data-access-tier]').map((el) => el.attributes('data-access-tier'))).toEqual([
'full',
'read_only',
'custom',
])
const twoTiers = mount(ScopeAccessControl, {
props: {
catalog: [STAR, ADMIN_READ],
availableTiers: ['full', 'read_only'],
tier: 'read_only',
custom: { adminRead: false, scopes: new Set<string>() },
idPrefix: 'test-2',
},
attachTo: document.body,
})
expect(twoTiers.findAll('[data-access-tier]').map((el) => el.attributes('data-access-tier'))).toEqual([
'full',
'read_only',
])
const oneTier = mount(ScopeAccessControl, {
props: {
catalog: [STAR],
availableTiers: ['full'],
tier: 'full',
custom: { adminRead: false, scopes: new Set<string>() },
idPrefix: 'test-1',
},
attachTo: document.body,
})
expect(oneTier.find('[data-access-tiers]').exists()).toBe(false)
expect(oneTier.find('[data-scope-all-note]').exists()).toBe(true)
})
it('renders elevated-first chips capped at 6 + clickable +2 more chip that emits customize (backstop #7, D-06)', async () => {
const catalog: AdminAPITokenScope[] = [
STAR,
ADMIN_READ,
makeScope({ name: 'p1:read', label: 'P1 Read', read_only: true, plugin_id: 'acme.p1', group: 'P1' }),
makeScope({ name: 'p2:read', label: 'P2 Read', read_only: true, plugin_id: 'acme.p2', group: 'P2' }),
makeScope({ name: 'p3:write', label: 'P3 Write', read_only: false, plugin_id: 'acme.p3', group: 'P3' }),
makeScope({ name: 'p4:write', label: 'P4 Write', read_only: false, plugin_id: 'acme.p4', group: 'P4' }),
makeScope({ name: 'p5:read', label: 'P5 Read', read_only: true, plugin_id: 'acme.p5', group: 'P5' }),
makeScope({ name: 'p6:write', label: 'P6 Write', read_only: false, plugin_id: 'acme.p6', group: 'P6' }),
makeScope({ name: 'p7:read', label: 'P7 Read', read_only: true, plugin_id: 'acme.p7', group: 'P7' }),
makeScope({ name: 'p8:read', label: 'P8 Read', read_only: true, plugin_id: 'acme.p8', group: 'P8' }),
]
// 8 selected plugin scopes (3 writes + 5 reads) -> writes sorted before reads, capped at 6 + "+2 more"
const wrapper = mount(ScopeAccessControl, {
props: {
catalog,
availableTiers: ['full', 'read_only', 'custom'],
tier: 'custom',
custom: {
adminRead: false,
scopes: new Set(['p1:read', 'p2:read', 'p3:write', 'p4:write', 'p5:read', 'p6:write', 'p7:read', 'p8:read']),
},
idPrefix: 'cap-test',
},
attachTo: document.body,
})
const chips = wrapper.findAll('[data-summary-chip]')
expect(chips).toHaveLength(6)
expect(chips.map((c) => c.attributes('data-summary-chip'))).toEqual([
'p3:write',
'p4:write',
'p6:write',
'p1:read',
'p2:read',
'p5:read',
])
const moreBtn = wrapper.find('[data-action="customize-scopes-more"]')
expect(moreBtn.exists()).toBe(true)
expect(moreBtn.text()).toBe('+2 more')
await moreBtn.trigger('click')
expect(wrapper.emitted('customize')).toHaveLength(1)
// With admin:read ON + 7 writes -> admin:read chip renders FIRST, capped at 6 + "+2 more"
const writesCatalog: AdminAPITokenScope[] = [
STAR,
ADMIN_READ,
...Array.from({ length: 7 }, (_, i) =>
makeScope({
name: `w${i + 1}`,
label: `Write ${i + 1}`,
read_only: false,
plugin_id: `acme.w${i + 1}`,
group: `W${i + 1}`,
}),
),
]
const adminReadFirst = mount(ScopeAccessControl, {
props: {
catalog: writesCatalog,
availableTiers: ['full', 'read_only', 'custom'],
tier: 'custom',
custom: {
adminRead: true,
scopes: new Set(['w1', 'w2', 'w3', 'w4', 'w5', 'w6', 'w7']),
},
idPrefix: 'admin-read-first',
},
attachTo: document.body,
})
const arChips = adminReadFirst.findAll('[data-summary-chip]')
expect(arChips).toHaveLength(6)
expect(arChips[0]!.attributes('data-summary-chip')).toBe('admin:read')
expect(adminReadFirst.find('[data-action="customize-scopes-more"]').text()).toBe('+2 more')
})
it('renders empty state, invalid styling, and disabled controls accurately', async () => {
const blog = makeScope({ name: 'blog', label: 'Blog', read_only: false, plugin_id: 'acme.blog', group: 'Blog' })
const wrapper = mount(ScopeAccessControl, {
props: {
catalog: [STAR, ADMIN_READ, blog],
availableTiers: ['full', 'read_only', 'custom'],
tier: 'custom',
custom: { adminRead: false, scopes: new Set<string>() },
invalid: true,
disabled: true,
idPrefix: 'state-test',
},
attachTo: document.body,
})
const summary = wrapper.find('[data-scope-summary]')
expect(summary.attributes('aria-invalid')).toBe('true')
expect(summary.classes()).toContain('border-danger')
expect(wrapper.find('[data-scope-summary-count]').text()).toBe(
'No scopes selected yet. Choose at least one scope to continue.',
)
expect(wrapper.find('[data-scope-summary-chips]').exists()).toBe(false)
expect((wrapper.find('[data-action="customize-scopes"]').element as HTMLButtonElement).disabled).toBe(true)
})
})

View File

@@ -0,0 +1,309 @@
// Component tests for ScopePicker.vue (Phase 36 backstops #2, #4).
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { defineComponent, ref } from 'vue'
import { enableAutoUnmount, flushPromises, mount } from '@vue/test-utils'
import type { AdminAPITokenScope } from '../../src/api/types'
import { setBundle } from '../../src/app/i18n'
import ScopePicker from '../../src/components/scopes/ScopePicker.vue'
import { langFixture } from '../fixtures/typed'
import { resetState } from '../helpers'
const strings = {
'backend::lang.permissioneditor.other': { other: 'Other' },
'backend::lang.api_tokens.read_only': { other: 'Read-only' },
'backend::lang.api_tokens.via_admin_read': { other: 'via admin:read' },
'backend::lang.api_tokens.scope_search_label': { other: 'Search scopes' },
'backend::lang.api_tokens.scope_search_placeholder': { other: 'Search plugins or scopes…' },
'backend::lang.api_tokens.scope_search_clear': { other: 'Clear search' },
'backend::lang.api_tokens.scope_filter_label': { other: 'Filter scopes' },
'backend::lang.api_tokens.scope_filter_all': { other: 'All (:count)' },
'backend::lang.api_tokens.scope_filter_selected': { other: 'Selected (:count)' },
'backend::lang.api_tokens.scope_filter_read_only': { other: 'Read-only (:count)' },
'backend::lang.api_tokens.scope_filter_reset': { other: 'Show all scopes' },
'backend::lang.api_tokens.scope_also_admin_read': { other: 'Also allow reading everything in admin' },
'backend::lang.api_tokens.scope_also_admin_read_hint': { other: 'Includes all read-only scopes.' },
'backend::lang.api_tokens.group_select_read': { other: 'Read' },
'backend::lang.api_tokens.group_select_all': { other: 'All' },
'backend::lang.api_tokens.group_clear': { other: 'Clear' },
'backend::lang.api_tokens.group_select_read_named': { other: 'Select read-only scopes in :group' },
'backend::lang.api_tokens.group_select_all_named': { other: 'Select all scopes in :group' },
'backend::lang.api_tokens.group_clear_named': { other: 'Clear scopes in :group' },
'backend::lang.api_tokens.scope_empty_search_title': { other: 'No matching scopes' },
'backend::lang.api_tokens.scope_empty_search_body': { other: 'No scopes matched “:query”.' },
'backend::lang.api_tokens.scope_empty_selected_title': { other: 'No scopes selected' },
'backend::lang.api_tokens.scope_empty_selected_body': { other: 'Pick one or more scopes.' },
'backend::lang.api_tokens.scope_empty_readonly_title': { other: 'No read-only scopes' },
'backend::lang.api_tokens.scope_empty_readonly_body': { other: 'None of the available scopes are read-only.' },
'backend::lang.api_tokens.scope_picker_none_selected': { other: 'Select at least one scope to apply.' },
'backend::lang.api_tokens.scope_picker_apply': { other: 'Apply scopes' },
'backend::lang.api_tokens.scope_picker_selected': { other: ':scopes selected' },
'backend::lang.api_tokens.scope_picker_selected_admin_read': { other: 'admin:read + :scopes selected' },
'backend::lang.api_tokens.scope_summary_admin_read_only': { other: 'Read-only admin access' },
'backend::lang.api_tokens.scope_count': { one: ':count scope', other: ':count scopes' },
'backend::lang.api_tokens.scope_write_count': { one: ':count write scope', other: ':count write scopes' },
}
function makeScope(overrides: Partial<AdminAPITokenScope> & Pick<AdminAPITokenScope, 'name'>): AdminAPITokenScope {
return {
label: overrides.name,
description: `Description for ${overrides.name}`,
read_only: overrides.name.endsWith(':read'),
known: true,
plugin_id: 'acme.demo',
group: 'Demo',
...overrides,
}
}
const STAR = makeScope({ name: '*', label: 'Full access', read_only: false, plugin_id: '', group: '' })
const ADMIN_READ = makeScope({ name: 'admin:read', label: 'Read-only admin', read_only: true, plugin_id: '', group: '' })
function mountInteractivePicker(opts: {
catalog: AdminAPITokenScope[]
initialAdminRead?: boolean
initialScopes?: string[]
cancelLabel?: string
}) {
const Harness = defineComponent({
components: { ScopePicker },
setup() {
const draftAdminRead = ref(opts.initialAdminRead ?? false)
const draftScopes = ref<Set<string>>(new Set(opts.initialScopes ?? []))
const applied = ref(0)
const cancelled = ref(0)
return {
catalog: opts.catalog,
draftAdminRead,
draftScopes,
cancelLabel: opts.cancelLabel ?? 'Discard changes',
applied,
cancelled,
}
},
template: `
<ScopePicker
:catalog="catalog"
v-model:draft-admin-read="draftAdminRead"
v-model:draft-scopes="draftScopes"
:cancel-label="cancelLabel"
@apply="applied++"
@cancel="cancelled++"
/>
`,
})
return mount(Harness, { attachTo: document.body })
}
beforeEach(() => {
resetState()
setBundle({ ...langFixture.data, ...strings }, 'en')
})
afterEach(() => {
document.body.innerHTML = ''
})
enableAutoUnmount(afterEach)
describe('ScopePicker.vue', () => {
const smallCatalog: AdminAPITokenScope[] = [
STAR,
ADMIN_READ,
makeScope({
name: 'journal',
label: 'Journal',
description: 'Create and publish posts.',
read_only: false,
plugin_id: 'acme.journal',
group: 'Journal',
}),
makeScope({
name: 'journal:read',
label: 'Journal, read-only',
description: 'View posts and drafts.',
read_only: true,
plugin_id: 'acme.journal',
group: 'Journal',
}),
makeScope({
name: 'seo',
label: 'SEO',
description: 'Edit metadata and redirects.',
read_only: false,
plugin_id: 'acme.seo',
group: 'SEO',
}),
makeScope({
name: 'seo:read',
label: 'SEO, read-only',
description: 'Inspect metadata.',
read_only: true,
plugin_id: 'acme.seo',
group: 'SEO',
}),
]
it('implements admin:read lock semantics, via admin:read badge, disabled Read, selective Clear, and restores prior :read ticks (backstop #2, D-04, D-17)', async () => {
const wrapper = mountInteractivePicker({
catalog: smallCatalog,
initialAdminRead: false,
initialScopes: ['journal', 'journal:read'],
})
await flushPromises()
// Unchecked by default in Custom.
const adminReadCheckbox = wrapper.find('[data-admin-read-checkbox]')
expect((adminReadCheckbox.element as HTMLInputElement).checked).toBe(false)
expect(wrapper.findAll('[data-via-admin-read]')).toHaveLength(0)
// Enable admin:read opt-in toggle.
await adminReadCheckbox.setValue(true)
await flushPromises()
// Every read_only row is locked checked + disabled with via admin:read badge.
for (const roName of ['journal:read', 'seo:read']) {
const row = wrapper.find(`[data-scope="${roName}"]`)
const input = row.find('input[type="checkbox"]').element as HTMLInputElement
expect(input.checked).toBe(true)
expect(input.disabled).toBe(true)
expect(row.find('[data-via-admin-read]').exists()).toBe(true)
expect(row.find('[data-via-admin-read]').text()).toContain('via admin:read')
}
// Write rows remain unlocked.
const journalWriteInput = wrapper.find('[data-scope="journal"] input[type="checkbox"]').element as HTMLInputElement
expect(journalWriteInput.disabled).toBe(false)
expect(journalWriteInput.checked).toBe(true)
// Per-group Read button is disabled while admin:read is ON.
const journalGroup = wrapper.findAll('[data-scope-group]')[0]!
expect((journalGroup.find('[data-group-action="read"]').element as HTMLButtonElement).disabled).toBe(true)
// Per-group Clear unticks ONLY unlocked write scopes, leaving locked read_only scopes checked.
await journalGroup.find('[data-group-action="clear"]').trigger('click')
await flushPromises()
expect((wrapper.find('[data-scope="journal"] input[type="checkbox"]').element as HTMLInputElement).checked).toBe(
false,
)
expect(
(wrapper.find('[data-scope="journal:read"] input[type="checkbox"]').element as HTMLInputElement).checked,
).toBe(true)
// Toggling admin:read OFF restores prior :read ticks from draftScopes memory (journal:read was ticked, seo:read was not).
await adminReadCheckbox.setValue(false)
await flushPromises()
expect(wrapper.findAll('[data-via-admin-read]')).toHaveLength(0)
const journalReadInput = wrapper.find('[data-scope="journal:read"] input[type="checkbox"]')
.element as HTMLInputElement
const seoReadInput = wrapper.find('[data-scope="seo:read"] input[type="checkbox"]').element as HTMLInputElement
expect(journalReadInput.disabled).toBe(false)
expect(journalReadInput.checked).toBe(true)
expect(seoReadInput.disabled).toBe(false)
expect(seoReadInput.checked).toBe(false)
})
it('filters by search across plugin/group/label/code/description, auto-expands, restores expand state on clear, and shows empty search state (backstop #4)', async () => {
// Large catalog: 4 groups x 4 scopes = 16 scopes (> 3 groups AND > 12 scopes) -> all collapsed initially when empty.
const largeCatalog: AdminAPITokenScope[] = [STAR, ADMIN_READ]
for (let g = 1; g <= 4; g++) {
for (let i = 1; i <= 4; i++) {
largeCatalog.push(
makeScope({
name: `grp${g}:s${i}`,
label: `Group ${g} Action ${i}`,
description: g === 3 && i === 2 ? 'Special redirect sync tool' : `Desc ${g}.${i}`,
read_only: i % 2 === 0,
plugin_id: `acme.plug${g}`,
group: `Section ${g}`,
}),
)
}
}
const wrapper = mountInteractivePicker({ catalog: largeCatalog })
await flushPromises()
// Large catalog with 0 selected -> all 4 groups collapsed on mount (D-07).
const initialExpanded = wrapper
.findAll('[data-scope-group-toggle]')
.map((btn) => btn.attributes('aria-expanded'))
expect(initialExpanded).toEqual(['false', 'false', 'false', 'false'])
// Search matching description auto-expands matching group.
const search = wrapper.find('[data-scope-search]')
await search.setValue('redirect sync')
await flushPromises()
expect(wrapper.findAll('[data-scope-group]')).toHaveLength(1)
expect(wrapper.find('[data-scope-group-toggle]').attributes('aria-expanded')).toBe('true')
expect(wrapper.find('[data-scope="grp3:s2"]').exists()).toBe(true)
// Clear search restores pre-search collapsed expand state.
await wrapper.find('[data-action="clear-scope-search"]').trigger('click')
await flushPromises()
expect(wrapper.findAll('[data-scope-group]')).toHaveLength(4)
expect(wrapper.findAll('[data-scope-group-toggle]').map((btn) => btn.attributes('aria-expanded'))).toEqual([
'false',
'false',
'false',
'false',
])
// Search with 0 matches renders dashed empty state naming :query + Clear search button.
await search.setValue('nonexistent-xyz')
await flushPromises()
const empty = wrapper.find('[data-scope-picker-empty]')
expect(empty.exists()).toBe(true)
expect(empty.text()).toContain('No matching scopes')
expect(empty.text()).toContain('nonexistent-xyz')
await wrapper.find('[data-action="reset-scope-search"]').trigger('click')
await flushPromises()
expect(wrapper.findAll('[data-scope-group]')).toHaveLength(4)
})
it('shows live counts on filter pills, specific filter empty states, Show all scopes reset, and empty-draft Apply guard (backstop #4)', async () => {
const writeOnlyCatalog: AdminAPITokenScope[] = [
STAR,
makeScope({ name: 'a:write', label: 'A Write', read_only: false, plugin_id: 'acme.a', group: 'Alpha' }),
makeScope({ name: 'b:write', label: 'B Write', read_only: false, plugin_id: 'acme.b', group: 'Beta' }),
]
const wrapper = mountInteractivePicker({ catalog: writeOnlyCatalog })
await flushPromises()
// Small catalog (2 groups, 2 scopes) -> all expanded on mount.
expect(wrapper.findAll('[data-scope-group-toggle]').map((b) => b.attributes('aria-expanded'))).toEqual([
'true',
'true',
])
// Filter pills show live counts across full catalog.
expect(wrapper.find('[data-scope-filter="all"]').text()).toBe('All (2)')
expect(wrapper.find('[data-scope-filter="selected"]').text()).toBe('Selected (0)')
expect(wrapper.find('[data-scope-filter="read_only"]').text()).toBe('Read-only (0)')
// Empty draft disables Apply and announces none selected.
expect((wrapper.find('[data-action="scope-picker-apply"]').element as HTMLButtonElement).disabled).toBe(true)
expect(wrapper.find('[data-scope-picker-summary]').text()).toBe('Select at least one scope to apply.')
// Selected filter with 0 selected -> empty state + Show all scopes resets to All.
await wrapper.find('[data-scope-filter="selected"]').trigger('click')
await flushPromises()
expect(wrapper.find('[data-scope-picker-empty]').text()).toContain('No scopes selected')
await wrapper.find('[data-action="reset-scope-filter"]').trigger('click')
await flushPromises()
expect(wrapper.find('[data-scope-filter="all"]').attributes('aria-pressed')).toBe('true')
// Read-only filter with 0 read-only scopes -> empty state + Show all scopes.
await wrapper.find('[data-scope-filter="read_only"]').trigger('click')
await flushPromises()
expect(wrapper.find('[data-scope-picker-empty]').text()).toContain('No read-only scopes')
await wrapper.find('[data-action="reset-scope-filter"]').trigger('click')
await flushPromises()
// Ticking a scope updates live count and enables Apply.
await wrapper.find('[data-scope="a:write"] input[type="checkbox"]').setValue(true)
await flushPromises()
expect(wrapper.find('[data-scope-filter="selected"]').text()).toBe('Selected (1)')
expect((wrapper.find('[data-action="scope-picker-apply"]').element as HTMLButtonElement).disabled).toBe(false)
})
})