Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ config.py # or .env files containing sensitive API keys/credentials
*.tmp
!important.tmp

node_modules/
.vscode/
*.tgz
truss-report.json
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@
"truss:check:json": "tsx bin/truss.ts check --format json",
"docker:build": "docker build -t truss-lint .",
"docker:help": "docker run --rm truss-lint --help",
"docker:check": "docker run --rm -v \"$PWD:/workspace\" -w /workspace truss-lint check"
"docker:check": "docker run --rm -v \"$PWD:/workspace\" -w /workspace truss-lint check",
"test:coverage": "node --enable-source-maps --import tsx --test --experimental-test-coverage --test-coverage-exclude=\"tests/**\" --test-coverage-exclude=\"dist/**\" --test-coverage-exclude=\"node_modules/**\" --test-coverage-lines=80 --test-coverage-branches=80 --test-coverage-functions=80 tests/**/*.test.ts"
},
"dependencies": {
"@aws-sdk/client-s3": "^3.1084.0",
Expand Down
167 changes: 167 additions & 0 deletions tests/cli-artifacts.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
import test, { type TestContext } from "node:test";
import assert from "node:assert/strict";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { spawnSync } from "node:child_process";

const root = path.resolve(__dirname, "..");
const fixture = (name: string) => path.join(root, "tests/fixtures", name);
function run(args: string[], cwd = root) {
const result = spawnSync(process.execPath, ["--enable-source-maps", "--import", path.join(root, "node_modules/tsx/dist/loader.mjs"), path.join(root, "bin/truss.ts"), ...args], {
cwd, encoding: "utf8", timeout: 30_000,
env: { ...process.env, TRUSS_OTEL_CONSOLE: "0", TRUSS_S3_BUCKET: "", NO_COLOR: "1", FORCE_COLOR: "0" },
});
if (result.error) throw result.error;
assert.equal(result.signal, null);
return result;
}
function temp(t: TestContext) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "truss-tests-"));
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
return dir;
}

test("init creates a usable starter, preserves existing configuration, and overwrites only with force", (t) => {
const dir = temp(t);
const first = run(["init"], dir);
assert.equal(first.status, 0);
assert.match(first.stdout, /Created truss.yml/);
const config = path.join(dir, "truss.yml");
const starter = fs.readFileSync(config, "utf8");
fs.writeFileSync(path.join(dir, "app.ts"), "export const value = 1;\n");
assert.equal(run(["check", "--repo", dir]).status, 0);
fs.writeFileSync(config, "# existing custom configuration\n");
const refused = run(["init"], dir);
assert.equal(refused.status, 2);
assert.equal(refused.stdout, "");
assert.match(refused.stderr, /already exists.*--force/);
assert.equal(fs.readFileSync(config, "utf8"), "# existing custom configuration\n");
assert.equal(run(["init", "--force"], dir).status, 0);
assert.equal(fs.readFileSync(config, "utf8"), starter);
});

test("init reports a write failure when the config path is a directory", (t) => {
const dir = temp(t);
fs.mkdirSync(path.join(dir, "truss.yml"));
const result = run(["init", "--force"], dir);
assert.equal(result.status, 3);
assert.equal(result.stdout, "");
assert.match(result.stderr, /Truss: Internal error/);
assert.match(result.stderr, /EISDIR/);
});

for (const [repo, status] of [["ok-repo", 0], ["violations-repo", 1]] as const) {
for (const format of ["human", "json"]) {
test(`check writes nested HTML and JSON artifacts for ${repo} in ${format} mode`, (t) => {
const dir = temp(t);
fs.cpSync(fixture(repo), dir, { recursive: true });
const result = run(["check", "--repo", dir, "--format", format, "--report-dir", "reports/nested"]);
assert.equal(result.status, status);
const report = JSON.parse(fs.readFileSync(path.join(dir, "reports/nested/truss-report.json"), "utf8"));
assert.equal(report.kind, "report");
assert.equal(report.exitCode, status);
assert.equal(report.summary.unsuppressedCount, status);
const html = fs.readFileSync(path.join(dir, "reports/nested/truss-report.html"), "utf8");
assert.ok(html.includes(`class="badge">${status ? "FAIL" : "PASS"}`));
if (status) assert.match(html, /no-api-to-db/);
if (format === "json") {
assert.deepEqual(JSON.parse(result.stdout), report);
} else {
assert.match(result.stdout, /JSON report written to reports\/nested\/truss-report.json/);
assert.match(result.stdout, /HTML report written to reports\/nested\/truss-report.html/);
}
assert.equal(result.stderr, "");
});
}
}

