How to use checkMetrics method in Puppeteer

Best JavaScript code snippet using puppeteer

fs.tap.js

Source:fs.tap.js Github

copy

Full Screen

...98 )99 verifySegments(t, agent, NAMES.FS.PREFIX + 'truncate',100 needFD ? [] : [NAMES.FS.PREFIX + 'open']101 )102 trans.end(function checkMetrics() {103 t.ok(104 checkMetric(expectedSegments, agent, trans.name),105 'metric should exist after transaction end'106 )107 })108 })109 })110})111test('ftruncate', {skip: fs.ftruncate === undefined}, function(t) {112 var name = path.join(tempDir, 'ftruncate-me')113 var content = 'some-content'114 fs.writeFileSync(name, content)115 var fd = fs.openSync(name, 'r+')116 var agent = setupAgent(t)117 helper.runInNamedTransaction(agent, function(trans) {118 fs.ftruncate(fd, 4, function(err) {119 t.notOk(err, 'should not error')120 helper.unloadAgent(agent)121 t.equal(122 fs.readFileSync(name, 'utf8'),123 content.slice(0, 4),124 'content should be truncated'125 )126 verifySegments(t, agent, NAMES.FS.PREFIX + 'ftruncate')127 trans.end(function checkMetrics() {128 t.ok(129 checkMetric(['ftruncate'], agent, trans.name),130 'metric should exist after transaction end'131 )132 })133 })134 })135})136test('chown', function(t) {137 var name = path.join(tempDir, 'chown-me')138 var content = 'some-content'139 fs.writeFileSync(name, content)140 var agent = setupAgent(t)141 var uid = 0142 var gid = 0143 helper.runInNamedTransaction(agent, function(trans) {144 fs.chown(name, uid, gid, function(err) {145 t.ok(err, 'should error for non root users')146 verifySegments(t, agent, NAMES.FS.PREFIX + 'chown')147 trans.end(function checkMetrics() {148 t.ok(149 checkMetric(['chown'], agent, trans.name),150 'metric should exist after transaction end'151 )152 })153 })154 })155})156test('fchown', function(t) {157 var name = path.join(tempDir, 'chown-me')158 var content = 'some-content'159 fs.writeFileSync(name, content)160 var fd = fs.openSync(name, 'r+')161 var agent = setupAgent(t)162 var uid = 0163 var gid = 0164 helper.runInNamedTransaction(agent, function(trans) {165 fs.fchown(fd, uid, gid, function(err) {166 t.ok(err, 'should error for non root users')167 verifySegments(t, agent, NAMES.FS.PREFIX + 'fchown')168 trans.end(function checkMetrics() {169 t.ok(170 checkMetric(['fchown'], agent, trans.name),171 'metric should exist after transaction end'172 )173 })174 })175 })176})177// Only exists on Darwin currently, using this check to catch if it178// appears in other versions too.179test('lchown', {skip: fs.lchown === undefined}, function(t) {180 var name = path.join(tempDir, 'chown-me')181 var content = 'some-content'182 fs.writeFileSync(name, content)183 var agent = setupAgent(t)184 var uid = 0185 var gid = 0186 helper.runInNamedTransaction(agent, function(trans) {187 fs.lchown(name, uid, gid, function(err) {188 t.ok(err, 'should error for non root users')189 verifySegments(t, agent, NAMES.FS.PREFIX + 'lchown', [NAMES.FS.PREFIX + 'open'])190 trans.end(function checkMetrics() {191 t.ok(192 checkMetric(['lchown', 'open'], agent, trans.name),193 'metric should exist after transaction end'194 )195 })196 })197 })198})199test('chmod', function(t) {200 var name = path.join(tempDir, 'chmod-me')201 var content = 'some-content'202 fs.writeFileSync(name, content)203 var agent = setupAgent(t)204 t.equal((fs.statSync(name).mode & 511).toString(8), '666')205 helper.runInNamedTransaction(agent, function(trans) {206 fs.chmod(name, '0777', function(err) {207 t.equal(err, null, 'should not error')208 helper.unloadAgent(agent)209 t.equal((fs.statSync(name).mode & 511).toString(8), '777')210 verifySegments(t, agent, NAMES.FS.PREFIX + 'chmod')211 trans.end(function checkMetrics() {212 t.ok(213 checkMetric(['chmod'], agent, trans.name),214 'metric should exist after transaction end'215 )216 })217 })218 })219})220// Only exists on Darwin currently, using this check to catch if it221// appears in other versions too.222test('lchmod', {skip: fs.lchmod === undefined}, function(t) {223 var name = path.join(tempDir, 'lchmod-me')224 var content = 'some-content'225 fs.writeFileSync(name, content)226 var agent = setupAgent(t)227 t.equal((fs.statSync(name).mode & 511).toString(8), '666')228 helper.runInNamedTransaction(agent, function(trans) {229 fs.lchmod(name, '0777', function(err) {230 t.equal(err, null, 'should not error')231 helper.unloadAgent(agent)232 t.equal((fs.statSync(name).mode & 511).toString(8), '777')233 verifySegments(t, agent, NAMES.FS.PREFIX + 'lchmod', [NAMES.FS.PREFIX + 'open'])234 trans.end(function checkMetrics() {235 t.ok(236 checkMetric(['lchmod', 'open'], agent, trans.name),237 'metric should exist after transaction end'238 )239 })240 })241 })242})243test('fchmod', function(t) {244 var name = path.join(tempDir, 'fchmod-me')245 var content = 'some-content'246 fs.writeFileSync(name, content)247 var fd = fs.openSync(name, 'r+')248 var agent = setupAgent(t)249 t.equal((fs.statSync(name).mode & 511).toString(8), '666')250 helper.runInNamedTransaction(agent, function(trans) {251 fs.fchmod(fd, '0777', function(err) {252 t.equal(err, null, 'should not error')253 helper.unloadAgent(agent)254 t.equal((fs.statSync(name).mode & 511).toString(8), '777')255 verifySegments(t, agent, NAMES.FS.PREFIX + 'fchmod')256 trans.end(function checkMetrics() {257 t.ok(258 checkMetric(['fchmod'], agent, trans.name),259 'metric should exist after transaction end'260 )261 })262 })263 })264})265test('stat', function(t) {266 var name = path.join(tempDir, 'stat-me')267 var content = 'some-content'268 fs.writeFileSync(name, content)269 var agent = setupAgent(t)270 helper.runInNamedTransaction(agent, function(trans) {271 fs.stat(name, function(err, stat) {272 t.equal(err, null, 'should not error')273 t.equal((stat.mode & 511).toString(8), '666')274 verifySegments(t, agent, NAMES.FS.PREFIX + 'stat')275 trans.end(function checkMetrics() {276 t.ok(277 checkMetric(['stat'], agent, trans.name),278 'metric should exist after transaction end'279 )280 })281 })282 })283})284test('lstat', function(t) {285 var name = path.join(tempDir, 'lstat-me')286 var content = 'some-content'287 fs.writeFileSync(name, content)288 var agent = setupAgent(t)289 helper.runInNamedTransaction(agent, function(trans) {290 fs.lstat(name, function(err, stat) {291 t.equal(err, null, 'should not error')292 t.equal((stat.mode & 511).toString(8), '666')293 verifySegments(t, agent, NAMES.FS.PREFIX + 'lstat')294 trans.end(function checkMetrics() {295 t.ok(296 checkMetric(['lstat'], agent, trans.name),297 'metric should exist after transaction end'298 )299 })300 })301 })302})303test('fstat', function(t) {304 var name = path.join(tempDir, 'fstat-me')305 var content = 'some-content'306 fs.writeFileSync(name, content)307 var fd = fs.openSync(name, 'r+')308 var agent = setupAgent(t)309 helper.runInNamedTransaction(agent, function(trans) {310 fs.fstat(fd, function(err, stat) {311 t.equal(err, null, 'should not error')312 t.equal((stat.mode & 511).toString(8), '666')313 verifySegments(t, agent, NAMES.FS.PREFIX + 'fstat')314 trans.end(function checkMetrics() {315 t.ok(316 checkMetric(['fstat'], agent, trans.name),317 'metric should exist after transaction end'318 )319 })320 })321 })322})323test('link', function(t) {324 var name = path.join(tempDir, 'link-to-me')325 var link = path.join(tempDir, 'link-me')326 var content = 'some-content'327 fs.writeFileSync(name, content)328 var agent = setupAgent(t)329 helper.runInNamedTransaction(agent, function(trans) {330 fs.link(name, link, function(err) {331 t.equal(err, null, 'should not error')332 t.equal(333 fs.statSync(name).ino,334 fs.statSync(link).ino,335 'should point to the same file'336 )337 verifySegments(t, agent, NAMES.FS.PREFIX + 'link')338 trans.end(function checkMetrics() {339 t.ok(340 checkMetric(['link'], agent, trans.name),341 'metric should exist after transaction end'342 )343 })344 })345 })346})347test('symlink', function(t) {348 var name = path.join(tempDir, 'symlink-to-me')349 var link = path.join(tempDir, 'symlink-me')350 var content = 'some-content'351 fs.writeFileSync(name, content)352 var agent = setupAgent(t)353 helper.runInNamedTransaction(agent, function(trans) {354 fs.symlink(name, link, function(err) {355 t.equal(err, null, 'should not error')356 t.equal(357 fs.readlinkSync(link),358 name,359 'should point to the same file'360 )361 verifySegments(t, agent, NAMES.FS.PREFIX + 'symlink')362 trans.end(function checkMetrics() {363 t.ok(364 checkMetric(['symlink'], agent, trans.name),365 'metric should exist after transaction end'366 )367 })368 })369 })370})371test('readlink', function(t) {372 var name = path.join(tempDir, 'readlink')373 var link = path.join(tempDir, 'readlink-me')374 var content = 'some-content'375 fs.writeFileSync(name, content)376 fs.symlinkSync(name, link)377 var agent = setupAgent(t)378 helper.runInNamedTransaction(agent, function(trans) {379 fs.readlink(link, function(err, target) {380 t.equal(err, null, 'should not error')381 t.equal(target, name, 'should point to the same file')382 verifySegments(t, agent, NAMES.FS.PREFIX + 'readlink')383 trans.end(function checkMetrics() {384 t.ok(385 checkMetric(['readlink'], agent, trans.name),386 'metric should exist after transaction end'387 )388 })389 })390 })391})392test('realpath', function(t) {393 var name = path.join(tempDir, 'realpath')394 var link = path.join(tempDir, 'link-to-realpath')395 var content = 'some-content'396 fs.writeFileSync(name, content)397 fs.symlinkSync(name, link)398 var real = fs.realpathSync(name)399 var agent = setupAgent(t)400 helper.runInNamedTransaction(agent, function(trans) {401 fs.realpath(link, function(err, target) {402 t.equal(err, null, 'should not error')403 t.equal(target, real, 'should point to the same file')404 verifySegments(t, agent, NAMES.FS.PREFIX + 'realpath', [NAMES.FS.PREFIX + 'lstat'])405 trans.end(function checkMetrics() {406 t.ok(407 checkMetric(['lstat', 'realpath'], agent, trans.name),408 'metric should exist after transaction end'409 )410 })411 })412 })413})414test('unlink', function(t) {415 var name = path.join(tempDir, 'unlink-from-me')416 var link = path.join(tempDir, 'unlink-me')417 var content = 'some-content'418 fs.writeFileSync(name, content)419 fs.symlinkSync(name, link)420 var agent = setupAgent(t)421 helper.runInNamedTransaction(agent, function(trans) {422 fs.unlink(link, function(err) {423 t.equal(err, null, 'should not error')424 t.notOk(fs.existsSync(link), 'link should not exist')425 verifySegments(t, agent, NAMES.FS.PREFIX + 'unlink')426 trans.end(function checkMetrics() {427 t.ok(428 checkMetric(['unlink'], agent, trans.name),429 'metric should exist after transaction end'430 )431 })432 })433 })434})435test('mkdir', function(t) {436 var name = path.join(tempDir, 'mkdir')437 var agent = setupAgent(t)438 helper.runInNamedTransaction(agent, function(trans) {439 fs.mkdir(name, function(err) {440 t.equal(err, null, 'should not error')441 t.ok(fs.existsSync(name), 'dir should exist')442 t.ok(fs.readdirSync(name), 'dir should be readable')443 verifySegments(t, agent, NAMES.FS.PREFIX + 'mkdir')444 trans.end(function checkMetrics() {445 t.ok(446 checkMetric(['mkdir'], agent, trans.name),447 'metric should exist after transaction end'448 )449 })450 })451 })452})453test('rmdir', function(t) {454 var name = path.join(tempDir, 'rmdir')455 var agent = setupAgent(t)456 fs.mkdirSync(name)457 helper.runInNamedTransaction(agent, function(trans) {458 fs.rmdir(name, function(err) {459 t.equal(err, null, 'should not error')460 t.notOk(fs.existsSync(name), 'dir should not exist')461 verifySegments(t, agent, NAMES.FS.PREFIX + 'rmdir')462 trans.end(function checkMetrics() {463 t.ok(464 checkMetric(['rmdir'], agent, trans.name),465 'metric should exist after transaction end'466 )467 })468 })469 })470})471test('readdir', function(t) {472 var name = path.join(tempDir, 'readdir')473 var agent = setupAgent(t)474 fs.mkdirSync(name)475 helper.runInNamedTransaction(agent, function(trans) {476 fs.readdir(name, function(err, data) {477 t.equal(err, null, 'should not error')478 t.deepEqual(data, [], 'should get list of contents')479 verifySegments(t, agent, NAMES.FS.PREFIX + 'readdir')480 trans.end(function checkMetrics() {481 t.ok(482 checkMetric(['readdir'], agent, trans.name),483 'metric should exist after transaction end'484 )485 })486 })487 })488})489test('close', function(t) {490 var name = path.join(tempDir, 'close-me')491 var content = 'some-content'492 fs.writeFileSync(name, content)493 var fd = fs.openSync(name, 'r+')494 var agent = setupAgent(t)495 helper.runInNamedTransaction(agent, function(trans) {496 fs.close(fd, function(err) {497 t.equal(err, null, 'should not error')498 verifySegments(t, agent, NAMES.FS.PREFIX + 'close')499 trans.end(function checkMetrics() {500 t.ok(501 checkMetric(['close'], agent, trans.name),502 'metric should exist after transaction end'503 )504 })505 })506 })507})508test('open', function(t) {509 var name = path.join(tempDir, 'open-me')510 var content = 'some-content'511 fs.writeFileSync(name, content)512 var agent = setupAgent(t)513 helper.runInNamedTransaction(agent, function(trans) {514 fs.open(name, 'r+', function(err, fd) {515 t.equal(err, null, 'should not error')516 t.ok(fd, 'should get a file descriptor')517 verifySegments(t, agent, NAMES.FS.PREFIX + 'open')518 trans.end(function checkMetrics() {519 t.ok(520 checkMetric(['open'], agent, trans.name),521 'metric should exist after transaction end'522 )523 })524 })525 })526})527test('utimes', function(t) {528 var name = path.join(tempDir, 'utimes-me')529 var content = 'some-content'530 fs.writeFileSync(name, content)531 var agent = setupAgent(t)532 var accessed = 5533 var modified = 15534 helper.runInNamedTransaction(agent, function(trans) {535 fs.utimes(name, accessed, modified, function(err) {536 t.notOk(err, 'should not error')537 var stats = fs.statSync(name)538 t.equal(stats.atime.toISOString(), '1970-01-01T00:00:05.000Z')539 t.equal(stats.mtime.toISOString(), '1970-01-01T00:00:15.000Z')540 verifySegments(t, agent, NAMES.FS.PREFIX + 'utimes')541 trans.end(function checkMetrics() {542 t.ok(543 checkMetric(['utimes'], agent, trans.name),544 'metric should exist after transaction end'545 )546 })547 })548 })549})550test('futimes', function(t) {551 var name = path.join(tempDir, 'futimes-me')552 var content = 'some-content'553 fs.writeFileSync(name, content)554 var fd = fs.openSync(name, 'r+')555 var agent = setupAgent(t)556 var accessed = 5557 var modified = 15558 helper.runInNamedTransaction(agent, function(trans) {559 fs.futimes(fd, accessed, modified, function(err) {560 t.notOk(err, 'should not error')561 var stats = fs.statSync(name)562 t.equal(stats.atime.toISOString(), '1970-01-01T00:00:05.000Z')563 t.equal(stats.mtime.toISOString(), '1970-01-01T00:00:15.000Z')564 verifySegments(t, agent, NAMES.FS.PREFIX + 'futimes')565 trans.end(function checkMetrics() {566 t.ok(567 checkMetric(['futimes'], agent, trans.name),568 'metric should exist after transaction end'569 )570 })571 })572 })573})574test('fsync', function(t) {575 var name = path.join(tempDir, 'fsync-me')576 var content = 'some-content'577 fs.writeFileSync(name, content)578 var fd = fs.openSync(name, 'r+')579 var agent = setupAgent(t)580 helper.runInNamedTransaction(agent, function(trans) {581 fs.fsync(fd, function(err) {582 t.notOk(err, 'should not error')583 verifySegments(t, agent, NAMES.FS.PREFIX + 'fsync')584 trans.end(function checkMetrics() {585 t.ok(586 checkMetric(['fsync'], agent, trans.name),587 'metric should exist after transaction end'588 )589 })590 })591 })592})593test('readFile', function(t) {594 var name = path.join(tempDir, 'readFile')595 var content = 'some-content'596 fs.writeFileSync(name, content)597 var agent = setupAgent(t)598 helper.runInNamedTransaction(agent, function(trans) {599 fs.readFile(name, function(err, data) {600 t.notOk(err, 'should not error')601 t.equal(data.toString('utf8'), content)602 var expectFSOpen = true603 // io.js changed their implementation of fs.readFile to use process.binding.604 // This caused the file opening not to be added to the trace when using io.js.605 // By checking this value, we can determine whether or not to expect it.606 if (agent.getTransaction().trace.root.children[0].children.length === 1) {607 expectFSOpen = false608 }609 verifySegments(t, agent, NAMES.FS.PREFIX + 'readFile',610 expectFSOpen ? [NAMES.FS.PREFIX + 'open'] : []611 )612 trans.end(function checkMetrics() {613 t.ok(614 checkMetric(615 expectFSOpen ? ['open', 'readFile'] : ['readFile'],616 agent, trans.name617 ),618 'metric should exist after transaction end'619 )620 })621 })622 })623})624test('writeFile', function(t) {625 var name = path.join(tempDir, 'writeFile')626 var content = 'some-content'627 var agent = setupAgent(t)628 helper.runInNamedTransaction(agent, function(trans) {629 fs.writeFile(name, content, function(err) {630 t.notOk(err, 'should not error')631 t.equal(fs.readFileSync(name).toString('utf8'), content)632 verifySegments(t, agent, NAMES.FS.PREFIX + 'writeFile', [NAMES.FS.PREFIX + 'open'])633 trans.end(function checkMetrics() {634 t.ok(635 checkMetric(['writeFile', 'open'], agent, trans.name),636 'metric should exist after transaction end'637 )638 })639 })640 })641})642test('appendFile', function(t) {643 var name = path.join(tempDir, 'appendFile')644 var content = 'some-content'645 fs.writeFileSync(name, content)646 var agent = setupAgent(t)647 var expectedSegments = []648 var expectOpen = false649 if (semver.satisfies(process.version, '<0.10')) {650 expectedSegments = ['appendFile', 'open']651 expectOpen = true652 } else {653 expectedSegments = ['appendFile', 'writeFile']654 }655 helper.runInNamedTransaction(agent, function(trans) {656 fs.appendFile(name, '123', function(err, data) {657 t.notOk(err, 'should not error')658 t.equal(fs.readFileSync(name).toString('utf-8'), content + '123')659 verifySegments(t, agent, NAMES.FS.PREFIX + 'appendFile',660 expectOpen ? [NAMES.FS.PREFIX + 'open'] : [NAMES.FS.PREFIX + 'writeFile'])661 trans.end(function checkMetrics() {662 t.ok(663 checkMetric(expectedSegments, agent, trans.name),664 'metric should exist after transaction end'665 )666 })667 })668 })669})670test('exists', function(t) {671 var name = path.join(tempDir, 'exists')672 var content = 'some-content'673 fs.writeFileSync(name, content)674 var agent = setupAgent(t)675 helper.runInNamedTransaction(agent, function(trans) {676 fs.exists(name, function(exists) {677 t.ok(exists, 'should exist')678 verifySegments(t, agent, NAMES.FS.PREFIX + 'exists')679 trans.end(function checkMetrics() {680 t.ok(681 checkMetric(['exists'], agent, trans.name),682 'metric should exist after transaction end'683 )684 })685 })686 })687})688test('read', function(t) {689 var name = path.join(tempDir, 'read')690 var content = 'some-content'691 fs.writeFileSync(name, content)692 var fd = fs.openSync(name, 'r+')693 var agent = setupAgent(t)...

