Best JavaScript code snippet using testcafe
send.js
Source:send.js
...8var send = require('..')9// test server10var dateRegExp = /^\w{3}, \d+ \w+ \d+ \d+:\d+:\d+ \w+$/11var fixtures = path.join(__dirname, 'fixtures')12var app = http.createServer(function (req, res) {13 function error (err) {14 res.statusCode = err.status15 res.end(http.STATUS_CODES[err.status])16 }17 send(req, req.url, { root: fixtures })18 .on('error', error)19 .pipe(res)20})21describe('send(file).pipe(res)', function () {22 it('should stream the file contents', function (done) {23 request(app)24 .get('/name.txt')25 .expect('Content-Length', '4')26 .expect(200, 'tobi', done)27 })28 it('should stream a zero-length file', function (done) {29 request(app)30 .get('/empty.txt')31 .expect('Content-Length', '0')32 .expect(200, '', done)33 })34 it('should decode the given path as a URI', function (done) {35 request(app)36 .get('/some%20thing.txt')37 .expect(200, 'hey', done)38 })39 it('should serve files with dots in name', function (done) {40 request(app)41 .get('/do..ts.txt')42 .expect(200, '...', done)43 })44 it('should treat a malformed URI as a bad request', function (done) {45 request(app)46 .get('/some%99thing.txt')47 .expect(400, 'Bad Request', done)48 })49 it('should 400 on NULL bytes', function (done) {50 request(app)51 .get('/some%00thing.txt')52 .expect(400, 'Bad Request', done)53 })54 it('should treat an ENAMETOOLONG as a 404', function (done) {55 var path = Array(100).join('foobar')56 request(app)57 .get('/' + path)58 .expect(404, done)59 })60 it('should handle headers already sent error', function (done) {61 var app = http.createServer(function (req, res) {62 res.write('0')63 send(req, req.url, { root: fixtures })64 .on('error', function (err) { res.end(' - ' + err.message) })65 .pipe(res)66 })67 request(app)68 .get('/name.txt')69 .expect(200, '0 - Can\'t set headers after they are sent.', done)70 })71 it('should support HEAD', function (done) {72 request(app)73 .head('/name.txt')74 .expect(200)75 .expect('Content-Length', '4')76 .expect(shouldNotHaveBody())77 .end(done)78 })79 it('should add an ETag header field', function (done) {80 request(app)81 .get('/name.txt')82 .expect('etag', /^W\/"[^"]+"$/)83 .end(done)84 })85 it('should add a Date header field', function (done) {86 request(app)87 .get('/name.txt')88 .expect('date', dateRegExp, done)89 })90 it('should add a Last-Modified header field', function (done) {91 request(app)92 .get('/name.txt')93 .expect('last-modified', dateRegExp, done)94 })95 it('should add a Accept-Ranges header field', function (done) {96 request(app)97 .get('/name.txt')98 .expect('Accept-Ranges', 'bytes', done)99 })100 it('should 404 if the file does not exist', function (done) {101 request(app)102 .get('/meow')103 .expect(404, 'Not Found', done)104 })105 it('should emit ENOENT if the file does not exist', function (done) {106 var app = http.createServer(function (req, res) {107 send(req, req.url, { root: fixtures })108 .on('error', function (err) { res.end(err.statusCode + ' ' + err.code) })109 .pipe(res)110 })111 request(app)112 .get('/meow')113 .expect(200, '404 ENOENT', done)114 })115 it('should not override content-type', function (done) {116 var app = http.createServer(function (req, res) {117 res.setHeader('Content-Type', 'application/x-custom')118 send(req, req.url, { root: fixtures }).pipe(res)119 })120 request(app)121 .get('/name.txt')122 .expect('Content-Type', 'application/x-custom', done)123 })124 it('should set Content-Type via mime map', function (done) {125 request(app)126 .get('/name.txt')127 .expect('Content-Type', 'text/plain; charset=UTF-8')128 .expect(200, function (err) {129 if (err) return done(err)130 request(app)131 .get('/tobi.html')132 .expect('Content-Type', 'text/html; charset=UTF-8')133 .expect(200, done)134 })135 })136 it('should 404 if file disappears after stat, before open', function (done) {137 var app = http.createServer(function (req, res) {138 send(req, req.url, { root: 'test/fixtures' })139 .on('file', function () {140 // simulate file ENOENT after on open, after stat141 var fn = this.send142 this.send = function (path, stat) {143 fn.call(this, (path + '__xxx_no_exist'), stat)144 }145 })146 .pipe(res)147 })148 request(app)149 .get('/name.txt')150 .expect(404, done)151 })152 it('should 500 on file stream error', function (done) {153 var app = http.createServer(function (req, res) {154 send(req, req.url, { root: 'test/fixtures' })155 .on('stream', function (stream) {156 // simulate file error157 stream.on('open', function () {158 stream.emit('error', new Error('boom!'))159 })160 })161 .pipe(res)162 })163 request(app)164 .get('/name.txt')165 .expect(500, done)166 })167 describe('"headers" event', function () {168 it('should fire when sending file', function (done) {169 var cb = after(2, done)170 var server = http.createServer(function (req, res) {171 send(req, req.url, { root: fixtures })172 .on('headers', function () { cb() })173 .pipe(res)174 })175 request(server)176 .get('/name.txt')177 .expect(200, 'tobi', cb)178 })179 it('should not fire on 404', function (done) {180 var cb = after(1, done)181 var server = http.createServer(function (req, res) {182 send(req, req.url, { root: fixtures })183 .on('headers', function () { cb() })184 .pipe(res)185 })186 request(server)187 .get('/bogus')188 .expect(404, cb)189 })190 it('should fire on index', function (done) {191 var cb = after(2, done)192 var server = http.createServer(function (req, res) {193 send(req, req.url, { root: fixtures })194 .on('headers', function () { cb() })195 .pipe(res)196 })197 request(server)198 .get('/pets/')199 .expect(200, /tobi/, cb)200 })201 it('should not fire on redirect', function (done) {202 var cb = after(1, done)203 var server = http.createServer(function (req, res) {204 send(req, req.url, { root: fixtures })205 .on('headers', function () { cb() })206 .pipe(res)207 })208 request(server)209 .get('/pets')210 .expect(301, cb)211 })212 it('should provide path', function (done) {213 var cb = after(2, done)214 var server = http.createServer(function (req, res) {215 send(req, req.url, { root: fixtures })216 .on('headers', onHeaders)217 .pipe(res)218 })219 function onHeaders (res, filePath) {220 assert.ok(filePath)221 assert.strictEqual(path.normalize(filePath), path.normalize(path.join(fixtures, 'name.txt')))222 cb()223 }224 request(server)225 .get('/name.txt')226 .expect(200, 'tobi', cb)227 })228 it('should provide stat', function (done) {229 var cb = after(2, done)230 var server = http.createServer(function (req, res) {231 send(req, req.url, { root: fixtures })232 .on('headers', onHeaders)233 .pipe(res)234 })235 function onHeaders (res, path, stat) {236 assert.ok(stat)237 assert.ok('ctime' in stat)238 assert.ok('mtime' in stat)239 cb()240 }241 request(server)242 .get('/name.txt')243 .expect(200, 'tobi', cb)244 })245 it('should allow altering headers', function (done) {246 var server = http.createServer(function (req, res) {247 send(req, req.url, { root: fixtures })248 .on('headers', onHeaders)249 .pipe(res)250 })251 function onHeaders (res, path, stat) {252 res.setHeader('Cache-Control', 'no-cache')253 res.setHeader('Content-Type', 'text/x-custom')254 res.setHeader('ETag', 'W/"everything"')255 res.setHeader('X-Created', stat.ctime.toUTCString())256 }257 request(server)258 .get('/name.txt')259 .expect(200)260 .expect('Cache-Control', 'no-cache')261 .expect('Content-Type', 'text/x-custom')262 .expect('ETag', 'W/"everything"')263 .expect('X-Created', dateRegExp)264 .expect('tobi')265 .end(done)266 })267 })268 describe('when "directory" listeners are present', function () {269 it('should be called when sending directory', function (done) {270 var server = http.createServer(function (req, res) {271 send(req, req.url, { root: fixtures })272 .on('directory', onDirectory)273 .pipe(res)274 })275 function onDirectory (res) {276 res.statusCode = 400277 res.end('No directory for you')278 }279 request(server)280 .get('/pets')281 .expect(400, 'No directory for you', done)282 })283 it('should be called with path', function (done) {284 var server = http.createServer(function (req, res) {285 send(req, req.url, { root: fixtures })286 .on('directory', onDirectory)287 .pipe(res)288 })289 function onDirectory (res, dirPath) {290 res.end(path.normalize(dirPath))291 }292 request(server)293 .get('/pets')294 .expect(200, path.normalize(path.join(fixtures, 'pets')), done)295 })296 })297 describe('when no "directory" listeners are present', function () {298 it('should redirect directories to trailing slash', function (done) {299 request(createServer({ root: fixtures }))300 .get('/pets')301 .expect('Location', '/pets/')302 .expect(301, done)303 })304 it('should respond with an HTML redirect', function (done) {305 request(createServer({ root: fixtures }))306 .get('/pets')307 .expect('Location', '/pets/')308 .expect('Content-Type', /html/)309 .expect(301, />Redirecting to <a href="\/pets\/">\/pets\/<\/a></, done)310 })311 it('should respond with default Content-Security-Policy', function (done) {312 request(createServer({ root: fixtures }))313 .get('/pets')314 .expect('Location', '/pets/')315 .expect('Content-Security-Policy', "default-src 'none'")316 .expect(301, done)317 })318 it('should not redirect to protocol-relative locations', function (done) {319 request(createServer({ root: fixtures }))320 .get('//pets')321 .expect('Location', '/pets/')322 .expect(301, done)323 })324 it('should respond with an HTML redirect', function (done) {325 var app = http.createServer(function (req, res) {326 send(req, req.url.replace('/snow', '/snow â'), { root: 'test/fixtures' })327 .pipe(res)328 })329 request(app)330 .get('/snow')331 .expect('Location', '/snow%20%E2%98%83/')332 .expect('Content-Type', /html/)333 .expect(301, />Redirecting to <a href="\/snow%20%E2%98%83\/">\/snow%20%E2%98%83\/<\/a></, done)334 })335 })336 describe('when no "error" listeners are present', function () {337 it('should respond to errors directly', function (done) {338 request(createServer({ root: fixtures }))339 .get('/foobar')340 .expect(404, />Not Found</, done)341 })342 it('should respond with default Content-Security-Policy', function (done) {343 request(createServer({ root: fixtures }))344 .get('/foobar')345 .expect('Content-Security-Policy', "default-src 'none'")346 .expect(404, done)347 })348 it('should remove all previously-set headers', function (done) {349 var server = createServer({ root: fixtures }, function (req, res) {350 res.setHeader('X-Foo', 'bar')351 })352 request(server)353 .get('/foobar')354 .expect(shouldNotHaveHeader('X-Foo'))355 .expect(404, done)356 })357 })358 describe('with conditional-GET', function () {359 it('should remove Content headers with 304', function (done) {360 var server = createServer({ root: fixtures }, function (req, res) {361 res.setHeader('Content-Language', 'en-US')362 res.setHeader('Content-Location', 'http://localhost/name.txt')363 res.setHeader('Contents', 'foo')364 })365 request(server)366 .get('/name.txt')367 .expect(200, function (err, res) {368 if (err) return done(err)369 request(server)370 .get('/name.txt')371 .set('If-None-Match', res.headers.etag)372 .expect(shouldNotHaveHeader('Content-Language'))373 .expect(shouldNotHaveHeader('Content-Length'))374 .expect(shouldNotHaveHeader('Content-Type'))375 .expect('Content-Location', 'http://localhost/name.txt')376 .expect('Contents', 'foo')377 .expect(304, done)378 })379 })380 describe('where "If-Match" is set', function () {381 it('should respond with 200 when "*"', function (done) {382 request(app)383 .get('/name.txt')384 .set('If-Match', '*')385 .expect(200, done)386 })387 it('should respond with 412 when ETag unmatched', function (done) {388 request(app)389 .get('/name.txt')390 .set('If-Match', ' "foo", "bar" ')391 .expect(412, done)392 })393 it('should respond with 200 when ETag matched', function (done) {394 request(app)395 .get('/name.txt')396 .expect(200, function (err, res) {397 if (err) return done(err)398 request(app)399 .get('/name.txt')400 .set('If-Match', '"foo", "bar", ' + res.headers.etag)401 .expect(200, done)402 })403 })404 })405 describe('where "If-Modified-Since" is set', function () {406 it('should respond with 304 when unmodified', function (done) {407 request(app)408 .get('/name.txt')409 .expect(200, function (err, res) {410 if (err) return done(err)411 request(app)412 .get('/name.txt')413 .set('If-Modified-Since', res.headers['last-modified'])414 .expect(304, done)415 })416 })417 it('should respond with 200 when modified', function (done) {418 request(app)419 .get('/name.txt')420 .expect(200, function (err, res) {421 if (err) return done(err)422 var lmod = new Date(res.headers['last-modified'])423 var date = new Date(lmod - 60000)424 request(app)425 .get('/name.txt')426 .set('If-Modified-Since', date.toUTCString())427 .expect(200, 'tobi', done)428 })429 })430 })431 describe('where "If-None-Match" is set', function () {432 it('should respond with 304 when ETag matched', function (done) {433 request(app)434 .get('/name.txt')435 .expect(200, function (err, res) {436 if (err) return done(err)437 request(app)438 .get('/name.txt')439 .set('If-None-Match', res.headers.etag)440 .expect(304, done)441 })442 })443 it('should respond with 200 when ETag unmatched', function (done) {444 request(app)445 .get('/name.txt')446 .expect(200, function (err, res) {447 if (err) return done(err)448 request(app)449 .get('/name.txt')450 .set('If-None-Match', '"123"')451 .expect(200, 'tobi', done)452 })453 })454 })455 describe('where "If-Unmodified-Since" is set', function () {456 it('should respond with 200 when unmodified', function (done) {457 request(app)458 .get('/name.txt')459 .expect(200, function (err, res) {460 if (err) return done(err)461 request(app)462 .get('/name.txt')463 .set('If-Unmodified-Since', res.headers['last-modified'])464 .expect(200, done)465 })466 })467 it('should respond with 412 when modified', function (done) {468 request(app)469 .get('/name.txt')470 .expect(200, function (err, res) {471 if (err) return done(err)472 var lmod = new Date(res.headers['last-modified'])473 var date = new Date(lmod - 60000).toUTCString()474 request(app)475 .get('/name.txt')476 .set('If-Unmodified-Since', date)477 .expect(412, done)478 })479 })480 it('should respond with 200 when invalid date', function (done) {481 request(app)482 .get('/name.txt')483 .set('If-Unmodified-Since', 'foo')484 .expect(200, done)485 })486 })487 })488 describe('with Range request', function () {489 it('should support byte ranges', function (done) {490 request(app)491 .get('/nums.txt')492 .set('Range', 'bytes=0-4')493 .expect(206, '12345', done)494 })495 it('should ignore non-byte ranges', function (done) {496 request(app)497 .get('/nums.txt')498 .set('Range', 'items=0-4')499 .expect(200, '123456789', done)500 })501 it('should be inclusive', function (done) {502 request(app)503 .get('/nums.txt')504 .set('Range', 'bytes=0-0')505 .expect(206, '1', done)506 })507 it('should set Content-Range', function (done) {508 request(app)509 .get('/nums.txt')510 .set('Range', 'bytes=2-5')511 .expect('Content-Range', 'bytes 2-5/9')512 .expect(206, done)513 })514 it('should support -n', function (done) {515 request(app)516 .get('/nums.txt')517 .set('Range', 'bytes=-3')518 .expect(206, '789', done)519 })520 it('should support n-', function (done) {521 request(app)522 .get('/nums.txt')523 .set('Range', 'bytes=3-')524 .expect(206, '456789', done)525 })526 it('should respond with 206 "Partial Content"', function (done) {527 request(app)528 .get('/nums.txt')529 .set('Range', 'bytes=0-4')530 .expect(206, done)531 })532 it('should set Content-Length to the # of octets transferred', function (done) {533 request(app)534 .get('/nums.txt')535 .set('Range', 'bytes=2-3')536 .expect('Content-Length', '2')537 .expect(206, '34', done)538 })539 describe('when last-byte-pos of the range is greater the length', function () {540 it('is taken to be equal to one less than the length', function (done) {541 request(app)542 .get('/nums.txt')543 .set('Range', 'bytes=2-50')544 .expect('Content-Range', 'bytes 2-8/9')545 .expect(206, done)546 })547 it('should adapt the Content-Length accordingly', function (done) {548 request(app)549 .get('/nums.txt')550 .set('Range', 'bytes=2-50')551 .expect('Content-Length', '7')552 .expect(206, done)553 })554 })555 describe('when the first- byte-pos of the range is greater length', function () {556 it('should respond with 416', function (done) {557 request(app)558 .get('/nums.txt')559 .set('Range', 'bytes=9-50')560 .expect('Content-Range', 'bytes */9')561 .expect(416, done)562 })563 })564 describe('when syntactically invalid', function () {565 it('should respond with 200 and the entire contents', function (done) {566 request(app)567 .get('/nums.txt')568 .set('Range', 'asdf')569 .expect(200, '123456789', done)570 })571 })572 describe('when multiple ranges', function () {573 it('should respond with 200 and the entire contents', function (done) {574 request(app)575 .get('/nums.txt')576 .set('Range', 'bytes=1-1,3-')577 .expect(shouldNotHaveHeader('Content-Range'))578 .expect(200, '123456789', done)579 })580 it('should respond with 206 is all ranges can be combined', function (done) {581 request(app)582 .get('/nums.txt')583 .set('Range', 'bytes=1-2,3-5')584 .expect('Content-Range', 'bytes 1-5/9')585 .expect(206, '23456', done)586 })587 })588 describe('when if-range present', function () {589 it('should respond with parts when etag unchanged', function (done) {590 request(app)591 .get('/nums.txt')592 .expect(200, function (err, res) {593 if (err) return done(err)594 var etag = res.headers.etag595 request(app)596 .get('/nums.txt')597 .set('If-Range', etag)598 .set('Range', 'bytes=0-0')599 .expect(206, '1', done)600 })601 })602 it('should respond with 200 when etag changed', function (done) {603 request(app)604 .get('/nums.txt')605 .expect(200, function (err, res) {606 if (err) return done(err)607 var etag = res.headers.etag.replace(/"(.)/, '"0$1')608 request(app)609 .get('/nums.txt')610 .set('If-Range', etag)611 .set('Range', 'bytes=0-0')612 .expect(200, '123456789', done)613 })614 })615 it('should respond with parts when modified unchanged', function (done) {616 request(app)617 .get('/nums.txt')618 .expect(200, function (err, res) {619 if (err) return done(err)620 var modified = res.headers['last-modified']621 request(app)622 .get('/nums.txt')623 .set('If-Range', modified)624 .set('Range', 'bytes=0-0')625 .expect(206, '1', done)626 })627 })628 it('should respond with 200 when modified changed', function (done) {629 request(app)630 .get('/nums.txt')631 .expect(200, function (err, res) {632 if (err) return done(err)633 var modified = Date.parse(res.headers['last-modified']) - 20000634 request(app)635 .get('/nums.txt')636 .set('If-Range', new Date(modified).toUTCString())637 .set('Range', 'bytes=0-0')638 .expect(200, '123456789', done)639 })640 })641 it('should respond with 200 when invalid value', function (done) {642 request(app)643 .get('/nums.txt')644 .set('If-Range', 'foo')645 .set('Range', 'bytes=0-0')646 .expect(200, '123456789', done)647 })648 })649 })650 describe('when "options" is specified', function () {651 it('should support start/end', function (done) {652 request(createServer({ root: fixtures, start: 3, end: 5 }))653 .get('/nums.txt')654 .expect(200, '456', done)655 })656 it('should adjust too large end', function (done) {657 request(createServer({ root: fixtures, start: 3, end: 90 }))658 .get('/nums.txt')659 .expect(200, '456789', done)660 })661 it('should support start/end with Range request', function (done) {662 request(createServer({ root: fixtures, start: 0, end: 2 }))663 .get('/nums.txt')664 .set('Range', 'bytes=-2')665 .expect(206, '23', done)666 })667 it('should support start/end with unsatisfiable Range request', function (done) {668 request(createServer({ root: fixtures, start: 0, end: 2 }))669 .get('/nums.txt')670 .set('Range', 'bytes=5-9')671 .expect('Content-Range', 'bytes */3')672 .expect(416, done)673 })674 })675 describe('.etag()', function () {676 it('should support disabling etags', function (done) {677 var app = http.createServer(function (req, res) {678 send(req, req.url, { root: fixtures })679 .etag(false)680 .pipe(res)681 })682 request(app)683 .get('/name.txt')684 .expect(shouldNotHaveHeader('ETag'))685 .expect(200, done)686 })687 })688 describe('.from()', function () {689 it('should set with deprecated from', function (done) {690 var app = http.createServer(function (req, res) {691 send(req, req.url)692 .from(fixtures)693 .pipe(res)694 })695 request(app)696 .get('/pets/../name.txt')697 .expect(200, 'tobi', done)698 })699 })700 describe('.hidden()', function () {701 it('should default support sending hidden files', function (done) {702 var app = http.createServer(function (req, res) {703 send(req, req.url, { root: fixtures })704 .hidden(true)705 .pipe(res)706 })707 request(app)708 .get('/.hidden.txt')709 .expect(200, 'secret', done)710 })711 })712 describe('.index()', function () {713 it('should be configurable', function (done) {714 var app = http.createServer(function (req, res) {715 send(req, req.url, { root: fixtures })716 .index('tobi.html')717 .pipe(res)718 })719 request(app)720 .get('/')721 .expect(200, '<p>tobi</p>', done)722 })723 it('should support disabling', function (done) {724 var app = http.createServer(function (req, res) {725 send(req, req.url, { root: fixtures })726 .index(false)727 .pipe(res)728 })729 request(app)730 .get('/pets/')731 .expect(403, done)732 })733 it('should support fallbacks', function (done) {734 var app = http.createServer(function (req, res) {735 send(req, req.url, { root: fixtures })736 .index(['default.htm', 'index.html'])737 .pipe(res)738 })739 request(app)740 .get('/pets/')741 .expect(200, fs.readFileSync(path.join(fixtures, 'pets', 'index.html'), 'utf8'), done)742 })743 })744 describe('.maxage()', function () {745 it('should default to 0', function (done) {746 var app = http.createServer(function (req, res) {747 send(req, 'test/fixtures/name.txt')748 .maxage(undefined)749 .pipe(res)750 })751 request(app)752 .get('/name.txt')753 .expect('Cache-Control', 'public, max-age=0', done)754 })755 it('should floor to integer', function (done) {756 var app = http.createServer(function (req, res) {757 send(req, 'test/fixtures/name.txt')758 .maxage(1234)759 .pipe(res)760 })761 request(app)762 .get('/name.txt')763 .expect('Cache-Control', 'public, max-age=1', done)764 })765 it('should accept string', function (done) {766 var app = http.createServer(function (req, res) {767 send(req, 'test/fixtures/name.txt')768 .maxage('30d')769 .pipe(res)770 })771 request(app)772 .get('/name.txt')773 .expect('Cache-Control', 'public, max-age=2592000', done)774 })775 it('should max at 1 year', function (done) {776 var app = http.createServer(function (req, res) {777 send(req, 'test/fixtures/name.txt')778 .maxage(Infinity)779 .pipe(res)780 })781 request(app)782 .get('/name.txt')783 .expect('Cache-Control', 'public, max-age=31536000', done)784 })785 })786 describe('.root()', function () {787 it('should set root', function (done) {788 var app = http.createServer(function (req, res) {789 send(req, req.url)790 .root(fixtures)791 .pipe(res)792 })793 request(app)794 .get('/pets/../name.txt')795 .expect(200, 'tobi', done)796 })797 })798})799describe('send(file, options)', function () {800 describe('acceptRanges', function () {801 it('should support disabling accept-ranges', function (done) {802 request(createServer({ acceptRanges: false, root: fixtures }))803 .get('/nums.txt')804 .expect(shouldNotHaveHeader('Accept-Ranges'))805 .expect(200, done)806 })807 it('should ignore requested range', function (done) {808 request(createServer({ acceptRanges: false, root: fixtures }))809 .get('/nums.txt')810 .set('Range', 'bytes=0-2')811 .expect(shouldNotHaveHeader('Accept-Ranges'))812 .expect(shouldNotHaveHeader('Content-Range'))813 .expect(200, '123456789', done)814 })815 })816 describe('cacheControl', function () {817 it('should support disabling cache-control', function (done) {818 request(createServer({ cacheControl: false, root: fixtures }))819 .get('/name.txt')820 .expect(shouldNotHaveHeader('Cache-Control'))821 .expect(200, done)822 })823 it('should ignore maxAge option', function (done) {824 request(createServer({ cacheControl: false, maxAge: 1000, root: fixtures }))825 .get('/name.txt')826 .expect(shouldNotHaveHeader('Cache-Control'))827 .expect(200, done)828 })829 })830 describe('etag', function () {831 it('should support disabling etags', function (done) {832 request(createServer({ etag: false, root: fixtures }))833 .get('/name.txt')834 .expect(shouldNotHaveHeader('ETag'))835 .expect(200, done)836 })837 })838 describe('extensions', function () {839 it('should reject numbers', function (done) {840 request(createServer({ extensions: 42, root: fixtures }))841 .get('/pets/')842 .expect(500, /TypeError: extensions option/, done)843 })844 it('should reject true', function (done) {845 request(createServer({ extensions: true, root: fixtures }))846 .get('/pets/')847 .expect(500, /TypeError: extensions option/, done)848 })849 it('should be not be enabled by default', function (done) {850 request(createServer({ root: fixtures }))851 .get('/tobi')852 .expect(404, done)853 })854 it('should be configurable', function (done) {855 request(createServer({ extensions: 'txt', root: fixtures }))856 .get('/name')857 .expect(200, 'tobi', done)858 })859 it('should support disabling extensions', function (done) {860 request(createServer({ extensions: false, root: fixtures }))861 .get('/name')862 .expect(404, done)863 })864 it('should support fallbacks', function (done) {865 request(createServer({ extensions: ['htm', 'html', 'txt'], root: fixtures }))866 .get('/name')867 .expect(200, '<p>tobi</p>', done)868 })869 it('should 404 if nothing found', function (done) {870 request(createServer({ extensions: ['htm', 'html', 'txt'], root: fixtures }))871 .get('/bob')872 .expect(404, done)873 })874 it('should skip directories', function (done) {875 request(createServer({ extensions: ['file', 'dir'], root: fixtures }))876 .get('/name')877 .expect(404, done)878 })879 it('should not search if file has extension', function (done) {880 request(createServer({ extensions: 'html', root: fixtures }))881 .get('/thing.html')882 .expect(404, done)883 })884 })885 describe('lastModified', function () {886 it('should support disabling last-modified', function (done) {887 request(createServer({ lastModified: false, root: fixtures }))888 .get('/name.txt')889 .expect(shouldNotHaveHeader('Last-Modified'))890 .expect(200, done)891 })892 })893 describe('from', function () {894 it('should set with deprecated from', function (done) {895 request(createServer({ from: fixtures }))896 .get('/pets/../name.txt')897 .expect(200, 'tobi', done)898 })899 })900 describe('dotfiles', function () {901 it('should default to "ignore"', function (done) {902 request(createServer({ root: fixtures }))903 .get('/.hidden.txt')904 .expect(404, done)905 })906 it('should allow file within dotfile directory for back-compat', function (done) {907 request(createServer({ root: fixtures }))908 .get('/.mine/name.txt')909 .expect(200, /tobi/, done)910 })911 it('should reject bad value', function (done) {912 request(createServer({ dotfiles: 'bogus' }))913 .get('/name.txt')914 .expect(500, /dotfiles/, done)915 })916 describe('when "allow"', function (done) {917 it('should send dotfile', function (done) {918 request(createServer({ dotfiles: 'allow', root: fixtures }))919 .get('/.hidden.txt')920 .expect(200, 'secret', done)921 })922 it('should send within dotfile directory', function (done) {923 request(createServer({ dotfiles: 'allow', root: fixtures }))924 .get('/.mine/name.txt')925 .expect(200, /tobi/, done)926 })927 it('should 404 for non-existent dotfile', function (done) {928 request(createServer({ dotfiles: 'allow', root: fixtures }))929 .get('/.nothere')930 .expect(404, done)931 })932 })933 describe('when "deny"', function (done) {934 it('should 403 for dotfile', function (done) {935 request(createServer({ dotfiles: 'deny', root: fixtures }))936 .get('/.hidden.txt')937 .expect(403, done)938 })939 it('should 403 for dotfile directory', function (done) {940 request(createServer({ dotfiles: 'deny', root: fixtures }))941 .get('/.mine')942 .expect(403, done)943 })944 it('should 403 for dotfile directory with trailing slash', function (done) {945 request(createServer({ dotfiles: 'deny', root: fixtures }))946 .get('/.mine/')947 .expect(403, done)948 })949 it('should 403 for file within dotfile directory', function (done) {950 request(createServer({ dotfiles: 'deny', root: fixtures }))951 .get('/.mine/name.txt')952 .expect(403, done)953 })954 it('should 403 for non-existent dotfile', function (done) {955 request(createServer({ dotfiles: 'deny', root: fixtures }))956 .get('/.nothere')957 .expect(403, done)958 })959 it('should 403 for non-existent dotfile directory', function (done) {960 request(createServer({ dotfiles: 'deny', root: fixtures }))961 .get('/.what/name.txt')962 .expect(403, done)963 })964 it('should 403 for dotfile in directory', function (done) {965 request(createServer({ dotfiles: 'deny', root: fixtures }))966 .get('/pets/.hidden')967 .expect(403, done)968 })969 it('should 403 for dotfile in dotfile directory', function (done) {970 request(createServer({ dotfiles: 'deny', root: fixtures }))971 .get('/.mine/.hidden')972 .expect(403, done)973 })974 it('should send files in root dotfile directory', function (done) {975 request(createServer({ dotfiles: 'deny', root: path.join(fixtures, '.mine') }))976 .get('/name.txt')977 .expect(200, /tobi/, done)978 })979 it('should 403 for dotfile without root', function (done) {980 var server = http.createServer(function onRequest (req, res) {981 send(req, fixtures + '/.mine' + req.url, { dotfiles: 'deny' }).pipe(res)982 })983 request(server)984 .get('/name.txt')985 .expect(403, done)986 })987 })988 describe('when "ignore"', function (done) {989 it('should 404 for dotfile', function (done) {990 request(createServer({ dotfiles: 'ignore', root: fixtures }))991 .get('/.hidden.txt')992 .expect(404, done)993 })994 it('should 404 for dotfile directory', function (done) {995 request(createServer({ dotfiles: 'ignore', root: fixtures }))996 .get('/.mine')997 .expect(404, done)998 })999 it('should 404 for dotfile directory with trailing slash', function (done) {1000 request(createServer({ dotfiles: 'ignore', root: fixtures }))1001 .get('/.mine/')1002 .expect(404, done)1003 })1004 it('should 404 for file within dotfile directory', function (done) {1005 request(createServer({ dotfiles: 'ignore', root: fixtures }))1006 .get('/.mine/name.txt')1007 .expect(404, done)1008 })1009 it('should 404 for non-existent dotfile', function (done) {1010 request(createServer({ dotfiles: 'ignore', root: fixtures }))1011 .get('/.nothere')1012 .expect(404, done)1013 })1014 it('should 404 for non-existent dotfile directory', function (done) {1015 request(createServer({ dotfiles: 'ignore', root: fixtures }))1016 .get('/.what/name.txt')1017 .expect(404, done)1018 })1019 it('should send files in root dotfile directory', function (done) {1020 request(createServer({ dotfiles: 'ignore', root: path.join(fixtures, '.mine') }))1021 .get('/name.txt')1022 .expect(200, /tobi/, done)1023 })1024 it('should 404 for dotfile without root', function (done) {1025 var server = http.createServer(function onRequest (req, res) {1026 send(req, fixtures + '/.mine' + req.url, { dotfiles: 'ignore' }).pipe(res)1027 })1028 request(server)1029 .get('/name.txt')1030 .expect(404, done)1031 })1032 })1033 })1034 describe('hidden', function () {1035 it('should default to false', function (done) {1036 request(app)1037 .get('/.hidden.txt')1038 .expect(404, 'Not Found', done)1039 })1040 it('should default support sending hidden files', function (done) {1041 request(createServer({ hidden: true, root: fixtures }))1042 .get('/.hidden.txt')1043 .expect(200, 'secret', done)1044 })1045 })1046 describe('immutable', function () {1047 it('should default to false', function (done) {1048 request(createServer({ root: fixtures }))1049 .get('/name.txt')1050 .expect('Cache-Control', 'public, max-age=0', done)1051 })1052 it('should set immutable directive in Cache-Control', function (done) {1053 request(createServer({ immutable: true, maxAge: '1h', root: fixtures }))1054 .get('/name.txt')1055 .expect('Cache-Control', 'public, max-age=3600, immutable', done)1056 })1057 })1058 describe('maxAge', function () {1059 it('should default to 0', function (done) {1060 request(createServer({ root: fixtures }))1061 .get('/name.txt')1062 .expect('Cache-Control', 'public, max-age=0', done)1063 })1064 it('should floor to integer', function (done) {1065 request(createServer({ maxAge: 123956, root: fixtures }))1066 .get('/name.txt')1067 .expect('Cache-Control', 'public, max-age=123', done)1068 })1069 it('should accept string', function (done) {1070 request(createServer({ maxAge: '30d', root: fixtures }))1071 .get('/name.txt')1072 .expect('Cache-Control', 'public, max-age=2592000', done)1073 })1074 it('should max at 1 year', function (done) {1075 request(createServer({ maxAge: '2y', root: fixtures }))1076 .get('/name.txt')1077 .expect('Cache-Control', 'public, max-age=31536000', done)1078 })1079 })1080 describe('index', function () {1081 it('should reject numbers', function (done) {1082 request(createServer({ root: fixtures, index: 42 }))1083 .get('/pets/')1084 .expect(500, /TypeError: index option/, done)1085 })1086 it('should reject true', function (done) {1087 request(createServer({ root: fixtures, index: true }))1088 .get('/pets/')1089 .expect(500, /TypeError: index option/, done)1090 })1091 it('should default to index.html', function (done) {1092 request(createServer({ root: fixtures }))1093 .get('/pets/')1094 .expect(fs.readFileSync(path.join(fixtures, 'pets', 'index.html'), 'utf8'), done)1095 })1096 it('should be configurable', function (done) {1097 request(createServer({ root: fixtures, index: 'tobi.html' }))1098 .get('/')1099 .expect(200, '<p>tobi</p>', done)1100 })1101 it('should support disabling', function (done) {1102 request(createServer({ root: fixtures, index: false }))1103 .get('/pets/')1104 .expect(403, done)1105 })1106 it('should support fallbacks', function (done) {1107 request(createServer({ root: fixtures, index: ['default.htm', 'index.html'] }))1108 .get('/pets/')1109 .expect(200, fs.readFileSync(path.join(fixtures, 'pets', 'index.html'), 'utf8'), done)1110 })1111 it('should 404 if no index file found (file)', function (done) {1112 request(createServer({ root: fixtures, index: 'default.htm' }))1113 .get('/pets/')1114 .expect(404, done)1115 })1116 it('should 404 if no index file found (dir)', function (done) {1117 request(createServer({ root: fixtures, index: 'pets' }))1118 .get('/')1119 .expect(404, done)1120 })1121 it('should not follow directories', function (done) {1122 request(createServer({ root: fixtures, index: ['pets', 'name.txt'] }))1123 .get('/')1124 .expect(200, 'tobi', done)1125 })1126 it('should work without root', function (done) {1127 var server = http.createServer(function (req, res) {1128 var p = path.join(fixtures, 'pets').replace(/\\/g, '/') + '/'1129 send(req, p, { index: ['index.html'] })1130 .pipe(res)1131 })1132 request(server)1133 .get('/')1134 .expect(200, /tobi/, done)1135 })1136 })1137 describe('root', function () {1138 describe('when given', function () {1139 it('should join root', function (done) {1140 request(createServer({ root: fixtures }))1141 .get('/pets/../name.txt')1142 .expect(200, 'tobi', done)1143 })1144 it('should work with trailing slash', function (done) {1145 var app = http.createServer(function (req, res) {1146 send(req, req.url, { root: fixtures + '/' })1147 .pipe(res)1148 })1149 request(app)1150 .get('/name.txt')1151 .expect(200, 'tobi', done)1152 })1153 it('should work with empty path', function (done) {1154 var app = http.createServer(function (req, res) {1155 send(req, '', { root: fixtures })1156 .pipe(res)1157 })1158 request(app)1159 .get('/name.txt')1160 .expect(301, /Redirecting to/, done)1161 })1162 //1163 // NOTE: This is not a real part of the API, but1164 // over time this has become something users1165 // are doing, so this will prevent unseen1166 // regressions around this use-case.1167 //1168 it('should try as file with empty path', function (done) {1169 var app = http.createServer(function (req, res) {1170 send(req, '', { root: path.join(fixtures, 'name.txt') })1171 .pipe(res)1172 })1173 request(app)1174 .get('/')1175 .expect(200, 'tobi', done)1176 })1177 it('should restrict paths to within root', function (done) {1178 request(createServer({ root: fixtures }))1179 .get('/pets/../../send.js')1180 .expect(403, done)1181 })1182 it('should allow .. in root', function (done) {1183 var app = http.createServer(function (req, res) {1184 send(req, req.url, { root: fixtures + '/../fixtures' })1185 .pipe(res)1186 })1187 request(app)1188 .get('/pets/../../send.js')1189 .expect(403, done)1190 })1191 it('should not allow root transversal', function (done) {1192 request(createServer({ root: path.join(fixtures, 'name.d') }))1193 .get('/../name.dir/name.txt')1194 .expect(403, done)1195 })1196 it('should not allow root path disclosure', function (done) {1197 request(createServer({ root: fixtures }))1198 .get('/pets/../../fixtures/name.txt')1199 .expect(403, done)1200 })1201 })1202 describe('when missing', function () {1203 it('should consider .. malicious', function (done) {1204 var app = http.createServer(function (req, res) {1205 send(req, fixtures + req.url)1206 .pipe(res)1207 })1208 request(app)1209 .get('/../send.js')1210 .expect(403, done)1211 })1212 it('should still serve files with dots in name', function (done) {1213 var app = http.createServer(function (req, res) {1214 send(req, fixtures + req.url)1215 .pipe(res)1216 })1217 request(app)1218 .get('/do..ts.txt')1219 .expect(200, '...', done)1220 })1221 })1222 })1223})1224describe('send.mime', function () {1225 it('should be exposed', function () {1226 assert.ok(send.mime)1227 })1228 describe('.default_type', function () {1229 before(function () {1230 this.default_type = send.mime.default_type1231 })1232 afterEach(function () {1233 send.mime.default_type = this.default_type1234 })1235 it('should change the default type', function (done) {1236 send.mime.default_type = 'text/plain'1237 request(createServer({ root: fixtures }))1238 .get('/no_ext')1239 .expect('Content-Type', 'text/plain; charset=UTF-8')1240 .expect(200, done)1241 })1242 it('should not add Content-Type for undefined default', function (done) {1243 send.mime.default_type = undefined1244 request(createServer({ root: fixtures }))1245 .get('/no_ext')1246 .expect(shouldNotHaveHeader('Content-Type'))1247 .expect(200, done)1248 })1249 })1250})1251function createServer (opts, fn) {1252 return http.createServer(function onRequest (req, res) {1253 try {1254 fn && fn(req, res)1255 send(req, req.url, opts).pipe(res)1256 } catch (err) {1257 res.statusCode = 5001258 res.end(String(err))1259 }1260 })1261}1262function shouldNotHaveBody () {1263 return function (res) {1264 assert.ok(res.text === '' || res.text === undefined)1265 }1266}...
SML_STAGING_MULTIPORT_SERVER_GPRS.js
Source:SML_STAGING_MULTIPORT_SERVER_GPRS.js
...56 //console.log('A worker is now connected to '+ address.address + ':'+address.port);57 });58} else if (cluster.isWorker) {59 60 //net.createServer(processdata).listen(8200, HOST);// for test61 //net.createServer(processdata).listen(8149, HOST);// for test62 net.createServer(processdata).listen(8100, HOST);63 net.createServer(processdata).listen(8101, HOST); 64 net.createServer(processdata).listen(8102, HOST);65 net.createServer(processdata).listen(8103, HOST);66 net.createServer(processdata).listen(8104, HOST);67 net.createServer(processdata).listen(8105, HOST); 68 net.createServer(processdata).listen(8106, HOST); 69 net.createServer(processdata).listen(8107, HOST); 70 net.createServer(processdata).listen(8108, HOST);71 net.createServer(processdata).listen(8109, HOST);72 net.createServer(processdata).listen(8110, HOST);73 net.createServer(processdata).listen(8111, HOST); 74 net.createServer(processdata).listen(8112, HOST);75 net.createServer(processdata).listen(8113, HOST);76 net.createServer(processdata).listen(8114, HOST); 77 net.createServer(processdata).listen(8115, HOST);78 net.createServer(processdata).listen(8116, HOST);79 net.createServer(processdata).listen(8117, HOST);80 net.createServer(processdata).listen(8118, HOST); 81 net.createServer(processdata).listen(8119, HOST);82 net.createServer(processdata).listen(8120, HOST);83 net.createServer(processdata).listen(8121, HOST);84 net.createServer(processdata).listen(8122, HOST); 85 net.createServer(processdata).listen(8123, HOST);86 net.createServer(processdata).listen(8124, HOST);87 net.createServer(processdata).listen(8125, HOST);88 net.createServer(processdata).listen(8126, HOST); 89 net.createServer(processdata).listen(8127, HOST); 90 net.createServer(processdata).listen(8128, HOST); 91 net.createServer(processdata).listen(8129, HOST);92 net.createServer(processdata).listen(8130, HOST);93 net.createServer(processdata).listen(8131, HOST);94 net.createServer(processdata).listen(8132, HOST); 95 net.createServer(processdata).listen(8133, HOST);96 net.createServer(processdata).listen(8134, HOST);97 net.createServer(processdata).listen(8135, HOST); 98 net.createServer(processdata).listen(8136, HOST);99 net.createServer(processdata).listen(8137, HOST);//No data is coming100 net.createServer(processdata).listen(8138, HOST);101 net.createServer(processdata).listen(8139, HOST);102 net.createServer(processdata).listen(8140, HOST);//End for Bilaspur103 net.createServer(processdata).listen(8141, HOST);//Start of DURG104 net.createServer(processdata).listen(8142, HOST);105 net.createServer(processdata).listen(8143, HOST);106 net.createServer(processdata).listen(8144, HOST);107 net.createServer(processdata).listen(8145, HOST);108 net.createServer(processdata).listen(8146, HOST);109 net.createServer(processdata).listen(8147, HOST);110 net.createServer(processdata).listen(8148, HOST);111 net.createServer(processdata).listen(8149, HOST);112 net.createServer(processdata).listen(8150, HOST);113 net.createServer(processdata).listen(8151, HOST);114 net.createServer(processdata).listen(8152, HOST);115 net.createServer(processdata).listen(8153, HOST);116 net.createServer(processdata).listen(8154, HOST);117 net.createServer(processdata).listen(8155, HOST);118 net.createServer(processdata).listen(8156, HOST);119 net.createServer(processdata).listen(8157, HOST);120 net.createServer(processdata).listen(8158, HOST);121 net.createServer(processdata).listen(8159, HOST);122 net.createServer(processdata).listen(8160, HOST);123 net.createServer(processdata).listen(8161, HOST);124 net.createServer(processdata).listen(8162, HOST);125 net.createServer(processdata).listen(8163, HOST);126 net.createServer(processdata).listen(8164, HOST);127 net.createServer(processdata).listen(8165, HOST);128 net.createServer(processdata).listen(8166, HOST);129 net.createServer(processdata).listen(8167, HOST);130 net.createServer(processdata).listen(8168, HOST);131 net.createServer(processdata).listen(8169, HOST);132 net.createServer(processdata).listen(8170, HOST);133 net.createServer(processdata).listen(8171, HOST);134 net.createServer(processdata).listen(8172, HOST);135 net.createServer(processdata).listen(8173, HOST);136 net.createServer(processdata).listen(8174, HOST);137 net.createServer(processdata).listen(8175, HOST); 138 net.createServer(processdata).listen(8176, HOST); 139 net.createServer(processdata).listen(8177, HOST); 140 net.createServer(processdata).listen(8178, HOST); 141 net.createServer(processdata).listen(8179, HOST);142 143 144 145 //8180-8200146 147 net.createServer(processdata).listen(8180, HOST);148 net.createServer(processdata).listen(8181, HOST);149 net.createServer(processdata).listen(8182, HOST);150 net.createServer(processdata).listen(8183, HOST);151 net.createServer(processdata).listen(8184, HOST);152 net.createServer(processdata).listen(8185, HOST);153 net.createServer(processdata).listen(8186, HOST);154 net.createServer(processdata).listen(8187, HOST);155 net.createServer(processdata).listen(8188, HOST);156 net.createServer(processdata).listen(8189, HOST);157 net.createServer(processdata).listen(8190, HOST);158 net.createServer(processdata).listen(8191, HOST);159 net.createServer(processdata).listen(8192, HOST);160 net.createServer(processdata).listen(8193, HOST);161 net.createServer(processdata).listen(8194, HOST);162 net.createServer(processdata).listen(8195, HOST);163 net.createServer(processdata).listen(8196, HOST);164 net.createServer(processdata).listen(8197, HOST);165 net.createServer(processdata).listen(8198, HOST);166 net.createServer(processdata).listen(8199, HOST);167 168 net.createServer(processdata).listen(8200, HOST);// Port used for instant messaging169 //8201 - 8240 Ambikapur170 171 net.createServer(processdata).listen(8201, HOST); 172 net.createServer(processdata).listen(8202, HOST);173 net.createServer(processdata).listen(8203, HOST);174 net.createServer(processdata).listen(8204, HOST);175 net.createServer(processdata).listen(8205, HOST); 176 net.createServer(processdata).listen(8206, HOST); 177 net.createServer(processdata).listen(8207, HOST); 178 net.createServer(processdata).listen(8208, HOST);179 net.createServer(processdata).listen(8209, HOST);180 net.createServer(processdata).listen(8210, HOST);181 net.createServer(processdata).listen(8211, HOST); 182 net.createServer(processdata).listen(8212, HOST);183 net.createServer(processdata).listen(8213, HOST);184 net.createServer(processdata).listen(8214, HOST); 185 net.createServer(processdata).listen(8215, HOST);186 net.createServer(processdata).listen(8216, HOST);187 net.createServer(processdata).listen(8217, HOST);188 net.createServer(processdata).listen(8218, HOST); 189 net.createServer(processdata).listen(8219, HOST);190 net.createServer(processdata).listen(8220, HOST);191 net.createServer(processdata).listen(8221, HOST);192 net.createServer(processdata).listen(8222, HOST); 193 net.createServer(processdata).listen(8223, HOST);194 net.createServer(processdata).listen(8224, HOST);195 net.createServer(processdata).listen(8225, HOST);196 net.createServer(processdata).listen(8226, HOST); 197 net.createServer(processdata).listen(8227, HOST); 198 net.createServer(processdata).listen(8228, HOST); 199 net.createServer(processdata).listen(8229, HOST);200 net.createServer(processdata).listen(8230, HOST);201 net.createServer(processdata).listen(8231, HOST);202 net.createServer(processdata).listen(8232, HOST); 203 net.createServer(processdata).listen(8233, HOST);204 net.createServer(processdata).listen(8234, HOST);205 net.createServer(processdata).listen(8235, HOST); 206 net.createServer(processdata).listen(8236, HOST);207 net.createServer(processdata).listen(8237, HOST);208 net.createServer(processdata).listen(8238, HOST);209 net.createServer(processdata).listen(8239, HOST);210 net.createServer(processdata).listen(8240, HOST); 211 212 net.createServer(processdata).listen(8241, HOST);//Start of Khairagarh213 net.createServer(processdata).listen(8242, HOST);214 net.createServer(processdata).listen(8243, HOST);215 net.createServer(processdata).listen(8244, HOST);216 net.createServer(processdata).listen(8245, HOST);217 net.createServer(processdata).listen(8246, HOST);218 net.createServer(processdata).listen(8247, HOST);219 net.createServer(processdata).listen(8248, HOST);220 net.createServer(processdata).listen(8249, HOST);221 net.createServer(processdata).listen(8250, HOST);222 net.createServer(processdata).listen(8251, HOST);223 net.createServer(processdata).listen(8252, HOST);224 net.createServer(processdata).listen(8253, HOST);225 net.createServer(processdata).listen(8254, HOST);226 net.createServer(processdata).listen(8255, HOST);227 net.createServer(processdata).listen(8256, HOST);228 net.createServer(processdata).listen(8257, HOST);229 net.createServer(processdata).listen(8258, HOST);230 net.createServer(processdata).listen(8259, HOST);231 net.createServer(processdata).listen(8260, HOST);232 net.createServer(processdata).listen(8261, HOST);233 net.createServer(processdata).listen(8262, HOST);234 net.createServer(processdata).listen(8263, HOST);235 net.createServer(processdata).listen(8264, HOST);236 net.createServer(processdata).listen(8265, HOST);237 net.createServer(processdata).listen(8266, HOST);238 net.createServer(processdata).listen(8267, HOST);239 net.createServer(processdata).listen(8268, HOST);240 net.createServer(processdata).listen(8269, HOST);241 net.createServer(processdata).listen(8270, HOST);242 net.createServer(processdata).listen(8271, HOST);243 net.createServer(processdata).listen(8272, HOST);244 net.createServer(processdata).listen(8273, HOST);245 net.createServer(processdata).listen(8274, HOST);246 net.createServer(processdata).listen(8275, HOST);247 net.createServer(processdata).listen(8276, HOST); 248 net.createServer(processdata).listen(8277, HOST); 249 net.createServer(processdata).listen(8278, HOST); 250 net.createServer(processdata).listen(8279, HOST);251 net.createServer(processdata).listen(8280, HOST);252 net.createServer(processdata).listen(8281, HOST);253 net.createServer(processdata).listen(8282, HOST);254 net.createServer(processdata).listen(8283, HOST);255 net.createServer(processdata).listen(8284, HOST);256 net.createServer(processdata).listen(8285, HOST);257 net.createServer(processdata).listen(8286, HOST);258 net.createServer(processdata).listen(8287, HOST);259 net.createServer(processdata).listen(8288, HOST);260 net.createServer(processdata).listen(8289, HOST);261 net.createServer(processdata).listen(8290, HOST);262 net.createServer(processdata).listen(8291, HOST);263 net.createServer(processdata).listen(8292, HOST);264 net.createServer(processdata).listen(8293, HOST);265 net.createServer(processdata).listen(8294, HOST);266 net.createServer(processdata).listen(8295, HOST);267 net.createServer(processdata).listen(8296, HOST);268 net.createServer(processdata).listen(8297, HOST);269 net.createServer(processdata).listen(8298, HOST);270 net.createServer(processdata).listen(8299, HOST);271 272 273 //port 8300 - 8330274 net.createServer(processdata).listen(8300, HOST); 275 net.createServer(processdata).listen(8301, HOST); 276 net.createServer(processdata).listen(8302, HOST);277 net.createServer(processdata).listen(8303, HOST);278 net.createServer(processdata).listen(8304, HOST);279 net.createServer(processdata).listen(8305, HOST); 280 net.createServer(processdata).listen(8306, HOST); 281 net.createServer(processdata).listen(8307, HOST); 282 net.createServer(processdata).listen(8308, HOST);283 net.createServer(processdata).listen(8309, HOST);284 net.createServer(processdata).listen(8310, HOST);285 net.createServer(processdata).listen(8311, HOST); 286 net.createServer(processdata).listen(8312, HOST);287 net.createServer(processdata).listen(8313, HOST);288 net.createServer(processdata).listen(8314, HOST); 289 net.createServer(processdata).listen(8315, HOST);290 net.createServer(processdata).listen(8316, HOST);291 net.createServer(processdata).listen(8317, HOST);292 net.createServer(processdata).listen(8318, HOST); 293 net.createServer(processdata).listen(8319, HOST);294 net.createServer(processdata).listen(8320, HOST);295 net.createServer(processdata).listen(8321, HOST);296 net.createServer(processdata).listen(8322, HOST); 297 net.createServer(processdata).listen(8323, HOST);298 net.createServer(processdata).listen(8324, HOST);299 net.createServer(processdata).listen(8325, HOST);300 net.createServer(processdata).listen(8326, HOST); 301 net.createServer(processdata).listen(8327, HOST); 302 net.createServer(processdata).listen(8328, HOST); 303 net.createServer(processdata).listen(8329, HOST);304 net.createServer(processdata).listen(8330, HOST); 305 306 function processdata(connection) {307 var SCUID = 0;308 var clientIP = 0;309 var clientPort = 0;310 var localport1 = 0;311 var vehObj = {};312 //var msgObj = {};313 var vehicleInformation = 0;314 console.log('client connected');315 316 connection.on('close', function() {317 console.log('client closed');318 });...
http.js
Source:http.js
...24 delete process.env.no_proxy;25 }26 });27 it('should respect the timeout property', function (done) {28 server = http.createServer(function (req, res) {29 setTimeout(function () {30 res.end();31 }, 1000);32 }).listen(4444, function () {33 var success = false, failure = false;34 var error;35 axios.get('http://localhost:4444/', {36 timeout: 25037 }).then(function (res) {38 success = true;39 }).catch(function (err) {40 error = err;41 failure = true;42 });43 setTimeout(function () {44 assert.equal(success, false, 'request should not succeed');45 assert.equal(failure, true, 'request should fail');46 assert.equal(error.code, 'ECONNABORTED');47 assert.equal(error.message, 'timeout of 250ms exceeded');48 done();49 }, 300);50 });51 });52 it('should allow passing JSON', function (done) {53 var data = {54 firstName: 'Fred',55 lastName: 'Flintstone',56 emailAddr: 'fred@example.com'57 };58 server = http.createServer(function (req, res) {59 res.setHeader('Content-Type', 'application/json;charset=utf-8');60 res.end(JSON.stringify(data));61 }).listen(4444, function () {62 axios.get('http://localhost:4444/').then(function (res) {63 assert.deepEqual(res.data, data);64 done();65 });66 });67 });68 it('should allow passing JSON with BOM', function (done) {69 var data = {70 firstName: 'Fred',71 lastName: 'Flintstone',72 emailAddr: 'fred@example.com'73 };74 server = http.createServer(function (req, res) {75 res.setHeader('Content-Type', 'application/json;charset=utf-8');76 var bomBuffer = Buffer.from([0xEF, 0xBB, 0xBF])77 var jsonBuffer = Buffer.from(JSON.stringify(data));78 res.end(Buffer.concat([bomBuffer, jsonBuffer]));79 }).listen(4444, function () {80 axios.get('http://localhost:4444/').then(function (res) {81 assert.deepEqual(res.data, data);82 done();83 });84 });85 });86 it('should redirect', function (done) {87 var str = 'test response';88 server = http.createServer(function (req, res) {89 var parsed = url.parse(req.url);90 if (parsed.pathname === '/one') {91 res.setHeader('Location', '/two');92 res.statusCode = 302;93 res.end();94 } else {95 res.end(str);96 }97 }).listen(4444, function () {98 axios.get('http://localhost:4444/one').then(function (res) {99 assert.equal(res.data, str);100 assert.equal(res.request.path, '/two');101 done();102 });103 });104 });105 it('should not redirect', function (done) {106 server = http.createServer(function (req, res) {107 res.setHeader('Location', '/foo');108 res.statusCode = 302;109 res.end();110 }).listen(4444, function () {111 axios.get('http://localhost:4444/', {112 maxRedirects: 0,113 validateStatus: function () {114 return true;115 }116 }).then(function (res) {117 assert.equal(res.status, 302);118 assert.equal(res.headers['location'], '/foo');119 done();120 });121 });122 });123 it('should support max redirects', function (done) {124 var i = 1;125 server = http.createServer(function (req, res) {126 res.setHeader('Location', '/' + i);127 res.statusCode = 302;128 res.end();129 i++;130 }).listen(4444, function () {131 axios.get('http://localhost:4444/', {132 maxRedirects: 3133 }).catch(function (error) {134 done();135 });136 });137 });138 it('should preserve the HTTP verb on redirect', function (done) {139 server = http.createServer(function (req, res) {140 if (req.method.toLowerCase() !== "head") {141 res.statusCode = 400;142 res.end();143 return;144 }145 var parsed = url.parse(req.url);146 if (parsed.pathname === '/one') {147 res.setHeader('Location', '/two');148 res.statusCode = 302;149 res.end();150 } else {151 res.end();152 }153 }).listen(4444, function () {154 axios.head('http://localhost:4444/one').then(function (res) {155 assert.equal(res.status, 200);156 done();157 }).catch(function (err) {158 done(err);159 });160 });161 });162 it('should support transparent gunzip', function (done) {163 var data = {164 firstName: 'Fred',165 lastName: 'Flintstone',166 emailAddr: 'fred@example.com'167 };168 zlib.gzip(JSON.stringify(data), function (err, zipped) {169 server = http.createServer(function (req, res) {170 res.setHeader('Content-Type', 'application/json;charset=utf-8');171 res.setHeader('Content-Encoding', 'gzip');172 res.end(zipped);173 }).listen(4444, function () {174 axios.get('http://localhost:4444/').then(function (res) {175 assert.deepEqual(res.data, data);176 done();177 });178 });179 });180 });181 it('should support gunzip error handling', function (done) {182 server = http.createServer(function (req, res) {183 res.setHeader('Content-Type', 'application/json;charset=utf-8');184 res.setHeader('Content-Encoding', 'gzip');185 res.end('invalid response');186 }).listen(4444, function () {187 axios.get('http://localhost:4444/').catch(function (error) {188 done();189 });190 });191 });192 it('should support disabling automatic decompression of response data', function(done) {193 var data = 'Test data';194 zlib.gzip(data, function(err, zipped) {195 server = http.createServer(function(req, res) {196 res.setHeader('Content-Type', 'text/html;charset=utf-8');197 res.setHeader('Content-Encoding', 'gzip');198 res.end(zipped);199 }).listen(4444, function() {200 axios.get('http://localhost:4444/', {201 decompress: false,202 responseType: 'arraybuffer'203 }).then(function(res) {204 assert.equal(res.data.toString('base64'), zipped.toString('base64'));205 done();206 });207 });208 });209 });210 it('should support UTF8', function (done) {211 var str = Array(100000).join('ж');212 server = http.createServer(function (req, res) {213 res.setHeader('Content-Type', 'text/html; charset=UTF-8');214 res.end(str);215 }).listen(4444, function () {216 axios.get('http://localhost:4444/').then(function (res) {217 assert.equal(res.data, str);218 done();219 });220 });221 });222 it('should support basic auth', function (done) {223 server = http.createServer(function (req, res) {224 res.end(req.headers.authorization);225 }).listen(4444, function () {226 var user = 'foo';227 var headers = { Authorization: 'Bearer 1234' };228 axios.get('http://' + user + '@localhost:4444/', { headers: headers }).then(function (res) {229 var base64 = Buffer.from(user + ':', 'utf8').toString('base64');230 assert.equal(res.data, 'Basic ' + base64);231 done();232 });233 });234 });235 it('should support basic auth with a header', function (done) {236 server = http.createServer(function (req, res) {237 res.end(req.headers.authorization);238 }).listen(4444, function () {239 var auth = { username: 'foo', password: 'bar' };240 var headers = { Authorization: 'Bearer 1234' };241 axios.get('http://localhost:4444/', { auth: auth, headers: headers }).then(function (res) {242 var base64 = Buffer.from('foo:bar', 'utf8').toString('base64');243 assert.equal(res.data, 'Basic ' + base64);244 done();245 });246 });247 });248 it('should support max content length', function (done) {249 var str = Array(100000).join('ж');250 server = http.createServer(function (req, res) {251 res.setHeader('Content-Type', 'text/html; charset=UTF-8');252 res.end(str);253 }).listen(4444, function () {254 var success = false, failure = false, error;255 axios.get('http://localhost:4444/', {256 maxContentLength: 2000257 }).then(function (res) {258 success = true;259 }).catch(function (err) {260 error = err;261 failure = true;262 });263 setTimeout(function () {264 assert.equal(success, false, 'request should not succeed');265 assert.equal(failure, true, 'request should fail');266 assert.equal(error.message, 'maxContentLength size of 2000 exceeded');267 done();268 }, 100);269 });270 });271 it('should support max content length for redirected', function (done) {272 var str = Array(100000).join('ж');273 server = http.createServer(function (req, res) {274 var parsed = url.parse(req.url);275 if (parsed.pathname === '/two') {276 res.setHeader('Content-Type', 'text/html; charset=UTF-8');277 res.end(str);278 } else {279 res.setHeader('Location', '/two');280 res.statusCode = 302;281 res.end();282 }283 }).listen(4444, function () {284 var success = false, failure = false, error;285 axios.get('http://localhost:4444/one', {286 maxContentLength: 2000287 }).then(function (res) {288 success = true;289 }).catch(function (err) {290 error = err;291 failure = true;292 });293 setTimeout(function () {294 assert.equal(success, false, 'request should not succeed');295 assert.equal(failure, true, 'request should fail');296 assert.equal(error.message, 'maxContentLength size of 2000 exceeded');297 done();298 }, 100);299 });300 });301 it('should support max body length', function (done) {302 var data = Array(100000).join('ж');303 server = http.createServer(function (req, res) {304 res.setHeader('Content-Type', 'text/html; charset=UTF-8');305 res.end();306 }).listen(4444, function () {307 var success = false, failure = false, error;308 axios.post('http://localhost:4444/', {309 data: data310 }, {311 maxBodyLength: 2000312 }).then(function (res) {313 success = true;314 }).catch(function (err) {315 error = err;316 failure = true;317 });318 setTimeout(function () {319 assert.equal(success, false, 'request should not succeed');320 assert.equal(failure, true, 'request should fail');321 assert.equal(error.code, 'ERR_FR_MAX_BODY_LENGTH_EXCEEDED');322 assert.equal(error.message, 'Request body larger than maxBodyLength limit');323 done();324 }, 100);325 });326 });327 it.skip('should support sockets', function (done) {328 server = net.createServer(function (socket) {329 socket.on('data', function () {330 socket.end('HTTP/1.1 200 OK\r\n\r\n');331 });332 }).listen('./test.sock', function () {333 axios({334 socketPath: './test.sock',335 url: '/'336 })337 .then(function (resp) {338 assert.equal(resp.status, 200);339 assert.equal(resp.statusText, 'OK');340 done();341 })342 .catch(function (error) {343 assert.ifError(error);344 done();345 });346 });347 });348 it('should support streams', function (done) {349 server = http.createServer(function (req, res) {350 req.pipe(res);351 }).listen(4444, function () {352 axios.post('http://localhost:4444/',353 fs.createReadStream(__filename), {354 responseType: 'stream'355 }).then(function (res) {356 var stream = res.data;357 var string = '';358 stream.on('data', function (chunk) {359 string += chunk.toString('utf8');360 });361 stream.on('end', function () {362 assert.equal(string, fs.readFileSync(__filename, 'utf8'));363 done();364 });365 });366 });367 });368 it('should pass errors for a failed stream', function (done) {369 var notExitPath = path.join(__dirname, 'does_not_exist');370 server = http.createServer(function (req, res) {371 req.pipe(res);372 }).listen(4444, function () {373 axios.post('http://localhost:4444/',374 fs.createReadStream(notExitPath)375 ).then(function (res) {376 assert.fail();377 }).catch(function (err) {378 assert.equal(err.message, `ENOENT: no such file or directory, open \'${notExitPath}\'`);379 done();380 });381 });382 });383 it('should support buffers', function (done) {384 var buf = Buffer.alloc(1024, 'x'); // Unsafe buffer < Buffer.poolSize (8192 bytes)385 server = http.createServer(function (req, res) {386 assert.equal(req.headers['content-length'], buf.length.toString());387 req.pipe(res);388 }).listen(4444, function () {389 axios.post('http://localhost:4444/',390 buf, {391 responseType: 'stream'392 }).then(function (res) {393 var stream = res.data;394 var string = '';395 stream.on('data', function (chunk) {396 string += chunk.toString('utf8');397 });398 stream.on('end', function () {399 assert.equal(string, buf.toString());400 done();401 });402 });403 });404 });405 it('should support HTTP proxies', function (done) {406 server = http.createServer(function (req, res) {407 res.setHeader('Content-Type', 'text/html; charset=UTF-8');408 res.end('12345');409 }).listen(4444, function () {410 proxy = http.createServer(function (request, response) {411 var parsed = url.parse(request.url);412 var opts = {413 host: parsed.hostname,414 port: parsed.port,415 path: parsed.path416 };417 http.get(opts, function (res) {418 var body = '';419 res.on('data', function (data) {420 body += data;421 });422 res.on('end', function () {423 response.setHeader('Content-Type', 'text/html; charset=UTF-8');424 response.end(body + '6789');425 });426 });427 }).listen(4000, function () {428 axios.get('http://localhost:4444/', {429 proxy: {430 host: 'localhost',431 port: 4000432 }433 }).then(function (res) {434 assert.equal(res.data, '123456789', 'should pass through proxy');435 done();436 });437 });438 });439 });440 it('should not pass through disabled proxy', function (done) {441 // set the env variable442 process.env.http_proxy = 'http://does-not-exists.example.com:4242/';443 server = http.createServer(function (req, res) {444 res.setHeader('Content-Type', 'text/html; charset=UTF-8');445 res.end('123456789');446 }).listen(4444, function () {447 axios.get('http://localhost:4444/', {448 proxy: false449 }).then(function (res) {450 assert.equal(res.data, '123456789', 'should not pass through proxy');451 done();452 });453 });454 });455 it('should support proxy set via env var', function (done) {456 server = http.createServer(function (req, res) {457 res.setHeader('Content-Type', 'text/html; charset=UTF-8');458 res.end('4567');459 }).listen(4444, function () {460 proxy = http.createServer(function (request, response) {461 var parsed = url.parse(request.url);462 var opts = {463 host: parsed.hostname,464 port: parsed.port,465 path: parsed.path466 };467 http.get(opts, function (res) {468 var body = '';469 res.on('data', function (data) {470 body += data;471 });472 res.on('end', function () {473 response.setHeader('Content-Type', 'text/html; charset=UTF-8');474 response.end(body + '1234');475 });476 });477 }).listen(4000, function () {478 // set the env variable479 process.env.http_proxy = 'http://localhost:4000/';480 axios.get('http://localhost:4444/').then(function (res) {481 assert.equal(res.data, '45671234', 'should use proxy set by process.env.http_proxy');482 done();483 });484 });485 });486 });487 it('should not use proxy for domains in no_proxy', function (done) {488 server = http.createServer(function (req, res) {489 res.setHeader('Content-Type', 'text/html; charset=UTF-8');490 res.end('4567');491 }).listen(4444, function () {492 proxy = http.createServer(function (request, response) {493 var parsed = url.parse(request.url);494 var opts = {495 host: parsed.hostname,496 port: parsed.port,497 path: parsed.path498 };499 http.get(opts, function (res) {500 var body = '';501 res.on('data', function (data) {502 body += data;503 });504 res.on('end', function () {505 response.setHeader('Content-Type', 'text/html; charset=UTF-8');506 response.end(body + '1234');507 });508 });509 }).listen(4000, function () {510 // set the env variable511 process.env.http_proxy = 'http://localhost:4000/';512 process.env.no_proxy = 'foo.com, localhost,bar.net , , quix.co';513 axios.get('http://localhost:4444/').then(function (res) {514 assert.equal(res.data, '4567', 'should not use proxy for domains in no_proxy');515 done();516 });517 });518 });519 });520 it('should use proxy for domains not in no_proxy', function (done) {521 server = http.createServer(function (req, res) {522 res.setHeader('Content-Type', 'text/html; charset=UTF-8');523 res.end('4567');524 }).listen(4444, function () {525 proxy = http.createServer(function (request, response) {526 var parsed = url.parse(request.url);527 var opts = {528 host: parsed.hostname,529 port: parsed.port,530 path: parsed.path531 };532 http.get(opts, function (res) {533 var body = '';534 res.on('data', function (data) {535 body += data;536 });537 res.on('end', function () {538 response.setHeader('Content-Type', 'text/html; charset=UTF-8');539 response.end(body + '1234');540 });541 });542 }).listen(4000, function () {543 // set the env variable544 process.env.http_proxy = 'http://localhost:4000/';545 process.env.no_proxy = 'foo.com, ,bar.net , quix.co';546 axios.get('http://localhost:4444/').then(function (res) {547 assert.equal(res.data, '45671234', 'should use proxy for domains not in no_proxy');548 done();549 });550 });551 });552 });553 it('should support HTTP proxy auth', function (done) {554 server = http.createServer(function (req, res) {555 res.end();556 }).listen(4444, function () {557 proxy = http.createServer(function (request, response) {558 var parsed = url.parse(request.url);559 var opts = {560 host: parsed.hostname,561 port: parsed.port,562 path: parsed.path563 };564 var proxyAuth = request.headers['proxy-authorization'];565 http.get(opts, function (res) {566 var body = '';567 res.on('data', function (data) {568 body += data;569 });570 res.on('end', function () {571 response.setHeader('Content-Type', 'text/html; charset=UTF-8');572 response.end(proxyAuth);573 });574 });575 }).listen(4000, function () {576 axios.get('http://localhost:4444/', {577 proxy: {578 host: 'localhost',579 port: 4000,580 auth: {581 username: 'user',582 password: 'pass'583 }584 }585 }).then(function (res) {586 var base64 = Buffer.from('user:pass', 'utf8').toString('base64');587 assert.equal(res.data, 'Basic ' + base64, 'should authenticate to the proxy');588 done();589 });590 });591 });592 });593 it('should support proxy auth from env', function (done) {594 server = http.createServer(function (req, res) {595 res.end();596 }).listen(4444, function () {597 proxy = http.createServer(function (request, response) {598 var parsed = url.parse(request.url);599 var opts = {600 host: parsed.hostname,601 port: parsed.port,602 path: parsed.path603 };604 var proxyAuth = request.headers['proxy-authorization'];605 http.get(opts, function (res) {606 var body = '';607 res.on('data', function (data) {608 body += data;609 });610 res.on('end', function () {611 response.setHeader('Content-Type', 'text/html; charset=UTF-8');612 response.end(proxyAuth);613 });614 });615 }).listen(4000, function () {616 process.env.http_proxy = 'http://user:pass@localhost:4000/';617 axios.get('http://localhost:4444/').then(function (res) {618 var base64 = Buffer.from('user:pass', 'utf8').toString('base64');619 assert.equal(res.data, 'Basic ' + base64, 'should authenticate to the proxy set by process.env.http_proxy');620 done();621 });622 });623 });624 });625 it('should support proxy auth with header', function (done) {626 server = http.createServer(function (req, res) {627 res.end();628 }).listen(4444, function () {629 proxy = http.createServer(function (request, response) {630 var parsed = url.parse(request.url);631 var opts = {632 host: parsed.hostname,633 port: parsed.port,634 path: parsed.path635 };636 var proxyAuth = request.headers['proxy-authorization'];637 http.get(opts, function (res) {638 var body = '';639 res.on('data', function (data) {640 body += data;641 });642 res.on('end', function () {643 response.setHeader('Content-Type', 'text/html; charset=UTF-8');644 response.end(proxyAuth);645 });646 });647 }).listen(4000, function () {648 axios.get('http://localhost:4444/', {649 proxy: {650 host: 'localhost',651 port: 4000,652 auth: {653 username: 'user',654 password: 'pass'655 }656 },657 headers: {658 'Proxy-Authorization': 'Basic abc123'659 }660 }).then(function (res) {661 var base64 = Buffer.from('user:pass', 'utf8').toString('base64');662 assert.equal(res.data, 'Basic ' + base64, 'should authenticate to the proxy');663 done();664 });665 });666 });667 });668 it('should support cancel', function (done) {669 var source = axios.CancelToken.source();670 server = http.createServer(function (req, res) {671 // call cancel() when the request has been sent, but a response has not been received672 source.cancel('Operation has been canceled.');673 }).listen(4444, function () {674 axios.get('http://localhost:4444/', {675 cancelToken: source.token676 }).catch(function (thrown) {677 assert.ok(thrown instanceof axios.Cancel, 'Promise must be rejected with a Cancel obejct');678 assert.equal(thrown.message, 'Operation has been canceled.');679 done();680 });681 });682 });683 it('should combine baseURL and url', function (done) {684 server = http.createServer(function (req, res) {685 res.end();686 }).listen(4444, function () {687 axios.get('/foo', {688 baseURL: 'http://localhost:4444/',689 }).then(function (res) {690 assert.equal(res.config.baseURL, 'http://localhost:4444/');691 assert.equal(res.config.url, '/foo');692 done();693 });694 });695 });...
Server.spec.js
Source:Server.spec.js
1/*2Copyright 2019 Javier Brea3Copyright 2019 XbyOrange4Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at5http://www.apache.org/licenses/LICENSE-2.06Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.7*/8const sinon = require("sinon");9const http = require("http");10const LibsMocks = require("../Libs.mocks.js");11const MocksMocks = require("../mocks-legacy/Mocks.mocks.js");12const CoreMocks = require("../Core.mocks.js");13const Server = require("../../../src/server/Server");14const tracer = require("../../../src/tracer");15const wait = (time = 1000) => {16 return new Promise((resolve) => {17 setTimeout(() => {18 resolve();19 }, time);20 });21};22describe("Server", () => {23 let sandbox;24 let callbacks;25 let libsMocks;26 let mocksMocks;27 let coreMocks;28 let coreInstance;29 let processOnStub;30 let server;31 beforeEach(() => {32 sandbox = sinon.createSandbox();33 callbacks = {34 addAlert: sandbox.stub(),35 removeAlerts: sandbox.stub(),36 };37 processOnStub = sandbox.stub(process, "on");38 sandbox.stub(process, "exit");39 sandbox.stub(tracer, "error");40 sandbox.stub(tracer, "info");41 sandbox.stub(tracer, "debug");42 libsMocks = new LibsMocks();43 mocksMocks = new MocksMocks();44 coreMocks = new CoreMocks();45 coreInstance = coreMocks.stubs.instance;46 server = new Server(47 coreInstance._eventEmitter,48 coreInstance.settings,49 mocksMocks.stubs.instance,50 coreInstance,51 callbacks52 );53 expect.assertions(1);54 libsMocks.stubs.http.createServer.onListen.delay(200);55 });56 afterEach(() => {57 libsMocks.restore();58 sandbox.restore();59 coreMocks.restore();60 mocksMocks.restore();61 });62 describe("when initialized", () => {63 it("should be listening to process exit signals and stop the server if occurs", async () => {64 processOnStub.callsFake((event, cb) => {65 wait().then(() => {66 cb();67 });68 });69 libsMocks.stubs.http.createServer.onListen.returns(null);70 await server.init();71 await server.start();72 await wait();73 expect(libsMocks.stubs.http.createServer.close.callCount).toEqual(1);74 });75 });76 describe("add custom routers method", () => {77 it("should be registered when initializating http server", async () => {78 const fooRouter = sandbox.spy();79 server.addCustomRouter("fooPath", fooRouter);80 libsMocks.stubs.http.createServer.onListen.returns(null);81 await server.start();82 expect(libsMocks.stubs.express.use.calledWith("fooPath", fooRouter)).toEqual(true);83 });84 it("should reinit and restart the server if it was already started", async () => {85 expect.assertions(3);86 const fooRouter = sandbox.spy();87 libsMocks.stubs.http.createServer.onListen.returns(null);88 await server.start();89 await server.addCustomRouter("fooPath", fooRouter);90 expect(libsMocks.stubs.express.use.calledWith("fooPath", fooRouter)).toEqual(true);91 expect(http.createServer.callCount).toEqual(2);92 expect(libsMocks.stubs.http.createServer.listen.callCount).toEqual(2);93 });94 it("should wait for the server to start, then reinit and restart the server if it was already starting", async () => {95 expect.assertions(3);96 const fooRouter = sandbox.spy();97 libsMocks.stubs.http.createServer.onListen.delay(500);98 libsMocks.stubs.http.createServer.onListen.returns(null);99 server.start();100 server.start();101 server.start();102 await server.addCustomRouter("fooPath", fooRouter);103 expect(libsMocks.stubs.express.use.calledWith("fooPath", fooRouter)).toEqual(true);104 expect(http.createServer.callCount).toEqual(2);105 expect(libsMocks.stubs.http.createServer.listen.callCount).toEqual(2);106 });107 it("should add the router next time server is started if it is stopped", async () => {108 expect.assertions(4);109 const fooRouter = sandbox.spy();110 libsMocks.stubs.http.createServer.onListen.delay(500);111 libsMocks.stubs.http.createServer.onListen.returns(null);112 await server.start();113 await server.stop();114 await server.addCustomRouter("fooPath", fooRouter);115 expect(libsMocks.stubs.express.use.calledWith("fooPath", fooRouter)).toEqual(false);116 await server.start();117 expect(libsMocks.stubs.express.use.calledWith("fooPath", fooRouter)).toEqual(true);118 expect(http.createServer.callCount).toEqual(2);119 expect(libsMocks.stubs.http.createServer.listen.callCount).toEqual(2);120 });121 });122 describe("remove custom routers method", () => {123 it("should not be registered when initializating http server if called before it is started", async () => {124 const fooRouter = sandbox.spy();125 server.addCustomRouter("fooPath", fooRouter);126 server.removeCustomRouter("fooPath", fooRouter);127 libsMocks.stubs.http.createServer.onListen.returns(null);128 await server.start();129 expect(libsMocks.stubs.express.use.calledWith("fooPath", fooRouter)).toEqual(false);130 });131 it("should remove router, reinit and restart the server if it was already started", async () => {132 expect.assertions(4);133 const fooRouter = sandbox.spy();134 libsMocks.stubs.http.createServer.onListen.returns(null);135 server.addCustomRouter("fooPath", fooRouter);136 await server.start();137 expect(libsMocks.stubs.express.use.calledWith("fooPath", fooRouter)).toEqual(true);138 libsMocks.stubs.express.use.reset();139 await server.removeCustomRouter("fooPath", fooRouter);140 expect(libsMocks.stubs.express.use.calledWith("fooPath", fooRouter)).toEqual(false);141 expect(http.createServer.callCount).toEqual(2);142 expect(libsMocks.stubs.http.createServer.listen.callCount).toEqual(2);143 });144 it("should do nothing if router to remove was not registered in same path", async () => {145 expect.assertions(3);146 const fooRouter = sandbox.spy();147 libsMocks.stubs.http.createServer.onListen.returns(null);148 server.addCustomRouter("fooPath", fooRouter);149 await server.start();150 expect(libsMocks.stubs.express.use.calledWith("fooPath", fooRouter)).toEqual(true);151 libsMocks.stubs.express.use.reset();152 await server.removeCustomRouter("foooooPath", fooRouter);153 expect(http.createServer.callCount).toEqual(1);154 expect(libsMocks.stubs.http.createServer.listen.callCount).toEqual(1);155 });156 it("should do nothing if router to remove was not the same registered in the path", async () => {157 expect.assertions(3);158 const fooRouter = sandbox.spy();159 libsMocks.stubs.http.createServer.onListen.returns(null);160 server.addCustomRouter("fooPath", fooRouter);161 await server.start();162 expect(libsMocks.stubs.express.use.calledWith("fooPath", fooRouter)).toEqual(true);163 libsMocks.stubs.express.use.reset();164 await server.removeCustomRouter("fooPath", () => {165 // do nothing166 });167 expect(http.createServer.callCount).toEqual(1);168 expect(libsMocks.stubs.http.createServer.listen.callCount).toEqual(1);169 });170 it("should remove router, wait for the server to start, then reinit and restart the server if it was already starting", async () => {171 expect.assertions(4);172 const fooRouter = sandbox.spy();173 libsMocks.stubs.http.createServer.onListen.delay(500);174 libsMocks.stubs.http.createServer.onListen.returns(null);175 server.addCustomRouter("fooPath", fooRouter);176 server.start();177 await server.start();178 expect(libsMocks.stubs.express.use.calledWith("fooPath", fooRouter)).toEqual(true);179 libsMocks.stubs.express.use.reset();180 await server.stop();181 server.start();182 await server.removeCustomRouter("fooPath", fooRouter);183 expect(libsMocks.stubs.express.use.calledWith("fooPath", fooRouter)).toEqual(false);184 expect(http.createServer.callCount).toEqual(2);185 expect(libsMocks.stubs.http.createServer.listen.callCount).toEqual(3);186 });187 it("should add the router next time server is started if it is stopped", async () => {188 expect.assertions(4);189 const fooRouter = sandbox.spy();190 libsMocks.stubs.http.createServer.onListen.delay(500);191 libsMocks.stubs.http.createServer.onListen.returns(null);192 server.addCustomRouter("fooPath", fooRouter);193 await server.start();194 expect(libsMocks.stubs.express.use.calledWith("fooPath", fooRouter)).toEqual(true);195 libsMocks.stubs.express.use.reset();196 await server.stop();197 await server.removeCustomRouter("fooPath", fooRouter);198 await server.start();199 expect(libsMocks.stubs.express.use.calledWith("fooPath", fooRouter)).toEqual(false);200 expect(http.createServer.callCount).toEqual(2);201 expect(libsMocks.stubs.http.createServer.listen.callCount).toEqual(2);202 });203 });204 describe("when started", () => {205 it("should init server only once", async () => {206 libsMocks.stubs.http.createServer.onListen.returns(null);207 await server.init();208 await server.start();209 await server.start();210 await server.start();211 expect(http.createServer.callCount).toEqual(1);212 });213 it("should add cors middleware if cors option is enabled", async () => {214 libsMocks.stubs.http.createServer.onListen.returns(null);215 coreInstance.settings.get.withArgs("cors").returns(true);216 await server.init();217 await server.start();218 expect(libsMocks.stubs.express.use.callCount).toEqual(9);219 });220 it("should not add cors middleware if cors option is disabled", async () => {221 libsMocks.stubs.http.createServer.onListen.returns(null);222 coreInstance.settings.get.withArgs("cors").returns(false);223 await server.init();224 await server.start();225 expect(libsMocks.stubs.express.use.callCount).toEqual(8);226 });227 it("should reject the promise if an error occurs when calling to server listen method", async () => {228 const error = new Error("Foo error");229 libsMocks.stubs.http.createServer.listen.throws(error);230 await server.init();231 try {232 await server.start();233 } catch (err) {234 expect(err).toEqual(error);235 }236 });237 it("should add an alert if an error occurs when calling to server listen method", async () => {238 const error = new Error("Foo error");239 libsMocks.stubs.http.createServer.listen.throws(error);240 await server.init();241 try {242 await server.start();243 } catch (err) {244 expect(callbacks.addAlert.calledWith("start", "Error starting server", err)).toEqual(true);245 }246 });247 it("should remove start alerts when starts successfully", async () => {248 libsMocks.stubs.http.createServer.onListen.returns(null);249 await server.start();250 expect(callbacks.removeAlerts.calledWith("start")).toEqual(true);251 });252 it("should call to start only once even when called multiple times in parallel", async () => {253 libsMocks.stubs.http.createServer.onListen.returns(null);254 libsMocks.stubs.http.createServer.onListen.delay(200);255 await server.init();256 server.start();257 server.start();258 server.start();259 await server.start();260 expect(libsMocks.stubs.http.createServer.listen.callCount).toEqual(1);261 });262 it("should be listening to server errors and throw an error if occurs", async () => {263 const error = new Error();264 libsMocks.stubs.http.createServer.onError.returns(error);265 try {266 await server.init();267 await server.start();268 } catch (err) {269 expect(callbacks.addAlert.calledWith("server", "Server error", err)).toEqual(true);270 }271 });272 it("should add an alert if server errors", async () => {273 const error = new Error();274 libsMocks.stubs.http.createServer.onError.returns(error);275 try {276 await server.init();277 await server.start();278 } catch (err) {279 expect(err).toEqual(error);280 }281 });282 it("should log the server host and port", async () => {283 libsMocks.stubs.http.createServer.onListen.returns(null);284 coreInstance.settings.get.withArgs("host").returns("0.0.0.0");285 coreInstance.settings.get.withArgs("port").returns(3000);286 await server.start();287 expect(288 tracer.info.calledWith("Server started and listening at http://localhost:3000")289 ).toEqual(true);290 });291 it("should log the server host and port when host is custom", async () => {292 libsMocks.stubs.http.createServer.onListen.returns(null);293 coreInstance.settings.get.withArgs("host").returns("foo-host");294 coreInstance.settings.get.withArgs("port").returns(5000);295 await server.start();296 expect(297 tracer.info.calledWith("Server started and listening at http://foo-host:5000")298 ).toEqual(true);299 });300 it("should not init httpServer more than once", async () => {301 libsMocks.stubs.http.createServer.onListen.returns(null);302 await server.start();303 await server.start();304 await server.start();305 expect(libsMocks.stubs.http.createServer.on.callCount).toEqual(1);306 });307 it("should call to server listen, and resolve the promise when started", async () => {308 libsMocks.stubs.http.createServer.onListen.returns(null);309 await server.init();310 expect(await server.start()).toEqual(server);311 });312 it("should call to server listen, and rejects the promise when starts throw an error", async () => {313 const error = new Error();314 libsMocks.stubs.http.createServer.onListen.returns(new Error());315 await server.init();316 try {317 await server.start();318 } catch (err) {319 expect(err).toEqual(error);320 }321 });322 });323 describe("stop method", () => {324 beforeEach(() => {325 libsMocks.stubs.http.createServer.onListen.returns(null);326 });327 it("should call to stop the server", async () => {328 await server.init();329 await server.start();330 await server.stop();331 expect(libsMocks.stubs.http.createServer.close.callCount).toEqual(1);332 });333 it("should call to stop the server only once while it is stopping", async () => {334 await server.init();335 await server.start();336 server.stop();337 server.stop();338 server.stop();339 await server.stop();340 expect(libsMocks.stubs.http.createServer.close.callCount).toEqual(1);341 });342 it("should not call to stop server if it has not been initialized", async () => {343 await server.init();344 await server.stop();345 expect(libsMocks.stubs.http.createServer.close.callCount).toEqual(0);346 });347 });348 describe("restart method", () => {349 beforeEach(() => {350 libsMocks.stubs.http.createServer.onListen.returns(null);351 });352 it("should call to stop the server", async () => {353 await server.init();354 await server.start();355 await server.restart();356 expect(libsMocks.stubs.http.createServer.close.callCount).toEqual(1);357 });358 it("should call to start server again", async () => {359 await server.init();360 await server.start();361 await server.restart();362 expect(libsMocks.stubs.http.createServer.listen.callCount).toEqual(2);363 });364 });365 describe("error getter", () => {366 it("should return null if there is no error", async () => {367 await server.init();368 expect(server.error).toEqual(null);369 });370 it("should return current error if there was an error", async () => {371 const error = new Error();372 libsMocks.stubs.http.createServer.onListen.returns(new Error());373 await server.init();374 try {375 await server.start();376 } catch (err) {377 expect(server.error).toEqual(error);378 }379 });380 });381 describe("behaviors middleware", () => {382 const fooRequest = {383 method: "get",384 url: "foo-route",385 };386 let resMock;387 let nextSpy;388 beforeEach(async () => {389 resMock = {};390 nextSpy = sandbox.spy();391 libsMocks.stubs.http.createServer.onListen.returns(null);392 coreInstance.settings.get.withArgs("delay").returns(0);393 });394 it("should call to current fixture matching handleRequest method", async () => {395 expect.assertions(3);396 const handleRequestSpy = sandbox.spy();397 mocksMocks.stubs.instance.behaviors.current.getRequestMatchingFixture.returns({398 handleRequest: handleRequestSpy,399 });400 await server.start();401 server._fixturesMiddleware(fooRequest, resMock, nextSpy);402 await wait(10);403 expect(handleRequestSpy.getCall(0).args[0]).toEqual(fooRequest);404 expect(handleRequestSpy.getCall(0).args[1]).toEqual(resMock);405 expect(handleRequestSpy.getCall(0).args[2]).toEqual(nextSpy);406 });407 it("should call next if no matching fixture is found", async () => {408 mocksMocks.stubs.instance.behaviors.current.getRequestMatchingFixture.returns(null);409 await server.start();410 server._fixturesMiddleware(fooRequest, resMock, nextSpy);411 await wait(10);412 expect(nextSpy.callCount).toEqual(1);413 });414 });...
manoow.js
Source:manoow.js
1var http = require('http');2http.createServer(function (req, res) {3 res.writeHead(200, {'Content-Type': 'text/plain'});4 res.end('Hello World!');5}).listen(8080);var http = require('http');6http.createServer(function (req, res) {7 res.writeHead(200, {'Content-Type': 'text/plain'});8 res.end('Hello World!');9}).listen(8080);var http = require('http');10http.createServer(function (req, res) {11 res.writeHead(200, {'Content-Type': 'text/plain'});12 res.end('Hello World!');13}).listen(8080);var http = require('http');14http.createServer(function (req, res) {15 res.writeHead(200, {'Content-Type': 'text/plain'});16 res.end('Hello World!');17}).listen(8080);var http = require('http');18http.createServer(function (req, res) {19 res.writeHead(200, {'Content-Type': 'text/plain'});20 res.end('Hello World!');21}).listen(8080);var http = require('http');22http.createServer(function (req, res) {23 res.writeHead(200, {'Content-Type': 'text/plain'});24 res.end('Hello World!');25}).listen(8080);var http = require('http');26http.createServer(function (req, res) {27 res.writeHead(200, {'Content-Type': 'text/plain'});28 res.end('Hello World!');29}).listen(8080);var http = require('http');30http.createServer(function (req, res) {31 res.writeHead(200, {'Content-Type': 'text/plain'});32 res.end('Hello World!');33}).listen(8080);var http = require('http');34http.createServer(function (req, res) {35 res.writeHead(200, {'Content-Type': 'text/plain'});36 res.end('Hello World!');37}).listen(8080);var http = require('http');38http.createServer(function (req, res) {39 res.writeHead(200, {'Content-Type': 'text/plain'});40 res.end('Hello World!');41}).listen(8080);var http = require('http');42http.createServer(function (req, res) {43 res.writeHead(200, {'Content-Type': 'text/plain'});44 res.end('Hello World!');45}).listen(8080);var http = require('http');46http.createServer(function (req, res) {47 res.writeHead(200, {'Content-Type': 'text/plain'});48 res.end('Hello World!');49}).listen(8080);var http = require('http');50http.createServer(function (req, res) {51 res.writeHead(200, {'Content-Type': 'text/plain'});52 res.end('Hello World!');53}).listen(8080);var http = require('http');54http.createServer(function (req, res) {55 res.writeHead(200, {'Content-Type': 'text/plain'});56 res.end('Hello World!');57}).listen(8080);var http = require('http');58http.createServer(function (req, res) {59 res.writeHead(200, {'Content-Type': 'text/plain'});60 res.end('Hello World!');61}).listen(8080);var http = require('http');62http.createServer(function (req, res) {63 res.writeHead(200, {'Content-Type': 'text/plain'});64 res.end('Hello World!');65}).listen(8080);var http = require('http');66http.createServer(function (req, res) {67 res.writeHead(200, {'Content-Type': 'text/plain'});68 res.end('Hello World!');69}).listen(8080);var http = require('http');70http.createServer(function (req, res) {71 res.writeHead(200, {'Content-Type': 'text/plain'});72 res.end('Hello World!');73}).listen(8080);var http = require('http');74http.createServer(function (req, res) {75 res.writeHead(200, {'Content-Type': 'text/plain'});76 res.end('Hello World!');77}).listen(8080);var http = require('http');78http.createServer(function (req, res) {79 res.writeHead(200, {'Content-Type': 'text/plain'});80 res.end('Hello World!');81}).listen(8080);var http = require('http');82http.createServer(function (req, res) {83 res.writeHead(200, {'Content-Type': 'text/plain'});84 res.end('Hello World!');85}).listen(8080);var http = require('http');86http.createServer(function (req, res) {87 res.writeHead(200, {'Content-Type': 'text/plain'});88 res.end('Hello World!');89}).listen(8080);var http = require('http');90http.createServer(function (req, res) {91 res.writeHead(200, {'Content-Type': 'text/plain'});92 res.end('Hello World!');93}).listen(8080);var http = require('http');94http.createServer(function (req, res) {95 res.writeHead(200, {'Content-Type': 'text/plain'});96 res.end('Hello World!');97}).listen(8080);var http = require('http');98http.createServer(function (req, res) {99 res.writeHead(200, {'Content-Type': 'text/plain'});100 res.end('Hello World!');101}).listen(8080);var http = require('http');102http.createServer(function (req, res) {103 res.writeHead(200, {'Content-Type': 'text/plain'});104 res.end('Hello World!');105}).listen(8080);var http = require('http');106http.createServer(function (req, res) {107 res.writeHead(200, {'Content-Type': 'text/plain'});108 res.end('Hello World!');109}).listen(8080);var http = require('http');110http.createServer(function (req, res) {111 res.writeHead(200, {'Content-Type': 'text/plain'});112 res.end('Hello World!');113}).listen(8080);var http = require('http');114http.createServer(function (req, res) {115 res.writeHead(200, {'Content-Type': 'text/plain'});116 res.end('Hello World!');117}).listen(8080);var http = require('http');118http.createServer(function (req, res) {119 res.writeHead(200, {'Content-Type': 'text/plain'});120 res.end('Hello World!');121}).listen(8080);var http = require('http');122http.createServer(function (req, res) {123 res.writeHead(200, {'Content-Type': 'text/plain'});124 res.end('Hello World!');125}).listen(8080);var http = require('http');126http.createServer(function (req, res) {127 res.writeHead(200, {'Content-Type': 'text/plain'});128 res.end('Hello World!');129}).listen(8080);var http = require('http');130http.createServer(function (req, res) {131 res.writeHead(200, {'Content-Type': 'text/plain'});132 res.end('Hello World!');133}).listen(8080);var http = require('http');134http.createServer(function (req, res) {135 res.writeHead(200, {'Content-Type': 'text/plain'});136 res.end('Hello World!');137}).listen(8080);var http = require('http');138http.createServer(function (req, res) {139 res.writeHead(200, {'Content-Type': 'text/plain'});140 res.end('Hello World!');141}).listen(8080);var http = require('http');142http.createServer(function (req, res) {143 res.writeHead(200, {'Content-Type': 'text/plain'});144 res.end('Hello World!');145}).listen(8080);var http = require('http');146http.createServer(function (req, res) {147 res.writeHead(200, {'Content-Type': 'text/plain'});148 res.end('Hello World!');149}).listen(8080);var http = require('http');150http.createServer(function (req, res) {151 res.writeHead(200, {'Content-Type': 'text/plain'});152 res.end('Hello World!');153}).listen(8080);var http = require('http');154http.createServer(function (req, res) {155 res.writeHead(200, {'Content-Type': 'text/plain'});156 res.end('Hello World!');157}).listen(8080);var http = require('http');158http.createServer(function (req, res) {159 res.writeHead(200, {'Content-Type': 'text/plain'});160 res.end('Hello World!');161}).listen(8080);var http = require('http');162http.createServer(function (req, res) {163 res.writeHead(200, {'Content-Type': 'text/plain'});164 res.end('Hello World!');165}).listen(8080);var http = require('http');166http.createServer(function (req, res) {167 res.writeHead(200, {'Content-Type': 'text/plain'});168 res.end('Hello World!');169}).listen(8080);var http = require('http');170http.createServer(function (req, res) {171 res.writeHead(200, {'Content-Type': 'text/plain'});172 res.end('Hello World!');173}).listen(8080);var http = require('http');174http.createServer(function (req, res) {175 res.writeHead(200, {'Content-Type': 'text/plain'});176 res.end('Hello World!');177}).listen(8080);var http = require('http');178http.createServer(function (req, res) {179 res.writeHead(200, {'Content-Type': 'text/plain'});180 res.end('Hello World!');181}).listen(8080);var http = require('http');182http.createServer(function (req, res) {183 res.writeHead(200, {'Content-Type': 'text/plain'});184 res.end('Hello World!');185}).listen(8080);var http = require('http');186http.createServer(function (req, res) {187 res.writeHead(200, {'Content-Type': 'text/plain'});188 res.end('Hello World!');189}).listen(8080);var http = require('http');190http.createServer(function (req, res) {191 res.writeHead(200, {'Content-Type': 'text/plain'});192 res.end('Hello World!');193}).listen(8080);var http = require('http');194http.createServer(function (req, res) {195 res.writeHead(200, {'Content-Type': 'text/plain'});196 res.end('Hello World!');197}).listen(8080);var http = require('http');198http.createServer(function (req, res) {199 res.writeHead(200, {'Content-Type': 'text/plain'});200 res.end('Hello World!');201}).listen(8080);var http = require('http');202http.createServer(function (req, res) {203 res.writeHead(200, {'Content-Type': 'text/plain'});204 res.end('Hello World!');205}).listen(8080);var http = require('http');206http.createServer(function (req, res) {207 res.writeHead(200, {'Content-Type': 'text/plain'});208 res.end('Hello World!');209}).listen(8080);var http = require('http');210http.createServer(function (req, res) {211 res.writeHead(200, {'Content-Type': 'text/plain'});212 res.end('Hello World!');213}).listen(8080);var http = require('http');214http.createServer(function (req, res) {215 res.writeHead(200, {'Content-Type': 'text/plain'});216 res.end('Hello World!');217}).listen(8080);var http = require('http');218http.createServer(function (req, res) {219 res.writeHead(200, {'Content-Type': 'text/plain'});220 res.end('Hello World!');221}).listen(8080);var http = require('http');222http.createServer(function (req, res) {223 res.writeHead(200, {'Content-Type': 'text/plain'});224 res.end('Hello World!');225}).listen(8080);var http = require('http');226http.createServer(function (req, res) {227 res.writeHead(200, {'Content-Type': 'text/plain'});228 res.end('Hello World!');229}).listen(8080);var http = require('http');230http.createServer(function (req, res) {231 res.writeHead(200, {'Content-Type': 'text/plain'});232 res.end('Hello World!');233}).listen(8080);var http = require('http');234http.createServer(function (req, res) {235 res.writeHead(200, {'Content-Type': 'text/plain'});236 res.end('Hello World!');237}).listen(8080);var http = require('http');238http.createServer(function (req, res) {239 res.writeHead(200, {'Content-Type': 'text/plain'});240 res.end('Hello World!');241}).listen(8080);var http = require('http');242http.createServer(function (req, res) {243 res.writeHead(200, {'Content-Type': 'text/plain'});244 res.end('Hello World!');245}).listen(8080);var http = require('http');246http.createServer(function (req, res) {247 res.writeHead(200, {'Content-Type': 'text/plain'});248 res.end('Hello World!');249}).listen(8080);var http = require('http');250http.createServer(function (req, res) {251 res.writeHead(200, {'Content-Type': 'text/plain'});252 res.end('Hello World!');253}).listen(8080);var http = require('http');254http.createServer(function (req, res) {255 res.writeHead(200, {'Content-Type': 'text/plain'});256 res.end('Hello World!');257}).listen(8080);var http = require('http');258http.createServer(function (req, res) {259 res.writeHead(200, {'Content-Type': 'text/plain'});260 res.end('Hello World!');261}).listen(8080);var http = require('http');262http.createServer(function (req, res) {263 res.writeHead(200, {'Content-Type': 'text/plain'});264 res.end('Hello World!');265}).listen(8080);var http = require('http');266http.createServer(function (req, res) {267 res.writeHead(200, {'Content-Type': 'text/plain'});268 res.end('Hello World!');269}).listen(8080);var http = require('http');270http.createServer(function (req, res) {271 res.writeHead(200, {'Content-Type': 'text/plain'});272 res.end('Hello World!');273}).listen(8080);var http = require('http');274http.createServer(function (req, res) {275 res.writeHead(200, {'Content-Type': 'text/plain'});276 res.end('Hello World!');277}).listen(8080);var http = require('http');278http.createServer(function (req, res) {279 res.writeHead(200, {'Content-Type': 'text/plain'});280 res.end('Hello World!');...
index.js
Source:index.js
...13const autocannon = require('autocannon');14const autocannonConfig = { url: `https://localhost:${PORT}`, connections: 10, duration: 1 };15const httpRequestOptions = { agent: false, rejectUnauthorized: false };16// simple socket middleman for injecting PROXY proto headers17const injectProxyHeaders = app => net.createServer(socket => {18 socket.pause();19 socket.server = app;20 socket._server = app;21 app._connections++;22 app.emit('connection', socket);23 socket._handle.onread(proxyprotoHeader.length, proxyprotoHeader);24 socket.resume();25});26module.exports = async t => {27 const httpsConfig = await createCert({ days: 1, selfSigned: true })28 .then(d => { return { key: d.serviceKey, cert: d.certificate }; });29 const httpResponse = (req,res) => {30 const body = 'OK';31 res.writeHead(200, {32 'Content-Length': Buffer.byteLength(body),33 'Content-Type': 'text/plain'34 });35 res.end(body);36 };37 const httpServer = http.createServer(httpResponse);38 const httpsServer = https.createServer(httpsConfig, httpResponse);39 t.test('returns a net.Server instance', async (t) => {40 t.type(proxyproto.createServer(httpServer), 'Server');41 });42 t.test('server interface must be supplied', async (t) => {43 t.throws(() => proxyproto.createServer());44 t.doesNotThrow(() => proxyproto.createServer(httpServer));45 });46 t.test('vanilla http connections are untouched', async (t) => {47 await Promise.all([48 // ensure connection info is untouched49 new Promise(resolve => {50 const server = http.createServer((req,res) => {51 t.same(req.connection.remoteAddress, '::ffff:127.0.0.1');52 res.end('OK');53 proxied.close();54 resolve();55 });56 const proxied = proxyproto.createServer(server);57 proxied.listen(PORT);58 }),59 // ensure data is untouched60 new Promise(resolve => {61 http.get(`http://localhost:${PORT}`, httpRequestOptions, res => {62 res.setEncoding('utf8');63 let rawData = '';64 res.on('data', (chunk) => { rawData += chunk; });65 res.on('end', () => {66 t.same(rawData, 'OK');67 resolve();68 });69 });70 })71 ]);72 });73 t.test('vanilla https connections are untouched', async (t) => {74 await Promise.all([75 // ensure connection info is untouched76 new Promise(resolve => {77 const server = https.createServer(httpsConfig, (req,res) => {78 t.same(req.connection.remoteAddress, '::ffff:127.0.0.1');79 res.end('OK');80 proxied.close();81 resolve();82 });83 const proxied = proxyproto.createServer(server);84 proxied.listen(PORT);85 }),86 // ensure data is untouched87 new Promise(resolve => {88 https.get(`https://localhost:${PORT}`, httpRequestOptions, res => {89 res.setEncoding('utf8');90 let rawData = '';91 res.on('data', (chunk) => { rawData += chunk; });92 res.on('end', () => {93 t.same(rawData, 'OK');94 resolve();95 });96 });97 })98 ]);99 });100 t.test('http - PROXY protocol headers are parsed', async (t) => {101 await new Promise(resolve => {102 const server = http.createServer((req,res) => {103 t.same(req.connection.remoteAddress, '35.153.225.202');104 res.end('OK');105 proxied.close();106 resolve();107 });108 const proxied = injectProxyHeaders(proxyproto.createServer(server));109 proxied.listen(PORT);110 http.get(`http://localhost:${PORT}`, httpRequestOptions);111 });112 });113 t.test('https - PROXY protocol headers are parsed', async (t) => {114 await new Promise(resolve => {115 const server = https.createServer(httpsConfig, (req,res) => {116 t.same(req.connection.remoteAddress, '35.153.225.202');117 res.end('OK');118 proxied.close();119 resolve();120 });121 const proxied = injectProxyHeaders(proxyproto.createServer(server));122 proxied.listen(PORT);123 https.get(`https://localhost:${PORT}`, httpRequestOptions);124 });125 });126 t.test('listening port is re-used', async (t) => {127 await new Promise(resolve => {128 const server = http.createServer();129 server.listen(PORT, () => {130 const proxied = proxyproto.createServer(server);131 t.ok(proxied.listening);132 t.notOk(server.listening);133 t.same(proxied.address().port, PORT);134 proxied.close();135 resolve();136 });137 });138 });139 t.test('listening event is listened to', async (t) => {140 await new Promise(resolve => {141 const server = http.createServer();142 const proxied = proxyproto.createServer(server);143 proxied.on('listening', () => {144 t.ok(proxied.listening);145 t.notOk(server.listening);146 t.same(proxied.address().port, PORT);147 proxied.close();148 resolve();149 });150 server.listen(PORT);151 });152 });153 // first load test has ~.2ms added latency154 t.test('load test vanilla server', async (t) => {155 await new Promise(resolve => {156 const server = httpsServer;157 server.listen(PORT);158 autocannon(autocannonConfig, (err, result) => {159 t.notOk(err);160 t.same(result.non2xx, 0);161 t.notEqual(result['2xx'], 0);162 server.close();163 resolve();164 });165 });166 });167 t.test('load test proxied server', async (t) => {168 await new Promise(resolve => {169 const server = proxyproto.createServer(httpsServer);170 server.listen(PORT);171 autocannon(autocannonConfig, (err, result) => {172 t.notOk(err);173 t.same(result.non2xx, 0);174 t.notEqual(result['2xx'], 0);175 server.close();176 resolve();177 });178 });179 });180 t.test('load test injected proxied server', async (t) => {181 await new Promise(resolve => {182 const server = injectProxyHeaders(proxyproto.createServer(httpsServer));183 server.listen(PORT);184 autocannon(autocannonConfig, (err, result) => {185 t.notOk(err);186 t.same(result.non2xx, 0);187 t.notEqual(result['2xx'], 0);188 server.close();189 resolve();190 });191 });192 });193 t.test('handleCommonErrors - ECONNRESET', async (t) => {194 await new Promise(resolve => {195 let shouldNotErr = true;196 const server = proxyproto.createServer(httpsServer, {197 onError: () => shouldNotErr = false198 });199 server.listen(PORT);200 const client = net.connect(PORT, () => {201 client.destroy();202 setTimeout(() => {203 t.ok(shouldNotErr);204 server.close();205 resolve();206 });207 });208 });209 });210 t.test('handleCommonErrors - EPIPE', async (t) => {211 await new Promise(resolve => {212 let shouldNotErr = true;213 const server = net.createServer(socket =>214 socket.on('end', () => {215 socket.write('foo\n');216 socket.end();217 }));218 const proxied = proxyproto.createServer(server, {219 onError: () => shouldNotErr = false220 });221 proxied.listen(PORT);222 const client = net.connect(PORT, () => {223 client.end('yolo');224 setTimeout(() => {225 t.ok(shouldNotErr);226 proxied.close();227 resolve();228 });229 });230 });231 });232 t.test('handleCommonErrors - HPE_INVALID_EOF_STATE', async (t) => {233 await new Promise(resolve => {234 let shouldNotErr = true;235 const server = proxyproto.createServer(httpServer, {236 onError: () => shouldNotErr = false237 });238 server.listen(PORT);239 const client = net.connect(PORT, () => {240 client.write('GET /foo HTTP/1.1\r\nContent-Length:');241 client.end();242 setTimeout(() => {243 t.ok(shouldNotErr);244 server.close();245 resolve();246 });247 });248 });249 });250 t.test('handleCommonErrors - HPE_HEADER_OVERFLOW', async (t) => {251 await new Promise(resolve => {252 let shouldNotErr = true;253 const server = proxyproto.createServer(httpServer, {254 onError: () => shouldNotErr = false255 });256 server.listen(PORT);257 const client = net.connect(PORT, () => {258 const CRLF = '\r\n';259 const DUMMY_HEADER_NAME = 'Cookie: ';260 const DUMMY_HEADER_VALUE = 'a'.repeat(261 http.maxHeaderSize - DUMMY_HEADER_NAME.length - (2 * CRLF.length) + 1262 );263 const PAYLOAD = 'GET /foo HTTP/1.1' + CRLF +264 DUMMY_HEADER_NAME + DUMMY_HEADER_VALUE + CRLF.repeat(2);265 client.write(PAYLOAD);266 client.end();267 setTimeout(() => {268 t.ok(shouldNotErr);269 server.close();270 resolve();271 });272 });273 });274 });275 t.test('handleCommonErrors - SSL routines', async (t) => {276 await new Promise(resolve => {277 let shouldNotErr = true;278 const server = tls.createServer(httpsConfig, socket => socket.pipe(socket));279 const proxied = proxyproto.createServer(server, {280 onError: () => shouldNotErr = false281 });282 proxied.listen(PORT);283 const socket = net.connect(PORT);284 const client = tls.connect({285 socket,286 rejectUnauthorized: false287 }, () => {288 const BAD_RECORD = Buffer.from([0xff, 0xff, 0xff, 0xff, 0xff, 0xff]);289 client.write('x');290 client.on('error', () => { /* ignore client error */ });291 client.on('data', () => {292 socket.end(BAD_RECORD);293 setTimeout(() => {...
test.js
Source:test.js
1/* global require, describe, it */2'use strict';3var mpath = './../../../app/server';4// MODULES //5var // Expectation library:6 chai = require( 'chai' ),7 // Path module:8 path = require( 'path' ),9 // Module to mock dependencies:10 proxyquire = require( 'proxyquire' ),11 // Module to be tested:12 createServer = require( mpath );13// VARIABLES //14var expect = chai.expect,15 assert = chai.assert;16// MOCKS //17var keypath, certpath;18keypath = path.resolve( __dirname, '../../fixtures/agent2-key.pem' );19certpath = path.resolve( __dirname, '../../fixtures/agent2-cert.pem' );20/**21* FUNCTION: config( bool )22* Mocks the config dependency.23*24* @private25* @param {Boolean} bool - boolean indicating whether SSL is enabled26* @returns {Object} mock config27*/28function config( ssl ) {29 return {30 'get': function get( key ) {31 if ( key === 'ssl.enabled' ) {32 return ssl;33 }34 if ( key === 'port' ) {35 return 0;36 }37 if ( key === 'ssl' ) {38 return {39 'key': keypath,40 'cert': certpath41 };42 }43 }44 };45} // end FUNCTION config()46/**47* FUNCTION: noop()48* Non-operation.49*50* @private51*/52function noop() {53 // Do nothing...54} // end FUNCTION noop()55// TESTS //56describe( 'app/server', function tests() {57 it( 'should export a function', function test() {58 expect( createServer ).to.be.a( 'function' );59 });60 it( 'should create an HTTP server', function test( done ) {61 var createServer;62 createServer = proxyquire( mpath, {63 'config': config( false )64 });65 createServer.call( app, next );66 function app() {}67 function next() {68 assert.ok( app.server.address().port );69 app.server.close();70 done();71 }72 });73 it( 'should create an HTTPS server', function test( done ) {74 var createServer;75 createServer = proxyquire( mpath, {76 'config': config( true )77 });78 createServer.call( app, next );79 function app() {}80 function next() {81 assert.ok( app.server.address().port );82 app.server.close();83 done();84 }85 });86 it( 'should throw an error if unable to find a private key for SSL', function test() {87 var createServer,88 kpath;89 kpath = keypath;90 keypath = 'dfajdlfjadljfldsaj';91 createServer = proxyquire( mpath, {92 'config': config( true )93 });94 expect( foo ).to.throw( Error );95 keypath = kpath;96 function foo() {97 createServer.call( noop, noop );98 }99 });100 it( 'should throw an error if unable to find a public certificate for SSL', function test() {101 var createServer,102 cpath;103 cpath = certpath;104 certpath = 'dfajdlfjadljfldsaj';105 createServer = proxyquire( mpath, {106 'config': config( true )107 });108 expect( foo ).to.throw( Error );109 certpath = cpath;110 function foo() {111 createServer.call( noop, noop );112 }113 });114 it( 'should throw an error if the server port is already in use', function test( done ) {115 var err;116 createServer.call( app, next );117 function app() {}118 function next() {119 expect( foo ).to.throw( Error );120 done();121 }122 function foo() {123 err = new Error( 'Server address already in use.' );124 err.code = 'EADDRINUSE';125 app.server.emit( 'error', err );126 }127 });...
createServer.js
Source:createServer.js
1$.ajax({2 url:'/getUser',3 contentType: 'application/json',4 dataType: 'json',5 type:'post',6 headers: { 'Access-Control-Allow-Origin': '*' },7 success:function(data)8 {9 document.getElementById('servName').value = "Serveur de "+data.pseudo;10 console.log('success')11 }12})13$('#close').click(function(){14 let b = 5;15 setInterval(()=>{16 if(b<=0) return;17 b--;18 document.querySelector('#createServer').style.backgroundColor = 'rgba(0,0,0,'+b/10+')'19 },22)20 setTimeout(()=>{21 document.querySelector('#createServer').remove();22 },135)23 document.querySelector('#createServer .CForm').classList.add('CC');24})25$('#tab1').click(function(){26 27 $('#createServer .CForm').addClass('f1');28 $('#createServer .CForm .h').addClass('hide');29 $('#createServer .CForm .side1').removeClass('hide');30 $('#createServer .CForm .side1').addClass('show');31 32 33 34 35})36$('#return1').click(function(){37 $('#createServer .CForm').addClass('f1');38 $('#createServer .CForm .h').removeClass('hide');39 //$('#createServer .CForm .h').addClass('show');40 $('#createServer .CForm.f1').removeClass('f1');41 42 $('#createServer .CForm .side1').removeClass('show');43 $('#createServer .CForm .side1').addClass('hide');44})45$('#tab2,#tab3,#tbb').click(function(){46 $('#createServer .side1').removeClass('show');47 $('#createServer .side1').addClass('hide');48 $('#createServer .side2').removeClass('hide');49 $('#createServer .side2').addClass('show');50})51$('#joinServBTN').click(function()52{53 $('#createServer .CForm').addClass('f1');54 $('#createServer .CForm .h').addClass('hide');55 $('#createServer .CForm .side3').removeClass('hide');56 $('#createServer .CForm .side3').addClass('show');57})58$('#jsbmt').click(function(){59 $('#jsbmt').html('...');60 if($("#inviteLinkI").val().trim() == '')61 {62 $('#iVT').css('color','#F04747');63 $('#iVT').html(`Lien d'invitation - <i style="font-size:10px;">Tu dois entrer un lien d'invitation ou un code d'invitation valide.</i>`)64 $('#jsbmt').html('Rejoindre le serveur');65 66 }else{67 $.post({68 url:'/joinGuild',69 data:{70 invite:$("#inviteLinkI").val().trim()71 },72 success:function(res){73 $('#jsbmt').html('Rejoindre le serveur');74 if(res == '1')75 {76 $('#iVT').css('color','');77 $('#iVT').html(`Lien d'invitation *`)78 window.location.reload();79 }else{80 $('#iVT').css('color','#F04747');81 $('#iVT').html(`Lien d'invitation - <i>L'invitation est invalide ou a expiré.</i>`)82 }83 }84 })85}...
Using AI Code Generation
1const createTestCafe = require('testcafe');2let testcafe = null;3createTestCafe('localhost', 1337, 1338)4 .then(tc => {5 testcafe = tc;6 const runner = testcafe.createRunner();7 .src('test.js')8 .browsers('chrome')9 .run();10 })11 .then(failedCount => {12 console.log('Tests failed: ' + failedCount);13 testcafe.close();14 });15const createTestCafe = require('testcafe');16const testcafe = await createTestCafe('localhost', 1337, 1338);17const runner = testcafe.createRunner();18 .src('test.js')19 .browsers('chrome')20 .run();21testcafe.close();22const createTestCafe = require('testcafe');23const testcafe = await createTestCafe('localhost', 1337, 1338);24const runner = testcafe.createRunner();25 .src('test.js')26 .browsers('chrome')27 .run();28testcafe.close();29const createTestCafe = require('testcafe');30const testcafe = await createTestCafe('localhost', 1337, 1338);31const runner = testcafe.createRunner();32 .src('test.js')33 .browsers('chrome')34 .run();35testcafe.close();36const createTestCafe = require('testcafe');37const testcafe = await createTestCafe('localhost', 1337, 1338);38const runner = testcafe.createRunner();39 .src('test.js')40 .browsers('chrome')41 .run();42testcafe.close();43const createTestCafe = require('testcafe');44const testcafe = await createTestCafe('localhost', 1337, 1338);45const runner = testcafe.createRunner();
Using AI Code Generation
1const createTestCafe = require('testcafe');2let testcafe = null;3createTestCafe('localhost', 1337, 1338)4 .then(tc => {5 testcafe = tc;6 const runner = testcafe.createRunner();7 .src('test.js')8 .browsers(['chrome'])9 .run();10 })11 .then(failedCount => {12 console.log('Tests failed: ' + failedCount);13 testcafe.close();14 });15`testcafe chrome test.js -b myprovider:arg1=value1;arg2=value2`
Using AI Code Generation
1const createTestCafe = require('testcafe');2let testcafe = null;3createTestCafe('localhost', 1337, 1338)4 .then(tc => {5 testcafe = tc;6 const runner = testcafe.createRunner();7 .src(['test.js'])8 .browsers(['chrome'])9 .run();10 })11 .then(failedCount => {12 console.log('Tests failed: ' + failedCount);13 testcafe.close();14 });15test('My test', async t => {16 .typeText('#developer-name', 'John Smith')17 .click('#submit-button');18});19const createTestCafe = require('testcafe');20let testcafe = null;21createTestCafe('localhost', 1337, 1338)22 .then(tc => {23 testcafe = tc;24 const runner = testcafe.createRunner();25 .src(['test.js'])26 .browsers(['chrome'])27 .run();28 })29 .then(failedCount => {30 console.log('Tests failed: ' + failedCount);31 testcafe.close();32 });33test('My test', async t => {34 .typeText('#developer-name', 'John Smith')35 .click('#submit-button');36});37const createTestCafe = require('testcafe');38let testcafe = null;39createTestCafe('localhost', 1337, 1338)40 .then(tc => {41 testcafe = tc;42 const runner = testcafe.createRunner();43 .src(['test.js'])44 .browsers(['chrome'])45 .run();46 })47 .then(failedCount => {
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3});4import createTestCafe from 'testcafe';5const testcafe = await createTestCafe('localhost', 1337, 1338);6const runner = testcafe.createRunner();7 .src('test.js')8 .browsers(['chrome'])9 .run();10import { createBrowserConnection } from 'testcafe';11const connection = createBrowserConnection();12console.log(`To connect, open the remote browser and navigate to ${connection.url}`);13connection.once('ready', async () => {14 const runner = testcafe.createRunner();15 .src('test.js')16 .browsers(connection)17 .run();18 console.log('Tests failed: ' + failedCount);19 testcafe.close();20});
Using AI Code Generation
1const createTestCafe = require('testcafe');2const testCafeConfig = require('./testcaferc.json');3let testcafe = null;4createTestCafe('localhost', 1337, 1338)5 .then(tc => {6 testcafe = tc;7 const runner = testcafe.createRunner();8 .run(testCafeConfig);9 })10 .then(failedCount => {11 console.log('Tests failed: ' + failedCount);12 testcafe.close();13 });14{15 {16 }17}18import { Selector } from 'testcafe';19test('My first test', async t => {20 .typeText('#developer-name', 'John Smith')21 .click('#submit-button');22});
Using AI Code Generation
1import { createServer } from 'http';2import { createProxyServer } from 'http-proxy';3import { createProxyMiddleware } from 'http-proxy-middleware';4import { createProxyMiddleware as createProxyMiddleware2 } from 'http-proxy-middleware';5import { createProxyMiddleware as createProxyMiddleware3 } from 'http-proxy-middleware';6import { createProxyMiddleware as createProxyMiddleware4 } from 'http-proxy-middleware';7import { createProxyMiddleware as createProxyMiddleware5 } from 'http-proxy-middleware';8import { createProxyMiddleware as createProxyMiddleware6 } from 'http-proxy-middleware';9import { createProxyMiddleware as createProxyMiddleware7 } from 'http-proxy-middleware';10import { createProxyMiddleware as createProxyMiddleware8 } from 'http-proxy-middleware';11import { createProxyMiddleware as createProxyMiddleware9 } from 'http-proxy-middleware';12import { createProxyMiddleware as createProxyMiddleware10 } from 'http-proxy-middleware';13import { createProxyMiddleware as createProxyMiddleware11 } from 'http-proxy-middleware';14import { createProxyMiddleware as createProxyMiddleware12 } from 'http-proxy-middleware';15import { createProxyMiddleware as createProxyMiddleware13 } from 'http-proxy-middleware';16import { createProxyMiddleware as createProxyMiddleware14 } from 'http-proxy-middleware';17import { createProxyMiddleware as createProxyMiddleware15 } from 'http-proxy-middleware';
Using AI Code Generation
1import { createServer } from 'http';2const server = createServer((req, res) => {3 res.end('Hello, world!');4});5server.listen(1337, () => {6 console.log('Server is listening on port 1337');7});8import { createTestCafe } from 'testcafe';9createTestCafe('localhost', 1338, 1339)10 .then(testcafe => {11 console.log('Running tests...');12 .createRunner()13 .src('test.js')14 .browsers('chrome')15 .run()16 .then(failedCount => {17 console.log('Tests failed: ' + failedCount);18 testcafe.close();19 });20 });
Using AI Code Generation
1const createTestCafe = require('testcafe');2const testCafe = await createTestCafe('localhost', 1337, 1338);3const runner = testCafe.createRunner();4 .src('tests/')5 .browsers('chrome')6 .run();7testCafe.close();
Using AI Code Generation
1import { Selector } from 'testcafe';2import { createServer } from 'http-server';3import { resolve } from 'path';4const httpServer = createServer({ root: resolve('public') });5test('My first test', async t => {6 .typeText('#developer-name', 'John Smith')7 .click('#submit-button');8 const articleHeader = Selector('#article-header');9 const headerText = await articleHeader.innerText;10 const expectedText = 'Thank you, John Smith!';11 await t.expect(headerText).eql(expectedText);12});13import { resolve } from 'path';14import { exec } from 'child_process';15const testcafeProcess = exec(`testcafe chrome ${resolve('test.js')}`);16testcafeProcess.stdout.pipe(process.stdout);17testcafeProcess.on('exit', () => {18 httpServer.close();19});20httpServer.listen(8080);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!