aboutsummaryrefslogtreecommitdiffstats
path: root/test/runner/createTestServer.js
blob: 9b9810bcb8bfa97645ec3f5d8da73791183aca0c (plain)
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
import http from "node:http";
import { readFile, stat } from "node:fs/promises";
import { createReadStream } from "node:fs";
import mockServer from "../middleware-mockserver.cjs";
import getRawBody from "raw-body";

export async function createTestServer( report, { quiet } = {} ) {
	const indexHTML = await readFile( "./test/index.html", "utf8" );

	// Support connect-style middleware
	const middlewares = [];
	function use( middleware ) {
		middlewares.push( middleware );
	}

	function run( req, res ) {
		let i = 0;

		// Log responses unless quiet is set
		if ( !quiet ) {
			const originalEnd = res.end;
			res.end = function( ...args ) {
				console.log( `${ req.method } ${ req.url } ${ this.statusCode }` );
				originalEnd.call( this, ...args );
			};
		}

		// Add a parsed URL object to the request object
		req.parsedUrl = new URL(
			`http://${ process.env.HOST ?? "localhost" }${ req.url }`
		);

		// Add a simplified redirect helper to the response object
		res.redirect = ( status, location ) => {
			if ( !location ) {
				location = status;
				status = 303;
			}

			res.writeHead( status, { Location: location } );
			res.end();
		};

		const next = () => {
			const middleware = middlewares[ i++ ];
			if ( middleware ) {
				try {
					middleware( req, res, next );
				} catch ( error ) {
					console.error( error );
					res.writeHead( 500, { "Content-Type": "application/json" } );
					res.end( "Internal Server Error" );
				}
			} else {
				res.writeHead( 404 );
				res.end();
			}
		};

		next();
	}

	// Redirect home to test page
	use( ( req, res, next ) => {
		if ( req.parsedUrl.pathname === "/" ) {
			res.redirect( "/test/" );
		} else {
			next();
		}
	} );

	// Redirect to trailing slash
	use( ( req, res, next ) => {
		if ( req.parsedUrl.pathname === "/test" ) {
			res.redirect( 308, `${ req.parsedUrl.pathname }/${ req.parsedUrl.search }` );
		} else {
			next();
		}
	} );

	// Add a script tag to the index.html to load the QUnit listeners
	use( ( req, res, next ) => {
		if (
			( req.method === "GET" || req.method === "HEAD" ) &&
			( req.parsedUrl.pathname === "/test/" ||
				req.parsedUrl.pathname === "/test/index.html" )
		) {
			res.writeHead( 200, { "Content-Type": "text/html" } );
			res.end(
				indexHTML.replace(
					"</head>",
					"<script src=\"/test/runner/listeners.js\"></script></head>"
				)
			);
		} else {
			next();
		}
	} );

	// Bind the reporter
	use( async( req, res, next ) => {
		if ( req.url !== "/api/report" || req.method !== "POST" ) {
			return next();
		}
		let body;
		try {
			body = JSON.parse( await getRawBody( req ) );
		} catch ( error ) {
			if ( error.code === "ECONNABORTED" ) {
				return;
			}
			console.error( error );
			res.writeHead( 400, { "Content-Type": "application/json" } );
			res.end( JSON.stringify( { error: "Invalid JSON" } ) );
			return;
		}
		const response = await report( body );
		if ( response ) {
			res.writeHead( 200, { "Content-Type": "application/json" } );
			res.end( JSON.stringify( response ) );
		} else {
			res.writeHead( 204 );
			res.end();
		}
	} );

	// Hook up mock server
	use( mockServer() );

	// Serve static files
	const validMimeTypes = {

		// No .mjs or .cjs files are used in tests
		".js": "application/javascript",
		".css": "text/css",
		".html": "text/html",
		".xml": "application/xml",
		".xhtml": "application/xhtml+xml",
		".jpg": "image/jpeg",
		".png": "image/png",
		".svg": "image/svg+xml",
		".ico": "image/x-icon",
		".map": "application/json",
		".txt": "text/plain",
		".log": "text/plain"
	};
	use( async( req, res, next ) => {
		if (
			!req.url.startsWith( "/dist/" ) &&
			!req.url.startsWith( "/src/" ) &&
			!req.url.startsWith( "/test/" ) &&
			!req.url.startsWith( "/external/" )
		) {
			return next();
		}
		const file = req.parsedUrl.pathname.slice( 1 );
		const ext = file.slice( file.lastIndexOf( "." ) );

		// Allow POST to .html files in tests
		if (
			req.method !== "GET" &&
			req.method !== "HEAD" &&
			( ext !== ".html" || req.method !== "POST" )
		) {
			return next();
		}
		const mimeType = validMimeTypes[ ext ];
		if ( mimeType ) {
			try {
				await stat( file );
			} catch ( error ) {
				res.writeHead( 404 );
				res.end();
				return;
			}
			res.writeHead( 200, { "Content-Type": mimeType } );
			createReadStream( file )
				.pipe( res )
				.on( "error", ( error ) => {
					console.error( error );
					res.writeHead( 500 );
					res.end();
				} );
		} else {
			console.error( `Invalid file extension: ${ ext }` );
			res.writeHead( 404 );
			res.end();
		}
	} );

	return http.createServer( run );
}