affectedTests.test.mjs 7.93 KB
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import fs from 'node:fs'
import os from 'node:os'
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 fixtureRoot = path.join(
  projectRoot,
  'tests/knowledge-graph/fixtures/mini-program',
)
const affectedPath = path.join(
  projectRoot,
  'scripts/knowledge-graph/affected-tests.mjs',
)

async function loadAffected() {
  assert.equal(fs.existsSync(affectedPath), true, 'affected test selector must exist')
  return import(pathToFileURL(affectedPath))
}

async function fixtureGraph() {
  const { buildKnowledgeGraph } = await import(
    pathToFileURL(
      path.join(projectRoot, 'scripts/knowledge-graph/build-knowledge-graph.mjs'),
    )
  )
  return buildKnowledgeGraph({ rootDir: fixtureRoot })
}

function git(rootDir, ...args) {
  const result = spawnSync('git', args, { cwd: rootDir, encoding: 'utf8' })
  assert.equal(result.status, 0, result.stderr)
  return result.stdout.trim()
}

test('selects direct tests and the owning domain for a page-local service', async () => {
  const { selectAffectedTests } = await loadAffected()
  const graph = await fixtureGraph()
  const result = selectAffectedTests({
    graph,
    changedFiles: ['pages/home/services/order-service.js'],
  })

  assert.equal(result.mode, 'targeted')
  assert.deepEqual(result.domains, ['main'])
  assert.deepEqual(result.tests, [
    'tests/home.test.mjs',
    'tests/main-unrelated.test.mjs',
    'tests/order-service.test.mjs',
  ])
  assert.deepEqual(result.reasons, ['page-local-change'])
})

test('upgrades shared, cross-domain, unresolved, and unclassified changes to full', async () => {
  const { selectAffectedTests } = await loadAffected()
  const graph = await fixtureGraph()
  const cases = [
    {
      files: ['api/order.js'],
      reason: 'shared-runtime-layer',
    },
    {
      files: ['pages/home/services/order-service.js', 'pkg/pages/detail/detail.js'],
      reason: 'cross-domain-change',
    },
    {
      files: ['pages/home/home.js'],
      reason: 'unresolved-relation',
    },
    {
      files: ['unknown/runtime.js'],
      reason: 'unclassified-runtime-file',
    },
  ]

  for (const fixture of cases) {
    const result = selectAffectedTests({ graph, changedFiles: fixture.files })
    assert.equal(result.mode, 'full', fixture.reason)
    assert.ok(result.reasons.includes(fixture.reason), fixture.reason)
  }
})

test('uses knowledge and governance checks for documentation-only changes', async () => {
  const { selectAffectedTests } = await loadAffected()
  const graph = await fixtureGraph()
  const result = selectAffectedTests({
    graph,
    changedFiles: ['docs/home.md'],
  })

  assert.equal(result.mode, 'docs-only')
  assert.deepEqual(result.tests, [
    'tests/knowledge-graph/artifactsAndImpact.test.mjs',
    'tests/knowledge-graph/buildKnowledgeGraph.test.mjs',
    'tests/project-governance/agentDocsLayout.test.mjs',
  ])
  assert.deepEqual(result.commands, ['npm run knowledge:check'])

  const graphConfig = selectAffectedTests({
    graph,
    changedFiles: ['docs/knowledge/domain-catalog.json'],
  })
  assert.equal(graphConfig.mode, 'docs-only')
  assert.deepEqual(graphConfig.reasons, ['knowledge-config-change'])
  assert.deepEqual(graphConfig.tests, [
    'tests/knowledge-graph',
    'tests/project-governance',
  ])
})

test('returns no work for an empty local change set and honors --full', async () => {
  const { selectAffectedTests } = await loadAffected()
  const graph = await fixtureGraph()

  assert.equal(
    selectAffectedTests({ graph, changedFiles: [] }).mode,
    'none',
  )
  assert.equal(
    selectAffectedTests({ graph, changedFiles: [], forceFull: true }).mode,
    'full',
  )
})