for (const format of ["human", "json"]) {
test(`report output failures return an internal error in ${format} mode`, (t) => {
const dir = temp(t);
const blocked = path.join(dir, "file");
fs.writeFileSync(blocked, "keep");
const result = run(["check", "--repo", fixture("ok-repo"), "--format", format, "--report-dir", blocked]);
assert.equal(result.status, 3);
if (format === "human") {
assert.match(result.stderr, /Truss: Internal error/);
assert.match(result.stderr, /EEXIST/);
} else {
// The CLI prints the analysis before attempting artifact writes.
const error = JSON.parse(result.stdout.slice(result.stdout.indexOf('\n{') + 1));
assert.equal(error.kind, "error");
assert.equal(error.exitCode, 3);
assert.match(error.error, /Internal error:.*EEXIST/);
assert.equal(result.stderr, "");
}
assert.equal(fs.readFileSync(blocked, "utf8"), "keep");
});
}

test("S3 upload without a bucket fails locally after writing report artifacts", (t) => {
const dir = temp(t);
const result = run(["check", "--repo", fixture("ok-repo"), "--report-dir", dir, "--upload-s3"]);
assert.equal(result.status, 2);
assert.match(result.stderr, /TRUSS_S3_BUCKET is required when using --upload-s3/);
assert.equal(JSON.parse(fs.readFileSync(path.join(dir, "truss-report.json"), "utf8")).exitCode, 0);
assert.ok(fs.existsSync(path.join(dir, "truss-report.html")));
});

for (const repo of ["ok-repo", "violations-repo", "suppressed-repo"]) {
test(`graph renders ${repo} with only unsuppressed internal violations highlighted`, () => {
const result = run(["graph", "--repo", fixture(repo)]);
assert.equal(result.status, 0);
assert.equal(result.stderr, "");
assert.ok(result.stdout.startsWith("digraph G {\n"));
assert.ok(result.stdout.endsWith("}\n"));
if (repo === "violations-repo") {
assert.match(result.stdout, /"src\/api\/user.ts" -> "src\/db\/client.ts" \[color="red", penwidth=2.5\]/);
} else {
assert.match(result.stdout, / -> /);
assert.doesNotMatch(result.stdout, /color="red"/);
}
});
}

test("graph rejects unsupported formats and reports analysis failures", () => {
const invalid = run(["graph", "--format", "json"]);
assert.equal(invalid.status, 2);
assert.equal(invalid.stdout, "");
assert.match(invalid.stderr, /Expected "dot"/);
const missing = run(["graph", "--repo", fixture("missing-config-repo")]);
assert.equal(missing.status, 3);
assert.equal(missing.stdout, "");
assert.match(missing.stderr, /Truss: Internal error/);
assert.match(missing.stderr, /truss.yml/);
});

test("custom missing config paths receive actionable JSON errors and create no artifacts", (t) => {
const dir = temp(t);
const result = run(["check", "--repo", dir, "--config", "custom.yml", "--format", "json", "--report-dir", "reports"]);
assert.equal(result.status, 2);
assert.equal(result.stderr, "");
const error = JSON.parse(result.stdout);
assert.equal(error.kind, "error");
assert.equal(error.exitCode, 2);
assert.match(error.error, /Config file not found: custom.yml.*fix --config/);
assert.equal(fs.existsSync(path.join(dir, "reports")), false);
});

