mirror of
https://github.com/fsolla/teqo.git
synced 2026-11-26 21:53:06 +00:00
Merge pull request #4 from fsolla/cursor/p4-test-allocator-guard-78a7
Miss #73 guardrail: allocate municipalities, never pin seeded slugs (+ deterministic guards)
This commit is contained in:
commit
ef7edacb60
8 changed files with 200 additions and 48 deletions
|
|
@ -7,7 +7,7 @@ Responsável: —
|
|||
|
||||
## Contexto
|
||||
|
||||
O PR #82 (A6) entrega o card **"Dobradinhas potenciais para 2026"** na aba Eleições do detalhe do município: candidatos proporcionais com `runningAgain2026 = sim`, ranqueados por score `0,6 alinhamento + 0,4 força local 2022`. Enquanto o TSE não publica as candidaturas de 2026 e a Fase 5 não reconcilia `runningAgain2026`, o loader retorna `{ status: 'pending2026' }` e o card mostra *"Indisponível até as candidaturas de 2026"*.
|
||||
O PR #82 (A6) entrega o card **"Dobradinhas potenciais para 2026"** na aba Eleições do detalhe do município: candidatos proporcionais com `runningAgain2026 = sim`, ranqueados por score `0,6 alinhamento + 0,4 força local 2022`. Enquanto o TSE não publica as candidaturas de 2026 e a Fase 5 não reconcilia `runningAgain2026`, o loader retorna `{ status: 'pending2026' }` e o card mostra _"Indisponível até as candidaturas de 2026"_.
|
||||
|
||||
Os dados de **2022 já estão no banco** (`electionCandidate` + `electionCandidateVote` via `pnpm db:seed:tse`). O staff precisa da inteligência **agora** — quem teve força local em 2022 e qual o alinhamento partidário — para priorizar dobradinhas antes de agosto.
|
||||
|
||||
|
|
@ -30,7 +30,7 @@ Os dados de **2022 já estão no banco** (`electionCandidate` + `electionCandida
|
|||
|
||||
## Questões em aberto — RESOLVIDAS (proposta)
|
||||
|
||||
- **Copy do estado provisório** — RESOLVIDA. Título mantém "Dobradinhas potenciais para 2026"; subtítulo/aviso: *"Lista provisória com base em quem concorreu aqui em 2022. Atualiza automaticamente quando o TSE publicar as candidaturas de 2026."*
|
||||
- **Copy do estado provisório** — RESOLVIDA. Título mantém "Dobradinhas potenciais para 2026"; subtítulo/aviso: _"Lista provisória com base em quem concorreu aqui em 2022. Atualiza automaticamente quando o TSE publicar as candidaturas de 2026."_
|
||||
- **Candidatos `runningAgain2026 = desconhecido` após reconcile** — RESOLVIDA. Fora da lista confirmada (mesmo critério conservador de A6: só `sim` entra). Não inventar parceiro sem confirmação.
|
||||
- **Badge "eleito em 2022"** — RESOLVIDA. Mantém no modo provisório e confirmado (campo `elected` já no registry).
|
||||
|
||||
|
|
|
|||
|
|
@ -82,17 +82,22 @@ test.describe('Início — busca global (B47)', () => {
|
|||
const coordinator = await fixtures.createCampaignUser('coordinator', {
|
||||
name: fixtures.value('Coordenadora Geral'),
|
||||
})
|
||||
// Claimed, never hardcoded: parallel specs sharing one seeded municipality
|
||||
// raced each other's mutations on it (miss #73).
|
||||
const municipality = await fixtures.claimMunicipality()
|
||||
|
||||
await campaign.login(page, coordinator.email!, coordinator.password)
|
||||
const search = page.getByLabel('Buscar na campanha')
|
||||
await search.fill('Cairu')
|
||||
await search.fill(municipality.name)
|
||||
|
||||
const group = page.getByRole('region', { name: 'Resultados da busca' })
|
||||
await expect(group.getByRole('heading', { name: 'Municípios' })).toBeVisible({
|
||||
timeout: 15000,
|
||||
})
|
||||
await group.getByRole('link', { name: /Cairu/i }).click()
|
||||
await page.waitForURL(/\/campanha\/municipios\/cairu/)
|
||||
// Disambiguate by href, not by name: catalog names are not prefix-unique
|
||||
// ("Conde" also matches "Condeúba" — the unanchored-regex lesson).
|
||||
await group.locator(`a[href$="/campanha/municipios/${municipality.slug}"]`).click()
|
||||
await page.waitForURL(new RegExp(`^https?://[^/]+/campanha/municipios/${municipality.slug}$`))
|
||||
})
|
||||
})
|
||||
|
||||
|
|
@ -158,20 +163,28 @@ test.describe('Wizard — busca município (B60)', () => {
|
|||
const coordinator = await fixtures.createCampaignUser('coordinator', {
|
||||
name: fixtures.value('Coordenadora Geral'),
|
||||
})
|
||||
const municipality = await fixtures.claimMunicipality()
|
||||
|
||||
await campaign.login(page, coordinator.email!, coordinator.password)
|
||||
await page.goto('/campanha/acoes/atualizar-votos')
|
||||
await expect(page.getByRole('heading', { name: WIZARD_MUNICIPALITY_STEP_TITLE })).toBeVisible()
|
||||
|
||||
const search = page.getByLabel('Buscar município')
|
||||
await search.fill('Cairu')
|
||||
await search.fill(municipality.name)
|
||||
|
||||
const results = page.getByRole('region', { name: 'Resultados da busca' })
|
||||
await expect(results.getByRole('link', { name: /Cairu/i })).toBeVisible({ timeout: 15000 })
|
||||
await results.getByRole('link', { name: /Cairu/i }).click()
|
||||
const hit = results.locator(`a[href*="municipio=${municipality.slug}"]`)
|
||||
await expect(hit).toBeVisible({ timeout: 15000 })
|
||||
await hit.click()
|
||||
|
||||
await page.waitForURL(/\/campanha\/acoes\/atualizar-votos\?municipio=cairu/)
|
||||
await expect(page.getByLabel(/Município em atualização: Cairu/i)).toBeVisible()
|
||||
await page.waitForURL(
|
||||
new RegExp(
|
||||
`^https?://[^/]+/campanha/acoes/atualizar-votos\\?municipio=${municipality.slug}$`,
|
||||
),
|
||||
)
|
||||
await expect(
|
||||
page.getByLabel(new RegExp(`^Município em atualização: ${municipality.name}`, 'i')),
|
||||
).toBeVisible()
|
||||
await expect(page.getByRole('heading', { name: 'Ajustar votos estimados' })).toBeVisible()
|
||||
})
|
||||
})
|
||||
|
|
@ -188,9 +201,10 @@ test.describe('Wizard — ajuste de votos (B61 / B77)', () => {
|
|||
const coordinator = await fixtures.createCampaignUser('coordinator', {
|
||||
name: fixtures.value('Coordenadora Geral'),
|
||||
})
|
||||
const municipality = await fixtures.claimMunicipality()
|
||||
|
||||
await campaign.login(page, coordinator.email!, coordinator.password)
|
||||
await page.goto('/campanha/acoes/atualizar-votos?municipio=cairu')
|
||||
await page.goto(`/campanha/acoes/atualizar-votos?municipio=${municipality.slug}`)
|
||||
|
||||
const step = wizardVoteStep(page)
|
||||
await expect(page.getByRole('heading', { name: 'Ajustar votos estimados' })).toBeVisible({
|
||||
|
|
@ -217,9 +231,10 @@ test.describe('Wizard — ajuste de votos (B61 / B77)', () => {
|
|||
const coordinator = await fixtures.createCampaignUser('coordinator', {
|
||||
name: fixtures.value('Coordenadora Geral'),
|
||||
})
|
||||
const municipality = await fixtures.claimMunicipality()
|
||||
|
||||
await campaign.login(page, coordinator.email!, coordinator.password)
|
||||
await page.goto('/campanha/acoes/atualizar-votos?municipio=cairu')
|
||||
await page.goto(`/campanha/acoes/atualizar-votos?municipio=${municipality.slug}`)
|
||||
|
||||
await expect(page.getByRole('heading', { name: 'Ajustar votos estimados' })).toBeVisible({
|
||||
timeout: 15000,
|
||||
|
|
@ -239,11 +254,18 @@ test.describe('Wizard — ajuste de votos (B61 / B77)', () => {
|
|||
const coordinator = await fixtures.createCampaignUser('coordinator', {
|
||||
name: fixtures.value('Coordenadora Geral'),
|
||||
})
|
||||
const municipality = await fixtures.claimMunicipality()
|
||||
|
||||
await campaign.login(page, coordinator.email!, coordinator.password)
|
||||
await page.goto('/campanha/acoes/atualizar-votos?municipio=cairu&cenario=pessimistic')
|
||||
await page.goto(
|
||||
`/campanha/acoes/atualizar-votos?municipio=${municipality.slug}&cenario=pessimistic`,
|
||||
)
|
||||
|
||||
await page.waitForURL(/\/campanha\/acoes\/atualizar-votos\?municipio=cairu$/)
|
||||
await page.waitForURL(
|
||||
new RegExp(
|
||||
`^https?://[^/]+/campanha/acoes/atualizar-votos\\?municipio=${municipality.slug}$`,
|
||||
),
|
||||
)
|
||||
await expect(page.getByRole('heading', { name: 'Ajustar votos estimados' })).toBeVisible({
|
||||
timeout: 15000,
|
||||
})
|
||||
|
|
@ -256,10 +278,11 @@ test.describe('Wizard — atualizar liderança (B70)', () => {
|
|||
const coordinator = await fixtures.createCampaignUser('coordinator', {
|
||||
name: fixtures.value('Coordenadora Geral'),
|
||||
})
|
||||
const municipality = await fixtures.claimMunicipality()
|
||||
const suffix = Date.now().toString().slice(-8).padStart(8, '0')
|
||||
|
||||
await campaign.login(page, coordinator.email!, coordinator.password)
|
||||
await page.goto('/campanha/acoes/atualizar-lideranca?municipio=cairu')
|
||||
await page.goto(`/campanha/acoes/atualizar-lideranca?municipio=${municipality.slug}`)
|
||||
|
||||
await expect(page.getByRole('heading', { name: 'Quem coordena por aqui?' })).toBeVisible({
|
||||
timeout: 15000,
|
||||
|
|
@ -293,8 +316,10 @@ test.describe('Wizard — registrar sinal (B63)', () => {
|
|||
name: fixtures.value('Coordenadora Geral'),
|
||||
})
|
||||
|
||||
const municipality = await fixtures.claimMunicipality()
|
||||
|
||||
await campaign.login(page, coordinator.email!, coordinator.password)
|
||||
await page.goto('/campanha/acoes/registrar-sinal?municipio=cairu')
|
||||
await page.goto(`/campanha/acoes/registrar-sinal?municipio=${municipality.slug}`)
|
||||
|
||||
await expect(page.getByRole('heading', { name: 'Que tipo de sinal?' })).toBeVisible({
|
||||
timeout: 15000,
|
||||
|
|
@ -319,9 +344,10 @@ test.describe('Wizard — registrar sinal (B63)', () => {
|
|||
const coordinator = await fixtures.createCampaignUser('coordinator', {
|
||||
name: fixtures.value('Coordenadora Geral'),
|
||||
})
|
||||
const municipality = await fixtures.claimMunicipality()
|
||||
|
||||
await campaign.login(page, coordinator.email!, coordinator.password)
|
||||
await page.goto('/campanha/acoes/registrar-sinal?municipio=cairu')
|
||||
await page.goto(`/campanha/acoes/registrar-sinal?municipio=${municipality.slug}`)
|
||||
|
||||
await expect(page.getByRole('heading', { name: 'Que tipo de sinal?' })).toBeVisible({
|
||||
timeout: 15000,
|
||||
|
|
@ -341,9 +367,12 @@ test.describe('Wizard — registrar sinal (B63)', () => {
|
|||
const coordinator = await fixtures.createCampaignUser('coordinator', {
|
||||
name: fixtures.value('Coordenadora Geral'),
|
||||
})
|
||||
const municipality = await fixtures.claimMunicipality()
|
||||
|
||||
await campaign.login(page, coordinator.email!, coordinator.password)
|
||||
await page.goto('/campanha/acoes/registrar-sinal?municipio=cairu&entry=update-votes')
|
||||
await page.goto(
|
||||
`/campanha/acoes/registrar-sinal?municipio=${municipality.slug}&entry=update-votes`,
|
||||
)
|
||||
|
||||
await expect(page.getByRole('link', { name: 'Pular registro de sinal' })).toBeVisible({
|
||||
timeout: 15000,
|
||||
|
|
|
|||
|
|
@ -382,7 +382,8 @@ test.describe('Municípios — cards no celular (B42)', () => {
|
|||
await expect(page.getByRole('link', { name: 'Abrir município' })).toHaveCount(0)
|
||||
|
||||
await card.getByRole('button', { name: 'Editar tendência política' }).click()
|
||||
const drawer = page.locator('[data-slot="drawer-popup"]')
|
||||
// B79 keeps CampaignQuickActionsDrawer mounted (modal=false); scope to the trend dialog.
|
||||
const drawer = page.getByRole('dialog', { name: 'Editar tendência' })
|
||||
await expect(drawer).toBeVisible()
|
||||
await expect(drawer.getByText(municipality.name, { exact: true })).toBeVisible()
|
||||
await expect(page).toHaveURL(listURL)
|
||||
|
|
|
|||
|
|
@ -35,9 +35,12 @@ test.describe('Wizard — header mobile (B75)', () => {
|
|||
const coordinator = await fixtures.createCampaignUser('coordinator', {
|
||||
name: fixtures.value('Coordenadora Geral'),
|
||||
})
|
||||
// Claimed, never hardcoded: parallel specs sharing one seeded municipality
|
||||
// raced each other's mutations on it (miss #73).
|
||||
const municipality = await fixtures.claimMunicipality()
|
||||
|
||||
await campaign.login(page, coordinator.email!, coordinator.password)
|
||||
await page.goto('/campanha/acoes/atualizar-votos?municipio=cairu')
|
||||
await page.goto(`/campanha/acoes/atualizar-votos?municipio=${municipality.slug}`)
|
||||
|
||||
await expect(page.getByRole('heading', { name: 'Ajustar votos estimados' })).toBeVisible({
|
||||
timeout: 15000,
|
||||
|
|
@ -45,7 +48,9 @@ test.describe('Wizard — header mobile (B75)', () => {
|
|||
|
||||
const topBar = page.locator('[data-slot="campaign-mobile-top-bar"][data-mode="wizard"]')
|
||||
await expect(topBar.getByText('Ajustar votos', { exact: true })).toBeVisible()
|
||||
await expect(topBar.getByLabel(/Município em atualização: Cairu/i)).toBeVisible()
|
||||
await expect(
|
||||
topBar.getByLabel(new RegExp(`^Município em atualização: ${municipality.name}`, 'i')),
|
||||
).toBeVisible()
|
||||
await expect(page.getByRole('link', { name: /Voltar/ })).toBeVisible()
|
||||
|
||||
await page.getByRole('link', { name: /Voltar/ }).click()
|
||||
|
|
|
|||
|
|
@ -48,8 +48,8 @@ describe('searchHomeMunicipalities (B48)', () => {
|
|||
const advisor = await fixtures.createCampaignUser('advisor')
|
||||
const coordinator = await fixtures.createCampaignUser('coordinator')
|
||||
|
||||
const administered = await fixtures.getMunicipality('cairu')
|
||||
const other = await fixtures.getMunicipality('feira-de-santana')
|
||||
const administered = await fixtures.getMunicipality()
|
||||
const other = await fixtures.getMunicipality()
|
||||
await fixtures.assignMunicipalityAdvisors(administered.id, [advisor.id])
|
||||
|
||||
const otherQuery = distinctWordStartQuery(other.name, administered.name)
|
||||
|
|
|
|||
|
|
@ -68,11 +68,13 @@ describe('searchHomeStateDeputies (B52)', () => {
|
|||
const fixtures = campaignFixtures()
|
||||
const coordinator = await fixtures.createCampaignUser('coordinator')
|
||||
const stateDeputy = await fixtures.createStateDeputy({ name: 'Carteira Dobradinha' })
|
||||
const cairu = await fixtures.getMunicipality('cairu')
|
||||
const feira = await fixtures.getMunicipality('feira-de-santana')
|
||||
// Allocated, never pinned slugs: parallel specs mutating the same seeded
|
||||
// municipality deadlocked municipality_rels (miss #73).
|
||||
const first = await fixtures.getMunicipality()
|
||||
const second = await fixtures.getMunicipality()
|
||||
await setStateDeputyMunicipalitiesBatchRecord(payload, coordinator, {
|
||||
stateDeputyId: stateDeputy.id,
|
||||
municipalityIds: [cairu.id, feira.id],
|
||||
municipalityIds: [first.id, second.id],
|
||||
assigned: true,
|
||||
})
|
||||
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { getPayload } from 'payload'
|
|||
import { beforeAll, describe, expect, it } from 'vitest'
|
||||
|
||||
import { getMunicipalityCatalogEntry, municipalityCatalog } from '@/lib/municipalityCatalog'
|
||||
import { territorialClassSortWeight } from '@/lib/territorialClassSortWeight'
|
||||
import config from '@/payload.config'
|
||||
import { loadMunicipalityListPageBundle } from '@/utilities/municipality/municipalityPageData'
|
||||
import { computeMunicipalityTerritorialClass } from '@/utilities/municipality/municipalityTerritorialClass'
|
||||
|
|
@ -287,19 +288,27 @@ describe('loadMunicipalityListPageBundle', () => {
|
|||
const fixtures = campaignFixtures()
|
||||
const coordinator = await fixtures.createCampaignUser('coordinator')
|
||||
|
||||
const redutoEntry = municipalityCatalog.find(
|
||||
(entry) => computeMunicipalityTerritorialClass(entry.slug).class === 'reduto',
|
||||
)!
|
||||
const marginalEntry = municipalityCatalog.find(
|
||||
(entry) => computeMunicipalityTerritorialClass(entry.slug).class === 'marginal',
|
||||
)!
|
||||
const reduto = await fixtures.getMunicipality(redutoEntry.slug)
|
||||
const marginal = await fixtures.getMunicipality(marginalEntry.slug)
|
||||
// Two allocated municipalities with DISTINCT territorial classes: the
|
||||
// behavior pinned here (class filter narrows, totals stay honest, classe
|
||||
// sort follows the weight table) does not care WHICH classes they are —
|
||||
// and pinning fixed catalog slugs raced parallel specs mutating the same
|
||||
// seeded rows (deadlock on municipality_rels, miss #73).
|
||||
const first = await fixtures.getMunicipality()
|
||||
const firstClass = computeMunicipalityTerritorialClass(first.slug).class
|
||||
let second = await fixtures.getMunicipality()
|
||||
let secondClass = computeMunicipalityTerritorialClass(second.slug).class
|
||||
for (let attempt = 0; secondClass === firstClass && attempt < 20; attempt++) {
|
||||
second = await fixtures.getMunicipality()
|
||||
secondClass = computeMunicipalityTerritorialClass(second.slug).class
|
||||
}
|
||||
if (secondClass === firstClass) {
|
||||
throw new Error('could not allocate municipalities of two distinct classes')
|
||||
}
|
||||
|
||||
const marker = `e10-classe-${Date.now()}`
|
||||
for (const [municipality, suffix] of [
|
||||
[reduto, 'reduto'],
|
||||
[marginal, 'marginal'],
|
||||
[first, 'filtrada'],
|
||||
[second, 'fora'],
|
||||
] as const) {
|
||||
await payload.update({
|
||||
collection: 'municipality',
|
||||
|
|
@ -313,29 +322,39 @@ describe('loadMunicipalityListPageBundle', () => {
|
|||
|
||||
const filtered = await loadMunicipalityListPageBundle(payload, coordinator, {
|
||||
q: marker,
|
||||
class: 'reduto',
|
||||
class: firstClass,
|
||||
})
|
||||
expect(filtered.municipalities.map((row) => row.slug)).toEqual([reduto.slug])
|
||||
expect(filtered.municipalities.map((row) => row.slug)).toEqual([first.slug])
|
||||
expect(filtered.totalDocs).toBe(1)
|
||||
expect(filtered.overview?.municipalityCount).toBe(1)
|
||||
expect(filtered.municipalities[0]!.territorialClass).toBe('reduto')
|
||||
expect(filtered.municipalities[0]!.territorialClass).toBe(firstClass)
|
||||
expect(filtered.municipalities[0]!.territorialClassFactors.length).toBeGreaterThan(0)
|
||||
|
||||
// A native sort key would otherwise let Payload paginate before the class
|
||||
// filter runs, which would hand back a short page with an inflated total.
|
||||
const byName = await loadMunicipalityListPageBundle(payload, coordinator, {
|
||||
q: marker,
|
||||
class: 'reduto',
|
||||
class: firstClass,
|
||||
sort: 'name',
|
||||
})
|
||||
expect(byName.municipalities.map((row) => row.slug)).toEqual([reduto.slug])
|
||||
expect(byName.municipalities.map((row) => row.slug)).toEqual([first.slug])
|
||||
expect(byName.totalDocs).toBe(1)
|
||||
|
||||
const sorted = await loadMunicipalityListPageBundle(payload, coordinator, {
|
||||
q: marker,
|
||||
sort: 'classe',
|
||||
})
|
||||
expect(sorted.municipalities.map((row) => row.slug)).toEqual([reduto.slug, marginal.slug])
|
||||
// `classe` sorts strongest class first (reduto 4 … marginal 1; every
|
||||
// catalog row classes into a weighted class, so no null weight exists).
|
||||
const expectedOrder = [first, second]
|
||||
.map((municipality) => ({
|
||||
slug: municipality.slug,
|
||||
weight:
|
||||
territorialClassSortWeight[computeMunicipalityTerritorialClass(municipality.slug).class],
|
||||
}))
|
||||
.sort((left, right) => (right.weight ?? 0) - (left.weight ?? 0))
|
||||
.map((entry) => entry.slug)
|
||||
expect(sorted.municipalities.map((row) => row.slug)).toEqual(expectedOrder)
|
||||
})
|
||||
|
||||
/**
|
||||
|
|
@ -348,9 +367,9 @@ describe('loadMunicipalityListPageBundle', () => {
|
|||
const fixtures = campaignFixtures()
|
||||
const coordinator = await fixtures.createCampaignUser('coordinator')
|
||||
|
||||
const low = await fixtures.getMunicipality(municipalityCatalog[0]!.slug)
|
||||
const high = await fixtures.getMunicipality(municipalityCatalog[1]!.slug)
|
||||
const none = await fixtures.getMunicipality(municipalityCatalog[2]!.slug)
|
||||
const low = await fixtures.getMunicipality()
|
||||
const high = await fixtures.getMunicipality()
|
||||
const none = await fixtures.getMunicipality()
|
||||
|
||||
const marker = `e14-nivel-${Date.now()}`
|
||||
for (const [municipality, suffix, engagementLevel] of [
|
||||
|
|
@ -446,9 +465,7 @@ describe('loadMunicipalityListPageBundle', () => {
|
|||
data: { priority: 'alta' },
|
||||
overrideAccess: true,
|
||||
})
|
||||
const covered = await fixtures.getMunicipality(
|
||||
municipalityCatalog.find((entry) => entry.slug !== priorityMunicipality.slug)!.slug,
|
||||
)
|
||||
const covered = await fixtures.getMunicipality()
|
||||
await fixtures.assignMunicipalityAdvisors(covered.id, [advisor.id])
|
||||
|
||||
// "Prioritária" lives in the Município popover, so it must not hide the
|
||||
|
|
|
|||
98
tests/unit/testMunicipalityAllocatorConventions.unit.spec.ts
Normal file
98
tests/unit/testMunicipalityAllocatorConventions.unit.spec.ts
Normal file
|
|
@ -0,0 +1,98 @@
|
|||
import { readdirSync, readFileSync } from 'node:fs'
|
||||
import { relative, resolve } from 'node:path'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { municipalityCatalog } from '@/lib/municipalityCatalog'
|
||||
|
||||
// Miss #73 (2026-07-31): int specs pinning seeded municipality slugs
|
||||
// (`getMunicipality('cairu')` et al.) and mutating them deadlocked
|
||||
// `municipality_rels` under the parallel suite (Postgres 40P01), and e2e specs
|
||||
// deep-linking `?municipio=cairu` raced the same row from two workers. The
|
||||
// allocator (`getMunicipality()` / `claimMunicipality()`, Postgres sequence)
|
||||
// hands out a unique row per claim; pinning is what breaks the contract.
|
||||
//
|
||||
// Rule 3 is the literal-regex sibling of the anchored-template guard (P3-C):
|
||||
// `new RegExp(\`…\`)` was hardened there, but `/Cairu/i` literals dodged it —
|
||||
// and catalog names are not prefix-unique (Conde/Condeúba, Barra ×4, Laje ×3).
|
||||
|
||||
const repoRoot = process.cwd()
|
||||
const repoPath = (absolute: string) => relative(repoRoot, absolute)
|
||||
|
||||
const walkFiles = (root: string, extensions: readonly string[]): string[] =>
|
||||
readdirSync(root, { recursive: true, withFileTypes: true })
|
||||
.filter((entry) => entry.isFile() && extensions.some((ext) => entry.name.endsWith(ext)))
|
||||
.map((entry) => resolve(entry.parentPath, entry.name))
|
||||
|
||||
const specFiles = [
|
||||
...walkFiles(resolve(repoRoot, 'tests/int'), ['.ts']),
|
||||
...walkFiles(resolve(repoRoot, 'tests/e2e'), ['.ts']),
|
||||
]
|
||||
|
||||
/** `getMunicipality(…)` called with a non-empty argument (a pinned slug). */
|
||||
const FIXED_SLUG_CALL = /\bgetMunicipality\s*\(\s*[^)\s]/
|
||||
|
||||
const MUTATION_PATTERN = new RegExp(
|
||||
[
|
||||
'\\b(?:assignMunicipalityAdvisors(?:Record)?|touchMunicipality|createLeadership|createVotePledge|createCampaignDemand|createMunicipalityUpdate|setStateDeputyMunicipalitiesBatchRecord)\\s*\\(',
|
||||
'payload\\.update\\(\\s*\\{\\s*collection:\\s*[\'"]municipality[\'"]',
|
||||
].join('|'),
|
||||
)
|
||||
|
||||
describe('municipality allocator discipline (miss #73)', () => {
|
||||
it('never pins a fixed-slug municipality in a spec that mutates municipalities', () => {
|
||||
const offenders: string[] = []
|
||||
|
||||
for (const file of specFiles) {
|
||||
const source = readFileSync(file, 'utf8')
|
||||
if (!FIXED_SLUG_CALL.test(source)) continue
|
||||
if (!MUTATION_PATTERN.test(source)) continue
|
||||
offenders.push(repoPath(file))
|
||||
}
|
||||
|
||||
expect(
|
||||
offenders,
|
||||
'allocate with getMunicipality() (no slug) — read-only catalog lookups belong to getMunicipalityCatalogEntry',
|
||||
).toEqual([])
|
||||
})
|
||||
|
||||
it('never deep-links a hardcoded municipality slug in e2e specs', () => {
|
||||
const offenders: string[] = []
|
||||
|
||||
for (const file of walkFiles(resolve(repoRoot, 'tests/e2e'), ['.ts'])) {
|
||||
const lines = readFileSync(file, 'utf8').split('\n')
|
||||
for (const [index, line] of lines.entries()) {
|
||||
if (/municipio=[a-z0-9-]/.test(line)) offenders.push(`${repoPath(file)}:${index + 1}`)
|
||||
}
|
||||
}
|
||||
|
||||
expect(offenders, 'interpolate claimMunicipality().slug into wizard deep links').toEqual([])
|
||||
})
|
||||
|
||||
it('anchors e2e name regexes that mention a catalog municipality', () => {
|
||||
const offenders: string[] = []
|
||||
const nameLiteral = /name:\s*\/([^/\n]+)\/i?\b/g
|
||||
const catalogNames = municipalityCatalog
|
||||
.map((entry) => entry.name)
|
||||
.filter((name) => name.length >= 4)
|
||||
|
||||
for (const file of walkFiles(resolve(repoRoot, 'tests/e2e'), ['.ts'])) {
|
||||
const source = readFileSync(file, 'utf8')
|
||||
nameLiteral.lastIndex = 0
|
||||
let match: RegExpExecArray | null
|
||||
while ((match = nameLiteral.exec(source)) !== null) {
|
||||
const pattern = match[1]!
|
||||
if (pattern.startsWith('^')) continue
|
||||
const hit = catalogNames.find((name) => pattern.toLowerCase().includes(name.toLowerCase()))
|
||||
if (hit) {
|
||||
const line = source.slice(0, match.index).split('\n').length
|
||||
offenders.push(`${repoPath(file)}:${line} (unanchored, matches "${hit}")`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expect(
|
||||
offenders,
|
||||
'anchor with ^ (or locate by href) — catalog names are not prefix-unique',
|
||||
).toEqual([])
|
||||
})
|
||||
})
|
||||
Loading…
Reference in a new issue