Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add configurable status codes #49

Merged
merged 4 commits into from
Oct 15, 2023
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
43 changes: 29 additions & 14 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ let nodeTestingServer = {
console.log(packageName, 'Served back /post body JSON from the server to the client');

// Print outcoming response CODE
console.log(`\nResponse: ${res.statusCode}`);
console.log(`\nResponse status code: ${res.statusCode}`);
console.log(
'\nResponse data (incoming request body):',
JSON.stringify(JSON.parse(data), null, spacesToIndent)
Expand Down Expand Up @@ -125,7 +125,7 @@ let nodeTestingServer = {
// Show logs if they are enabled in nodeTestingServer.config.logsEnabled
if (nodeTestingServer.config.logsEnabled >= 1) {
// Print outcoming response CODE
console.log(`\nResponse: ${res.statusCode}`);
console.log(`\nResponse status code: ${res.statusCode}`);
console.log(packageName, `Served ${mainPagePath} from the server to the client`);
console.log('\nResponse data:', data);
console.log('========');
Expand Down Expand Up @@ -179,32 +179,38 @@ let nodeTestingServer = {
}

if (supportedFileExtensions.indexOf(fileExtension) === -1) {
res.writeHead(status404, { 'Content-Type': 'text/html' });
res.writeHead(status404, { 'Content-Type': 'text/html', 'Connection': 'close' });
res.end(`<h1>Error 404: ${fileExtension} is not among supported file formats:
${supportedFileExtensions.join(', ')}</h1>`);

// Show logs if they are enabled in nodeTestingServer.config.logsEnabled
if (nodeTestingServer.config.logsEnabled >= 1) {
// Print outcoming response CODE
console.log(`Response: ${res.statusCode}`);
console.log(`Response status code: ${res.statusCode}`);
console.log('========');
}
} else {
fs.exists(filePath, (exists) => {
if (!exists) {
if (typeof nodeTestingServer.config.pages[fileURL] === 'undefined') {
res.writeHead(status404, { 'Content-Type': 'text/html' });
res.writeHead(status404, { 'Content-Type': 'text/html', 'Connection': 'close' });
res.end(`<h1>Error 404: ${fileURL} is not set in nodeTestingServer.config.pages</h1>`);
} else {
// If requested page cannot be found in public/ folder,
// then it will be generated from nodeTestingServer.config.pages
res.writeHead(status200, { 'Content-Type': contentType });
res.end(nodeTestingServer.config.pages[fileURL]);
const pageStatusCode = nodeTestingServer.config.pages[fileURL].pageStatusCode || status200;
const pageBody = nodeTestingServer.config.pages[fileURL].pageBody ||
nodeTestingServer.config.pages[fileURL];

res.writeHead(pageStatusCode, { 'Content-Type': contentType, 'Connection': 'close' });
res.end(pageBody);
// Show logs if they are enabled in nodeTestingServer.config.logsEnabled
if (nodeTestingServer.config.logsEnabled >= 1) {
// Print outcoming response CODE
console.log(`Response: ${res.statusCode}`);
console.log(packageName, `Generated ${fileURL} from nodeTestingServer.config.pages`);
console.log(`\nResponse status code: ${res.statusCode}`);
console.log(`\n${packageName} Generated ${fileURL}` +
'from nodeTestingServer.config.pages');
console.log(`\nResponse data: ${pageBody}`);
console.log('========');
}
if (nodeTestingServer.config.logsEnabled === 2) {
Expand All @@ -216,7 +222,10 @@ let nodeTestingServer = {

return;
}
res.writeHead(status200, { 'Content-Type': contentType });
res.writeHead(
status200,
{ 'Content-Type': contentType, 'Connection': 'close' }
);

let stream = fs.createReadStream(filePath);

Expand All @@ -226,7 +235,7 @@ let nodeTestingServer = {
// Show logs if they are enabled in nodeTestingServer.config.logsEnabled
if (nodeTestingServer.config.logsEnabled >= 1) {
// Print outcoming response CODE
console.log(`\nResponse: ${res.statusCode}`);
console.log(`\nResponse status code: ${res.statusCode}`);
console.log(packageName, `Served ${filePath} from the server to the client`);
console.log('\nResponse data:', data);
console.log('========');
Expand All @@ -243,20 +252,26 @@ let nodeTestingServer = {
});
}
} else {
res.writeHead(status404, { 'Content-Type': 'text/html' });
res.writeHead(
status404,
{ 'Content-Type': 'text/html', 'Connection': 'close' }
);
res.end(`<h1>Error 404: ${req.method} is not supported</h1>`);

// Show logs if they are enabled in nodeTestingServer.config.logsEnabled
if (nodeTestingServer.config.logsEnabled >= 1) {
// Print outcoming response CODE
console.log(`Response: ${res.statusCode}`);
console.log(`Response status code: ${res.statusCode}`);
console.log('========');
}
}
}),

start () {
return this.server.listen(nodeTestingServer.config.port, nodeTestingServer.config.hostname)
return this.server.listen(
nodeTestingServer.config.port,
nodeTestingServer.config.hostname
)
.on('listening', () => console.log(
packageName,
`Server running at http://${nodeTestingServer.config.hostname}:${nodeTestingServer.config.port}/`))
Expand Down
48 changes: 41 additions & 7 deletions tests/page-content-tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,22 @@
<li>Eighth</li>
<li>Ninth</li>
<li>Tenth</li>
</ul>`
</ul>`,
'/test-status-code.html': {
pageStatusCode: 201,
pageBody: `<ul class="items">
<li>First</li>
<li>Second</li>
<li>Third</li>
<li>Fourth</li>
<li>Fifth</li>
<li>Sixth</li>
<li>Seventh</li>
<li>Eighth</li>
<li>Ninth</li>
<li>Tenth</li>
</ul>`
}
}
};

Expand All @@ -34,7 +49,7 @@
* @param {string} bodyString
* @returns {Promise} response
*/
function createRequest (method, requestUrl, bodyString = '') {
function sendRequest (method, requestUrl, bodyString = '') {
return new Promise((resolve, reject) => {
// Check incoming body string to have proper JSON inside of it
const requestBody = bodyString.length > 0 ? JSON.stringify(JSON.parse(bodyString)) : '';
Expand Down Expand Up @@ -75,7 +90,10 @@

console.log(`\nResponse body: ${response}`);
// Resolve after response was finished and all data from response was accumulated
resolve(data);
resolve({
statusCode: res.statusCode,
body: response
});
});
});

Expand All @@ -93,20 +111,21 @@

fixture(
'node-testing-server .html page content tests'
).before(async (ctx) => {

Check warning on line 114 in tests/page-content-tests.js

View workflow job for this annotation

GitHub Actions / build-and-test (ubuntu-latest, 18.x)

'ctx' is defined but never used

Check warning on line 114 in tests/page-content-tests.js

View workflow job for this annotation

GitHub Actions / build-and-test (ubuntu-latest, 20.x)

'ctx' is defined but never used
// Output some information about current tests process
console.log(`==> Tests running at: ${process.cwd()}`);
console.log(`==> With argv: ${process.argv}`);

// Start node testing server
await nodeTestingServer.start();
}).after(async (ctx) => {

Check warning on line 121 in tests/page-content-tests.js

View workflow job for this annotation

GitHub Actions / build-and-test (ubuntu-latest, 18.x)

'ctx' is defined but never used

Check warning on line 121 in tests/page-content-tests.js

View workflow job for this annotation

GitHub Actions / build-and-test (ubuntu-latest, 20.x)

'ctx' is defined but never used
// Stop node testing server
await nodeTestingServer.stop();
});

test.page(
`http://${nodeTestingServer.config.hostname}:${nodeTestingServer.config.port}/`
`http://${nodeTestingServer.config.hostname}` +
`:${nodeTestingServer.config.port}/`
)(
'should get the h1 text from the /index.html main test server page',
async (t) => {
Expand All @@ -132,12 +151,27 @@
test(
'should get the post body string from the /post server page',
async (t) => {
const response = await createRequest(
const response = await sendRequest(
'POST',
`http://${nodeTestingServer.config.hostname}:${nodeTestingServer.config.port}/post`,
`http://${nodeTestingServer.config.hostname}` +
`:${nodeTestingServer.config.port}/post`,
'{ "test1": 1, "test2": "Test text" }'
);

await t.expect(response).contains('Test text');
await t.expect(response.body).contains('Test text');
}
);

test(
'should get the 201 status code from the /test-status-code.html server page',
async (t) => {
const status201 = 201;
const response = await sendRequest(
'GET',
`http://${nodeTestingServer.config.hostname}` +
`:${nodeTestingServer.config.port}/test-status-code.html`
);

await t.expect(response.statusCode === status201).ok();
}
);