1+ const assert = require ( 'assert' )
2+ const childProcess = require ( 'child_process' ) ;
3+ const fs = require ( 'fs' ) ;
4+ const http = require ( 'http' )
5+ const https = require ( 'https' )
6+ const app = require ( '../index.js' )
7+
8+ // run an external script located in the scriptPath
9+ function runScript ( scriptPath , args = [ ] , background = false ) {
10+ return new Promise ( ( resolve , reject ) => {
11+ const process = childProcess . fork ( scriptPath , args )
12+ process . on ( 'error' , err => reject ( err ) )
13+ process . on ( 'exit' , code => {
14+ if ( code === 0 ) resolve ( )
15+ else reject ( code )
16+ } )
17+ if ( background ) resolve ( process )
18+ } )
19+ }
20+
21+ // sleep function, must be used with await
22+ async function sleep ( ms = 0 ) {
23+ return new Promise ( resolve => setTimeout ( resolve , ms ) ) ;
24+ }
25+
26+ // make an http request on the specified path
27+ function makeRequest ( path = "/" , secure = false ) {
28+ const agentOptions = {
29+ host : 'localhost' ,
30+ port : '443' ,
31+ path : '/' ,
32+ rejectUnauthorized : false
33+ }
34+ const options = {
35+ host : "localhost" ,
36+ path : path ,
37+ method : "GET" ,
38+ headers : { }
39+ }
40+ if ( secure ) options . agent = new https . Agent ( agentOptions )
41+ const protocol = secure ? https : http
42+ return new Promise ( ( resolve , reject ) => {
43+ protocol . request ( options , resp => {
44+ let data = ""
45+ resp . on ( 'data' , chunk => data += chunk )
46+ resp . on ( 'end' , ( ) => resolve ( {
47+ data : data ,
48+ statusCode : resp . statusCode
49+ } ) )
50+ } ) . on ( "error" , err => reject ( err ) )
51+ . end ( )
52+ } )
53+ }
54+
55+ let process
56+
57+ // TESTS
58+ describe ( "Testing https-localhost" , ( ) => {
59+ it ( 'redirect http to https' , async function ( ) {
60+ await makeRequest ( )
61+ . then ( res => assert ( res . statusCode === 301 ) )
62+ } )
63+ it ( 'works as a module' , async function ( ) {
64+ app . get ( "/test" , ( req , res ) => res . send ( "TEST" ) )
65+ await makeRequest ( "/test" , true )
66+ . then ( res => assert ( res . data === "TEST" ) )
67+ } )
68+ it ( 'serve static file used as standalone tool' , async function ( ) {
69+ await app . close ( )
70+ runScript ( "index.js" , [ "test" ] , true )
71+ . then ( proc => process = proc )
72+ . catch ( err => console . error ( err ) )
73+ await sleep ( 500 )
74+ await makeRequest ( "/test.html" , true )
75+ . then ( res => assert ( res . data . toString ( ) === fs . readFileSync ( "test/test.html" ) . toString ( ) ) )
76+ if ( process ) process . kill ( 'SIGINT' )
77+ } )
78+ } )
0 commit comments