-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
144 lines (127 loc) · 5.08 KB
/
cli.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#!/usr/bin/env node
"use strict";
const fs = require("fs");
const path = require("path");
const { Command } = require("commander");
const { loadAndParseSpec, extractOperationsFromSpec } = require("./lib/swagger");
const { loadPostmanCollection, extractRequestsFromPostman } = require("./lib/postman");
const { matchOperationsDetailed } = require("./lib/match");
const { generateHtmlReport } = require("./lib/report");
const { loadExcelSpec } = require("./lib/excel");
const program = new Command();
program
.name("swagger-coverage-cli")
.description(
"CLI tool for comparing an OpenAPI/Swagger specification with a Postman collection, producing an enhanced HTML report"
)
.version("1.0.1")
.argument("<swaggerFile>", "Path to the Swagger/OpenAPI file (JSON or YAML).")
.argument("<postmanCollection>", "Path to the Postman collection (JSON).")
.option("-v, --verbose", "Show verbose debug info")
.option("--strict-query", "Enable strict validation of query parameters")
.option("--strict-body", "Enable strict validation of requestBody (JSON)")
.option("--output <file>", "HTML report output file", "coverage-report.html")
.action(async (swaggerFile, postmanFile, options) => {
try {
const { verbose, strictQuery, strictBody, output } = options;
const ext = path.extname(swaggerFile).toLowerCase();
const excelExtensions = [".xlsx", ".xls", ".csv"];
let specOperations;
let specName; // Add this variable
if (excelExtensions.includes(ext)) {
// Parse Excel
specOperations = loadExcelSpec(swaggerFile);
specName = path.basename(swaggerFile); // Set name for Excel files
} else {
// Original Swagger flow
const spec = await loadAndParseSpec(swaggerFile);
specName = spec.info.title; // Set name for Swagger files
if (verbose) {
console.log(
"Specification loaded successfully:",
specName,
spec.info.version
);
}
specOperations = extractOperationsFromSpec(spec, verbose);
}
// Ensure Postman file exists
if (!fs.existsSync(postmanFile)) {
throw new Error(`Postman file not found: ${postmanFile}`);
}
// Safely parse Postman JSON
let postmanData;
try {
const rawPostman = fs.readFileSync(postmanFile, "utf8");
if (!rawPostman.trim()) {
throw new Error("Postman file is empty.");
}
postmanData = JSON.parse(rawPostman);
} catch (err) {
throw new Error(`Unable to parse Postman JSON: ${err.message}`);
}
if (verbose) {
console.log(
`Postman collection loaded successfully: "${postmanData.info.name}"`
);
}
// 4. Extract Postman requests
const postmanRequests = extractRequestsFromPostman(postmanData, verbose);
// 5. Match operations in a "detailed" way that returns coverageItems
const coverageItems = matchOperationsDetailed(specOperations, postmanRequests, {
verbose,
strictQuery,
strictBody,
});
// coverageItems is an array of objects:
// [
// {
// method: "GET",
// path: "/v2/artist/elements",
// name: "listElements",
// tags: ["Artists", "Collections"],
// expectedStatusCodes: ["200", "400"],
// statusCode: "200",
// unmatched: false,
// matchedRequests: [
// { name: "Get Elements (Postman)", rawUrl: "...", method: "GET", testedStatusCodes: ["200", "404"], scriptCode: "..." },
// ...
// ]
// },
// ...
// ]
// Calculate coverage: # of spec items that are NOT unmatched
const totalSpecOps = coverageItems.length;
const matchedCount = coverageItems.filter(item => !item.unmatched).length;
const coverage = totalSpecOps ? (matchedCount / totalSpecOps) * 100 : 0;
// 6. Print console summary
console.log("=== Swagger Coverage Report ===");
console.log(`Total operations in spec: ${totalSpecOps}`);
console.log(`Matched operations in Postman: ${matchedCount}`);
console.log(`Coverage: ${coverage.toFixed(2)}%`);
// Also show which items are truly unmatched
const unmatchedItems = coverageItems.filter(item => item.unmatched);
if (unmatchedItems.length > 0) {
console.log("\nUnmatched Spec operations:");
unmatchedItems.forEach(item => {
console.log(` - [${item.method}] ${item.path} (statusCode=${item.statusCode || ""})`);
});
}
// 7. Generate HTML report with specName instead of spec.info.title
const html = generateHtmlReport({
coverage,
coverageItems,
meta: {
timestamp: new Date().toLocaleString(),
specName, // Use specName here
postmanCollectionName: postmanData.info.name,
},
});
fs.writeFileSync(path.resolve(output), html, "utf8");
console.log(`\nHTML report saved to: ${output}`);
} catch (err) {
console.error("Error:", err.message);
process.exit(1);
}
});
program.parse(process.argv);