UNPKG

@pact-foundation/pact

Version:
76 lines 3.13 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.executeTest = exports.readBinaryData = void 0; const fs = require("node:fs"); const logger_1 = __importDefault(require("../../common/logger")); const display_1 = require("../../v3/display"); const readBinaryData = (file) => { try { const body = fs.readFileSync(file); return body; } catch (e) { const error = e instanceof Error ? e : new Error(String(e)); throw new Error(`unable to read file for binary payload : ${error.message}`); } }; exports.readBinaryData = readBinaryData; const cleanup = (success, pact, opts, server, cleanupFn) => { if (success) { pact.writePactFile(opts.dir || './pacts'); } pact.cleanupMockServer(server.port); pact.cleanupPlugins(); cleanupFn(); }; const executeTest = async (pact, opts, testFn, cleanupFn) => { const scheme = opts.tls ? 'https' : 'http'; const host = opts.host || '127.0.0.1'; const cors = opts.cors ?? true; const config = JSON.stringify({ corsPreflight: cors }); const port = pact.pactffiCreateMockServerForTransport(host, scheme, config, opts.port); if (port <= 0) { throw new Error(`Failed to start mock server: received error code ${port}`); } const server = { port, url: `${scheme}://${host}:${port}`, id: 'unknown' }; let val; let error; try { val = await testFn(server); } catch (e) { error = e instanceof Error ? e : new Error(String(e)); } const matchingResults = pact.mockServerMismatches(port); const errors = (0, display_1.filterMissingFeatureFlag)(matchingResults); const success = pact.mockServerMatchedSuccessfully(port); // Scenario: Pact validation failed if (!success && errors.length > 0) { let errorMessage = 'Test failed for the following reasons:'; errorMessage += `\n\n ${(0, display_1.generateMockServerError)(matchingResults, '\t')}`; cleanup(false, pact, opts, server, cleanupFn); // If the tests throws an error, we need to rethrow the error, but print out // any additional mock server errors to help the user understand what happened // (The proximate cause here is often the HTTP 500 from the mock server, // where the HTTP client then throws) if (error) { logger_1.default.error(errorMessage); throw error; } // Test didn't throw, so we need to ensure the test fails return Promise.reject(new Error(errorMessage)); } // Scenario: test threw an error, but Pact validation was OK (error in client or test) if (error) { cleanup(false, pact, opts, server, cleanupFn); throw error; } // Scenario: Pact validation passed, test didn't throw - return the callback value cleanup(true, pact, opts, server, cleanupFn); return val; }; exports.executeTest = executeTest; //# sourceMappingURL=index.js.map