Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@newrelic/test-utilities

newrelic70.3kApache-2.09.1.0

Test library for New Relic instrumentation modules.

readme

<picture><source media="(prefers-color-scheme: dark)" srcset="https://github.com/newrelic/opensource-website/raw/main/src/images/categories/dark/Community_Project.png"><source media="(prefers-color-scheme: light)" srcset="https://github.com/newrelic/opensource-website/raw/main/src/images/categories/Community_Project.png">New Relic Open Source community project banner.</picture>

New Relic Test Utilities

npm status badge Test Utilities CI codecov

Library full of test utilities and helpers for New Relic instrumentation modules. The full documentation for this module can be found on GitHub.

Installation

It can be installed and used as such:

npm install @newrelic/test-utilities
// index.js
require('@newrelic/test-utilities')

Usage

TestAgent Helper

The TestAgent class helps set up a New Relic agent suitable for tests. With this you can run your tests within transactions without having to actually set up a full New Relic application. The helper should be created and torn down for each test to ensure you are running in a clean environment each time. In tap this may look like this:

tap.test('some test suite', (t) => {
  let helper = null
  t.beforeEach((done) => {
    helper = utils.TestAgent.makeInstrumented()
    done()
  })

  t.afterEach((done) => {
    helper && helper.unload()
    done()
  })

  t.test('test 1', (t) => {
    helper.runInTransaction((tx) => {
      // Your test is now in transaction context and normal instrumentation
      // logic should occur.
    })
  })
})

Assertions

There are a number of assertions provided to help write your tests. Each of these assertions can either be used directly (utils.assert.segments(...)) or as tap tests (t.segments(...)). In the direct use case they will throw exceptions, and thus can be used like any other assertion library. Here are a few examples of using them:

let tap = require('tap')
let utils = require('@newrelic/test-utilities')

// This adds all the assertions to tap's `Test` class.
utils.assert.extendTap(tap)

tap.test((t) => {
  let helper = utils.TestAgent.makeInstrumented()
  t.tearDown(() => helper.unload())

  helper.runInTransaction((tx) => {
    // Do some testing logic...

    // This will check that transaction state hasn't been lost and that the given
    // transaction is the currently active one. A good check to make in the
    // callbacks to asynchronous methods.
    t.transaction(tx, 'should be in correct context')

    // This will check that the transaction trace has the segment structure you
    // describe. Extra segments in the trace are allowed.
    t.segments(tx.trace.root, [{name: 'mysegment'}], 'should have expected segments')

    // Like above, this checks the structure of the trace against the one you
    // describe but they must exactly match. Any extra segments in the trace are
    // considered a failure.
    t.exactSegments(tx.trace.root, [{name: 'mysegment'}], 'should have expected segments')

    // Many metrics are not created until the transaction ends, if you're
    // missing metrics in your instrumentation tests, this may help.
    tx.end()

    // This will check that the metrics given have been created. Extra metrics
    // are allowed.
    t.metrics(['/My/Metric'], 'should have created metrics')

    // Like above, this checks that the given metrics were created. Any extra
    // metrics that were created are considered a failure.
    t.exactMetrics(['/My/Metric', '/Another/Metric'], 'should have exactly these metrics')
  })
})

Versioned Tests

The versioned-tests script can be used to execute a series of tests against several versions of dependencies. For example, the command below would run all the tests suffixed with .tap.js against every minor version of the specified dependencies.

$ versioned-tests --minor tests/versioned/*.tap.js

The following command will run only those test files whose names include the keyword redis:

$ versioned-tests tests/versioned/ -P redis

You can then specify the versions you want to run this against by adding a package.json file in your tests directory. This package file should have a tests array describing each suite. For example, the one shown below will test different files for each version of mongodb from v1.0.0 through to the latest.

{
  "name": "mongodb-tests",
  "version": "0.0.0",
  "private": true,
  "tests": [
    {
      "engines": {
        "node": ">=0.10 <7"
      },
      "dependencies": {
        "mongodb": "^1"
      },
      "files": [
        "v1-tests.tap.js"
      ]
    },
    {
      "engines": {
        "node": ">=0.10"
      },
      "dependencies": {
        "mongodb": ">=2.1 <3"
      },
      "files": [
        "v2-tests.tap.js",
        "shared-tests.tap.js"
      ]
    },
    {
      "engines": {
        "node": ">=4"
      },
      "dependencies": {
        "mongodb": ">=3"
      },
      "files": [
        "v3-tests.tap.js",
        "shared-tests.tap.js"
      ]
    }
  ]
}

The versioned tests runner has a timeout for tests that defaults to one minute. That is, if running a test -- including installing its dependencies! -- takes longer than a minute, then that test is considered to have failed. You can change this timeout with the TEST_CHILD_TIMEOUT environment variable, which is interpreted as a number of milliseconds. For example, to set a test timeout of ten minutes, you could invoke the test runner like this:

$ TEST_CHILD_TIMEOUT=600000 versioned-tests

As ten minutes is 600,000 milliseconds.

Testing

The module includes a suite of unit and functional tests which should be used to verify that your changes don't break existing functionality.

All tests are stored in tests/ and are written using Node-Tap with the extension .tap.js.

To run the full suite, run: npm test.

Individual test scripts include:

npm run lint
npm run unit

Support

Should you need assistance with New Relic products, you are in good hands with several support channels.

If the issue has been confirmed as a bug or is a feature request, please file a GitHub issue.

Support Channels

Privacy

At New Relic we take your privacy and the security of your information seriously, and are committed to protecting your information. We must emphasize the importance of not sharing personal data in public forums, and ask all users to scrub logs and diagnostic information for sensitive information, whether personal, proprietary, or otherwise.

We define “Personal Data” as any information relating to an identified or identifiable individual, including, for example, your name, phone number, post code or zip code, Device ID, IP address and email address.

For more information, review New Relic’s General Data Privacy Notice.

Contribute

We encourage your contributions to improve New Relic Test Utilities! Keep in mind when you submit your pull request, you'll need to sign the CLA via the click-through using CLA-Assistant. You only have to sign the CLA one time per project.

If you have any questions, or to execute our corporate CLA, required if your contribution is on behalf of a company, please drop us an email at opensource@newrelic.com.

A note about vulnerabilities

As noted in our security policy, New Relic is committed to the privacy and security of our customers and their data. We believe that providing coordinated disclosure by security researchers and engaging with the security community are important means to achieve our security goals.

If you believe you have found a security vulnerability in this project or any of New Relic's products or websites, we welcome and greatly appreciate you reporting it to New Relic through Hacour bug bounty program.

If you would like to contribute to this project, review these guidelines.

To all contributors, we thank you! Without your contribution, this project would not be what it is today. We also host a community project page dedicated to New Relic Node Test Utilities.

License

New Relic Test Utilities is licensed under the Apache 2.0 License.

New Relic Test Utilities also uses source code from third-party libraries. You can find full details on which libraries are used and the terms under which they are licensed in the third-party notices document.

changelog

v9.1.0 (2024-08-19)

Features

  • Added a --matrix-count parameter to versioned tests (#230) (72d8c7d)

v9.0.0 (2024-07-31)

⚠ BREAKING CHANGES

  • Dropped support for Node.js 16

Features

Code refactoring

  • Reduced dependency on async library (#219) (582efe6)
  • Removed install queue from versioned runner. It will install before running a given test and rely on the jobs limit (#221) (d9c6d1b)

Continuous integration

  • Fixed test script to run all unit tests (#218) (61336d4)

v8.7.0 (2024-06-28)

Features

  • Added support for Node 22

Code refactoring

  • Removed --all flag from versioned runner as all runs will be using this since we no longer support Node.js versions that do not ship with npm7 (#216) (0db82d8)

Miscellaneous chores

Continuous integration

v8.6.0 (2024-06-03)

Miscellaneous chores

  • Updated mock agent to exclusively rely on InstrumentationTracker (#203) (0e4d810)

v8.5.0 (2024-04-15)

Features

  • Added a quiet mode printer to versioned-tests (#201) (9477251)

Continuous integration

  • Removed use_new_release input from prepare release workflow (#200) (0f40f8b)
  • removed changelog.json file (#198) (3a32b2b)

v8.4.0 (2024-04-02)

Miscellaneous chores

Continuous integration

  • Updated repo to use conventional commits for releases (#194) (4254669)

v8.3.0 (2024-03-06)

  • Added new Amazon Titan LLM responses to support token_count work.

v8.2.0 (2024-02-01)

  • Adds a new module that provides a mock server for AWS Bedrock.
  • Bumps follow-redirects from 1.15.3 to 1.15.4.
  • Bumps axios to 1.6.0 and updates ancestor dependency newrelic. These dependencies need to be updated together.
  • Updates axios from 0.21.4 to 1.6.0
  • Updates newrelic from 11.0.0 to 11.5.0
  • Bumps and @babel/traverse. These dependencies needed to be updated together.
  • Updates @babel/traverse from 7.22.8 to 7.23.2
  • Updates @babel/traverse from 7.21.3 to 7.23.2

v8.1.0 (2023-08-29)

  • Updated the TestAgent to call shimmer.registerHooks and shimmer.removeHooks to set up instrumentation and remove it.

v8.0.0 (2023-08-28)

  • BREAKING CHANGE: Removed support for Node 14.

  • Added support for Node 20.

  • Gated usage of loader in versioned tests by NR_LOADER environment variable

  • Updated vulnerable dependencies:

    • word-wrap from 1.2.3 to 1.2.4.
    • protobufjs from 7.2.2 to 7.2.4.
    • fast-xml-parser from 4.2.4 to 4.2.5
    • @aws-sdk/client-lambda from 3.357.0 to 3.363.0

v7.3.2 (2023-06-22)

  • Updated semver to 7.5.2
  • Updated newrelic dev dependency to 10.3.0
  • Updated @newrelic/eslint-config to 0.3.0
  • Updated eslint dev dependency to 8.43.0

  • Updated README links to point to new forum link due to repolinter ruleset change

v7.3.1 (2023-05-03)

  • Updated TestAgent.getShim to require an exported module and pull the shim symbol.

v7.3.0 (2023-03-23)

  • Provided ability to register only core instrumentation or both core and 3rd party instrumentation. TestAgent.makeFullyInstrumented will register both. TestAgent.makeInstrumented will only register core instrumentation.

  • Updated README header image to latest OSS office required images

v7.2.1 (2023-01-10)

  • Bumps json5 from 2.2.1 to 2.2.2.
  • Streamlined CLM assertions to inherit tap from context.
  • Bypassed tapper/asserter abstractions so that CLM test failures are exposed.
  • Added lockfile checks to CI workflow to prevent malicious changes

v7.2.0 (2022-12-12)

  • Added assertCLMAttrs testing method to utils, so it can be used to test CLM behavior in external repos

v7.1.1 (2022-09-15)

  • Added detection for node version < 18, to supply correct loader flag

v7.1.0 (2022-09-14)

  • Added the capacity of running ES module tests with the ESM loader from agent or a path to an ESM loader set as process.env.NR_LOADER.

v7.0.0 (2022-07-27)

v6.5.5 (2022-06-01)

  • Added TEST_CHILD_TIMEOUT environment variable to modify test timeout limits.

v6.5.4 (2022-05-27)

  • Updated version runner to fail if package fails to install and not attempt to clean the npm cache.

v6.5.3 (2022-04-20)

  • Bumped async to ^3.2.3.

    Updated usage of queue.drain which was a 3.x breaking change.

  • Resolved dev-only audit warnings.

  • Bumped moment from 2.29.1 to 2.29.2.

  • Bumped tap to ^16.0.1.

v6.5.2 (2022-03-24)

  • Fixed util.maxVersionPerMode sorting by handling numbers as semver versions and not floats.

v6.5.1 (2022-03-24)

  • Fixed util.maxVersionPerMode by sorting versions to ensure the last package is the latest.

v6.5.0 (2022-03-21)

  • Fixed how version resolution occurs when semver ranges are not the latest major version.

  • Fixed how latest gets resolved by actually using the latest version.

  • Added printing list of packages and their versions at the end of a run.

v6.4.1 (2022-02-23)

  • Fixed link to discuss.newrelic.com in README.

  • Resolved several dev-dependency audit warnings.

  • Bumped glob to ^7.2.0.

v6.4.0 (2022-01-31)

  • Added a warning and/or error when tests present in testing directory are not included in test specification.

  • Updated add-to-board to use org level NODE_AGENT_GH_TOKEN

v6.3.0 (2022-01-10)

  • Added workflow to automate preparing release notes by reusing the newrelic/node-newrelic/.github/workflows/prep-release.yml@main workflow from agent repository.

  • Added job to automatically add issues/pr to Node.js Engineering board

  • Fixed overeager pattern-filter interpretation.

  • Added getShim method for retrieving a test Shim instance.

    This enables test setup involving instrumentation like scenarios (adding segments, etc.) without reaching into the internal tracer.

v6.2.0 (2021-11-19)

  • Added clearing of registered instrumentation to unload.

  • Added getContextManager to retrieve the active context manager in agent versions 8.6.0+.

  • Bumped newrelic dev dependency to ^8.6.0.

v6.1.1 (2021-10-20)

  • Fix pattern matching regression when parsing names of test files.

  • Refactored test pattern filtering by extracting to its own function. Also added a few missing test pattern test cases.

v6.1.0 (2021-10-19)

  • Added the -P, --pattern flag to allow filtering tests by keyword(s).

  • Added support for running specific test files by name or globbing pattern.

  • Added a --samples value to CLI to allow an override of sampling for a given test run.

    Global sample value will be used when it is less than the samples value set on a given package in the tests stanza.

  • Added ability to run versioned tests against version tags. For example: newrelic@latest.

    When a version such as package@latest is specified in the versioned test package.json declarations, it won't directly satisfy semver matches against the package versions manually pulled down and cached. The runner now attempts to directly install the configured version, which also results in a test failure if the package fails to install. Previously, failure to be able to install a dependency would log a warning and then just not run any tests and let CI pass.

  • Upgraded setup-node CI job to v2 and changed the linting node version to lts/* for future proofing.

  • Added @newrelic/eslint-config to rely on a centralized eslint ruleset.

  • Added a pre-commit hook to check if package.json changes and run oss third-party manifest and oss third-party notices.

    This will ensure the third_party_manifest.json and THIRD_PARTY_NOTICES.md are up to date.

  • Changed runner output to only list package versions when a test fails.

v6.0.0 (2021-07-20):

v5.1.0 (2021-05-11):

  • Added enumerating and printing versions of every module being tested.
  • Added flag to install every package on each test run for npm v7 compatibility.
  • Added husky + lint-staged to run linting on all staged files.

v5.0.0 (2020-11-03):

  • Added Node v14.x to CI.
  • Removed Node v8.x from CI.
  • Updates to README to match New Relic OSS template.

v4.1.2 (2020-10-01):

  • Creates config instance via Config.createInstance() to pass to agent instead of using Config.initialize().

    Previously, the agent and created segments could end up with different config instances resulting in config updates (such as attribute configuration) not propagating correctly for tests. Now, the agent uses the same initialized singleton similar to regular execution.

v4.1.1 (2020-09-16):

  • Improved handling of soft-matching segments for cases where siblings have duplicate names.

v4.1.0 (2020-09-03):

  • Added TestAgent.getAgentApi() function that returns an agent API instance for the underlying agent instance.

v4.0.0 (2020-07-21):

  • Updated to Apache 2.0 license.
  • Bumped minimum dev dependency of newrelic (agent) to 6.11 for license matching.
  • Updated metric retrieval from agent for assert.metrics to match newer agent versions.

    Breaking: assertions are now only compatible with newrelic (agent) versions 6+.

  • Added third party notices file and metadata for dependencies.
  • Updated readme with more detail.
  • Added issue templates for bugs and enhancements.
  • Added code of conduct file.
  • Added contributing guide.
  • Added pull request template.
  • Migrated CI to GitHub Actions.
  • Added copyright headers to all source files.
  • Added .vscode to .gitignore.
  • Added additional items to .npmignore.

v3.3.0 (2020-05-20):

  • Added the ability to skip tests using multiple keywords

v3.2.0 (2019-11-12):

  • Added new format for versioned test

    Dependency version may now be sampled down to a constant number of versions. For example:

    "dependencies": {
      "redis": {
        "versions": ">1.0.0",
        "samples": 10
      }
    }

v3.1.0 (2019-09-03):

  • Added --skip flag to allow for skipping certain test suites.

v3.0.0 (2019-01-07):

  • Added setState argument to TestAgent constructor, which allows for automatic data collection in tests by default.

  • Removed obsoleted flags argument from TestAgent constructor. Feature flags are now accounted for in standard config.

v2.0.1 (2018-11-06):

  • Versioned test runner now uses --no-package-lock when installing test deps.

v2.0.0 (2018-10-26):

  • Dropped support for Node 0.10 and Node 0.12.

  • Added isLocalhost and getDelocalizedHostname to utilities methods.

    These methods are useful for determining the host name as the New Relic agent sees it. When making metrics and event attributes, the delocalized hostname is what the agent will use.

v1.2.1 (2018-07-10):

  • Fixed default messages for tap assertions.

v1.2.0 (2018-02-26):

  • Added check for AGENT_PATH environment variable.

    This environment variable can be used to specify the location of the newrelic package that these test utilities will load. It should be the path to the root directory of the agent. If the environment variable is not set, then the newrelic module that was installed (e.g. is in a node_modules directory) is used instead.

  • With this change, the following syntaxes are now valid:

    • versioned-tests: Will look for tests with the following globs:
      • test/versioned/**/package.json
      • tests/versioned/**/package.json
      • node_modules/**/tests/versioned/**/package.json <-- For the agent to seamlessly work with the tests of deps!
    • versioned-tests test/versioned/hapi: Will look with these globs:
      • test/versioned/hapi/package.json
      • test/versioned/hapi/**/package.json
    • versioned-tests test/versioned/mongodb/package.json: Will look only at:
      • test/versioned/mongodb/package.json

v1.1.2 (2018-02-23):

  • Added agent#registerInstrumentation method to registering third-party instrumentations in a testing environment.

v1.1.1 (2018-02-23):

  • Fixed invalid TestAgent.extendTap reference in index.js to assert.extendTap.

v1.1.0 (2018-02-20):

  • Added TestAgent#registerInstrumentation method.

    This method allows third-party instrumentations to be registered in a test environment.

v1.0.0 (2018-02-20):

  • Added TestAgent helper class.

    This class provides simple to use helpers for running your tests with the agent and in transactions.

  • Added tap assertions.

    If your tests use tap, then you can add some helpful assertions to your tests using this module.

  • Added version matrix test running.

    This is a script for executing your instrumentation's tests against many versions of the module you are instrumenting.