for (const [config, message] of [
["null", /expected a YAML object/],
['{"layers":{}}', /must define at least one layer/],
['{"layers":{"app":["src/**"]}}', /"rules" must be an array/],
['{"layers":{"app":["src/**"]},"rules":[{"name":"boundary","from":"missing","disallow":["app"]}]}', /unknown layer in "from": "missing"/],
] as const) {
test(`invalid config reports ${message.source} through the CLI`, (t) => {
const dir = temp(t);
fs.writeFileSync(path.join(dir, "truss.yml"), config);
const result = run(["check", "--repo", dir, "--format", "json"]);
assert.equal(result.status, 2);
assert.equal(result.stderr, "");
const error = JSON.parse(result.stdout);
assert.equal(error.kind, "error");
assert.equal(error.exitCode, 2);
assert.match(error.error, message);
});
}
55 changes: 55 additions & 0 deletions tests/config-loader.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import test from "node:test";
import assert from "node:assert/strict";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { loadTrussConfig } from "../src/config/configLoader";
import { ConfigError } from "../src/utils/errors";

const rule = { name: "boundary", from: "app", disallow: ["db"] };
const valid = { layers: { app: ["src/app"], db: ["src/db"] }, rules: [rule] };
const cases: Array<[string, unknown, RegExp]> = [
["missing layers", { rules: [] }, /"layers" must be an object/],
["array layers", { layers: [], rules: [] }, /"layers" must be an object/],
["non-list patterns", { ...valid, layers: { app: "src/app" } }, /Invalid layer "app"/],
["empty patterns", { ...valid, layers: { app: [] } }, /Invalid layer "app"/],
["non-string patterns", { ...valid, layers: { app: [42] } }, /Invalid layer "app"/],
["non-array rules", { ...valid, rules: {} }, /"rules" must be an array/],
["null rule", { ...valid, rules: [null] }, /expected an object/],
["scalar rule", { ...valid, rules: ["boundary"] }, /expected an object/],
["missing rule name", { ...valid, rules: [{ from: "app", disallow: ["db"] }] }, /missing "name"/],
["non-string rule name", { ...valid, rules: [{ ...rule, name: 1 }] }, /missing "name"/],
["missing source layer", { ...valid, rules: [{ name: "boundary", disallow: ["db"] }] }, /missing "from"/],
["non-string source layer", { ...valid, rules: [{ ...rule, from: 1 }] }, /missing "from"/],
["non-array targets", { ...valid, rules: [{ ...rule, disallow: "db" }] }, /non-empty string\[\]/],
["empty targets", { ...valid, rules: [{ ...rule, disallow: [] }] }, /non-empty string\[\]/],
["non-string targets", { ...valid, rules: [{ ...rule, disallow: [1] }] }, /non-empty string\[\]/],
["non-string message", { ...valid, rules: [{ ...rule, message: 42 }] }, /invalid "message"/],
["unknown target layer", { ...valid, rules: [{ ...rule, disallow: ["missing"] }] }, /unknown disallow layer: "missing"/],
];

for (const [name, config, message] of cases) {
test(`configuration rejects ${name} with a labeled configuration error`, (t) => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "truss-config-test-"));
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const file = path.join(dir, "custom.yml");
fs.writeFileSync(file, JSON.stringify(config));
assert.throws(() => loadTrussConfig(file, "custom.yml"), error => {
assert.ok(error instanceof ConfigError);
assert.match(error.message, message);
assert.match(error.message, /custom.yml/);
return true;
});
});
}

test("configuration normalizes directory patterns while retaining globs and optional settings", (t) => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "truss-config-test-"));
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
const file = path.join(dir, "custom.yml");
const config = { ...valid, layers: { app: [" src/app/ ", "src/app", "src/**/*.tsx"], db: ["src/db"] },
ignore: ["generated"], suppressions: [{ file: "src/app/a.ts", rule: "boundary", reason: "accepted" }] };
fs.writeFileSync(file, JSON.stringify(config));
assert.deepEqual(loadTrussConfig(file), { ...config,
layers: { app: ["src/app/**", "src/app/**", "src/**/*.tsx"], db: ["src/db/**"] } });
});
77 changes: 77 additions & 0 deletions tests/dot-renderer.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import test from "node:test";
import assert from "node:assert/strict";
import { renderGraphAsDot } from "../src/graph/dotRenderer";
import type { DependencyGraph } from "../src/graph/graphBuilder";

function graph(nodes: string[], edges: [string, string[]][] = []): DependencyGraph {
return { nodes: new Set(nodes), adjacency: new Map(edges.map(([from, to]) => [from, new Set(to)])) };
}