Full Screen

Full Screen

segments.tap.js

Source:segments.tap.js Github

copy

Full Screen

...33 'Expressjs/Route Path: /test', [34 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>'35 ]36 ], assertSegmentsOptions)37 checkMetrics(t, transaction.metrics, [38 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>//test'39 ])40 t.end()41 })42})43test('middleware with child segment gets named correctly', function(t) {44 setup(t)45 app.all('/test', function(req, res) {46 setTimeout(function() {47 res.end()48 }, 1)49 })50 runTest(t, function(segments, transaction) {51 checkMetrics(t, transaction.metrics, [52 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>//test'53 ])54 t.end()55 })56})57test('segments for route handler', function(t) {58 setup(t)59 app.all('/test', function(req, res) {60 res.end()61 })62 runTest(t, function(segments, transaction) {63 checkSegments(t, transaction.trace.root.children[0], [64 NAMES.EXPRESS.MIDDLEWARE + 'query',65 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',66 'Expressjs/Route Path: /test', [67 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>'68 ]69 ], assertSegmentsOptions)70 checkMetrics(t, transaction.metrics, [71 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>//test'72 ])73 t.end()74 })75})76test('route function names are in segment names', function(t) {77 setup(t)78 app.all('/test', function myHandler(req, res) {79 res.end()80 })81 runTest(t, function(segments, transaction) {82 checkSegments(t, transaction.trace.root.children[0], [83 NAMES.EXPRESS.MIDDLEWARE + 'query',84 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',85 'Expressjs/Route Path: /test', [86 NAMES.EXPRESS.MIDDLEWARE + 'myHandler'87 ]88 ], assertSegmentsOptions)89 checkMetrics(t, transaction.metrics, [90 NAMES.EXPRESS.MIDDLEWARE + 'myHandler//test'91 ])92 t.end()93 })94})95test('middleware mounted on a path should produce correct names', function(t) {96 setup(t)97 app.use('/test/:id', function handler(req, res) {98 res.send()99 })100 runTest(t, '/test/1', function(segments, transaction) {101 var routeSegment = segments[2]102 t.equal(routeSegment.name, NAMES.EXPRESS.MIDDLEWARE + 'handler//test/:id')103 checkMetrics(t, transaction.metrics, [104 NAMES.EXPRESS.MIDDLEWARE + 'handler//test/:id'105 ], '/test/:id')106 t.end()107 })108})109test('each handler in route has its own segment', function(t) {110 setup(t)111 app.all('/test', function handler1(req, res, next) {112 next()113 }, function handler2(req, res) {114 res.send()115 })116 runTest(t, function(segments, transaction) {117 checkSegments(t, transaction.trace.root.children[0], [118 NAMES.EXPRESS.MIDDLEWARE + 'query',119 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',120 'Expressjs/Route Path: /test', [121 NAMES.EXPRESS.MIDDLEWARE + 'handler1',122 NAMES.EXPRESS.MIDDLEWARE + 'handler2'123 ]124 ], assertSegmentsOptions)125 checkMetrics(t, transaction.metrics, [126 NAMES.EXPRESS.MIDDLEWARE + 'handler1//test',127 NAMES.EXPRESS.MIDDLEWARE + 'handler2//test'128 ])129 t.end()130 })131})132test('segments for routers', function(t) {133 setup(t)134 var router = express.Router() // eslint-disable-line new-cap135 router.all('/test', function(req, res) {136 res.end()137 })138 app.use('/router1', router)139 runTest(t, '/router1/test', function(segments, transaction) {140 checkSegments(t, transaction.trace.root.children[0], [141 NAMES.EXPRESS.MIDDLEWARE + 'query',142 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',143 'Expressjs/Router: /router1', [144 'Expressjs/Route Path: /test', [145 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>'146 ]147 ]148 ], assertSegmentsOptions)149 checkMetrics(t, transaction.metrics, [150 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>//router1/test'151 ], '/router1/test')152 t.end()153 })154})155test('two root routers', function(t) {156 setup(t)157 var router1 = express.Router() // eslint-disable-line new-cap158 router1.all('/', function(req, res) {159 res.end()160 })161 app.use('/', router1)162 var router2 = express.Router() // eslint-disable-line new-cap163 router2.all('/test', function(req, res) {164 res.end()165 })166 app.use('/', router2)167 runTest(t, '/test', function(segments, transaction) {168 checkSegments(t, transaction.trace.root.children[0], [169 NAMES.EXPRESS.MIDDLEWARE + 'query',170 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',171 'Expressjs/Router: /',172 'Expressjs/Router: /', [173 'Expressjs/Route Path: /test', [174 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>'175 ]176 ]177 ], assertSegmentsOptions)178 checkMetrics(t, transaction.metrics, [179 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>//test'180 ], '/test')181 t.end()182 })183})184test('router mounted as a route handler', function(t) {185 setup(t)186 var router1 = express.Router() // eslint-disable-line new-cap187 router1.all('/test', function testHandler(req, res) {188 res.send('test')189 })190 app.get('*', router1)191 runTest(t, '/test', function(segments, transaction) {192 checkSegments(t, transaction.trace.root.children[0], [193 NAMES.EXPRESS.MIDDLEWARE + 'query',194 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',195 'Expressjs/Route Path: /*', [196 'Expressjs/Router: /', [197 'Expressjs/Route Path: /test', [198 NAMES.EXPRESS.MIDDLEWARE + 'testHandler'199 ]200 ]201 ]202 ], assertSegmentsOptions)203 checkMetrics(t, transaction.metrics, [204 NAMES.EXPRESS.MIDDLEWARE + 'testHandler//*/test'205 ], '/*/test')206 t.end()207 })208})209test('segments for routers', function(t) {210 setup(t)211 var router = express.Router() // eslint-disable-line new-cap212 router.all('/test', function(req, res) {213 res.end()214 })215 app.use('/router1', router)216 runTest(t, '/router1/test', function(segments, transaction) {217 checkSegments(t, transaction.trace.root.children[0], [218 NAMES.EXPRESS.MIDDLEWARE + 'query',219 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',220 'Expressjs/Router: /router1', [221 'Expressjs/Route Path: /test', [222 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>'223 ]224 ]225 ], assertSegmentsOptions)226 checkMetrics(t, transaction.metrics, [227 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>//router1/test'228 ], '/router1/test')229 t.end()230 })231})232test('segments for sub-app', function(t) {233 setup(t)234 var subapp = express()235 subapp.all('/test', function(req, res) {236 res.end()237 })238 app.use('/subapp1', subapp)239 runTest(t, '/subapp1/test', function(segments, transaction) {240 checkSegments(t, transaction.trace.root.children[0], [241 NAMES.EXPRESS.MIDDLEWARE + 'query',242 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',243 'Expressjs/Mounted App: /subapp1', [244 NAMES.EXPRESS.MIDDLEWARE + 'query',245 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',246 'Expressjs/Route Path: /test', [247 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>'248 ]249 ]250 ], assertSegmentsOptions)251 checkMetrics(t, transaction.metrics, [252 NAMES.EXPRESS.MIDDLEWARE + 'query//subapp1',253 NAMES.EXPRESS.MIDDLEWARE + 'expressInit//subapp1',254 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>//subapp1/test'255 ], '/subapp1/test')256 t.end()257 })258})259test('segments for sub-app', function(t) {260 setup(t)261 var subapp = express()262 subapp.get('/test', function(req, res, next) {263 next()264 }, function(req, res, next) {265 next()266 })267 subapp.get('/test', function(req, res) {268 res.end()269 })270 app.use('/subapp1', subapp)271 runTest(t, '/subapp1/test', function(segments, transaction) {272 checkSegments(t, transaction.trace.root.children[0], [273 NAMES.EXPRESS.MIDDLEWARE + 'query',274 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',275 'Expressjs/Mounted App: /subapp1', [276 NAMES.EXPRESS.MIDDLEWARE + 'query',277 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',278 'Expressjs/Route Path: /test', [279 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>',280 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>'281 ],282 'Expressjs/Route Path: /test', [283 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>'284 ]285 ]286 ], assertSegmentsOptions)287 checkMetrics(t, transaction.metrics, [288 NAMES.EXPRESS.MIDDLEWARE + 'query//subapp1',289 NAMES.EXPRESS.MIDDLEWARE + 'expressInit//subapp1',290 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>//subapp1/test'291 ], '/subapp1/test')292 t.end()293 })294})295test('segments for wildcard', function(t) {296 setup(t)297 var subapp = express()298 subapp.all('/:app', function(req, res) {299 res.end()300 })301 app.use('/subapp1', subapp)302 runTest(t, '/subapp1/test', function(segments, transaction) {303 checkSegments(t, transaction.trace.root.children[0], [304 NAMES.EXPRESS.MIDDLEWARE + 'query',305 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',306 'Expressjs/Mounted App: /subapp1', [307 NAMES.EXPRESS.MIDDLEWARE + 'query',308 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',309 'Expressjs/Route Path: /:app', [310 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>'311 ]312 ]313 ], assertSegmentsOptions)314 checkMetrics(t, transaction.metrics, [315 NAMES.EXPRESS.MIDDLEWARE + 'query//subapp1',316 NAMES.EXPRESS.MIDDLEWARE + 'expressInit//subapp1',317 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>//subapp1/:app'318 ], '/subapp1/:app')319 t.end()320 })321})322test('router with subapp', function(t) {323 setup(t)324 var router = express.Router() // eslint-disable-line new-cap325 var subapp = express()326 subapp.all('/test', function(req, res) {327 res.end()328 })329 router.use('/subapp1', subapp)330 app.use('/router1', router)331 runTest(t, '/router1/subapp1/test', function(segments, transaction) {332 checkSegments(t, transaction.trace.root.children[0], [333 NAMES.EXPRESS.MIDDLEWARE + 'query',334 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',335 'Expressjs/Router: /router1', [336 'Expressjs/Mounted App: /subapp1', [337 NAMES.EXPRESS.MIDDLEWARE + 'query',338 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',339 'Expressjs/Route Path: /test', [340 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>'341 ]342 ]343 ]344 ], assertSegmentsOptions)345 checkMetrics(t, transaction.metrics, [346 NAMES.EXPRESS.MIDDLEWARE + 'query//router1/subapp1',347 NAMES.EXPRESS.MIDDLEWARE + 'expressInit//router1/subapp1',348 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>//router1/subapp1/test'349 ], '/router1/subapp1/test')350 t.end()351 })352})353test('mounted middleware', function(t) {354 setup(t)355 app.use('/test', function myHandler(req, res) {356 res.end()357 })358 runTest(t, function(segments, transaction) {359 checkSegments(t, transaction.trace.root.children[0], [360 NAMES.EXPRESS.MIDDLEWARE + 'query',361 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',362 NAMES.EXPRESS.MIDDLEWARE + 'myHandler//test'363 ], assertSegmentsOptions)364 checkMetrics(t, transaction.metrics, [365 NAMES.EXPRESS.MIDDLEWARE + 'myHandler//test'366 ])367 t.end()368 })369})370test('error middleware', function(t) {371 setup(t)372 app.get('/test', function() {373 throw new Error('some error')374 })375 app.use(function myErrorHandler(err, req, res, next) { // eslint-disable-line376 res.end()377 })378 runTest(t, function(segments, transaction) {379 checkSegments(t, transaction.trace.root.children[0], [380 NAMES.EXPRESS.MIDDLEWARE + 'query',381 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',382 'Expressjs/Route Path: /test', [383 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>'384 ],385 NAMES.EXPRESS.MIDDLEWARE + 'myErrorHandler'386 ], assertSegmentsOptions)387 checkMetrics(t, transaction.metrics, [388 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>//test',389 NAMES.EXPRESS.MIDDLEWARE + 'myErrorHandler//test'390 ], '/test')391 t.end()392 })393})394test('error handler in router', function(t) {395 setup(t)396 var router = express.Router() // eslint-disable-line new-cap397 router.get('/test', function() {398 throw new Error('some error')399 })400 router.use(function myErrorHandler(error, req, res, next) { // eslint-disable-line401 res.end()402 })403 app.use('/router', router)404 var endpoint = '/router/test'405 runTest(t, {406 endpoint: endpoint,407 errors: 0408 }, function(segments, transaction) {409 checkSegments(t, transaction.trace.root.children[0], [410 NAMES.EXPRESS.MIDDLEWARE + 'query',411 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',412 'Expressjs/Router: /router', [413 'Expressjs/Route Path: /test', [414 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>'415 ],416 NAMES.EXPRESS.MIDDLEWARE + 'myErrorHandler'417 ]418 ], assertSegmentsOptions)419 checkMetrics(t, transaction.metrics, [420 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>//router/test',421 NAMES.EXPRESS.MIDDLEWARE + 'myErrorHandler//router/test'422 ], endpoint)423 t.end()424 })425})426test('error handler in second router', function(t) {427 setup(t)428 var router1 = express.Router() // eslint-disable-line new-cap429 var router2 = express.Router() // eslint-disable-line new-cap430 router2.get('/test', function() {431 throw new Error('some error')432 })433 router2.use(function myErrorHandler(error, req, res, next) { // eslint-disable-line434 res.end()435 })436 router1.use('/router2', router2)437 app.use('/router1', router1)438 var endpoint = '/router1/router2/test'439 runTest(t, {440 endpoint: endpoint,441 errors: 0442 }, function(segments, transaction) {443 checkSegments(t, transaction.trace.root.children[0], [444 NAMES.EXPRESS.MIDDLEWARE + 'query',445 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',446 'Expressjs/Router: /router1', [447 'Expressjs/Router: /router2', [448 'Expressjs/Route Path: /test', [449 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>'450 ],451 NAMES.EXPRESS.MIDDLEWARE + 'myErrorHandler'452 ]453 ]454 ], assertSegmentsOptions)455 checkMetrics(t, transaction.metrics, [456 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>//router1/router2/test',457 NAMES.EXPRESS.MIDDLEWARE + 'myErrorHandler//router1/router2/test'458 ], endpoint)459 t.end()460 })461})462test('error handler outside of router', function(t) {463 setup(t)464 var router = express.Router() // eslint-disable-line new-cap465 router.get('/test', function() {466 throw new Error('some error')467 })468 app.use('/router', router)469 app.use(function myErrorHandler(error, req, res, next) { // eslint-disable-line470 res.end()471 })472 var endpoint = '/router/test'473 runTest(t, {474 endpoint: endpoint,475 errors: 0476 }, function(segments, transaction) {477 checkSegments(t, transaction.trace.root.children[0], [478 NAMES.EXPRESS.MIDDLEWARE + 'query',479 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',480 'Expressjs/Router: /router', [481 'Expressjs/Route Path: /test', [482 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>'483 ]484 ],485 NAMES.EXPRESS.MIDDLEWARE + 'myErrorHandler'486 ], assertSegmentsOptions)487 checkMetrics(t, transaction.metrics, [488 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>//router/test',489 NAMES.EXPRESS.MIDDLEWARE + 'myErrorHandler//router/test'490 ], endpoint)491 t.end()492 })493})494test('error handler outside of two routers', function(t) {495 setup(t)496 var router1 = express.Router() // eslint-disable-line new-cap497 var router2 = express.Router() // eslint-disable-line new-cap498 router1.use('/router2', router2)499 router2.get('/test', function() {500 throw new Error('some error')501 })502 app.use('/router1', router1)503 app.use(function myErrorHandler(error, req, res, next) { // eslint-disable-line504 res.end()505 })506 var endpoint = '/router1/router2/test'507 runTest(t, {508 endpoint: endpoint,509 errors: 0510 }, function(segments, transaction) {511 checkSegments(t, transaction.trace.root.children[0], [512 NAMES.EXPRESS.MIDDLEWARE + 'query',513 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',514 'Expressjs/Router: /router1', [515 'Expressjs/Router: /router2', [516 'Expressjs/Route Path: /test', [517 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>'518 ]519 ]520 ],521 NAMES.EXPRESS.MIDDLEWARE + 'myErrorHandler'522 ], assertSegmentsOptions)523 checkMetrics(t, transaction.metrics, [524 NAMES.EXPRESS.MIDDLEWARE + '<anonymous>//router1/router2/test',525 NAMES.EXPRESS.MIDDLEWARE + 'myErrorHandler//router1/router2/test'526 ], endpoint)527 t.end()528 })529})530test('when using a route variable', function(t) {531 setup(t)532 app.get('/:foo/:bar', function myHandler(req, res) {533 res.end()534 })535 runTest(t, '/a/b', function(segments, transaction) {536 checkSegments(t, transaction.trace.root.children[0], [537 NAMES.EXPRESS.MIDDLEWARE + 'query',538 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',539 'Expressjs/Route Path: /:foo/:bar', [540 NAMES.EXPRESS.MIDDLEWARE + 'myHandler'541 ]542 ], assertSegmentsOptions)543 checkMetrics(t, transaction.metrics, [544 NAMES.EXPRESS.MIDDLEWARE + 'myHandler//:foo/:bar'545 ], '/:foo/:bar')546 t.end()547 })548})549test('when using a string pattern in path', function(t) {550 setup(t)551 app.get('/ab?cd', function myHandler(req, res) {552 res.end()553 })554 runTest(t, '/abcd', function(segments, transaction) {555 checkSegments(t, transaction.trace.root.children[0], [556 NAMES.EXPRESS.MIDDLEWARE + 'query',557 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',558 'Expressjs/Route Path: /ab?cd', [559 NAMES.EXPRESS.MIDDLEWARE + 'myHandler'560 ]561 ], assertSegmentsOptions)562 checkMetrics(t, transaction.metrics, [563 NAMES.EXPRESS.MIDDLEWARE + 'myHandler//ab?cd'564 ], '/ab?cd')565 t.end()566 })567})568test('when using a regular expression in path', function(t) {569 setup(t)570 app.get(/a/, function myHandler(req, res) {571 res.end()572 })573 runTest(t, '/a', function(segments, transaction) {574 checkSegments(t, transaction.trace.root.children[0], [575 NAMES.EXPRESS.MIDDLEWARE + 'query',576 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',577 'Expressjs/Route Path: /a/', [578 NAMES.EXPRESS.MIDDLEWARE + 'myHandler'579 ]580 ], assertSegmentsOptions)581 checkMetrics(t, transaction.metrics, [582 NAMES.EXPRESS.MIDDLEWARE + 'myHandler//a/'583 ], '/a/')584 t.end()585 })586})587function setup(t) {588 agent = helper.instrumentMockedAgent({589 feature_flag: {express_segments: true}590 })591 express = require('express')592 app = express()593 t.teardown(function cb_tearDown() {594 helper.unloadAgent(agent)595 })596}597function runTest(t, options, callback) {598 var errors599 var endpoint600 if (options instanceof Function) {601 callback = options602 endpoint = '/test'603 errors = 0604 } else if (typeof options === 'string') {605 endpoint = options606 errors = 0607 } else {608 endpoint = options.endpoint || '/test'609 errors = options.errors || 0610 }611 agent.on('transactionFinished', function(tx) {612 const baseSegment = tx.trace.root.children[0]613 t.equal(614 agent.errors.traceAggregator.errors.length,615 errors,616 'should have errors'617 )618 callback(baseSegment.children, tx)619 })620 var server = app.listen(function() {621 makeRequest(server, endpoint, function(response) {622 response.resume()623 })624 })625 t.teardown(function cb_tearDown() {626 server.close()627 })628}629function makeRequest(server, path, callback) {630 var port = server.address().port631 http.request({port: port, path: path}, callback).end()632}633function checkSegments(t, segments, expected, opts) {634 t.doesNotThrow(function() {635 assertSegments(segments, expected, opts)636 }, 'should have expected segments')637}638function checkMetrics(t, metrics, expected, path) {639 if (path === undefined) {640 path = '/test'641 }642 var expectedAll = [643 [{name : 'WebTransaction'}],644 [{name : 'WebTransactionTotalTime'}],645 [{name : 'HttpDispatcher'}],646 [{name : 'WebTransaction/Expressjs/GET/' + path}],647 [{name : 'WebTransactionTotalTime/Expressjs/GET/' + path}],648 [{name : 'Apdex/Expressjs/GET/' + path}],649 [{name : 'Apdex'}],650 [{name : NAMES.EXPRESS.MIDDLEWARE + 'query//'}],651 [{name : NAMES.EXPRESS.MIDDLEWARE + 'expressInit//'}],652 [{name : NAMES.EXPRESS.MIDDLEWARE + 'query//',...

Full Screen

Full Screen

express4-segments.tap.js

Source:express4-segments.tap.js Github

copy

Full Screen

...30 [31 NAMES.EXPRESS.MIDDLEWARE + 'anonymous'32 ]33 ], assertSegmentsOptions)34 checkMetrics(t, transaction.metrics, [35 NAMES.EXPRESS.MIDDLEWARE + 'anonymous//test'36 ])37 t.end()38 })39})40test('middleware with child segment gets named correctly', function(t) {41 setup(t)42 app.all('/test', function(req, res) {43 setTimeout(function() {44 res.end()45 }, 1)46 })47 runTest(t, function(segments, transaction) {48 checkMetrics(t, transaction.metrics, [49 NAMES.EXPRESS.MIDDLEWARE + 'anonymous//test'50 ])51 t.end()52 })53})54test('segments for route handler', function(t) {55 setup(t)56 app.all('/test', function(req, res) {57 res.end()58 })59 runTest(t, function(segments, transaction) {60 checkSegments(t, transaction.trace.root.children[0], [61 NAMES.EXPRESS.MIDDLEWARE + 'query',62 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',63 'Expressjs/Route Path: /test',64 [65 NAMES.EXPRESS.MIDDLEWARE + 'anonymous'66 ]67 ], assertSegmentsOptions)68 checkMetrics(t, transaction.metrics, [69 NAMES.EXPRESS.MIDDLEWARE + 'anonymous//test'70 ])71 t.end()72 })73})74test('route function names are in segment names', function(t) {75 setup(t)76 app.all('/test', function myHandler(req, res) {77 res.end()78 })79 runTest(t, function(segments, transaction) {80 checkSegments(t, transaction.trace.root.children[0], [81 NAMES.EXPRESS.MIDDLEWARE + 'query',82 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',83 'Expressjs/Route Path: /test',84 [85 NAMES.EXPRESS.MIDDLEWARE + 'myHandler'86 ]87 ], assertSegmentsOptions)88 checkMetrics(t, transaction.metrics, [89 NAMES.EXPRESS.MIDDLEWARE + 'myHandler//test'90 ])91 t.end()92 })93})94test('middleware mounted on a path should produce correct names', function(t) {95 setup(t)96 app.use('/test/:id', function handler(req, res, next) {97 res.send()98 })99 runTest(t, '/test/1', function(segments, transaction) {100 var routeSegment = segments[2]101 t.equal(routeSegment.name, NAMES.EXPRESS.MIDDLEWARE + 'handler')102 checkMetrics(t, transaction.metrics, [103 NAMES.EXPRESS.MIDDLEWARE + 'handler//test/:id'104 ], '/test/:id')105 t.end()106 })107})108test('each handler in route has its own segment', function(t) {109 setup(t)110 app.all('/test', function handler1(req, res, next) {111 next()112 }, function handler2(req, res, next) {113 res.send()114 })115 runTest(t, function(segments, transaction) {116 checkSegments(t, transaction.trace.root.children[0], [117 NAMES.EXPRESS.MIDDLEWARE + 'query',118 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',119 'Expressjs/Route Path: /test',120 [121 NAMES.EXPRESS.MIDDLEWARE + 'handler1',122 NAMES.EXPRESS.MIDDLEWARE + 'handler2'123 ]124 ], assertSegmentsOptions)125 checkMetrics(t, transaction.metrics, [126 NAMES.EXPRESS.MIDDLEWARE + 'handler1//test',127 NAMES.EXPRESS.MIDDLEWARE + 'handler2//test'128 ])129 t.end()130 })131})132test('segments for routers', function(t) {133 setup(t)134 var router = express.Router()135 router.all('/test', function(req, res) {136 res.end()137 })138 app.use('/router1', router)139 runTest(t, '/router1/test', function(segments, transaction) {140 checkSegments(t, transaction.trace.root.children[0], [141 NAMES.EXPRESS.MIDDLEWARE + 'query',142 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',143 'Expressjs/Router: /router1',144 [145 'Expressjs/Route Path: /test',146 [147 NAMES.EXPRESS.MIDDLEWARE + 'anonymous'148 ]149 ]150 ], assertSegmentsOptions)151 checkMetrics(t, transaction.metrics, [152 NAMES.EXPRESS.MIDDLEWARE + 'anonymous//router1/test'153 ], '/router1/test')154 t.end()155 })156})157test('two root routers', function(t) {158 setup(t)159 var router1 = express.Router()160 router1.all('/', function(req, res) {161 res.end()162 })163 app.use('/', router1)164 var router2 = express.Router()165 router2.all('/test', function(req, res) {166 res.end()167 })168 app.use('/', router2)169 runTest(t, '/test', function(segments, transaction) {170 checkSegments(t, transaction.trace.root.children[0], [171 NAMES.EXPRESS.MIDDLEWARE + 'query',172 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',173 'Expressjs/Router: /',174 'Expressjs/Router: /',175 [176 'Expressjs/Route Path: /test',177 [178 NAMES.EXPRESS.MIDDLEWARE + 'anonymous'179 ]180 ]181 ], assertSegmentsOptions)182 checkMetrics(t, transaction.metrics, [183 NAMES.EXPRESS.MIDDLEWARE + 'anonymous//test'184 ], '/test')185 t.end()186 })187})188test('router mounted as a route handler', function(t) {189 setup(t)190 var router1 = express.Router()191 router1.all('/test', function testHandler(req, res) {192 res.send('test')193 })194 app.get('*', router1)195 runTest(t, '/test', function(segments, transaction) {196 checkSegments(t, transaction.trace.root.children[0], [197 NAMES.EXPRESS.MIDDLEWARE + 'query',198 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',199 'Expressjs/Route Path: *',200 [201 'Expressjs/Router: /',202 [203 'Expressjs/Route Path: /test',204 [205 NAMES.EXPRESS.MIDDLEWARE + 'testHandler'206 ]207 ]208 ]209 ], assertSegmentsOptions)210 checkMetrics(t, transaction.metrics, [211 NAMES.EXPRESS.MIDDLEWARE + 'testHandler//*/test'212 ], '/*/test')213 t.end()214 })215})216test('segments for routers', function(t) {217 setup(t)218 var router = express.Router()219 router.all('/test', function(req, res) {220 res.end()221 })222 app.use('/router1', router)223 runTest(t, '/router1/test', function(segments, transaction) {224 checkSegments(t, transaction.trace.root.children[0], [225 NAMES.EXPRESS.MIDDLEWARE + 'query',226 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',227 'Expressjs/Router: /router1',228 [229 'Expressjs/Route Path: /test',230 [231 NAMES.EXPRESS.MIDDLEWARE + 'anonymous'232 ]233 ]234 ], assertSegmentsOptions)235 checkMetrics(t, transaction.metrics, [236 NAMES.EXPRESS.MIDDLEWARE + 'anonymous//router1/test'237 ], '/router1/test')238 t.end()239 })240})241test('segments for sub-app', function(t) {242 setup(t)243 var subapp = express()244 subapp.all('/test', function(req, res) {245 res.end()246 })247 app.use('/subapp1', subapp)248 runTest(t, '/subapp1/test', function(segments, transaction) {249 checkSegments(t, transaction.trace.root.children[0], [250 NAMES.EXPRESS.MIDDLEWARE + 'query',251 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',252 'Expressjs/Mounted App: /subapp1',253 [254 NAMES.EXPRESS.MIDDLEWARE + 'query',255 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',256 'Expressjs/Route Path: /test',257 [258 NAMES.EXPRESS.MIDDLEWARE + 'anonymous'259 ]260 ]261 ], assertSegmentsOptions)262 checkMetrics(t, transaction.metrics, [263 NAMES.EXPRESS.MIDDLEWARE + 'anonymous//subapp1/test',264 NAMES.EXPRESS.MIDDLEWARE + 'query//subapp1',265 NAMES.EXPRESS.MIDDLEWARE + 'expressInit//subapp1'266 ], '/subapp1/test')267 t.end()268 })269})270test('segments for sub-app', function(t) {271 setup(t)272 var subapp = express()273 subapp.get('/test', function(req, res, next) {274 next()275 }, function(req, res, next) {276 next()277 })278 subapp.get('/test', function(req, res) {279 res.end()280 })281 app.use('/subapp1', subapp)282 runTest(t, '/subapp1/test', function(segments, transaction) {283 checkSegments(t, transaction.trace.root.children[0], [284 NAMES.EXPRESS.MIDDLEWARE + 'query',285 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',286 'Expressjs/Mounted App: /subapp1',287 [288 NAMES.EXPRESS.MIDDLEWARE + 'query',289 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',290 'Expressjs/Route Path: /test',291 [292 NAMES.EXPRESS.MIDDLEWARE + 'anonymous',293 NAMES.EXPRESS.MIDDLEWARE + 'anonymous'294 ],295 'Expressjs/Route Path: /test',296 [297 NAMES.EXPRESS.MIDDLEWARE + 'anonymous'298 ]299 ]300 ], assertSegmentsOptions)301 checkMetrics(t, transaction.metrics, [302 NAMES.EXPRESS.MIDDLEWARE + 'anonymous//subapp1/test',303 NAMES.EXPRESS.MIDDLEWARE + 'query//subapp1',304 NAMES.EXPRESS.MIDDLEWARE + 'expressInit//subapp1'305 ], '/subapp1/test')306 t.end()307 })308})309test('segments for wildcard', function(t) {310 setup(t)311 var subapp = express()312 subapp.all('/:app', function(req, res) {313 res.end()314 })315 app.use('/subapp1', subapp)316 runTest(t, '/subapp1/test', function(segments, transaction) {317 checkSegments(t, transaction.trace.root.children[0], [318 NAMES.EXPRESS.MIDDLEWARE + 'query',319 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',320 'Expressjs/Mounted App: /subapp1',321 [322 NAMES.EXPRESS.MIDDLEWARE + 'query',323 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',324 'Expressjs/Route Path: /:app',325 [326 NAMES.EXPRESS.MIDDLEWARE + 'anonymous',327 ]328 ]329 ], assertSegmentsOptions)330 checkMetrics(t, transaction.metrics, [331 NAMES.EXPRESS.MIDDLEWARE + 'anonymous//subapp1/:app',332 NAMES.EXPRESS.MIDDLEWARE + 'query//subapp1',333 NAMES.EXPRESS.MIDDLEWARE + 'expressInit//subapp1'334 ], '/subapp1/:app')335 t.end()336 })337})338test('router with subapp', function(t) {339 setup(t)340 var router = express.Router()341 var subapp = express()342 subapp.all('/test', function(req, res) {343 res.end()344 })345 router.use('/subapp1', subapp)346 app.use('/router1', router)347 runTest(t, '/router1/subapp1/test', function(segments, transaction) {348 checkSegments(t, transaction.trace.root.children[0], [349 NAMES.EXPRESS.MIDDLEWARE + 'query',350 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',351 'Expressjs/Router: /router1',352 [353 'Expressjs/Mounted App: /subapp1',354 [355 NAMES.EXPRESS.MIDDLEWARE + 'query',356 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',357 'Expressjs/Route Path: /test',358 [359 NAMES.EXPRESS.MIDDLEWARE + 'anonymous'360 ]361 ]362 ]363 ], assertSegmentsOptions)364 checkMetrics(t, transaction.metrics, [365 NAMES.EXPRESS.MIDDLEWARE + 'anonymous//router1/subapp1/test',366 NAMES.EXPRESS.MIDDLEWARE + 'query//router1/subapp1',367 NAMES.EXPRESS.MIDDLEWARE + 'expressInit//router1/subapp1'368 ], '/router1/subapp1/test')369 t.end()370 })371})372test('mounted middleware', function(t) {373 setup(t)374 app.use('/test', function myHandler(req, res) {375 res.end()376 })377 runTest(t, function(segments, transaction) {378 checkSegments(t, transaction.trace.root.children[0], [379 NAMES.EXPRESS.MIDDLEWARE + 'query',380 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',381 // TODO: should have the path?382 // NAMES.EXPRESS.MIDDLEWARE + 'myHandler /test',383 NAMES.EXPRESS.MIDDLEWARE + 'myHandler',384 ], assertSegmentsOptions)385 checkMetrics(t, transaction.metrics, [386 NAMES.EXPRESS.MIDDLEWARE + 'myHandler//test'387 ])388 t.end()389 })390})391test('error middleware', function(t) {392 setup(t)393 app.get('/test', function(req, res) {394 throw new Error('some error')395 })396 app.use(function myErrorHandler(err, req, res, next) {397 res.end()398 })399 runTest(t, function(segments, transaction) {400 checkSegments(t, transaction.trace.root.children[0], [401 NAMES.EXPRESS.MIDDLEWARE + 'query',402 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',403 'Expressjs/Route Path: /test',404 [405 NAMES.EXPRESS.MIDDLEWARE + 'anonymous'406 ],407 NAMES.EXPRESS.MIDDLEWARE + 'myErrorHandler'408 ], assertSegmentsOptions)409 checkMetrics(t, transaction.metrics, [410 NAMES.EXPRESS.MIDDLEWARE + 'anonymous//test',411 NAMES.EXPRESS.MIDDLEWARE + 'myErrorHandler'412 ])413 t.end()414 })415})416test('error handler in router', function(t) {417 setup(t)418 var router = express.Router()419 router.get('/test', function(req, res) {420 throw new Error('some error')421 })422 router.use(function myErrorHandler(error, req, res, next) {423 res.end()424 })425 app.use('/router', router)426 var endpoint = '/router/test'427 runTest(t, {428 endpoint: endpoint,429 errors: 0430 }, function(segments, transaction) {431 checkSegments(t, transaction.trace.root.children[0], [432 NAMES.EXPRESS.MIDDLEWARE + 'query',433 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',434 'Expressjs/Router: /router',435 [436 'Expressjs/Route Path: /test',437 [438 NAMES.EXPRESS.MIDDLEWARE + 'anonymous'439 ],440 NAMES.EXPRESS.MIDDLEWARE + 'myErrorHandler'441 ]442 ], assertSegmentsOptions)443 checkMetrics(t, transaction.metrics, [444 NAMES.EXPRESS.MIDDLEWARE + 'anonymous/' + endpoint,445 NAMES.EXPRESS.MIDDLEWARE + 'myErrorHandler'446 ], endpoint)447 t.end()448 })449})450test('error handler in second router', function(t) {451 setup(t)452 var router1 = express.Router()453 var router2 = express.Router()454 router2.get('/test', function(req, res) {455 throw new Error('some error')456 })457 router2.use(function myErrorHandler(error, req, res, next) {458 res.end()459 })460 router1.use('/router2', router2)461 app.use('/router1', router1)462 var endpoint = '/router1/router2/test'463 runTest(t, {464 endpoint: endpoint,465 errors: 0466 }, function(segments, transaction) {467 checkSegments(t, transaction.trace.root.children[0], [468 NAMES.EXPRESS.MIDDLEWARE + 'query',469 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',470 'Expressjs/Router: /router1',471 [472 'Expressjs/Router: /router2',473 [474 'Expressjs/Route Path: /test',475 [476 NAMES.EXPRESS.MIDDLEWARE + 'anonymous'477 ],478 NAMES.EXPRESS.MIDDLEWARE + 'myErrorHandler'479 ]480 ]481 ], assertSegmentsOptions)482 checkMetrics(t, transaction.metrics, [483 NAMES.EXPRESS.MIDDLEWARE + 'anonymous/' + endpoint,484 NAMES.EXPRESS.MIDDLEWARE + 'myErrorHandler'485 ], endpoint)486 t.end()487 })488})489test('error handler outside of router', function(t) {490 setup(t)491 var router = express.Router()492 router.get('/test', function(req, res) {493 throw new Error('some error')494 })495 app.use('/router', router)496 app.use(function myErrorHandler(error, req, res, next) {497 res.end()498 })499 var endpoint = '/router/test'500 runTest(t, {501 endpoint: endpoint,502 errors: 0503 }, function(segments, transaction) {504 checkSegments(t, transaction.trace.root.children[0], [505 NAMES.EXPRESS.MIDDLEWARE + 'query',506 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',507 'Expressjs/Router: /router',508 [509 'Expressjs/Route Path: /test',510 [511 NAMES.EXPRESS.MIDDLEWARE + 'anonymous'512 ]513 ],514 NAMES.EXPRESS.MIDDLEWARE + 'myErrorHandler'515 ], assertSegmentsOptions)516 checkMetrics(t, transaction.metrics, [517 NAMES.EXPRESS.MIDDLEWARE + 'anonymous/' + endpoint,518 NAMES.EXPRESS.MIDDLEWARE + 'myErrorHandler'519 ], endpoint)520 t.end()521 })522})523test('error handler outside of two routers', function(t) {524 setup(t)525 var router1 = express.Router()526 var router2 = express.Router()527 router1.use('/router2', router2)528 router2.get('/test', function(req, res) {529 throw new Error('some error')530 })531 app.use('/router1', router1)532 app.use(function myErrorHandler(error, req, res, next) {533 res.end()534 })535 var endpoint = '/router1/router2/test'536 runTest(t, {537 endpoint: endpoint,538 errors: 0539 }, function(segments, transaction) {540 checkSegments(t, transaction.trace.root.children[0], [541 NAMES.EXPRESS.MIDDLEWARE + 'query',542 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',543 'Expressjs/Router: /router1',544 [545 'Expressjs/Router: /router2',546 [547 'Expressjs/Route Path: /test',548 [549 NAMES.EXPRESS.MIDDLEWARE + 'anonymous'550 ]551 ]552 ],553 NAMES.EXPRESS.MIDDLEWARE + 'myErrorHandler'554 ], assertSegmentsOptions)555 checkMetrics(t, transaction.metrics, [556 NAMES.EXPRESS.MIDDLEWARE + 'anonymous/' + endpoint,557 NAMES.EXPRESS.MIDDLEWARE + 'myErrorHandler'558 ], endpoint)559 t.end()560 })561})562test('when using a route variable', function(t) {563 setup(t)564 app.get('/:foo/:bar', function myHandler(req, res) {565 res.end()566 })567 runTest(t, '/a/b', function(segments, transaction) {568 checkSegments(t, transaction.trace.root.children[0], [569 NAMES.EXPRESS.MIDDLEWARE + 'query',570 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',571 'Expressjs/Route Path: /:foo/:bar',572 [573 NAMES.EXPRESS.MIDDLEWARE + 'myHandler'574 ]575 ], assertSegmentsOptions)576 checkMetrics(t, transaction.metrics, [577 NAMES.EXPRESS.MIDDLEWARE + 'myHandler//:foo/:bar'578 ], '/:foo/:bar')579 t.end()580 })581})582test('when using a string pattern in path', function(t) {583 setup(t)584 app.get('/ab?cd', function myHandler(req, res) {585 res.end()586 })587 runTest(t, '/abcd', function(segments, transaction) {588 checkSegments(t, transaction.trace.root.children[0], [589 NAMES.EXPRESS.MIDDLEWARE + 'query',590 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',591 'Expressjs/Route Path: /ab?cd',592 [593 NAMES.EXPRESS.MIDDLEWARE + 'myHandler'594 ]595 ], assertSegmentsOptions)596 checkMetrics(t, transaction.metrics, [597 NAMES.EXPRESS.MIDDLEWARE + 'myHandler//ab?cd'598 ], '/ab?cd')599 t.end()600 })601})602test('when using a regular expression in path', function(t) {603 setup(t)604 app.get(/a/, function myHandler(req, res) {605 res.end()606 })607 runTest(t, '/a', function(segments, transaction) {608 checkSegments(t, transaction.trace.root.children[0], [609 NAMES.EXPRESS.MIDDLEWARE + 'query',610 NAMES.EXPRESS.MIDDLEWARE + 'expressInit',611 'Expressjs/Route Path: /a/',612 [613 NAMES.EXPRESS.MIDDLEWARE + 'myHandler'614 ]615 ], assertSegmentsOptions)616 checkMetrics(t, transaction.metrics, [617 NAMES.EXPRESS.MIDDLEWARE + 'myHandler//a/'618 ], '/a/')619 t.end()620 })621})622function setup(t) {623 agent = helper.instrumentMockedAgent({624 express_segments: true625 })626 express = require('express')627 app = express()628 t.tearDown(function cb_tearDown() {629 helper.unloadAgent(agent)630 })631}632function runTest(t, options, callback) {633 var statusCode634 var errors635 var endpoint636 if (options instanceof Function) {637 callback = options638 endpoint = '/test'639 errors = 0640 } else if (typeof options === 'string') {641 endpoint = options642 errors = 0643 } else {644 endpoint = options.endpoint || '/test'645 errors = options.errors || 0646 }647 agent.on('transactionFinished', function(tx) {648 var webSegment = tx.trace.root.children[0]649 if (errors != agent.errors.getTotalErrorCount()) {650 t.fail('unexpected error count')651 }652 callback(webSegment.children, tx)653 })654 var server = app.listen(function(){655 makeRequest(server, endpoint, function(response) {656 response.resume()657 })658 })659 t.tearDown(function cb_tearDown() {660 server.close()661 })662}663function makeRequest(server, path, callback) {664 var port = server.address().port665 http.request({port: port, path: path}, callback).end()666}667function checkSegments(t, segments, expected, opts) {668 t.doesNotThrow(function() {669 assertSegments(segments, expected, opts)670 }, 'should have expected segments')671}672function checkMetrics(t, metrics, expected, path) {673 if (path === undefined) {674 path = '/test'675 }676 var expectedAll = [677 [{name : 'WebTransaction'}],678 [{name : 'WebTransactionTotalTime'}],679 [{name : 'HttpDispatcher'}],680 [{name : 'WebTransaction/Expressjs/GET/' + path}],681 [{name : 'WebTransactionTotalTime/Expressjs/GET/' + path}],682 [{name : 'Apdex/Expressjs/GET/' + path}],683 [{name : 'Apdex'}],684 [{name : NAMES.EXPRESS.MIDDLEWARE + 'query//'}],685 [{name : NAMES.EXPRESS.MIDDLEWARE + 'expressInit//'}],686 [{name : NAMES.EXPRESS.MIDDLEWARE + 'query//',...

Full Screen

Full Screen

awsNodeSdk.js

Source:awsNodeSdk.js Github

copy

Full Screen

...188}189describe('utapi v2 metrics incoming and outgoing bytes', function t() {190 this.timeout(30000);191 const utapi = new MockUtapi();192 function checkMetrics(inBytes, outBytes, objCount) {193 const accountMetrics = utapi.getAccountMetrics();194 assert(accountMetrics);195 assert.strictEqual(accountMetrics.incomingBytes, inBytes);196 assert.strictEqual(accountMetrics.outgoingBytes, outBytes);197 assert.strictEqual(accountMetrics.numberOfObjects, objCount);198 }199 before(() => {200 const config = getConfig('default', { signatureVersion: 'v4' });201 s3Client = new S3(config);202 utapi.start();203 });204 afterEach(() => {205 utapi.reset();206 });207 after(() => {208 utapi.stop();209 });210 it('should set metrics for createBucket and deleteBucket', done => {211 const bucket = 'bucket1';212 async.series([213 next => createBucket(bucket, next),214 next => wait(WAIT_MS, () => {215 checkMetrics(0, 0, 0);216 next();217 }),218 next => deleteBucket(bucket, next),219 next => wait(WAIT_MS, () => {220 checkMetrics(0, 0, 0);221 next();222 }),223 ], done);224 });225 it('should set metrics for putObject and deleteObject', done => {226 const bucket = 'bucket2';227 const objectSize = 1024 * 1024;228 const obj1Size = objectSize * 1;229 const obj2Size = objectSize * 2;230 const key1 = '1.txt';231 const key2 = '2.txt';232 async.series([233 next => createBucket(bucket, next),234 next => putObject(bucket, key1, obj1Size, next),235 next => wait(WAIT_MS, () => {236 checkMetrics(obj1Size, 0, 1);237 next();238 }),239 next => putObject(bucket, key2, obj2Size, next),240 next => wait(WAIT_MS, () => {241 checkMetrics(obj1Size + obj2Size, 0, 2);242 next();243 }),244 next => deleteObject(bucket, key1, next),245 next => wait(WAIT_MS, () => {246 checkMetrics(obj2Size, 0, 1);247 next();248 }),249 next => deleteObject(bucket, key2, next),250 next => wait(WAIT_MS, () => {251 checkMetrics(0, 0, 0);252 next();253 }),254 next => deleteBucket(bucket, next),255 ], done);256 });257 it('should set metrics for copyObject', done => {258 const bucket = 'bucket3';259 const objectSize = 1024 * 1024 * 2;260 const key = '3.txt';261 async.series([262 next => createBucket(bucket, next),263 next => putObject(bucket, key, objectSize, next),264 next => copyObject(bucket, key, next),265 next => wait(WAIT_MS, () => {266 checkMetrics(objectSize * 2, 0, 2);267 next();268 }),269 next => deleteObject(bucket, key, next),270 next => wait(WAIT_MS, () => {271 checkMetrics(objectSize, 0, 1);272 next();273 }),274 next => deleteObject(bucket, `${key}-copy`, next),275 next => wait(WAIT_MS, () => {276 checkMetrics(0, 0, 0);277 next();278 }),279 next => deleteBucket(bucket, next),280 ], done);281 });282 it('should set metrics for getObject', done => {283 const bucket = 'bucket4';284 const objectSize = 1024 * 1024 * 2;285 const key = '4.txt';286 async.series([287 next => createBucket(bucket, next),288 next => putObject(bucket, key, objectSize, next),289 next => getObject(bucket, key, next),290 next => wait(WAIT_MS, () => {291 checkMetrics(objectSize, objectSize, 1);292 next();293 }),294 next => deleteObject(bucket, key, next),295 next => wait(WAIT_MS, () => {296 checkMetrics(0, objectSize, 0);297 next();298 }),299 next => deleteBucket(bucket, next),300 ], done);301 });302 it('should set metrics for multiObjectDelete', done => {303 const bucket = 'bucket5';304 const objectSize = 1024 * 1024;305 const obj1Size = objectSize * 2;306 const obj2Size = objectSize * 1;307 const key1 = '1.txt';308 const key2 = '2.txt';309 async.series([310 next => createBucket(bucket, next),311 next => putObject(bucket, key1, obj1Size, next),312 next => wait(WAIT_MS, next),313 next => putObject(bucket, key2, obj2Size, next),314 next => wait(WAIT_MS, () => {315 checkMetrics(obj1Size + obj2Size, 0, 2);316 next();317 }),318 next => deleteObjects(bucket, [key1, key2], next),319 next => wait(WAIT_MS, () => {320 checkMetrics(0, 0, 0);321 next();322 }),323 next => deleteBucket(bucket, next),324 ], done);325 });326 it('should set metrics for multiPartUpload', done => {327 const bucket = 'bucket6';328 const partSize = 1024 * 1024 * 6;329 const parts = 2;330 const key = '6.txt';331 async.series([332 next => createBucket(bucket, next),333 next => objectMPU(bucket, key, parts, partSize, next),334 next => wait(WAIT_MS, () => {335 checkMetrics(partSize * parts, 0, 1);336 next();337 }),338 next => deleteObject(bucket, key, next),339 next => wait(WAIT_MS, () => {340 checkMetrics(0, 0, 0);341 next();342 }),343 next => deleteBucket(bucket, next),344 ], done);345 });346 it('should set metrics in versioned bucket', done => {347 const bucket = 'bucket7';348 const objectSize = 1024 * 1024;349 const key = '7.txt';350 async.series([351 next => createBucket(bucket, next),352 next => enableVersioning(bucket, true, next),353 next => putObject(bucket, key, objectSize, next),354 next => wait(WAIT_MS, next),355 next => putObject(bucket, key, objectSize, next),356 next => wait(WAIT_MS, () => {357 checkMetrics(objectSize * 2, 0, 2);358 next();359 }),360 next => deleteObject(bucket, key, next),361 next => wait(WAIT_MS, () => {362 checkMetrics(objectSize * 2, 0, 3);363 next();364 }),365 next => removeVersions([bucket], next),366 next => wait(WAIT_MS, () => {367 checkMetrics(0, 0, 0);368 next();369 }),370 next => deleteBucket(bucket, next),371 ], done);372 });373 it('should set metrics for multipartUpload in a versioned bucket', done => {374 const bucket = 'bucket8';375 const partSize = 1024 * 1024 * 6;376 const parts = 2;377 const key = '8.txt';378 async.series([379 next => createBucket(bucket, next),380 next => enableVersioning(bucket, true, next),381 next => objectMPU(bucket, key, parts, partSize, next),382 next => wait(WAIT_MS, () => {383 checkMetrics(partSize * parts, 0, 1);384 next();385 }),386 next => removeVersions([bucket], next),387 next => wait(WAIT_MS, () => {388 checkMetrics(0, 0, 0);389 next();390 }),391 next => deleteBucket(bucket, next),392 ], done);393 });394 it('should set metrics for multipartUpload overwrite in a versioned bucket', done => {395 const bucket = 'bucket9';396 const partSize = 1024 * 1024 * 6;397 const parts = 2;398 const key = '9.txt';399 async.series([400 next => createBucket(bucket, next),401 next => enableVersioning(bucket, true, next),402 next => objectMPU(bucket, key, parts, partSize, next),403 next => objectMPU(bucket, key, parts, partSize, next),404 next => wait(WAIT_MS, () => {405 checkMetrics(partSize * parts * 2, 0, 2);406 next();407 }),408 next => removeVersions([bucket], next),409 next => wait(WAIT_MS, () => {410 checkMetrics(0, 0, 0);411 next();412 }),413 next => deleteBucket(bucket, next),414 ], done);415 });416 it('should set metrics for multiPartUpload overwrite', done => {417 const bucket = 'bucket10';418 const partSize = 1024 * 1024 * 6;419 const parts = 2;420 const key = '10.txt';421 async.series([422 next => createBucket(bucket, next),423 next => objectMPU(bucket, key, parts, partSize, next),424 next => objectMPU(bucket, key, parts, partSize, next),425 next => wait(WAIT_MS, () => {426 checkMetrics(partSize * parts, 0, 1);427 next();428 }),429 next => deleteObject(bucket, key, next),430 next => wait(WAIT_MS, () => {431 checkMetrics(0, 0, 0);432 next();433 }),434 next => deleteBucket(bucket, next),435 ], done);436 });437 it('should set metrics for multiObjectDelete in a versioned bucket', done => {438 const bucket = 'bucket11';439 const objectSize = 1024 * 1024;440 const obj1Size = objectSize * 2;441 const obj2Size = objectSize * 1;442 const key1 = '1.txt';443 const key2 = '2.txt';444 async.series([445 next => createBucket(bucket, next),446 next => enableVersioning(bucket, true, next),447 next => putObject(bucket, key1, obj1Size, next),448 next => wait(WAIT_MS, next),449 next => putObject(bucket, key2, obj2Size, next),450 next => wait(WAIT_MS, () => {451 checkMetrics(obj1Size + obj2Size, 0, 2);452 next();453 }),454 next => deleteObjects(bucket, [key1, key2], next),455 next => wait(WAIT_MS, () => {456 checkMetrics(obj1Size + obj2Size, 0, 4);457 next();458 }),459 next => removeVersions([bucket], next),460 next => wait(WAIT_MS, () => {461 checkMetrics(0, 0, 0);462 next();463 }),464 next => deleteBucket(bucket, next),465 ], done);466 });467 it('should not push a metric for a filtered bucket', done => {468 const bucket = 'utapi-event-filter-deny-bucket';469 const objSize = 2 * 1024 * 1024;470 const key = '1.txt';471 async.series([472 next => createBucket(bucket, next),473 next => putObject(bucket, key, objSize, next),474 next => wait(WAIT_MS, () => {475 checkMetrics(0, 0, 0);476 next();477 }),478 next => deleteObject(bucket, key, next),479 next => wait(WAIT_MS, () => {480 checkMetrics(0, 0, 0);481 next();482 }),483 next => deleteBucket(bucket, next),484 ], done);485 });...

Full Screen

Full Screen

test.js

Source:test.js Github

copy

Full Screen

1/*2 * Copyright (c) Sematext Group, Inc.3 * All Rights Reserved4 *5 * SPM for NodeJS is free-to-use, proprietary software.6 * THIS IS PROPRIETARY SOURCE CODE OF Sematext Group, Inc. (Sematext)7 * This source code may not be copied, reverse engineered, or altered for any purpose.8 * This source code is to be used exclusively by users and customers of Sematext.9 * Please see the full license (found in LICENSE in this distribution) for details on its license and the licenses of its dependencies.10 */11/* global describe, it */12process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'13// make sure config has a infra token before spm-agent is laoded first time14if (!process.env.INFRA_TOKEN) {15 process.env.INFRA_TOKEN = 'INFRA_TOKEN'16}17var SpmAgent = require('spm-agent')18var config = SpmAgent.Config19var port = (process.env.NJS_TEST_PORT || 8097)20var receiverUrl = 'http://127.0.0.1:' + port21config.rcFlat.spmSenderBulkInsertUrl = receiverUrl22config.collectionInterval = 123function httpTest (njsAgent, done) {24 try {25 var checkMetric = function (metric) {26 if (metric.fields.requests) {27 done()28 } else {29 njsAgent.once('metric', checkMetric)30 }31 }32 njsAgent.once('metric', checkMetric)33 } catch (ex) {34 console.error('Error in HTTP Worker:' + ex.stack)35 done(ex)36 }37}38describe('SPM for Node.js tests', function () {39 it('Generic HTTP Server Agent sends metrics', function (done) {40 try {41 this.timeout(25000)42 config.collectionInterval = 50043 var HttpAgent = require('../lib/httpServerAgent.js')44 var njsAgent = new HttpAgent()45 njsAgent.start()46 var http = require('http')47 http.createServer(function (req, res) {48 res.writeHead(200, { 'Content-Type': 'text/plain' })49 res.end('{"code":"200"}\n')50 }).listen(port, '127.0.0.1')51 httpTest(njsAgent, done)52 setTimeout(function () {53 var request = require('request')54 request.get('http://127.0.0.1:' + (port) + '/', function (err) {55 if (err) {56 console.log('Error' + err.stack)57 }58 })59 }, 700)60 } catch (err) {61 console.error(err.stack)62 done(err)63 }64 })65 it('GC Agent metrics', function (done) {66 try {67 this.timeout(300000)68 var GcAgent = require('../lib/gcAgent.js')69 var agent = new GcAgent()70 agent.start()71 var checkMetric = function () {72 agent.stop()73 done()74 }75 agent.once('metric', checkMetric)76 var wasteMemory = []77 for (var i = 0; i < 300000; i++) {78 var tmp = 'Wasting some memory'79 }80 wasteMemory.push(tmp)81 } catch (err) {82 console.error(err.stack)83 done(err)84 }85 })86 it('EventLoop Agent metrics', function (done) {87 try {88 this.timeout(15000)89 var ElAgent = require('../lib/eventLoopAgent.js')90 var agent = new ElAgent()91 agent.start()92 var checkMetric = function () {93 agent.removeListener('metric', checkMetric)94 agent.stop()95 done()96 }97 agent.once('metric', checkMetric)98 } catch (err) {99 done(err)100 }101 })102 it('Wait for metrics: GC, Event Loop and OS monitor', function (done) {103 this.timeout(30000)104 config.maxDataPoints = 1105 config.logger.console = false106 config.logger.level = 'debug'107 var NjsAgent = require('../lib/index.js')108 var metricTypes = { gc: 0, eventloop: 0 }109 function checkMetrics (metric) {110 if (metric.fields.time) {111 metricTypes.eventloop = 1112 }113 if (metric.fields['heap.size']) {114 metricTypes.gc = 1115 }116 metricTypes[metric.name] = 1117 var checksum = metricTypes.gc + metricTypes.eventloop118 if (checksum > 1) {119 NjsAgent.removeListener('metric', checkMetrics)120 done()121 NjsAgent.stop()122 }123 }124 NjsAgent.on('metric', checkMetrics)125 })126 it('Wait for metrics: Worker Agent', function (done) {127 this.timeout(30000)128 config.maxDataPoints = 1129 config.logger.console = false130 config.logger.level = 'debug'131 var NjsAgent = require('../lib/index.js')132 let metricCounter = 0133 function checkMetrics (metric) {134 if (metric.fields && metric.fields.workers) {135 metricCounter++136 }137 if (metricCounter > 0) {138 NjsAgent.removeListener('metric', checkMetrics)139 done()140 NjsAgent.stop()141 }142 }143 NjsAgent.on('metric', checkMetrics)144 })145 it('Wait for metrics: Process Agent', function (done) {146 this.timeout(30000)147 config.maxDataPoints = 1148 config.logger.console = false149 config.logger.level = 'debug'150 let metricCounter = 0151 let errorReported = false152 const ProcessAgent = require('../lib/processAgent.js')153 const agent = new ProcessAgent()154 agent.start()155 function checkMetrics (metric) {156 if (errorReported) {157 return158 }159 if (metric.measurement && metric.measurement.indexOf('process') > -1 &&160 metric.fields.uptime &&161 metric.fields.rss &&162 metric.fields['cpu.usage'] &&163 metric.fields['thread.count']) {164 if (metric.tags.token !== config.tokens.infra) {165 done(new Error(`No infra token set ${metric.tags.token} != ${config.tokens.infra}`))166 errorReported = true167 }168 metricCounter = metricCounter + 1169 }170 if (metric.measurement && metric.measurement.indexOf('process') > -1 && metric.fields.count) {171 if (metric.tags.token !== config.tokens.infra) {172 done(new Error(`No infra token set ${metric.tags.token} != ${config.tokens.infra}`))173 errorReported = true174 }175 metricCounter = metricCounter + 1176 }177 if (metricCounter > 2) {178 agent.removeListener('metric', checkMetrics)179 agent.stop()180 done()181 }182 }183 agent.on('metric', checkMetrics)184 })...

Full Screen

Full Screen

dashboard-agent.spec.js

Source:dashboard-agent.spec.js Github

copy

Full Screen

...42 }43 socket.on("metrics", (data) => {44 tryCatch(done, () => {45 socket.removeAllListeners("metrics");46 checkMetrics(JSON.parse(data));47 });48 });49 });50 });51 });52 describe("reporting", () => {53 it("should provide basic metrics", (done) => {54 const checkMetrics = function (metrics) {55 expect(metrics).to.be.an("object");56 expect(metrics.eventLoop.delay).to.be.a("number");57 expect(metrics.eventLoop.high).to.be.a("number");58 expect(metrics.mem.systemTotal).to.equal(20);59 expect(metrics.mem.rss).to.equal(30);60 expect(metrics.mem.heapTotal).to.equal(40);61 expect(metrics.mem.heapUsed).to.equal(50);62 expect(metrics.cpu.utilization).to.equal(60);63 };64 sandbox.stub(process, "memoryUsage").callsFake(() => ({65 systemTotal: 20,66 rss: 30,67 heapTotal: 40,68 heapUsed: 5069 }));70 sandbox.stub(pusage, "stat").callsFake((processId, callback) => {71 expect(processId).to.equal(process.pid);72 expect(callback).to.be.a("function");73 callback(null, { cpu: 60 });74 });75 agent._getStats((err, metrics) => {76 tryCatch(done, () => {77 expect(err).to.be.null;78 checkMetrics(metrics);79 });80 });81 });82 it("should report an event loop delay and cpu stats", (done) => {83 const delay = { current: 100,84 max: 150 };85 const pusageResults = { cpu: 50 };86 sandbox.stub(pusage, "stat").yields(null, pusageResults);87 agent._delayed(delay.max);88 agent._delayed(delay.current);89 const checkMetrics = function (metrics) {90 expect(metrics.eventLoop.delay).to.equal(delay.current);91 expect(metrics.eventLoop.high).to.equal(delay.max);92 expect(metrics.cpu.utilization).to.equal(pusageResults.cpu);93 };94 agent._getStats((err, metrics) => {95 tryCatch(done, () => {96 expect(err).to.be.null;97 checkMetrics(metrics);98 });99 });100 });101 it("should return an error when pusage fails", (done) => {102 sandbox.stub(pusage, "stat").yields(new Error("bad error"));103 agent._getStats((err, metrics) => {104 tryCatch(done, () => {105 expect(err).to.exist;106 expect(metrics).to.be.undefined;107 expect(err.message).to.equal("bad error");108 });109 });110 });111 });...

