diff --git a/README.md b/README.md index ac1fed44..c6d4bc10 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,7 @@ This is an [Electron](https://electronjs.org/) app. The shell is built with elec `yarn test:e2e` builds the shell, then [Playwright](https://playwright.dev/) launches `out/main/index.js`. There is no dev server. Specs in `e2e/` check the UI and output files: -- `modeltest-then-raxml-ng.spec.js` — ModelTest, then a full raxml-ng analysis -- `raxmlHPC.spec.js` — classic raxmlHPC (ML search), including copying the command and the citation +- `modeltest-outcome.spec.js` — ModelTest, then a raxml-ng tree inference and a serial raxmlHPC ML search with the model it picked, each checked against a per-host fixture in `e2e/fixtures/`. The raxmlHPC test also copies the command and the citation Download binaries once, then run: diff --git a/e2e/fixtures/darwin-arm64/modeltest.json b/e2e/fixtures/darwin-arm64/modeltest.json new file mode 100644 index 00000000..1725c45f --- /dev/null +++ b/e2e/fixtures/darwin-arm64/modeltest.json @@ -0,0 +1,28 @@ +{ + "settings": { + "seed": 12345, + "runs": 1, + "analysis": "modeltest", + "criterion": "AICc", + "binary": "modeltest-ng-ARM64", + "binaryVersions": { + "modeltest-ng": "0.1.7" + } + }, + "outcome": { + "criteria": { + "BIC": { + "model": "TPM2uf+I", + "score": 2639.0324 + }, + "AIC": { + "model": "TVM+I", + "score": 2460.0698 + }, + "AICc": { + "model": "TVM+I", + "score": 2465.0698 + } + } + } +} diff --git a/e2e/fixtures/darwin-arm64/raxml-ng.json b/e2e/fixtures/darwin-arm64/raxml-ng.json new file mode 100644 index 00000000..f623f018 --- /dev/null +++ b/e2e/fixtures/darwin-arm64/raxml-ng.json @@ -0,0 +1,16 @@ +{ + "settings": { + "seed": 12345, + "runs": 1, + "analysis": "TI", + "binary": "raxml-ng", + "binaryVersions": { + "raxml-ng": "1.2.2" + } + }, + "outcome": { + "model": "TVM+FO+I", + "logLikelihood": -1184.201009, + "bestTree": "(TAXON_1:0.011965,((((TAXON_5:0.004875,(TAXON_11:0.000001,TAXON_13:0.000001):0.003275):0.001605,TAXON_10:0.001653):0.001599,(((((TAXON_9:0.003212,(((TAXON_15:0.001593,(TAXON_2:0.010048,TAXON_4:0.003299):0.000001):0.001582,TAXON_7:0.001567):0.000001,TAXON_3:0.003190):0.000001):0.001632,TAXON_6:0.003863):0.003130,(TAXON_8:0.004816,TAXON_14:0.000001):0.001588):0.000001,TAXON_16:0.000001):0.001871,TAXON_17:0.000001):0.000001):0.001503,TAXON_18:0.000328):0.001611,TAXON_19:0.002346);" + } +} diff --git a/e2e/fixtures/darwin-arm64/raxmlHPC.json b/e2e/fixtures/darwin-arm64/raxmlHPC.json new file mode 100644 index 00000000..99824612 --- /dev/null +++ b/e2e/fixtures/darwin-arm64/raxmlHPC.json @@ -0,0 +1,16 @@ +{ + "settings": { + "seed": 12345, + "runs": 1, + "analysis": "ML", + "binary": "raxmlHPC", + "binaryVersions": { + "raxmlHPC": "8.2.12" + } + }, + "outcome": { + "model": "GTRCATIX", + "score": -1183.120275, + "bestTree": "(TAXON_19:0.00244607530621962976,(((TAXON_10:0.00165460077468338688,(TAXON_5:0.00490169990410668430,(TAXON_11:0.00000100000050002909,TAXON_13:0.00000100000050002909):0.00326460786816565492):0.00159662967916767979):0.00159732624854270924,(TAXON_17:0.00000100000050002909,(((((((TAXON_15:0.00161828822768687029,(TAXON_2:0.01023582658137301565,TAXON_4:0.00340503013899453926):0.00000100000050002909):0.00158288002901413468,TAXON_7:0.00160944904780967483):0.00000100000050002909,TAXON_3:0.00326681961445571571):0.00002345716699163092,TAXON_9:0.00327614007924441385):0.00149308198240371724,TAXON_6:0.00422084577883892823):0.00327631431077851643,TAXON_16:0.00000100000050002909):0.00000100000050002909,(TAXON_14:0.00000100000050002909,TAXON_8:0.00490291155260013604):0.00160702621607535195):0.00191993844272083020):0.00000100000050002909):0.00013743433944014784,TAXON_18:0.00153047559521670459):0.00168622373656522064,TAXON_1:0.01197460871080295412):0.0;" + } +} diff --git a/e2e/fixtures/linux-x64/modeltest.json b/e2e/fixtures/linux-x64/modeltest.json new file mode 100644 index 00000000..c86ca19b --- /dev/null +++ b/e2e/fixtures/linux-x64/modeltest.json @@ -0,0 +1,28 @@ +{ + "settings": { + "seed": 12345, + "runs": 1, + "analysis": "modeltest", + "criterion": "AICc", + "binary": "modeltest-ng", + "binaryVersions": { + "modeltest-ng": "x.y.z" + } + }, + "outcome": { + "criteria": { + "BIC": { + "model": "TPM2uf+I", + "score": 2638.9532 + }, + "AIC": { + "model": "TVM+I", + "score": 2460.0397 + }, + "AICc": { + "model": "TVM+I", + "score": 2465.0397 + } + } + } +} diff --git a/e2e/fixtures/linux-x64/raxml-ng.json b/e2e/fixtures/linux-x64/raxml-ng.json new file mode 100644 index 00000000..9090dbfe --- /dev/null +++ b/e2e/fixtures/linux-x64/raxml-ng.json @@ -0,0 +1,16 @@ +{ + "settings": { + "seed": 12345, + "runs": 1, + "analysis": "TI", + "binary": "raxml-ng", + "binaryVersions": { + "raxml-ng": "1.2.2-master" + } + }, + "outcome": { + "model": "TVM+FO+I", + "logLikelihood": -1184.201361, + "bestTree": "(TAXON_7:0.001567,((TAXON_2:0.010036,TAXON_4:0.003295):0.000001,TAXON_15:0.001591):0.001580,((TAXON_9:0.003208,(TAXON_6:0.003858,((TAXON_14:0.000001,TAXON_8:0.004812):0.001587,(TAXON_16:0.000001,(((((TAXON_11:0.000001,TAXON_13:0.000001):0.003272,TAXON_5:0.004870):0.001604,TAXON_10:0.001652):0.001598,((TAXON_1:0.011966,TAXON_19:0.002344):0.001603,TAXON_18:0.000332):0.001502):0.000001,TAXON_17:0.000001):0.001876):0.000001):0.003137):0.001589):0.000044,TAXON_3:0.003188):0.000001);" + } +} diff --git a/e2e/fixtures/linux-x64/raxmlHPC.json b/e2e/fixtures/linux-x64/raxmlHPC.json new file mode 100644 index 00000000..26a48742 --- /dev/null +++ b/e2e/fixtures/linux-x64/raxmlHPC.json @@ -0,0 +1,16 @@ +{ + "settings": { + "seed": 12345, + "runs": 1, + "analysis": "ML", + "binary": "raxmlHPC", + "binaryVersions": { + "raxmlHPC": "8.2.12" + } + }, + "outcome": { + "model": "GTRCATIX", + "score": -1183.120275, + "bestTree": "(TAXON_19:0.00244607530473719102,(((TAXON_10:0.00165460077670411400,(TAXON_5:0.00490169990999902820,(TAXON_11:0.00000100000050002909,TAXON_13:0.00000100000050002909):0.00326460787716503342):0.00159662968071902674):0.00159732625053941239,(TAXON_17:0.00000100000050002909,(((((((TAXON_15:0.00161828823041654875,(TAXON_2:0.01023582659058935168,TAXON_4:0.00340503014194076066):0.00000100000050002909):0.00158288003065052709,TAXON_7:0.00160944905088082754):0.00000100000050002909,TAXON_3:0.00326681961677442951):0.00002345717677958670,TAXON_9:0.00327614008220529279):0.00149308199646746675,TAXON_6:0.00422084576034152930):0.00327631430549322035,TAXON_16:0.00000100000050002909):0.00000100000050002909,(TAXON_14:0.00000100000050002909,TAXON_8:0.00490291155601087995):0.00160702621743578325):0.00191993844408858399):0.00000100000050002909):0.00013743440375832238,TAXON_18:0.00153047555790677883):0.00168622372143269867,TAXON_1:0.01197460875703067369):0.0;" + } +} diff --git a/e2e/fixtures/win32-x64/modeltest.json b/e2e/fixtures/win32-x64/modeltest.json new file mode 100644 index 00000000..df3a981e --- /dev/null +++ b/e2e/fixtures/win32-x64/modeltest.json @@ -0,0 +1,28 @@ +{ + "settings": { + "seed": 12345, + "runs": 1, + "analysis": "modeltest", + "criterion": "AICc", + "binary": "modeltest-ng.exe", + "binaryVersions": { + "modeltest-ng": "0.1.7" + } + }, + "outcome": { + "criteria": { + "BIC": { + "model": "TPM2uf+I", + "score": 2639.0324 + }, + "AIC": { + "model": "TVM+I", + "score": 2460.0698 + }, + "AICc": { + "model": "TVM+I", + "score": 2465.0698 + } + } + } +} diff --git a/e2e/fixtures/win32-x64/raxmlHPC.json b/e2e/fixtures/win32-x64/raxmlHPC.json new file mode 100644 index 00000000..585bd4c0 --- /dev/null +++ b/e2e/fixtures/win32-x64/raxmlHPC.json @@ -0,0 +1,16 @@ +{ + "settings": { + "seed": 12345, + "runs": 1, + "analysis": "ML", + "binary": "raxmlHPC.exe", + "binaryVersions": { + "raxmlHPC": "8.2.12" + } + }, + "outcome": { + "model": "GTRCATIX", + "score": -1183.120275, + "bestTree": "(TAXON_19:0.00244607532222351374,(((TAXON_10:0.00165460077416372054,(TAXON_5:0.00490169990266712489,(TAXON_11:0.00000100000050002909,TAXON_13:0.00000100000050002909):0.00326460786435126384):0.00159662967851137904):0.00159732624784359616,(TAXON_17:0.00000100000050002909,(((((((TAXON_15:0.00161828822701187355,(TAXON_2:0.01023582658714253593,TAXON_4:0.00340503014127669940):0.00000100000050002909):0.00158288002917348161,TAXON_7:0.00160944904689838144):0.00000100000050002909,TAXON_3:0.00326681961657928179):0.00002345716191679346,TAXON_9:0.00327614007965075201):0.00149308197811563324,TAXON_6:0.00422084580040837411):0.00327631431276509703,TAXON_16:0.00000100000050002909):0.00000100000050002909,(TAXON_14:0.00000100000050002909,TAXON_8:0.00490291155409224542):0.00160702621604032355):0.00191993844179090024):0.00000100000050002909):0.00013743422052569246,TAXON_18:0.00153047566661464640):0.00168622376581414207,TAXON_1:0.01197460869009258147):0.0;" + } +} diff --git a/e2e/helpers/fixtures.js b/e2e/helpers/fixtures.js new file mode 100644 index 00000000..08347e87 --- /dev/null +++ b/e2e/helpers/fixtures.js @@ -0,0 +1,203 @@ +const fs = require('fs'); +const path = require('path'); +const { parseNewick, edges, compareTopologies } = require('./newick'); + +const RTOL = 1e-4; +const TREE_RTOL = 1e-3; +const REGENERATE = 'yarn test:e2e:update-fixtures'; + +/** @param {unknown} value */ +const show = (value) => + typeof value === 'string' ? value : JSON.stringify(value); + +/** @param {Record} obj @param {string} [prefix] */ +function flatten(obj, prefix = '') { + /** @type {Record} */ + const out = {}; + for (const [key, value] of Object.entries(obj)) { + const name = prefix ? `${prefix}.${key}` : key; + if (value && typeof value === 'object') { + Object.assign(out, flatten(value, name)); + } else { + out[name] = value; + } + } + return out; +} + +/** + * Differences between two Newick trees: topology exact (RF distance 0), then + * each branch length within TREE_RTOL relative to the larger length. + * @param {string} expected + * @param {string} actual + * @returns {{ field: string, expected: unknown, actual: unknown, delta: unknown, tolerance: string }[]} + */ +function compareTrees(expected, actual) { + const topology = compareTopologies(expected, actual); + if ('taxaMismatch' in topology) { + const { onlyInA, onlyInB } = topology.taxaMismatch; + return [ + { + field: 'bestTree taxa', + expected: `unique to fixture: ${onlyInA.join(' ') || 'none'}`, + actual: `unique to actual: ${onlyInB.join(' ') || 'none'}`, + delta: 'n/a', + tolerance: 'exact', + }, + ]; + } + if (topology.rf) { + return [ + { + field: 'bestTree topology', + expected: 'RF distance 0', + actual: `RF distance ${topology.rf}\n splits unique to fixture: ${topology.uniqueA.join(' | ') || 'none'}\n splits unique to actual: ${topology.uniqueB.join(' | ') || 'none'}`, + delta: topology.rf, + tolerance: 'exact', + }, + ]; + } + const ea = edges(parseNewick(expected)); + const eb = edges(parseNewick(actual)); + /** @type {ReturnType} */ + const diffs = []; + for (const [key, x] of ea) { + const y = eb.get(key); + if (typeof x !== 'number' || typeof y !== 'number') continue; + const delta = Number((y - x).toPrecision(6)); + if (Math.abs(delta) > TREE_RTOL * Math.max(Math.abs(x), Math.abs(y))) { + diffs.push({ + field: `bestTree branch ${key}`, + expected: x, + actual: y, + delta, + tolerance: `${TREE_RTOL} relative`, + }); + } + } + return diffs; +} + +/** + * Differing fields, binary versions first. Numbers agree within RTOL + * relative to the larger magnitude; everything else must be equal. A + * `bestTree` field is compared as a tree. + * @param {Record} expected + * @param {Record} actual + */ +function compareOutcome(expected, actual) { + const { bestTree: expectedTree, ...expectedRest } = expected; + const { bestTree: actualTree, ...actualRest } = actual; + const e = flatten(expectedRest); + const a = flatten(actualRest); + /** @type {{ field: string, expected: unknown, actual: unknown, delta: unknown, tolerance: string }[]} */ + const diffs = []; + if (expectedTree !== undefined || actualTree !== undefined) { + if (typeof expectedTree === 'string' && typeof actualTree === 'string') { + diffs.push(...compareTrees(expectedTree, actualTree)); + } else { + diffs.push({ + field: 'bestTree', + expected: expectedTree, + actual: actualTree, + delta: 'n/a', + tolerance: 'exact', + }); + } + } + for (const field of new Set([...Object.keys(e), ...Object.keys(a)])) { + const x = e[field]; + const y = a[field]; + if (typeof x === 'number' && typeof y === 'number') { + const delta = Number((y - x).toPrecision(6)); + if (Math.abs(delta) > RTOL * Math.max(Math.abs(x), Math.abs(y))) { + diffs.push({ + field, + expected: x, + actual: y, + delta, + tolerance: `${RTOL} relative`, + }); + } + } else if (x !== y) { + diffs.push({ + field, + expected: x, + actual: y, + delta: 'n/a', + tolerance: 'exact', + }); + } + } + const isVersion = (/** @type {{ field: string }} */ d) => + d.field.startsWith('binaryVersions'); + return [...diffs.filter(isVersion), ...diffs.filter((d) => !isVersion(d))]; +} + +/** + * @param {ReturnType} diffs + * @param {string} fixturePath + */ +function formatReport(diffs, fixturePath) { + const blocks = diffs.map( + (d) => + `${d.field}\n expected: ${show(d.expected)}\n actual: ${show(d.actual)}\n delta: ${show(d.delta)}\n tolerance: ${d.tolerance}`, + ); + return `${blocks.join('\n\n')}\n\nFixture: ${fixturePath}\nRegenerate: ${REGENERATE}`; +} + +/** + * The one entry point per run. Compares the outcome with this host's fixture, + * or writes the fixture when RAXMLGUI_UPDATE_FIXTURES is set. + * @param {string} name fixture file name without extension + * @param {Record & { binaryVersions: Record }} settings what the spec ran with + * @param {Record & { binaryVersions: Record }} actual parsed outcome + * @returns {{ ok: boolean, message: string }} + */ +function checkFixture(name, settings, actual) { + const host = `${process.platform}-${process.arch}`; + const fixturePath = path.join(__dirname, '..', 'fixtures', host, `${name}.json`); + const { binaryVersions, ...outcome } = actual; + + if (process.env.RAXMLGUI_UPDATE_FIXTURES === '1') { + // A fixture must not record a binary the spec does not declare + const diffs = compareOutcome( + { binaryVersions: settings.binaryVersions }, + { binaryVersions }, + ); + if (diffs.length) return { ok: false, message: formatReport(diffs, fixturePath) }; + fs.mkdirSync(path.dirname(fixturePath), { recursive: true }); + fs.writeFileSync( + fixturePath, + `${JSON.stringify({ settings, outcome }, null, 2)}\n`, + ); + return { ok: true, message: `Wrote ${fixturePath}` }; + } + + if (!fs.existsSync(fixturePath)) { + return { + ok: false, + message: `No fixture for ${host}: ${fixturePath}\nRegenerate: ${REGENERATE}`, + }; + } + const fixture = JSON.parse(fs.readFileSync(fixturePath, 'utf8')); + const drift = Object.keys({ ...fixture.settings, ...settings }).filter( + (key) => + JSON.stringify(fixture.settings[key]) !== JSON.stringify(settings[key]), + ); + if (drift.length) { + return { + ok: false, + message: `Settings differ from the fixture: ${drift.join(', ')}\nFixture: ${fixturePath}\nRegenerate: ${REGENERATE}`, + }; + } + const diffs = compareOutcome( + { binaryVersions: fixture.settings.binaryVersions, ...fixture.outcome }, + actual, + ); + return diffs.length + ? { ok: false, message: formatReport(diffs, fixturePath) } + : { ok: true, message: '' }; +} + +module.exports = { checkFixture, compareOutcome, formatReport }; diff --git a/e2e/helpers/modeltestOutcome.js b/e2e/helpers/modeltestOutcome.js new file mode 100644 index 00000000..5dec07e2 --- /dev/null +++ b/e2e/helpers/modeltestOutcome.js @@ -0,0 +1,25 @@ +/** + * Reduce a ModelTest-NG results file to what a fixture keeps: the tool + * version and, per criterion, the selected model and its score. Paths, thread + * counts, tree files and the per-model tables are left out. + * @param {string} text contents of RAxML_GUI_ModelTest_.out + * @returns {{ binaryVersions: Record, + * criteria: Record }} + */ +function parseModelTestLog(text) { + const version = /^ModelTest-NG v(\S+)/m.exec(text); + if (!version) throw new Error('ModelTest log: no version line'); + /** @type {Record} */ + const criteria = {}; + const blocks = + /^Best model according to (\S+)\n-+\nModel:\s+(\S+)\n(?:.*\n)*?Score:\s+(\S+)/gm; + for (const [, criterion, model, score] of text.matchAll(blocks)) { + criteria[criterion] = { model, score: Number(score) }; + } + if (!Object.keys(criteria).length) { + throw new Error('ModelTest log: no "Best model according to" block'); + } + return { binaryVersions: { 'modeltest-ng': version[1] }, criteria }; +} + +module.exports = { parseModelTestLog }; diff --git a/e2e/helpers/modeltestOutcome.test.js b/e2e/helpers/modeltestOutcome.test.js new file mode 100644 index 00000000..5c0e1945 --- /dev/null +++ b/e2e/helpers/modeltestOutcome.test.js @@ -0,0 +1,122 @@ +const { parseModelTestLog } = require('./modeltestOutcome'); +const { compareOutcome, formatReport } = require('./fixtures'); + +const log = `-------------------------------------------------------------------------------- +ModelTest-NG v0.1.7 + +Input data: + MSA: /Users/someone/static/example-files/fasta/nucleotide.txt + #taxa: 18 + +Output: + Log: /Users/someone/out.log + Results: /Users/someone/out.out + +Additional options: + threads: 2/10 + RNG seed: 12345 + +BIC model K lnL score delta weight +-------------------------------------------------------------------------------- + 1 TPM2uf+I 6 -1192.3928 2639.0324 0.0000 0.6626 +-------------------------------------------------------------------------------- +Best model according to BIC +--------------------------- +Model: TPM2uf+I +lnL: -1192.3928 +Frequencies: 0.3367 0.1353 0.1500 0.3780 +Score: 2639.0324 +Weight: 0.6626 +--------------------------- + +Commands: + > raxml-ng --msa /Users/someone/nucleotide.txt --model TPM2uf+I + +AICc model K lnL score delta weight +-------------------------------------------------------------------------------- +Best model according to AICc +--------------------------- +Model: TVM+I +lnL: -1189.0349 +Score: 2465.0698 +Weight: 0.2654 +--------------------------- +Done +`; + +describe('parseModelTestLog', () => { + it('keeps version, model and score per criterion and drops the rest', () => { + expect(parseModelTestLog(log)).toEqual({ + binaryVersions: { 'modeltest-ng': '0.1.7' }, + criteria: { + BIC: { model: 'TPM2uf+I', score: 2639.0324 }, + AICc: { model: 'TVM+I', score: 2465.0698 }, + }, + }); + }); + + it('throws on a log with no result block', () => { + expect(() => parseModelTestLog('ModelTest-NG v0.1.7\n')).toThrow(/Best model/); + }); +}); + +describe('failure report', () => { + const expected = { + binaryVersions: { 'modeltest-ng': '0.1.7' }, + criteria: { AICc: { model: 'TVM+I', score: 2465.0698 } }, + }; + + it('accepts a score inside the relative tolerance', () => { + const actual = { ...expected, criteria: { AICc: { model: 'TVM+I', score: 2465.2 } } }; + expect(compareOutcome(expected, actual)).toEqual([]); + }); + + it('lists the binary version first, one block per field, then fixture and command', () => { + const actual = { + binaryVersions: { 'modeltest-ng': '0.1.8' }, + criteria: { AICc: { model: 'GTR+I', score: 2500 } }, + }; + const diffs = compareOutcome(expected, actual); + expect(diffs[0].field).toBe('binaryVersions.modeltest-ng'); + expect(formatReport(diffs, '/fx/modeltest.json')).toBe( + [ + 'binaryVersions.modeltest-ng\n expected: 0.1.7\n actual: 0.1.8\n delta: n/a\n tolerance: exact', + 'criteria.AICc.model\n expected: TVM+I\n actual: GTR+I\n delta: n/a\n tolerance: exact', + 'criteria.AICc.score\n expected: 2465.0698\n actual: 2500\n delta: 34.9302\n tolerance: 0.0001 relative', + ].join('\n\n') + + '\n\nFixture: /fx/modeltest.json\nRegenerate: yarn test:e2e:update-fixtures', + ); + }); +}); + +describe('tree comparison', () => { + const tree = '((A:0.1,B:0.2):0.05,C:0.3,D:0.4);'; + const expected = { bestTree: tree }; + + it('accepts branch lengths inside 1e-3 relative', () => { + const actual = { bestTree: '((A:0.1,B:0.2):0.05,C:0.3,D:0.4001);' }; + expect(compareOutcome(expected, actual)).toEqual([]); + }); + + it('reports the RF distance and the unique splits for a changed topology', () => { + const actual = { bestTree: '((A:0.1,C:0.3):0.05,B:0.2,D:0.4);' }; + const [diff] = compareOutcome(expected, actual); + expect(diff.field).toBe('bestTree topology'); + expect(diff.delta).toBe(2); + expect(diff.actual).toContain('splits unique to fixture: C,D'); + expect(diff.actual).toContain('splits unique to actual: B,D'); + }); + + it('reports expected, actual, delta and tolerance for a branch length', () => { + const actual = { bestTree: '((A:0.1,B:0.2):0.05,C:0.3,D:0.5);' }; + expect(compareOutcome(expected, actual)).toEqual([ + { + field: 'bestTree branch D', + expected: 0.4, + actual: 0.5, + delta: 0.1, + tolerance: '0.001 relative', + }, + ]); + }); +}); diff --git a/e2e/helpers/newick.js b/e2e/helpers/newick.js new file mode 100644 index 00000000..e264dabb --- /dev/null +++ b/e2e/helpers/newick.js @@ -0,0 +1,172 @@ +/** + * @typedef {{ name: string, length: number | null, children: Node[] }} Node + */ + +/** + * Parse a Newick string. Support values on internal nodes are read as names. + * @param {string} text + * @returns {Node} + */ +function parseNewick(text) { + const s = text.trim(); + let i = 0; + + const readLabel = () => { + let out = ''; + if (s[i] === "'") { + i++; + while (i < s.length && s[i] !== "'") out += s[i++]; + i++; + return out; + } + while (i < s.length && !'(),:;'.includes(s[i])) out += s[i++]; + return out.trim(); + }; + + /** @returns {Node} */ + const readNode = () => { + /** @type {Node[]} */ + const children = []; + if (s[i] === '(') { + do { + i++; + children.push(readNode()); + } while (s[i] === ','); + if (s[i] !== ')') throw new Error(`Newick: expected ')' at ${i}`); + i++; + } + const name = readLabel(); + let length = null; + if (s[i] === ':') { + i++; + const start = i; + while (i < s.length && !'(),;'.includes(s[i])) i++; + length = Number(s.slice(start, i)); + if (Number.isNaN(length)) throw new Error(`Newick: bad length at ${start}`); + } + return { name, length, children }; + }; + + const root = readNode(); + if (s[i] === ';') i++; + if (i < s.length) throw new Error(`Newick: unexpected '${s[i]}' at ${i}`); + return root; +} + +/** @param {Node} node @returns {string[]} */ +function leafNames(node) { + return node.children.length + ? node.children.flatMap(leafNames) + : [node.name]; +} + +/** @param {string | Node} tree @returns {string[]} sorted taxa */ +function getTaxa(tree) { + return leafNames(typeof tree === 'string' ? parseNewick(tree) : tree).sort(); +} + +/** + * Edges of the unrooted tree as split key -> length. A split key is the + * sorted taxa on the side without the first taxon, joined by ','. Leaf edges + * use the taxon name as key. The two root edges of a rooted tree merge. + * @param {Node} root + * @returns {Map} + */ +function edges(root) { + const first = getTaxa(root)[0]; + /** @type {Map} */ + const out = new Map(); + /** @param {Node} node */ + const walk = (node, isRoot) => { + const leaves = leafNames(node).sort(); + if (!isRoot) { + const key = node.children.length + ? (leaves.includes(first) + ? getTaxa(root).filter((t) => !leaves.includes(t)) + : leaves + ).join(',') + : node.name; + const prev = out.get(key); + out.set( + key, + prev === undefined + ? node.length + : prev === null || node.length === null + ? null + : prev + node.length, + ); + } + node.children.forEach((c) => walk(c, false)); + }; + walk(root, true); + return out; +} + +/** @param {Node} root @returns {Set} non-trivial splits */ +function splits(root) { + return new Set([...edges(root).keys()].filter((k) => k.includes(','))); +} + +/** + * @param {string} a Newick + * @param {string} b Newick + * @returns {{ taxaMismatch: { onlyInA: string[], onlyInB: string[] } } + * | { rf: number, uniqueA: string[], uniqueB: string[] }} + */ +function compareTopologies(a, b) { + const ta = parseNewick(a); + const tb = parseNewick(b); + const taxaA = getTaxa(ta); + const taxaB = getTaxa(tb); + const onlyInA = taxaA.filter((t) => !taxaB.includes(t)); + const onlyInB = taxaB.filter((t) => !taxaA.includes(t)); + if (onlyInA.length || onlyInB.length) { + return { taxaMismatch: { onlyInA, onlyInB } }; + } + const sa = splits(ta); + const sb = splits(tb); + const uniqueA = [...sa].filter((k) => !sb.has(k)).sort(); + const uniqueB = [...sb].filter((k) => !sa.has(k)).sort(); + return { rf: uniqueA.length + uniqueB.length, uniqueA, uniqueB }; +} + +/** + * Compare matching branch lengths. Two lengths agree when they differ by at + * most max(atol, rtol * larger); atol keeps near-zero branches from failing. + * @param {string} a Newick + * @param {string} b Newick + * @param {{ rtol?: number, atol?: number }} [options] + * @returns {{ ok: boolean, mismatches: string[] }} + */ +function compareBranchLengths(a, b, { rtol = 0.01, atol = 1e-6 } = {}) { + const ea = edges(parseNewick(a)); + const eb = edges(parseNewick(b)); + /** @type {string[]} */ + const mismatches = []; + for (const [key, la] of ea) { + if (!eb.has(key)) { + mismatches.push(`${key}: missing in second tree`); + continue; + } + const lb = eb.get(key); + if (la === null || lb === null || lb === undefined) { + if (la !== lb) mismatches.push(`${key}: length present in one tree only`); + continue; + } + if (Math.abs(la - lb) > Math.max(atol, rtol * Math.max(Math.abs(la), Math.abs(lb)))) { + mismatches.push(`${key}: ${la} vs ${lb}`); + } + } + for (const key of eb.keys()) { + if (!ea.has(key)) mismatches.push(`${key}: missing in first tree`); + } + return { ok: mismatches.length === 0, mismatches }; +} + +module.exports = { + parseNewick, + getTaxa, + edges, + compareTopologies, + compareBranchLengths, +}; diff --git a/e2e/helpers/newick.test.js b/e2e/helpers/newick.test.js new file mode 100644 index 00000000..f824768b --- /dev/null +++ b/e2e/helpers/newick.test.js @@ -0,0 +1,52 @@ +const { + parseNewick, + getTaxa, + compareTopologies, + compareBranchLengths, +} = require('./newick'); + +describe('newick helpers', () => { + it('parses branch lengths and lists taxa', () => { + const tree = parseNewick('((A:0.1,B:0.2):0.3,(C:0.4,D:0.5):0.6);'); + expect(tree.children[0].length).toBe(0.3); + expect(tree.children[0].children[1]).toMatchObject({ name: 'B', length: 0.2 }); + expect(getTaxa('((D:1,B:1):1,(C:1,A:1):1);')).toEqual(['A', 'B', 'C', 'D']); + }); + + it('gives RF 0 for another rooting or child order', () => { + const base = '((A,B),(C,D),(E,F));'; + expect(compareTopologies(base, '((F,E),(D,C),(B,A));')).toMatchObject({ rf: 0 }); + // rerooted on the A,B edge + expect(compareTopologies(base, '(A,B,((C,D),(E,F)));')).toMatchObject({ rf: 0 }); + // rooted binary vs unrooted trifurcation + expect(compareTopologies('(((A,B),C),D);', '((A,B),C,D);')).toMatchObject({ rf: 0 }); + }); + + it('names the unique splits of a different topology', () => { + expect(compareTopologies('((A,B),(C,D));', '((A,C),(B,D));')).toEqual({ + rf: 2, + uniqueA: ['C,D'], + uniqueB: ['B,D'], + }); + }); + + it('reports a taxa mismatch without an RF distance', () => { + const result = compareTopologies('((A,B),(C,D));', '((A,B),(C,E));'); + expect(result).toEqual({ taxaMismatch: { onlyInA: ['D'], onlyInB: ['E'] } }); + expect(result).not.toHaveProperty('rf'); + }); + + it('compares branch lengths by relative tolerance', () => { + const a = '((A:1.0,B:2.0):0.5,(C:3.0,D:4.0):0.5);'; + expect(compareBranchLengths(a, '((A:1.005,B:2.0):0.5,(C:3.0,D:4.0):0.5);').ok).toBe(true); + const bad = compareBranchLengths(a, '((A:1.5,B:2.0):0.5,(C:3.0,D:4.0):0.5);'); + expect(bad.ok).toBe(false); + expect(bad.mismatches[0]).toMatch(/^A:/); + }); + + it('does not fail a near-zero branch on relative error', () => { + const a = '((A:0.0000001,B:1):1,(C:1,D:1):1);'; + const b = '((A:0.0000003,B:1):1,(C:1,D:1):1);'; + expect(compareBranchLengths(a, b).ok).toBe(true); + }); +}); diff --git a/e2e/helpers/raxmlHpcOutcome.js b/e2e/helpers/raxmlHpcOutcome.js new file mode 100644 index 00000000..eadd486c --- /dev/null +++ b/e2e/helpers/raxmlHpcOutcome.js @@ -0,0 +1,26 @@ +/** + * Reduce a raxmlHPC run to what a fixture keeps: the tool version, the model + * passed with -m, the final score and the best tree. Paths and timings are + * left out. + * @param {{ info: string, bestTree: string }} files contents of + * RAxML_info. and RAxML_bestTree. + * @returns {{ binaryVersions: Record, model: string, + * score: number, bestTree: string }} + */ +function parseRaxmlHpcOutput({ info, bestTree }) { + const version = /^This is RAxML version (\S+)/m.exec(info); + if (!version) throw new Error('raxmlHPC info: no version line'); + // The command line follows the heading after one empty line + const model = /^RAxML was called as follows:\s+.* -m (\S+)/m.exec(info); + if (!model) throw new Error('raxmlHPC info: no -m in the command line'); + const score = /^Final GAMMA-based Score of best tree (\S+)/m.exec(info); + if (!score) throw new Error('raxmlHPC info: no "Final GAMMA-based Score" line'); + return { + binaryVersions: { raxmlHPC: version[1] }, + model: model[1], + score: Number(score[1]), + bestTree: bestTree.trim(), + }; +} + +module.exports = { parseRaxmlHpcOutput }; diff --git a/e2e/helpers/raxmlHpcOutcome.test.js b/e2e/helpers/raxmlHpcOutcome.test.js new file mode 100644 index 00000000..b2be78d3 --- /dev/null +++ b/e2e/helpers/raxmlHpcOutcome.test.js @@ -0,0 +1,37 @@ +const { parseRaxmlHpcOutput } = require('./raxmlHpcOutcome'); + +const info = ` + +This is RAxML version 8.2.12 released by Alexandros Stamatakis on May 2018. + +Substitution Matrix: GTR + +RAxML was called as follows: + +/bin/Mac/raxmlHPC -f d -m GTRCATIX -N 1 -p 12345 -n out.tre -s /a/nucleotide.txt -w /out + +Inference[0] final GAMMA-based Likelihood: -1183.449461 tree written to file /out/RAxML_result.out.tre + +Final GAMMA-based Score of best tree -1183.120275 + +Overall execution time: 0.113251 secs or 0.000031 hours or 0.000001 days +`; + +describe('parseRaxmlHpcOutput', () => { + it('keeps version, model, final score and the trimmed best tree', () => { + expect( + parseRaxmlHpcOutput({ info, bestTree: '(A:0.1,B:0.2,C:0.3):0.0;\n' }), + ).toEqual({ + binaryVersions: { raxmlHPC: '8.2.12' }, + model: 'GTRCATIX', + score: -1183.120275, + bestTree: '(A:0.1,B:0.2,C:0.3):0.0;', + }); + }); + + it('throws on an info file with no final score', () => { + expect(() => + parseRaxmlHpcOutput({ info: info.replace(/^Final.*$/m, ''), bestTree: '' }), + ).toThrow(/Final GAMMA-based Score/); + }); +}); diff --git a/e2e/helpers/raxmlNgOutcome.js b/e2e/helpers/raxmlNgOutcome.js new file mode 100644 index 00000000..b6037455 --- /dev/null +++ b/e2e/helpers/raxmlNgOutcome.js @@ -0,0 +1,25 @@ +/** + * Reduce a raxml-ng run to what a fixture keeps: the tool version, the model + * of the first partition, the final log-likelihood and the best tree. Paths, + * timings, thread counts and the collapsed tree are left out. + * @param {{ log: string, bestTree: string }} files contents of + * .raxml.log.txt and .raxml.bestTree.tre + * @returns {{ binaryVersions: Record, model: string, + * logLikelihood: number, bestTree: string }} + */ +function parseRaxmlNgOutput({ log, bestTree }) { + const version = /^RAxML-NG v\. (\S+)/m.exec(log); + if (!version) throw new Error('raxml-ng log: no version line'); + const model = /^Model: (\S+)/m.exec(log); + if (!model) throw new Error('raxml-ng log: no "Model:" line'); + const lnl = /^Final LogLikelihood: (\S+)/m.exec(log); + if (!lnl) throw new Error('raxml-ng log: no "Final LogLikelihood" line'); + return { + binaryVersions: { 'raxml-ng': version[1] }, + model: model[1], + logLikelihood: Number(lnl[1]), + bestTree: bestTree.trim(), + }; +} + +module.exports = { parseRaxmlNgOutput }; diff --git a/e2e/helpers/raxmlNgOutcome.test.js b/e2e/helpers/raxmlNgOutcome.test.js new file mode 100644 index 00000000..c47c8f8c --- /dev/null +++ b/e2e/helpers/raxmlNgOutcome.test.js @@ -0,0 +1,31 @@ +const { parseRaxmlNgOutput } = require('./raxmlNgOutcome'); + +const log = `RAxML-NG v. 1.2.2 released on 30.04.2024 by The Exelixis Lab. + +Partition 0: noname +Model: TVM+FO+I +Alignment sites / patterns: 678 / 43 + +Final LogLikelihood: -1184.201009 + +AIC score: 2450.402017 / AICc score: 2455.817112 / BIC score: 2635.687056 +`; + +describe('parseRaxmlNgOutput', () => { + it('keeps version, model, final log-likelihood and the trimmed best tree', () => { + expect( + parseRaxmlNgOutput({ log, bestTree: '(A:0.1,B:0.2,C:0.3);\n' }), + ).toEqual({ + binaryVersions: { 'raxml-ng': '1.2.2' }, + model: 'TVM+FO+I', + logLikelihood: -1184.201009, + bestTree: '(A:0.1,B:0.2,C:0.3);', + }); + }); + + it('throws on a log with no final log-likelihood', () => { + expect(() => + parseRaxmlNgOutput({ log: log.replace(/^Final.*$/m, ''), bestTree: '' }), + ).toThrow(/Final LogLikelihood/); + }); +}); diff --git a/e2e/modeltest-outcome.spec.js b/e2e/modeltest-outcome.spec.js new file mode 100644 index 00000000..0d050c61 --- /dev/null +++ b/e2e/modeltest-outcome.spec.js @@ -0,0 +1,235 @@ +// @ts-check +const fs = require('fs/promises'); +const path = require('path'); +const { test, expect } = require('playwright/test'); +const { launchApp, getAppWindow, repoRoot } = require('./helpers/launchApp'); +const { cleanupOutputFiles } = require('./helpers/cleanupOutput'); +const { waitForOutputFile } = require('./helpers/waitForOutput'); +const { parseModelTestLog } = require('./helpers/modeltestOutcome'); +const { parseRaxmlNgOutput } = require('./helpers/raxmlNgOutcome'); +const { parseRaxmlHpcOutput } = require('./helpers/raxmlHpcOutcome'); +const { getTaxa } = require('./helpers/newick'); +const { checkFixture } = require('./helpers/fixtures'); + +const outputDir = path.join(repoRoot, 'static', 'test-results'); +const modelTestOutput = path.join(outputDir, 'RAxML_GUI_ModelTest_nucleotide'); + +// Same choice as src/app/store/Run.js +const binary = + process.platform === 'win32' + ? 'modeltest-ng.exe' + : process.platform === 'darwin' && process.arch === 'arm64' + ? 'modeltest-ng-ARM64' + : 'modeltest-ng'; + +// seed is ModelTest-NG's default; the GUI passes none +const settings = { + seed: 12345, + runs: 1, + analysis: 'modeltest', + criterion: 'AICc', + binary, + // The Linux binary prints the placeholder x.y.z instead of its version + binaryVersions: { + 'modeltest-ng': process.platform === 'linux' ? 'x.y.z' : '0.1.7', + }, +}; + +const alignmentFile = path.join( + repoRoot, + 'static', + 'example-files', + 'fasta', + 'nucleotide.txt', +); +const raxmlNgSettings = { + seed: 12345, + runs: 1, + analysis: 'TI', + binary: 'raxml-ng', + // The Linux binary reports a master build + binaryVersions: { + 'raxml-ng': process.platform === 'linux' ? '1.2.2-master' : '1.2.2', + }, +}; +const raxmlNgSuffixes = [ + 'raxml.bestTree.tre', + 'raxml.bestTreeCollapsed.tre', + 'raxml.bestModel.txt', + 'raxml.log.txt', + 'raxml.startTree.tre', + 'raxml.rba', +]; +// The serial build: the PTHREADS builds give other trees and scores +const raxmlHpcBinary = + process.platform === 'win32' ? 'raxmlHPC.exe' : 'raxmlHPC'; +const raxmlHpcSettings = { + seed: 12345, + runs: 1, + analysis: 'ML', + binary: raxmlHpcBinary, + binaryVersions: { raxmlHPC: '8.2.12' }, +}; + +const alignmentTaxa = async () => + (await fs.readFile(alignmentFile, 'utf8')) + .split('\n') + .filter((line) => line.startsWith('>')) + .map((line) => line.slice(1).trim()) + .sort(); + +test.describe.configure({ mode: 'serial', retries: 0 }); + +test.describe('ModelTest outcome', () => { + /** @type {import('playwright/test').ElectronApplication} */ + let electronApp; + const outputId = `e2e_modeltest_${Date.now()}`; + /** @type {import('playwright/test').Page} */ + let page; + let modelTestModel = ''; + + test.beforeAll(async () => { + electronApp = await launchApp(); + }); + + test.afterAll(async () => { + await electronApp?.close(); + await cleanupOutputFiles(outputDir, outputId); + }); + + test('AICc on nucleotide.txt matches the host fixture', async () => { + page = await getAppWindow(electronApp); + await expect(page.getByText('nucleotide', { exact: true })).toBeVisible({ + timeout: 60_000, + }); + await cleanupOutputFiles(outputDir, outputId); + await page.locator('#output-name').fill(outputId); + + await page.getByTestId('run-modeltest').click(); + await expect(page.getByTestId('console-output')).toContainText( + '> raxml-ng', + { timeout: 4 * 60 * 1000 }, + ); + await expect(page.locator('#error-dialog-title')).toHaveCount(0); + + for (const ext of ['out', 'log', 'tree']) { + await waitForOutputFile(`${modelTestOutput}.${ext}`, { timeout: 30_000 }); + } + + const actual = parseModelTestLog( + await fs.readFile(`${modelTestOutput}.out`, 'utf8'), + ); + modelTestModel = actual.criteria.AICc.model; + const { ok, message } = checkFixture('modeltest', settings, actual); + expect(ok, message).toBe(true); + }); + + test('TI with the ModelTest model matches the host fixture', async () => { + test.skip( + process.platform === 'win32', + 'Windows binary set has no raxml-ng', + ); + await page.locator('#mui-component-select-Analysis').click(); + await page + .getByRole('option', { name: 'ML tree inference', exact: true }) + .click(); + await page.getByTitle('Random seed').locator('input').fill('12345'); + + // The model comes from the ModelTest result, not from this test + const command = page.locator('p').filter({ hasText: /^raxml-ng/ }); + await expect(command).toContainText(`--model ${modelTestModel}`); + await expect(command).toContainText('--seed 12345'); + await expect(command).toContainText('rand{1}'); + + await page.getByTestId('run-analysis').click(); + await expect(page.getByText('Calculation finished!')).toBeVisible({ + timeout: 10 * 60 * 1000, + }); + await expect(page.locator('#error-dialog-title')).toHaveCount(0); + + for (const suffix of raxmlNgSuffixes) { + await waitForOutputFile(path.join(outputDir, `${outputId}.${suffix}`), { + timeout: 30_000, + }); + } + await waitForOutputFile( + path.join(outputDir, `RAxML_GUI_Settings_${outputId}.txt`), + { timeout: 30_000 }, + ); + + const actual = parseRaxmlNgOutput({ + log: await fs.readFile( + path.join(outputDir, `${outputId}.raxml.log.txt`), + 'utf8', + ), + bestTree: await fs.readFile( + path.join(outputDir, `${outputId}.raxml.bestTree.tre`), + 'utf8', + ), + }); + expect(getTaxa(actual.bestTree)).toEqual(await alignmentTaxa()); + + const { ok, message } = checkFixture('raxml-ng', raxmlNgSettings, actual); + expect(ok, message).toBe(true); + }); + + test('ML search with the ModelTest model matches the host fixture', async () => { + const readClipboard = () => + electronApp.evaluate(({ clipboard }) => clipboard.readText()); + // A name of its own, so the app does not rename it after the raxml-ng run + const hpcId = `${outputId}_hpc`; + await page.locator('#output-name').fill(hpcId); + await page.locator('#mui-component-select-Binary').click(); + await page + .getByRole('option', { name: raxmlHpcBinary, exact: true }) + .click(); + await page.locator('#mui-component-select-Analysis').click(); + await page.getByRole('option', { name: 'ML search', exact: true }).click(); + await page.getByTitle('Random seed').locator('input').fill('12345'); + + // The app filled this in from the ModelTest result; this test never sets it + const command = page.locator('p').filter({ hasText: /^raxmlHPC/ }); + await expect(command).toContainText('-f d'); + await expect(command).toContainText('-m GTRCATIX '); + await expect(command).toContainText('-N 1 '); + await expect(command).toContainText('-p 12345'); + await expect(command).not.toContainText('-T '); + const commandText = (await command.textContent()) || ''; + + await page.getByLabel('copy-command').click(); + await expect.poll(readClipboard).toBe(commandText); + + await page.getByText('How to cite?').click(); + await page.getByRole('button', { name: 'Copy to clipboard' }).click(); + await expect.poll(readClipboard).toContain('10.1111/2041-210X.13512'); + await page + .locator('#show-citation') + .getByRole('button', { name: 'Close' }) + .click(); + + await page.getByTestId('run-analysis').click(); + const bestTreePath = path.join(outputDir, `RAxML_bestTree.${hpcId}.tre`); + await waitForOutputFile(bestTreePath, { timeout: 3 * 60 * 1000 }); + const infoPath = await waitForOutputFile( + [ + path.join(outputDir, `RAxML_info.${hpcId}.txt`), + path.join(outputDir, `RAxML_info.${hpcId}.tre`), + ], + { timeout: 60_000 }, + ); + await waitForOutputFile( + path.join(outputDir, `RAxML_GUI_Settings_${hpcId}.txt`), + { timeout: 60_000 }, + ); + await expect(page.locator('#error-dialog-title')).toHaveCount(0); + + const actual = parseRaxmlHpcOutput({ + info: await fs.readFile(infoPath, 'utf8'), + bestTree: await fs.readFile(bestTreePath, 'utf8'), + }); + expect(getTaxa(actual.bestTree)).toEqual(await alignmentTaxa()); + + const { ok, message } = checkFixture('raxmlHPC', raxmlHpcSettings, actual); + expect(ok, message).toBe(true); + }); +}); diff --git a/e2e/modeltest-then-raxml-ng.spec.js b/e2e/modeltest-then-raxml-ng.spec.js deleted file mode 100644 index 9f2d5927..00000000 --- a/e2e/modeltest-then-raxml-ng.spec.js +++ /dev/null @@ -1,177 +0,0 @@ -// @ts-check -const fs = require('fs/promises'); -const path = require('path'); -const { test, expect } = require('playwright/test'); -const { launchApp, getAppWindow, repoRoot } = require('./helpers/launchApp'); -const { cleanupOutputFiles } = require('./helpers/cleanupOutput'); - -const outputDir = path.join(repoRoot, 'static', 'test-results'); - -test.describe('ModelTest then raxml-ng', () => { - /** @type {import('playwright/test').ElectronApplication | undefined} */ - let electronApp; - /** @type {string | undefined} */ - let outputId; - - test.afterEach(async () => { - if (electronApp) { - await electronApp.close(); - electronApp = undefined; - } - if (outputId) { - await cleanupOutputFiles(outputDir, outputId); - outputId = undefined; - } - }); - - test('prefilled alignment runs ModelTest and raxml-ng with correct output', async () => { - test.skip( - process.platform === 'win32', - 'Windows binary set has no raxml-ng', - ); - electronApp = await launchApp(); - const page = await getAppWindow(electronApp); - - await expect(page.getByText('nucleotide', { exact: true })).toBeVisible({ - timeout: 60_000, - }); - await expect(page.getByText(/sequences of length/i)).toBeVisible({ - timeout: 60_000, - }); - - outputId = `e2e_nucleotide_${Date.now()}`; - await cleanupOutputFiles(outputDir, outputId); - - const outputNameField = page.locator('#output-name'); - await outputNameField.click(); - await outputNameField.fill(''); - await outputNameField.fill(outputId); - await expect(outputNameField).toHaveValue(outputId); - - const modelTestButton = page.getByTestId('run-modeltest'); - await expect(modelTestButton).toBeEnabled(); - await modelTestButton.click(); - - const consoleOutput = page.getByTestId('console-output'); - await expect(consoleOutput).toContainText('> raxml-ng', { - timeout: 4 * 60 * 1000, - }); - await expect(page.locator('#error-dialog-title')).toHaveCount(0); - - const commandPreview = page.locator('p').filter({ hasText: /^raxml-ng/ }); - await expect(commandPreview).toBeVisible(); - const commandText = (await commandPreview.textContent()) || ''; - expect(commandText).toMatch(/--model \S+/); - expect(commandText).not.toMatch(/--model GTR(\s|$)/); - - const modeltestFiles = (await fs.readdir(outputDir)).filter((filename) => - filename.startsWith('RAxML_GUI_ModelTest_nucleotide'), - ); - expect(modeltestFiles.length).toBeGreaterThan(0); - - const runButton = page.getByTestId('run-analysis'); - await expect(runButton).toBeEnabled(); - await runButton.click(); - - await expect(page.getByText('Calculation finished!')).toBeVisible({ - timeout: 10 * 60 * 1000, - }); - await expect(page.locator('#error-dialog-title')).toHaveCount(0); - - await expect( - page.getByText(`Result for output id '${outputId}'`), - ).toBeVisible(); - await expect( - page.getByText(`${outputId}.raxml.bestTree.tre`), - ).toBeVisible(); - await expect(page.getByText(`${outputId}.raxml.support.tre`)).toBeVisible(); - await expect( - page.getByText(`${outputId}.raxml.bootstraps.tre`), - ).toBeVisible(); - - const bestTreePath = path.join(outputDir, `${outputId}.raxml.bestTree.tre`); - const supportTreePath = path.join( - outputDir, - `${outputId}.raxml.support.tre`, - ); - const bootstrapsTreePath = path.join( - outputDir, - `${outputId}.raxml.bootstraps.tre`, - ); - const logPath = path.join(outputDir, `${outputId}.raxml.log.txt`); - const bestModelPath = path.join( - outputDir, - `${outputId}.raxml.bestModel.txt`, - ); - const settingsPath = path.join( - outputDir, - `RAxML_GUI_Settings_${outputId}.txt`, - ); - - await expect - .poll(async () => - fs - .stat(bestTreePath) - .then(() => true) - .catch(() => false), - ) - .toBe(true); - await expect - .poll(async () => - fs - .stat(supportTreePath) - .then(() => true) - .catch(() => false), - ) - .toBe(true); - await expect - .poll(async () => - fs - .stat(bootstrapsTreePath) - .then(() => true) - .catch(() => false), - ) - .toBe(true); - await expect - .poll(async () => - fs - .stat(logPath) - .then(() => true) - .catch(() => false), - ) - .toBe(true); - await expect - .poll(async () => - fs - .stat(bestModelPath) - .then(() => true) - .catch(() => false), - ) - .toBe(true); - await expect - .poll(async () => - fs - .stat(settingsPath) - .then(() => true) - .catch(() => false), - ) - .toBe(true); - - const bestTree = await fs.readFile(bestTreePath, 'utf8'); - expect(bestTree).toContain('TAXON_'); - expect(bestTree).toMatch(/[()]/); - - const logText = await fs.readFile(logPath, 'utf8'); - expect(logText).toMatch(/Elapsed time/i); - expect(logText).not.toMatch(/\bERROR\b/); - - const bestModelText = await fs.readFile(bestModelPath, 'utf8'); - const modelMatch = /--model (\S+)/.exec(commandText); - expect(modelMatch).not.toBeNull(); - const baseModel = modelMatch[1].split('+')[0]; - expect(bestModelText).toContain(baseModel); - if (modelMatch[1].includes('+I')) { - expect(bestModelText).toMatch(/\+IU?\{/); - } - }); -}); diff --git a/e2e/playwright.config.js b/e2e/playwright.config.js index 75a98129..2157afa5 100644 --- a/e2e/playwright.config.js +++ b/e2e/playwright.config.js @@ -4,6 +4,7 @@ const path = require('path'); /** @type {import('playwright/test').PlaywrightTestConfig} */ const config = { testDir: path.join(__dirname), + testMatch: '**/*.spec.js', // Jest owns *.test.js testIgnore: ['docs/**'], // Locator checks use Playwright's 5s expect timeout. A long wait passes its own timeout. timeout: 15 * 60 * 1000, diff --git a/e2e/raxmlHPC.spec.js b/e2e/raxmlHPC.spec.js deleted file mode 100644 index 3e0e2de7..00000000 --- a/e2e/raxmlHPC.spec.js +++ /dev/null @@ -1,104 +0,0 @@ -// @ts-check -const fs = require('fs/promises'); -const path = require('path'); -const { test, expect } = require('playwright/test'); -const { launchApp, getAppWindow, repoRoot } = require('./helpers/launchApp'); -const { cleanupOutputFiles } = require('./helpers/cleanupOutput'); -const { waitForOutputFile } = require('./helpers/waitForOutput'); - -const outputDir = path.join(repoRoot, 'static', 'test-results'); - -test.describe('raxmlHPC', () => { - /** @type {import('playwright/test').ElectronApplication | undefined} */ - let electronApp; - /** @type {string | undefined} */ - let outputId; - - test.afterEach(async () => { - if (electronApp) { - await electronApp.close(); - electronApp = undefined; - } - if (outputId) { - await cleanupOutputFiles(outputDir, outputId); - outputId = undefined; - } - }); - - test('prefilled alignment runs raxmlHPC with correct output', async () => { - electronApp = await launchApp(); - const page = await getAppWindow(electronApp); - - await expect(page.getByText('nucleotide', { exact: true })).toBeVisible({ - timeout: 60_000, - }); - await expect(page.getByText(/sequences of length/i)).toBeVisible({ - timeout: 60_000, - }); - - outputId = `e2e_raxmlhpc_${Date.now()}`; - await cleanupOutputFiles(outputDir, outputId); - - const outputNameField = page.locator('#output-name'); - await outputNameField.click(); - await outputNameField.fill(''); - await outputNameField.fill(outputId); - await expect(outputNameField).toHaveValue(outputId); - - const raxmlHpcBinary = - process.platform === 'win32' ? 'raxmlHPC.exe' : 'raxmlHPC'; - await page.locator('#mui-component-select-Binary').click(); - await page - .getByRole('option', { name: raxmlHpcBinary, exact: true }) - .click(); - - await page.locator('#mui-component-select-Analysis').click(); - await page.getByRole('option', { name: 'ML search', exact: true }).click(); - - const commandPreview = page.locator('p').filter({ hasText: /^raxmlHPC/ }); - await expect(commandPreview).toBeVisible(); - const commandText = (await commandPreview.textContent()) || ''; - expect(commandText).toMatch(/-f d/); - expect(commandText).toMatch(/-m \S+/); - - await page.getByLabel('copy-command').click(); - await expect.poll(async () => electronApp.evaluate(async ({ clipboard }) => clipboard.readText())).toBe(commandText); - - await page.getByText('How to cite?').click(); - await page.getByRole('button', { name: 'Copy to clipboard' }).click(); - await expect.poll(async () => electronApp.evaluate(async ({ clipboard }) => clipboard.readText())).toContain('10.1111/2041-210X.13512'); - await page.locator('#show-citation').getByRole('button', { name: 'Close' }).click(); - - const outputFilename = `${outputId}.tre`; - const bestTreePath = path.join( - outputDir, - `RAxML_bestTree.${outputFilename}`, - ); - const infoPathTxt = path.join(outputDir, `RAxML_info.${outputId}.txt`); - const infoPathTre = path.join(outputDir, `RAxML_info.${outputFilename}`); - const settingsPath = path.join( - outputDir, - `RAxML_GUI_Settings_${outputId}.txt`, - ); - - const runButton = page.getByTestId('run-analysis'); - await expect(runButton).toBeEnabled(); - await runButton.click(); - - await waitForOutputFile(bestTreePath, { timeout: 3 * 60 * 1000 }); - await waitForOutputFile([infoPathTxt, infoPathTre], { timeout: 60_000 }); - await waitForOutputFile(settingsPath, { timeout: 60_000 }); - await expect(page.locator('#error-dialog-title')).toHaveCount(0); - - const bestTree = await fs.readFile(bestTreePath, 'utf8'); - expect(bestTree).toContain('TAXON_'); - expect(bestTree).toMatch(/[()]/); - - const infoPath = await fs - .stat(infoPathTxt) - .then(() => infoPathTxt) - .catch(() => infoPathTre); - const infoText = await fs.readFile(infoPath, 'utf8'); - expect(infoText.length).toBeGreaterThan(0); - }); -}); diff --git a/e2e/updateFixtures.js b/e2e/updateFixtures.js new file mode 100644 index 00000000..ba54ee83 --- /dev/null +++ b/e2e/updateFixtures.js @@ -0,0 +1,16 @@ +// Runs the ModelTest, raxml-ng and raxmlHPC spec against the real app in update mode. Never run by test:e2e. +const { spawnSync } = require('child_process'); +const path = require('path'); + +const result = spawnSync( + process.execPath, + [ + path.join(__dirname, '..', 'node_modules', 'playwright', 'cli.js'), + 'test', + '--config', + path.join(__dirname, 'playwright.config.js'), + 'modeltest-outcome.spec.js', + ], + { stdio: 'inherit', env: { ...process.env, RAXMLGUI_UPDATE_FIXTURES: '1' } }, +); +process.exit(result.status ?? 1); diff --git a/jest.config.js b/jest.config.js index b912988c..4b0a429a 100644 --- a/jest.config.js +++ b/jest.config.js @@ -2,7 +2,8 @@ module.exports = { testEnvironment: 'jsdom', setupFiles: [ '/jest/setup.js' ], setupFilesAfterEnv: [ '/jest/mobxActionWarning.js' ], - roots: [ '/src' ], + roots: [ '/src', '/e2e' ], + testMatch: [ '**/*.test.[jt]s?(x)' ], transform: { '^.+\\.(js|jsx|mjs|ts|tsx)$': '/jest/babelTransform.js', }, diff --git a/package.json b/package.json index b546e0de..2cc06336 100644 --- a/package.json +++ b/package.json @@ -26,6 +26,7 @@ "test": "jest --watchAll=false", "react-test": "jest --watchAll=false", "test:e2e": "yarn build && node node_modules/playwright/cli.js test --config e2e/playwright.config.js", + "test:e2e:update-fixtures": "yarn build && node e2e/updateFixtures.js", "test:docs": "node node_modules/playwright/cli.js test --config e2e/docs/playwright.config.js", "download-binaries": "node scripts/download-binaries.js", "electron-build": "electron-builder",