Skip to content

[Hackathon] fix(report): same-name tests collapse into one JUnit result in GitLab #515

Closed

Description

@luckyzd

Verified against (commit SHA or released version)

Public main 988c0355bb05631e9c6c1785e443937ff2a88c0e, package v0.14.0, checked again on 2026-10-18. Node v24.19.0, macOS. Rebuilt from the clean checkout. Reproduced through the real compiled CLI in a child process with HTTP fully intercepted; no hosted tests, real credentials or credits were used.

Discord Username / User ID

luckyzd.

What does this improvement do?

Give each distinct test a stable, unique JUnit identity while retaining its readable title. Currently, different tests named Checkout are emitted with the same testsuite / classname / name; the differing testId and runId attributes do not distinguish them for standard consumers.

A normal multi-project test list can contain a Checkout test from each project. With both tests failing, TestSprite's JSON and raw XML correctly contain two failures, but importing those cases through GitLab's actual public TestCase / TestSuite classes retains one failure and one run's diagnostic text. The CLI still exits 1: this is report data loss and undercounting, not a demonstrated green process exit or a hosted GitLab incident.

Details / implementation notes

Trigger and observations

  1. Put two distinct tests from two projects into one test list, both with the human title Checkout.
  2. Run testsprite --output json testlist run <list-id> --wait --report junit --report-file results.xml --summary-file summary.json.
  3. Both accepted run IDs finish failed. Collect the JUnit artifact in a CI report consumer using standard JUnit identities, such as GitLab.

Current output (no malformed XML or missing dispatches):

<testsuite name="testsprite:testlist:list" tests="2" failures="2" errors="0" skipped="0" time="5">
  <testcase classname="testlist:list" name="Checkout" testId="a" runId="run_a" time="2.5">
    <failure message="failed" type="failed">status: failed
runId: run_a</failure>
  </testcase>
  <testcase classname="testlist:list" name="Checkout" testId="b" runId="run_b" time="2.5">
    <failure message="failed" type="failed">status: failed
runId: run_b</failure>
  </testcase>
</testsuite>

Expected: both distinct logical tests remain distinct in the consumer, with both run identities/diagnostics retained and the failure count remaining 2. Stable logical test IDs should participate in the standard identity fields; using ephemeral run IDs as the identity would damage cross-run comparison.

Actual offline consumer check: GitLab's unmodified classes retain only run_b's failure and report total_count == 1, failed_count == 1. Changing only the titles to Checkout A / Checkout B keeps both failures. Missing titles also keep both because the current builder falls back to testId.

Evidence and contract

  • The CLI's JUnit builder prefers the human name. testId / runId are additional attributes, not part of the standard name/class identity.
  • testlist report assembly intentionally uses one classname for the whole multi-project list. The collision therefore does not require duplicate titles within one project.
  • GitLab documentation requires unique test names/classes to avoid missing results.
  • Checked the actual consumer source too: TestCase identity hashes suite/class/name; TestSuite collection assigns by status and key; JUnit parser mapping does not forward testId or runId. The local check uses these real, unchanged classes and the parser's field mapping, not a hand-written deduplication substitute.

Because this GitLab implementation partitions by status, a same-name pass/fail pair does not collapse in the tested collector. I am deliberately limiting the claim to the observed same-status collisions, not inferring a hidden failure from the broader documentation wording.

Offline actual-command fixture JSON / raw XML rows GitLab collector rows CLI exit
Same name, both failed, same project 2 1 1
Same name, both failed, different projects 2 1 1
Same name, both passed 2 1 0
Same name, one passed and one failed (control) 2 2 1
Different names, both failed (control) 2 2 1
Missing names, fallback to distinct IDs (control) 2 2 1

The cross-project collision and the two naming controls were additionally run through dist/index.js in separate processes; each exited 1 and produced JSON with total=2/failed=2. Those generated XML artifacts were then consumed by the same actual GitLab classes, yielding 1/2/2 records respectively. This is an offline command/consumer reproduction, not a claim that a live service returned the fixture values.

Duplicate check and scope

Searched open and closed Issues/PRs for JUnit + duplicate, same name, classname, collision, GitLab, and missing records; read #95, #396, #476 and PR #96's inline reviews, reviews and discussion.

Suggested scope: make standard JUnit testcase identity stable and unique per logical test, including multi-project lists, while preserving readable names, existing XML escaping, run metadata, timing and exit codes. Test same-title cases, absent titles, and consumer cardinality; do not require users to rename unrelated tests across projects.

Build passed. Existing focused tests passed: 221 tests / 6 files (JUnit, CI summary, testlist, flaky, wait and schedule writes). These passing tests do not cover/fix the reproduction.

This is an issue-first Season 4 CLI Improvement Bonus submission. I will wait for maintainer acceptance and assignment before implementation or a PR. AI disclosure: Codex assisted with source review, offline reproduction and duplicate checking.