Full Screen

Full Screen

metrics.js

Source:metrics.js Github

copy

Full Screen

...39 expect(metrics.requests.status_codes).not.to.be(undefined);40 expect(metrics.requests.statusCodes).to.be(undefined);41 });42 it('should provide defined metrics', () => {43 (function checkMetrics(currentMetric) {44 _.forOwn(currentMetric, value => {45 if (typeof value === 'object') return checkMetrics(value);46 expect(currentMetric).not.to.be(undefined);47 });48 }(metrics));49 });...

Full Screen

Full Screen

consumer.js

Source:consumer.js Github

copy

Full Screen

1const amqplib = require('amqplib');2const amqpUrl = process.env.AMQP_URL || 'amqp://localhost:5673';3require('../models')4const CheckMetrics = require('../models/checkMetrics')5async function processMessage(check) {6 //call your email service here to send the email7 await new Promise(resolve => {setTimeout(async () => {8 // after the check is complete9 check.endTime = new Date();10 // calculate the response time in milisecond and add that to the the check meterics history11 check.responseTime = check.endTime.getTime() - check.startTime.getTime()12 await CheckMetrics.create({13 checkId: check._id,14 responseTime: check.responseTime15 });16 resolve;17 }, 1000)});18}19(async () => {20 const connection = await amqplib.connect(amqpUrl, "heartbeat=60");21 const channel = await connection.createChannel();22 channel.prefetch(10);23 const queue = 'check.run_check';24 process.once('SIGINT', async () => { 25 console.log('got sigint, closing connection');26 await channel.close();27 await connection.close(); 28 process.exit(0);29 });30 await channel.assertQueue(queue, {durable: true});31 await channel.consume(queue, async (check) => {32 console.log('processing messages'); 33 await processMessage(check);34 await channel.ack(check);35 }, 36 {37 noAck: false,38 consumerTag: 'check_runner'39 });40 console.log(" [*] Waiting for messages. To exit press CTRL+C");...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 const metrics = await page.metrics();6 console.log(metrics);7 await browser.close();8})();9const puppeteer = require('puppeteer');10(async () => {11 const browser = await puppeteer.launch();12 const page = await browser.newPage();13 const metrics = await page.metrics();14 console.log(metrics);15 await browser.close();16})();17const puppeteer = require('puppeteer');18(async () => {19 const browser = await puppeteer.launch();20 const page = await browser.newPage();21 const metrics = await page.metrics();22 console.log(metrics);23 await browser.close();24})();25const puppeteer = require('puppeteer');26(async () => {27 const browser = await puppeteer.launch();28 const page = await browser.newPage();29 const metrics = await page.metrics();30 console.log(metrics);31 await browser.close();32})();33const puppeteer = require('puppeteer');34(async () => {35 const browser = await puppeteer.launch();36 const page = await browser.newPage();37 const metrics = await page.metrics();38 console.log(metrics);39 await browser.close();40})();41const puppeteer = require('puppeteer');42(async () => {43 const browser = await puppeteer.launch();44 const page = await browser.newPage();45 const metrics = await page.metrics();46 console.log(metrics);47 await browser.close();48})();49const puppeteer = require('puppeteer');50(async () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const { checkMetrics } = require('puppeteer-lighthouse');3(async () => {4 const browser = await puppeteer.launch();5 const page = await browser.newPage();6 throttling: { rttMs: 40, throughputKbps: 10 * 1024, cpuSlowdownMultiplier: 4 },7 });8 await browser.close();9})();10"scripts": {11 }12"dependencies": {13 "puppeteer": {14 "requires": {15 },16 "dependencies": {17 "debug": {

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const { checkMetrics } = require('puppeteer-lighthouse');3(async () => {4 const browser = await puppeteer.launch();5 const page = await browser.newPage();6 console.log(metrics);7 await browser.close();8})();9{ firstContentfulPaint: 0.5,10 cumulativeLayoutShift: 0.5 }

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const lighthouse = require('lighthouse');3const chromeLauncher = require('chrome-launcher');4const checkMetrics = require('./checkMetrics');5(async () => {6 const browser = await puppeteer.launch();7 const page = await browser.newPage();8 const metrics = await checkMetrics(page);9 console.log(metrics);10 await browser.close();11})();12const puppeteer = require('puppeteer');13const lighthouse = require('lighthouse');14const chromeLauncher = require('chrome-launcher');15module.exports = async function checkMetrics(page) {16 const metrics = await page.metrics();17 return metrics;18};

Full Screen

Using AI Code Generation

copy

Full Screen

1const { PuppeteerCrawler } = require('apify');2const { checkMetrics } = require('apify-shared/autoscaling');3const crawler = new PuppeteerCrawler({4 handlePageFunction: async ({ page }) => {5 await checkMetrics({ page });6 },7 handleFailedRequestFunction: async ({ request }) => {8 },9});10await crawler.run();11const { CheerioCrawler } = require('apify');12const { checkMetrics } = require('apify-shared/autoscaling');13const crawler = new CheerioCrawler({14 handlePageFunction: async ({ request, $ }) => {15 await checkMetrics({ $ });16 },17 handleFailedRequestFunction: async ({ request }) => {18 },19});20await crawler.run();21const { BasicCrawler } = require('apify');22const { checkMetrics } = require('apify-shared/autoscaling');23const crawler = new BasicCrawler({24 handleRequestFunction: async ({ request }) => {25 await checkMetrics({ request });26 },27 handleFailedRequestFunction: async ({ request }) => {28 },29});30await crawler.run();31const { AutoscaledPool } = require('apify');32const { checkMetrics } = require('apify-shared/autoscaling');33const pool = new AutoscaledPool({34 runTaskFunction: async () => {35 await checkMetrics({ runTaskFunction });36 },37 isTaskReadyFunction: async () => {38 await checkMetrics({ isTaskReadyFunction });39 },40 isFinishedFunction: async () => {41 await checkMetrics({ isFinishedFunction });42 },43});44await pool.run();45const { checkParamOrThrow } = require('ap

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const lighthouse = require('lighthouse');3const chromeLauncher = require('chrome-launcher');4(async () => {5 const browser = await puppeteer.launch();6 const page = await browser.newPage();7 await page.goto(URL, {waitUntil: 'networkidle2'});8 const metrics = await page.metrics();9 console.log(metrics);10 await browser.close();11})();12{ Timestamp: 1588001149388,13 JSHeapTotalSize: 0 }

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const fs = require('fs');3const lighthouse = require('lighthouse');4const chromeLauncher = require('chrome-launcher');5const flags = {chromeFlags: ['--headless']};6async function launchChromeAndRunLighthouse(url, flags, config = null) {7 const chrome = await chromeLauncher.launch({chromeFlags: flags.chromeFlags});8 flags.port = chrome.port;9 const result = await lighthouse(url, flags, config);10 const reportHtml = result.report;11 console.log('Report is done for', url);12 console.log('Performance score was', result.lhr.categories.performance.score * 100);13 await chrome.kill();14 return result.lhr;15}16(async() => {17 const browser = await puppeteer.launch();18 const page = await browser.newPage();19 await page.goto(url);20 const metrics = await page.metrics();21 console.log('Metrics', metrics);22 const lighthouseMetrics = await launchChromeAndRunLighthouse(url, flags);23 console.log('Lighthouse metrics', lighthouseMetrics);24 await browser.close();25})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const fs = require('fs');3(async () => {4 const browser = await puppeteer.launch({headless: false});5 const page = await browser.newPage();6 const metrics = await page.metrics();7 console.log(metrics);8 await browser.close();9})();10const puppeteer = require('puppeteer');11const fs = require('fs');12(async () => {13 const browser = await puppeteer.launch({headless: false});14 const page = await browser.newPage();15 const metrics = await page.metrics();16 console.log(metrics);17 await browser.close();18})();19{20}21The above output is for the initial metrics of the page. We can also use the page.metrics() method to get the metrics of the page after the page has loaded. To get the metrics of the page after the page has loaded, we need to use the page.metrics() method inside the page.on('load') event. The code is given below:22const puppeteer = require('puppeteer');23const fs = require('fs');24(async () => {25 const browser = await puppeteer.launch({headless: false});26 const page = await browser.newPage();27 await page.on('load', async () => {28 const metrics = await page.metrics();29 console.log(metrics);30 });31 await browser.close();32})();33{

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const fs = require('fs');3const path = require('path');4const { promisify } = require('util');5const { checkMetrics } = require('lighthouse/lighthouse-core/lib/emulation');6(async () => {7 const browser = await puppeteer.launch();8 const page = await browser.newPage();9 const metrics = await page.metrics();10 const metricsResults = await checkMetrics(metrics, {throttlingMethod: 'provided'});11 console.log(metricsResults);12 await browser.close();13})();14{15 "scripts": {16 },17 "dependencies": {18 }19}20{ score: 0,21 'Network throughput is too high to accurately measure FCP. Try throttling your network speed (DevTools -> Network -> Throttling).',22 displayValue: 'Network throughput: 0.00 Mbps' }23const puppeteer = require('puppeteer');24const fs = require('fs');25const path = require('path');26const { promisify } = require('util');27const { checkMetrics } = require('lighthouse/lighthouse-core/lib/emulation');28(async () => {29 const browser = await puppeteer.launch();30 const page = await browser.newPage();31 await page.emulate({32 networkConditions: {33 }34 });35 const metrics = await page.metrics();36 const metricsResults = await checkMetrics(metrics, {throttlingMethod: 'provided'});37 console.log(metricsResults);38 await browser.close();39})();

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful