Skip to content

Commit

Permalink
tests: refactor config tests service name (#3777)
Browse files Browse the repository at this point in the history
  • Loading branch information
david-luna authored Dec 6, 2023
1 parent 1287fd2 commit 38e9a8e
Show file tree
Hide file tree
Showing 14 changed files with 274 additions and 298 deletions.
289 changes: 0 additions & 289 deletions test/config.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,13 @@

'use strict';

var cp = require('child_process');
var fs = require('fs');
var IncomingMessage = require('http').IncomingMessage;
var os = require('os');
var path = require('path');
var util = require('util');

var test = require('tape');

const Agent = require('../lib/agent');
const { MockAPMServer } = require('./_mock_apm_server');
const { MockLogger } = require('./_mock_logger');
const { NoopApmClient } = require('../lib/apm-client/noop-apm-client');
const { ENV_TABLE } = require('../lib/config/schema');
const config = require('../lib/config/config');
Expand Down Expand Up @@ -103,290 +98,6 @@ test('should overwrite option property active by ELASTIC_APM_ACTIVE', function (
t.end();
});

test('invalid serviceName => inactive', function (t) {
const logger = new MockLogger();
const agent = new Agent();

agent.start(
Object.assign({}, agentOptsNoopTransport, {
serviceName: 'foo&bar',
logger,
}),
);

const error = logger.calls.find((log) => log.type === 'error');
t.ok(
error && error.message.indexOf('serviceName') !== -1,
'there was a log.error mentioning "serviceName"',
);
t.strictEqual(agent._conf.active, false, 'active is false');
agent.destroy();
t.end();
});

test('valid serviceName => active', function (t) {
var agent = new Agent();
agent.start(
Object.assign({}, agentOptsNoopTransport, {
serviceName: 'fooBAR0123456789_- ',
}),
);
t.strictEqual(agent._conf.active, true);
agent.destroy();
t.end();
});

test('serviceName/serviceVersion zero-conf: valid', function (t) {
cp.execFile(
process.execPath,
['index.js'],
{
timeout: 3000,
cwd: path.join(__dirname, 'fixtures', 'pkg-zero-conf-valid'),
},
function (err, stdout, stderr) {
t.error(err, 'no error running index.js: ' + err);
t.equal(stderr, '', 'no stderr');
const lines = stdout.trim().split('\n');
const conf = JSON.parse(lines[lines.length - 1]);
t.equal(
conf.serviceName,
'validName',
'serviceName was inferred from package.json',
);
t.equal(
conf.serviceVersion,
'1.2.3',
'serviceVersion was inferred from package.json',
);
t.end();
},
);
});

test('serviceName/serviceVersion zero-conf: cwd is outside package tree', function (t) {
const indexJs = path.join(
__dirname,
'fixtures',
'pkg-zero-conf-valid',
'index.js',
);
cp.execFile(
process.execPath,
[indexJs],
{
timeout: 3000,
// Set CWD to outside of the package tree to test whether the agent
// package.json searching uses `require.main`.
cwd: '/',
},
function (err, stdout, stderr) {
t.error(err, 'no error running index.js: ' + err);
t.equal(stderr, '', 'no stderr');
const lines = stdout.trim().split('\n');
const conf = JSON.parse(lines[lines.length - 1]);
t.equal(
conf.serviceName,
'validName',
'serviceName was inferred from package.json',
);
t.equal(
conf.serviceVersion,
'1.2.3',
'serviceVersion was inferred from package.json',
);
t.end();
},
);
});

test('serviceName/serviceVersion zero-conf: no "name" in package.json', function (t) {
cp.execFile(
process.execPath,
['index.js'],
{
timeout: 3000,
cwd: path.join(__dirname, 'fixtures', 'pkg-zero-conf-noname'),
},
function (err, stdout, stderr) {
t.error(err, 'no error running index.js: ' + err);
t.equal(stderr, '', 'no stderr');
const lines = stdout.trim().split('\n');
const conf = JSON.parse(lines[lines.length - 1]);
t.equal(
conf.serviceName,
'unknown-nodejs-service',
'serviceName is the `unknown-{service.agent.name}-service` zero-conf fallback',
);
t.equal(
conf.serviceVersion,
'1.2.3',
'serviceVersion was inferred from package.json',
);
t.end();
},
);
});

// A package.json#name that uses a scoped npm name, e.g. @ns/name, should get
// a normalized serviceName='ns-name'.
test('serviceName/serviceVersion zero-conf: namespaced package name', function (t) {
cp.execFile(
process.execPath,
['index.js'],
{
timeout: 3000,
cwd: path.join(__dirname, 'fixtures', 'pkg-zero-conf-nsname'),
},
function (err, stdout, stderr) {
t.error(err, 'no error running index.js: ' + err);
t.equal(stderr, '', 'no stderr');
const lines = stdout.trim().split('\n');
const conf = JSON.parse(lines[lines.length - 1]);
t.equal(
conf.serviceName,
'ns-name',
'serviceName was inferred and normalized from package.json',
);
t.equal(
conf.serviceVersion,
'1.2.3',
'serviceVersion was inferred from package.json',
);
t.end();
},
);
});

test('serviceName/serviceVersion zero-conf: a package name that requires sanitization', function (t) {
cp.execFile(
process.execPath,
['index.js'],
{
timeout: 3000,
cwd: path.join(__dirname, 'fixtures', 'pkg-zero-conf-sanitize'),
},
function (err, stdout, stderr) {
t.error(err, 'no error running index.js: ' + err);
t.equal(stderr, '', 'no stderr');
const lines = stdout.trim().split('\n');
const conf = JSON.parse(lines[lines.length - 1]);
// serviceName sanitization changes any disallowed char to an underscore.
// The pkg-zero-conf-sanitize/package.json has a name starting with the
// 7 characters that an npm package name can have, but a serviceName
// cannot.
// "name": "~*.!'()validNpmName"
t.equal(
conf.serviceName,
'_______validNpmName',
'serviceName was inferred and sanitized from package.json',
);
t.equal(
conf.serviceVersion,
'1.2.3',
'serviceVersion was inferred from package.json',
);
t.end();
},
);
});

test('serviceName/serviceVersion zero-conf: weird "name" in package.json', function (t) {
cp.execFile(
process.execPath,
['index.js'],
{
timeout: 3000,
cwd: path.join(__dirname, 'fixtures', 'pkg-zero-conf-weird'),
},
function (err, stdout, stderr) {
t.error(err, 'no error running index.js: ' + err);
t.equal(stderr, '', 'no stderr');
const lines = stdout.trim().split('\n');
const logs = lines.map((l) => JSON.parse(l));
const logWarn = logs.find((log) => log['log.level'] === 'warn');
t.ok(
logWarn['log.level'] === 'warn' &&
logWarn.message.indexOf('serviceName') !== -1,
'there is a log.warn about "serviceName"',
);
const conf = JSON.parse(
// Filter out log lines from the APM agent itself. We just want the
// `console.log(...)` from the index.js script.
lines.filter((ln) => ln.indexOf('"log.level":') === -1)[0],
);
t.equal(
conf.serviceName,
'unknown-nodejs-service',
'serviceName is the `unknown-{service.agent.name}-service` zero-conf fallback',
);
t.equal(
conf.serviceVersion,
'1.2.3',
'serviceVersion was inferred from package.json',
);
t.end();
},
);
});

test('serviceName/serviceVersion zero-conf: no package.json to find', function (t) {
// To test the APM agent's fallback serviceName, we need to execute
// a script in a dir that has no package.json in its dir, or any dir up
// from it (we assume/hope that `os.tmpdir()` works for that).
const dir = os.tmpdir();
const script = path.resolve(dir, 'elastic-apm-node-zero-conf-test-script.js');
// Avoid Windows '\' path separators that are interpreted as escapes when
// interpolated into the script content below.
const agentDir = path
.resolve(__dirname, '..')
.replace(new RegExp('\\' + path.win32.sep, 'g'), path.posix.sep);
function setupPkgEnv() {
fs.writeFileSync(
script,
`
const apm = require('${agentDir}').start({
disableSend: true
})
console.log(JSON.stringify(apm._conf))
`,
);
t.comment(`created ${script}`);
}
function teardownPkgEnv() {
fs.unlinkSync(script);
t.comment(`removed ${script}`);
}

setupPkgEnv();
cp.execFile(
process.execPath,
[script],
{
timeout: 3000,
cwd: dir,
},
function (err, stdout, stderr) {
t.error(err, 'no error running script: ' + err);
t.equal(stderr, '', 'no stderr');
const lines = stdout.trim().split('\n');
const conf = JSON.parse(
// Filter out log lines from the APM agent itself. We just want the
// `console.log(...)` from the index.js script.
lines.filter((ln) => ln.indexOf('"log.level":') === -1)[0],
);
t.equal(
conf.serviceName,
'unknown-nodejs-service',
'serviceName is the `unknown-{service.agent.name}-service` zero-conf fallback',
);
t.equal(conf.serviceVersion, undefined, 'serviceVersion is undefined');
teardownPkgEnv();
t.end();
},
);
});

var captureBodyTests = [
{ value: 'off', errors: '[REDACTED]', transactions: '[REDACTED]' },
{ value: 'transactions', errors: '[REDACTED]', transactions: 'test' },
Expand Down
Loading

0 comments on commit 38e9a8e

Please sign in to comment.