test("empty graphs produce valid DOT scaffolding with or without layers", () => {
const dot = renderGraphAsDot(graph([]));
assert.ok(dot.startsWith("digraph G {\n rankdir=LR;"));
assert.ok(dot.endsWith("\n}"));
assert.doesNotMatch(dot, / -> |subgraph|label=/);
assert.equal(renderGraphAsDot(graph([]), {}, []), dot);
});

test("nodes and edges are sorted, including isolated nodes and adjacency-only endpoints", () => {
const first = renderGraphAsDot(graph(["z", "a"], [["c", ["b", "a"]], ["b", ["a"]]]));
const second = renderGraphAsDot(graph(["a", "z"], [["b", ["a"]], ["c", ["a", "b"]]]));
assert.equal(first, second);
assert.deepEqual(first.split("\n").filter(line => line.includes("label=")),
["a", "b", "c", "z"].map(node => ` "${node}" [fillcolor="#f8fafc", label="${node}"];`));
assert.deepEqual(first.split("\n").filter(line => line.includes(" -> ")), [
' "b" -> "a";', ' "c" -> "a";', ' "c" -> "b";',
]);
});

test("DOT quotes special characters in node and layer labels and sanitizes cluster IDs", () => {
const layer = 'odd "layer"-雪';
const node = 'odd/"quoted"\\file\n雪.ts';
const dot = renderGraphAsDot(graph([node], [[node, ["target"]]]), { [layer]: ["odd/**"] });
assert.ok(dot.includes(`label=${JSON.stringify(layer)};`));
assert.ok(dot.includes(`subgraph cluster_${layer.replace(/[^a-zA-Z0-9_]/g, "_")} {`));
assert.ok(dot.includes(`${JSON.stringify(node)} -> "target";`));
assert.ok(dot.includes(`label=${JSON.stringify(node)}]`));
});

test("collapsed paths deduplicate edges, omit self edges and highlight normalized violations", () => {
const a = "client/src/features/cart/a.ts";
const b = "client/src/features/cart/b.ts";
const target = "server/services/orders/deep/index.ts";
const dot = renderGraphAsDot(graph([a, b], [[a, [b, target]], [b, [target, "plain.ts"]]]), undefined,
[{ from: b, to: target }]);
assert.deepEqual(dot.split("\n").filter(line => line.includes(" -> ")), [
' "client/src/features/cart" -> "server/services" [color="red", penwidth=2.5];',
' "client/src/features/cart" -> "plain.ts";',
]);
assert.equal(dot.split('label="client/src/features/cart"').length - 1, 1);
});

test("server and UI paths receive their documented subgroups, with unmatched nodes left outside", () => {
const serverGroups = ["routes", "controllers", "services", "db", "middleware", "lib", "types", "utils"];
const uiGroups = ["app", "api", "shared", "styles", "features"];
const nodes = [
...serverGroups.map(group => `server/${group}/deep/nested/file.ts`),
...uiGroups.map(group => `client/src/${group}`),
"client/src/features/cart/deep/file.ts", "client/src/app/deep/file.ts",
"server/custom/deep/nested/file.ts", "client/src/misc/file.ts", "shared/a.ts", "loose.ts",
];
const layers = { server: ["server/**"], ui: ["client/src/*"], shared: ["shared/**"], ignored: ["*"] };
const dot = renderGraphAsDot(graph(nodes), layers);
for (const group of [...serverGroups, ...uiGroups, "feature:cart", "other"]) {
assert.ok(dot.includes(`label="${group}";`), group);
}
for (const group of serverGroups) assert.ok(dot.includes(`label="server/${group}"]`));
assert.ok(dot.includes('"loose.ts" [fillcolor="#f8fafc", label="loose.ts"]'));
assert.doesNotMatch(dot, /cluster_ignored/);
assert.equal(dot, renderGraphAsDot(graph([...nodes].reverse()), layers));
});