Executable offline reproduction: real CLI plus actual GitLab collector

Requires the repository's dependencies and a supported Node version. Save the following as reproduce-junit-name-collision.mjs, build the repository, then run node reproduce-junit-name-collision.mjs /absolute/path/to/testsprite-cli > evidence.json. The script intercepts every fetch, uses a fake key, and cleans its own temporary directory.

import assert from 'node:assert/strict';
import {execFile} from 'node:child_process';
import {mkdtemp,readFile,writeFile,rm} from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {join,resolve} from 'node:path';
import {promisify} from 'node:util';

// Run the real compiled CLI with all HTTP intercepted. No hosted service or
// real API key is used. Both cases belong to an ordinary multi-project list.
const root=resolve(process.argv[2]??'work/testsprite-cli');
const temp=await mkdtemp(join(tmpdir(),'testsprite-junit-name-'));
const exec=promisify(execFile),preload=join(temp,'fixture.mjs');
await writeFile(preload,`
import assert from 'node:assert/strict';
const names=JSON.parse(process.env.FIXTURE_NAMES);
const stamp='2026-10-18T00:00:00.000Z';
const json=body=>new Response(JSON.stringify(body),{status:200,headers:{'content-type':'application/json'}});
const cases=['a','b'].map((id,i)=>({testId:id,type:'frontend',projectId:'project_'+id,projectName:'Project '+id,title:names[i],category:null,priority:null,modified:null,status:'ready'}));
globalThis.fetch=async(input,init={})=>{
 const u=new URL(typeof input==='string'?input:input.url??input.href);
 assert.equal(u.hostname,'mock.example.com','unexpected network destination');
 const p=u.pathname.replace('/api/cli/v1',''),method=init.method??'GET';
 if(method==='GET'&&p==='/testlist/list')return json({id:'list',name:'Fixture',orgId:'org',caseCount:2,projectEnvironments:[],lastExecutionId:null,createdAt:stamp,updatedAt:stamp,cases,stats:{total:2,passed:0,failed:0,blocked:0,running:0},lastExecutionCreated:null});
 if(p==='/projects/project_a/env'||p==='/projects/project_b/env')return json({environments:[{name:'default',url:'https://example.com',isDefault:true,isTemporary:false}]});
 if(method==='POST'&&p==='/testlist/list/run')return json({accepted:cases.map(c=>({testId:c.testId,runId:'run_'+c.testId,enqueuedAt:stamp})),conflicts:[],deferred:[]});
 const c=cases.find(c=>p==='/runs/run_'+c.testId);
 if(method==='GET'&&c){
  if(c.testId==='b')await new Promise(r=>setTimeout(r,25));
  return json({runId:'run_'+c.testId,testId:c.testId,projectId:c.projectId,userId:'fixture',status:'failed',source:'cli',createdAt:stamp,startedAt:stamp,finishedAt:'2026-10-18T00:00:02.500Z',codeVersion:'v1',targetUrl:'https://example.com',createdFrom:'cli',failedStepIndex:0,failureKind:'assertion',error:'Fixture assertion failed',videoUrl:null,testTitle:c.title,stepSummary:{total:1,completed:1,passedCount:0,failedCount:1}});
 }
 throw new Error('Unexpected fixture route '+method+' '+p);
};
`);
const records=[];
try {
 for(const names of [['Checkout','Checkout'],['Checkout A','Checkout B'],[null,null]]){
  const reportFile=join(temp,'results.xml'),summaryFile=join(temp,'summary.json');
  let stdout='',stderr='',exitCode=0;
  try {({stdout,stderr}=await exec(process.execPath,['--import',preload,join(root,'dist/index.js'),'--output','json','testlist','run','list','--wait','--timeout','3','--report','junit','--report-file',reportFile,'--summary-file',summaryFile],{
   cwd:temp,timeout:10000,env:{PATH:process.env.PATH,TESTSPRITE_API_KEY:'sk-user-offline',TESTSPRITE_API_URL:'https://mock.example.com',TESTSPRITE_NO_TELEMETRY:'1',TESTSPRITE_NO_UPDATE_NOTIFIER:'1',FIXTURE_NAMES:JSON.stringify(names)}
  }));}catch(e){if(typeof e.code!=='number')throw e;exitCode=e.code;stdout=e.stdout;stderr=e.stderr;}
  assert.equal(exitCode,1,stderr);
  const xml=await readFile(reportFile,'utf8'),summary=JSON.parse(await readFile(summaryFile,'utf8'));
  assert.equal(summary.total,2);assert.equal(summary.failed,2);
  const identities=[...xml.matchAll(/<testcase classname="([^"]*)" name="([^"]*)"/g)].map(x=>[x[1],x[2]]);
  assert.equal(identities.length,2);
  const uniqueKeys=new Set(identities.map(JSON.stringify)).size;
  assert.equal(uniqueKeys,names[0]==='Checkout'?1:2);
  records.push({names,exitCode,summary,identities,uniqueKeys,xml,stdout,stderr});
 }
 console.log(JSON.stringify({node:process.version,scope:'offline full CLI subprocess; no hosted observations',records},null,2));
}finally{await rm(temp,{recursive:true,force:true});}