test('reads deleted files from local and base/head Git change sets', async (t) => {
  const { readChangedFiles } = await loadAffected()
  const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'affected-deleted-'))
  t.after(() => fs.rmSync(rootDir, { recursive: true, force: true }))
  const sourcePath = path.join(rootDir, 'pages/example.js')

  git(rootDir, 'init')
  git(rootDir, 'config', 'user.email', 'affected-tests@example.invalid')
  git(rootDir, 'config', 'user.name', 'Affected Tests')
  fs.mkdirSync(path.dirname(sourcePath), { recursive: true })
  fs.writeFileSync(sourcePath, 'export const value = 1\n')
  git(rootDir, 'add', '.')
  git(rootDir, 'commit', '-m', 'add source')
  const base = git(rootDir, 'rev-parse', 'HEAD')

  fs.rmSync(sourcePath)
  assert.deepEqual(readChangedFiles({ rootDir }), ['pages/example.js'])

  git(rootDir, 'add', '-A')
  git(rootDir, 'commit', '-m', 'remove source')
  const head = git(rootDir, 'rev-parse', 'HEAD')
  assert.deepEqual(readChangedFiles({ rootDir, base, head }), ['pages/example.js'])
})

test('base/head change sets retain both sides of a cross-root rename', async (t) => {
  const { readChangedFiles } = await loadAffected()
  const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'affected-renamed-'))
  t.after(() => fs.rmSync(rootDir, { recursive: true, force: true }))
  const sharedPath = path.join(rootDir, 'components/shared.js')
  const localPath = path.join(rootDir, 'pages/local.js')

  git(rootDir, 'init')
  git(rootDir, 'config', 'user.email', 'affected-tests@example.invalid')
  git(rootDir, 'config', 'user.name', 'Affected Tests')
  fs.mkdirSync(path.dirname(sharedPath), { recursive: true })
  fs.writeFileSync(sharedPath, 'export const value = 1\n')
  git(rootDir, 'add', '.')
  git(rootDir, 'commit', '-m', 'add shared source')
  const base = git(rootDir, 'rev-parse', 'HEAD')

  fs.mkdirSync(path.dirname(localPath), { recursive: true })
  fs.renameSync(sharedPath, localPath)
  git(rootDir, 'add', '-A')
  git(rootDir, 'commit', '-m', 'move source')
  const head = git(rootDir, 'rev-parse', 'HEAD')

  assert.deepEqual(readChangedFiles({ rootDir, base, head }), [
    'components/shared.js',
    'pages/local.js',
  ])
})

test('maps knowledge tooling and workflow changes to governance suites', async () => {
  const { selectAffectedTests } = await loadAffected()
  const graph = await fixtureGraph()

  const knowledge = selectAffectedTests({
    graph,
    changedFiles: ['scripts/knowledge-graph/affected-tests.mjs'],
  })
  assert.equal(knowledge.mode, 'targeted')
  assert.deepEqual(knowledge.reasons, ['knowledge-tooling-change'])
  assert.deepEqual(knowledge.tests, ['tests/knowledge-graph'])

  const workflow = selectAffectedTests({
    graph,
    changedFiles: ['.github/workflows/project-quality.yml'],
  })
  assert.equal(workflow.mode, 'targeted')
  assert.deepEqual(workflow.reasons, ['automation-config-change'])
  assert.deepEqual(workflow.tests, ['tests/project-governance'])
})

test('full execution includes offline tests outside the five primary roots', async () => {
  const { FULL_TEST_ROOTS } = await loadAffected()

  assert.ok(
    FULL_TEST_ROOTS.includes(
      'tabWorkOrder/pages/refundApply/tests/refundApplyMarketing.test.mjs',
    ),
  )
  assert.ok(
    FULL_TEST_ROOTS.includes(
      'packageDynamicForm/pages/upgradeStaffDaily/tests/dailyReportInconsistency.helpers.test.mjs',
    ),
  )
})

test('affected CLI graph is rebuilt from current sources instead of stale artifacts', async (t) => {
  const { buildCurrentGraph } = await loadAffected()
  const rootDir = fs.mkdtempSync(path.join(os.tmpdir(), 'affected-current-graph-'))
  t.after(() => fs.rmSync(rootDir, { recursive: true, force: true }))
  fs.cpSync(fixtureRoot, rootDir, { recursive: true })
  const generatedPath = path.join(rootDir, 'docs/generated')
  fs.mkdirSync(generatedPath, { recursive: true })
  fs.writeFileSync(
    path.join(generatedPath, 'knowledge-graph.json'),
    '{"schemaVersion":"stale","nodes":[],"edges":[],"unresolved":[],"stats":{}}\n',
  )

  const graph = await buildCurrentGraph(rootDir)
  assert.equal(graph.schemaVersion, '1.0.0')
  assert.ok(graph.nodes.some((node) => node.id === 'page:pages/home/home'))
})