test("overlapping prefixes use the first matching layer and colors follow sorted layer names", () => {
const dot = renderGraphAsDot(graph(["src/a.ts", "src/b.ts"]), { zebra: ["missing/**", "src/**"], alpha: ["src/**"] });
assert.match(dot, /subgraph cluster_zebra/);
assert.doesNotMatch(dot, /subgraph cluster_alpha/);
assert.equal((dot.match(/fillcolor="#fef3c7"/g) ?? []).length, 2);
});
77 changes: 77 additions & 0 deletions tests/html-reporter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import test from "node:test";
import assert from "node:assert/strict";
import { renderHtmlReport } from "../src/reporting/htmlReporter";
import type { TrussReport, Violation } from "../src/core/types";

function emptyReport(): TrussReport {
return {
checkedFiles: 0, edges: 0, unsuppressed: [], suppressed: [], parserIssues: [],
analysis: { diagnostics: [], categories: { parser: 0, graph: 0, validation: 0, suppression: 0 } },
summary: { unsuppressedCount: 0, suppressedCount: 0, parserIssueCount: 0, diagnosticCount: 0, totalCount: 0 },
};
}

const special = '<script title="x">&\'雪</script>';
const escaped = '&lt;script title=&quot;x&quot;&gt;&amp;\'雪&lt;/script&gt;';
function violation(): Violation {
return { ruleName: special, fromLayer: special, toLayer: special, reason: special,
edge: { importKind: "internal", fromFile: special, toFile: "target.ts", line: 17, importText: "" } };
}

test("empty HTML report has a passing status, zero counters and no tables", (t) => {
t.mock.timers.enable({ apis: ["Date"], now: new Date("2025-01-02T03:04:05Z") });
const html = renderHtmlReport(emptyReport());
assert.ok(html.startsWith("<!DOCTYPE html>"));
assert.match(html, /Generated at 2025-01-02T03:04:05.000Z/);
assert.match(html, /class="badge">PASS/);
assert.match(html, /background: #16a34a/);
assert.equal((html.match(/class="value">0</g) ?? []).length, 4);
assert.match(html, /No unsuppressed architecture violations found/);
assert.match(html, /No diagnostics found/);
assert.doesNotMatch(html, /<table>/);
});

test("violations fail the report and escape every textual cell with null layer fallbacks", () => {
const report = emptyReport();
report.checkedFiles = 12;
report.edges = 23;
report.unsuppressed = [violation(), { ...violation(), fromLayer: null, toLayer: null }];
report.summary.unsuppressedCount = 2;
const html = renderHtmlReport(report);
assert.match(html, /class="badge">FAIL/);
assert.match(html, /background: #dc2626/);
assert.ok(html.includes(`<td>${escaped}:17</td>`));
assert.equal(html.split(`<td>${escaped}</td>`).length - 1, 6);
assert.equal(html.split("<td>unknown</td>").length - 1, 2);
for (const count of [12, 23, 2]) assert.ok(html.includes(`class="value">${count}</div>`));
assert.doesNotMatch(html, /<script/);
assert.doesNotMatch(html, /No unsuppressed architecture violations found/);
});

for (const severity of ["warning", "error"] as const) {
test(`${severity} diagnostics render escaped details and determine status without violations`, () => {
const report = emptyReport();
report.analysis.diagnostics = [
{ severity, category: "parser", code: special, message: special, file: special },
{ severity, category: "graph", code: "CYCLE", message: "Cycle detected" },
];
report.summary.diagnosticCount = 2;
const html = renderHtmlReport(report);
assert.ok(html.includes(`class="badge">${severity === "error" ? "FAIL" : "PASS"}`));
assert.equal(html.split(`<td>${escaped}</td>`).length - 1, 3);
assert.match(html, /<td>unknown<\/td>/);
assert.ok(html.includes(`<td>${severity}</td>`));
assert.match(html, /class="value">2<\/div>/);
assert.doesNotMatch(html, /No diagnostics found|<script/);
});
}

test("suppressed violations do not appear in the HTML violation table or fail the report", () => {
const report = emptyReport();
report.suppressed = [{ ...violation(), suppressionReason: "accepted" }];
report.summary.suppressedCount = report.summary.totalCount = 1;
const html = renderHtmlReport(report);
assert.match(html, /class="badge">PASS/);
assert.match(html, /No unsuppressed architecture violations found/);
assert.doesNotMatch(html, /<table>|&lt;script/);
});
Loading
Loading