For the consumer check, download the two unchanged Ruby files linked above at revision fa6a63c43dd8050dd297c4eae1bdbf9e0cfd7ff1 into a directory as test_case.rb and test_suite.rb. Save this as check-junit-name-collision.rb. Run ruby check-junit-name-collision.rb evidence.json /path/to/that/directory with Ruby and REXML installed. It imports the generated XML into GitLab's actual collector and asserts counts of 1, 2 and 2.

# Uses the unmodified GitLab TestCase and TestSuite source files from the
# pinned official mirror revision below; this is an offline collector check.
require 'digest'
require 'json'
require 'rexml/document'
require File.expand_path('test_case.rb', ARGV.fetch(1))
require File.expand_path('test_suite.rb', ARGV.fetch(1))
results = JSON.parse(File.read(ARGV.fetch(0))).fetch('records').map do |record|
  xml = REXML::Document.new(record.fetch('xml'))
  suite = Gitlab::Ci::Reports::TestSuite.new('fixture-job')
  REXML::XPath.match(xml, '//testcase').each do |tc|
    suite.add_test_case(Gitlab::Ci::Reports::TestCase.new(
      suite_name: tc.parent.attributes['name'], classname: tc.attributes['classname'],
      name: tc.attributes['name'], execution_time: tc.attributes['time'],
      status: tc.elements['failure'] ? 'failed' : 'success',
      system_output: tc.elements['failure']&.text
    ))
  end
  expected = record['names'] == ['Checkout', 'Checkout'] ? 1 : 2
  raise 'Unexpected consumer count' unless suite.total_count == expected
  { names: record['names'], cli_exit: record['exitCode'], json_total: record['summary']['total'],
    gitlab_total: suite.total_count, gitlab_failed: suite.failed_count,
    retained_outputs: suite.failed.values.map(&:system_output) }
end
puts JSON.pretty_generate(results)

Confirmations

  • I have searched existing issues and this is not a duplicate.
  • I have provided my Discord identity above for reward coordination.

Activity

  1. added
    needs-triage
    hackathon
    on Oct 18, 2026
  2. fyZhang66 commented on Oct 20, 2026

    @fyZhang66
    Contributor

    Plausible from the code, thanks @luckyzd: junit-report.ts names each case by title and keeps the test id only in a non-standard attribute, so two same-named tests share classname/name. We have not run GitLab's importer ourselves. Accepted, scope:

    • Make the identity unique only when two cases in one report would collide (append a short testId suffix to name); readable titles stay unchanged otherwise.
    • Tests (must fail before the fix): two same-named tests produce distinct names; a report without collisions is byte-identical to today.

    We'll review #521 against this; a before/after screenshot from GitLab's test report in the PR would confirm it. No new dependency.

  3. added
    accepted
    and removed
    needs-triage
    on Oct 20, 2026
  4. Herbicide7665 commented on Oct 21, 2026

    @Herbicide7665
    Contributor

    /assign

    Discord: weili_yang33

  5. added
    in-progress
    on Oct 21, 2026
  6. testsprite-hob commented on Oct 21, 2026

    @testsprite-hob

    Assigned to @Herbicide7665. Thanks for taking this on. (2 more slots available.)

    Your open assigned issues (1/3):
    (none)

  7. Herbicide7665 commented on Oct 21, 2026

    @Herbicide7665
    Contributor

    Yielding this one — I hadn't noticed #521 (opened pre-acceptance) already covers the accepted scope, and @luckyzd should keep it. Please feel free to unassign me. Happy to keep an eye on the remaining unclaimed accepted issues instead.

  8. Herbicide7665 commented on Oct 21, 2026

    @Herbicide7665
    Contributor

    /unassign

  9. removed
    in-progress
    on Oct 21, 2026
  10. testsprite-hob commented on Oct 21, 2026

    @testsprite-hob

    Unassigned @Herbicide7665. Thanks for the update — freeing this up for someone else.

  11. zhengqiuyang commented on Nov 3, 2026

    @zhengqiuyang
    Contributor

    /assign

  12. added
    in-progress
    on Nov 3, 2026
  13. testsprite-hob commented on Nov 3, 2026

    @testsprite-hob

    Assigned to @zhengqiuyang. Thanks for taking this on. (0 more slots available.)

    Your open assigned issues (3/3):

  14. added a commit that references this issue on Nov 10, 2026
    9d35e98
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

acceptedhackathonin-progress

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions