提交 10e57474 authored 作者: Iñaki Baz Castillo's avatar Iñaki Baz Castillo

- Update NPM and C/C++ deps

- Apply new eslint rules
上级 4da89d00
module.exports =
{
extends : [ 'eslint:recommended' ],
parserOptions :
env:
{
ecmaVersion : 6,
sourceType : 'module',
ecmaFeatures :
{
impliedStrict : true
}
es6: true,
node: true
},
env :
extends:
[
'eslint:recommended'
],
settings: {},
parserOptions:
{
'es6' : true,
'node' : true
ecmaVersion: 6,
sourceType: 'module',
ecmaFeatures:
{
impliedStrict: true
}
},
'rules' :
rules:
{
'comma-dangle' : 2,
'comma-spacing' : [ 2, { before: false, after: true } ],
'max-len' :
[
2,
{
code : 100,
ignoreStrings : true,
ignoreUrls : true,
ignoreTemplateLiterals : true,
tabWidth : 2,
ignoreComments : true
}
],
'no-console' : 0,
'no-constant-condition' : 2,
'no-control-regex' : 2,
'no-dupe-args' : 2,
'no-dupe-keys' : 2,
'no-duplicate-case' : 2,
'no-empty' : 0,
'no-empty-character-class' : 2,
'no-ex-assign' : 2,
'no-extra-boolean-cast' : 2,
'no-extra-parens' : [ 2, 'all', { nestedBinaryExpressions: false } ],
'no-extra-semi' : 2,
'no-func-assign' : 2,
'no-inner-declarations' : 2,
'no-invalid-regexp' : 2,
'no-irregular-whitespace' : 2,
'no-loop-func' : 2,
'no-negated-in-lhs' : 2,
'no-obj-calls' : 2,
'no-prototype-builtins' : 2,
'no-regex-spaces' : 2,
'no-sparse-arrays' : 2,
'no-undef' : 2,
'no-unexpected-multiline' : 2,
'no-unreachable' : 2,
'no-unsafe-finally' : 2,
'no-unused-vars' : [ 2, { vars: 'all', args: 'after-used' }],
'no-multi-spaces' : 0,
'no-whitespace-before-property' : 2,
'quotes' : [ 2, 'single', { avoidEscape: true } ],
'semi' : [ 2, 'always' ],
'space-before-blocks' : 2,
'space-before-function-paren' : [ 2, 'never' ],
'space-in-parens' : [ 2, 'never' ],
'spaced-comment' : [ 2, 'always' ],
'use-isnan' : 2,
'valid-typeof' : 2
'array-bracket-spacing': [ 2, 'always',
{
objectsInArrays: true,
arraysInArrays: true
}],
'arrow-parens': [ 2, 'always' ],
'arrow-spacing': 2,
'block-spacing': [ 2, 'always' ],
'brace-style': [ 2, 'allman', { allowSingleLine: true } ],
'camelcase': 2,
'comma-dangle': 2,
'comma-spacing': [ 2, { before: false, after: true } ],
'comma-style': 2,
'computed-property-spacing': 2,
'constructor-super': 2,
'func-call-spacing': 2,
'generator-star-spacing': 2,
'guard-for-in': 2,
'indent': [ 2, 'tab', { 'SwitchCase': 1 } ],
'key-spacing': [ 2,
{
singleLine:
{
beforeColon: false,
afterColon: true
},
multiLine:
{
beforeColon: true,
afterColon: true,
align: 'colon'
}
}],
'keyword-spacing': 2,
'linebreak-style': [ 2, 'unix' ],
'lines-around-comment': [ 2,
{
allowBlockStart: true,
allowObjectStart: true,
beforeBlockComment: true,
beforeLineComment: false
}],
'max-len': [ 2, 90,
{
tabWidth: 2,
comments: 110,
ignoreUrls: true,
ignoreStrings: true,
ignoreTemplateLiterals: true,
ignoreRegExpLiterals: true
}],
'newline-after-var': 2,
'newline-before-return': 2,
'newline-per-chained-call': 2,
'no-alert': 2,
'no-caller': 2,
'no-case-declarations': 2,
'no-catch-shadow': 2,
'no-class-assign': 2,
'no-confusing-arrow': 2,
'no-console': 2,
'no-const-assign': 2,
'no-debugger': 2,
'no-dupe-args': 2,
'no-dupe-keys': 2,
'no-duplicate-case': 2,
'no-div-regex': 2,
'no-empty': [ 2, { allowEmptyCatch: true } ],
'no-empty-pattern': 2,
'no-else-return': 0,
'no-eval': 2,
'no-extend-native': 2,
'no-ex-assign': 2,
'no-extra-bind': 2,
'no-extra-boolean-cast': 2,
'no-extra-label': 2,
'no-extra-parens': [ 2, 'all', { nestedBinaryExpressions: false } ],
'no-extra-semi': 2,
'no-fallthrough': 2,
'no-func-assign': 2,
'no-global-assign': 2,
'no-implicit-coercion': 2,
'no-implicit-globals': 2,
'no-inner-declarations': 2,
'no-invalid-regexp': 2,
'no-invalid-this': 2,
'no-irregular-whitespace': 2,
'no-lonely-if': 2,
'no-mixed-operators': 2,
'no-mixed-spaces-and-tabs': 2,
'no-multi-spaces': 2,
'no-multi-str': 2,
'no-multiple-empty-lines': 2,
'no-native-reassign': 2,
'no-negated-in-lhs': 2,
'no-new': 2,
'no-new-func': 2,
'no-new-wrappers': 2,
'no-obj-calls': 2,
'no-proto': 2,
'no-prototype-builtins': 0,
'no-redeclare': 2,
'no-regex-spaces': 2,
'no-restricted-imports': 2,
'no-return-assign': 2,
'no-self-assign': 2,
'no-self-compare': 2,
'no-sequences': 2,
'no-shadow': 2,
'no-shadow-restricted-names': 2,
'no-spaced-func': 2,
'no-sparse-arrays': 2,
'no-this-before-super': 2,
'no-throw-literal': 2,
'no-undef': 2,
'no-unexpected-multiline': 2,
'no-unmodified-loop-condition': 2,
'no-unreachable': 2,
'no-unused-vars': [ 1, { vars: 'all', args: 'after-used' }],
'no-use-before-define': [ 2, { functions: false } ],
'no-useless-call': 2,
'no-useless-computed-key': 2,
'no-useless-concat': 2,
'no-useless-rename': 2,
'no-var': 2,
'no-whitespace-before-property': 2,
'object-curly-newline': 0,
'object-curly-spacing': [ 2, 'always' ],
'object-property-newline': [ 2, { allowMultiplePropertiesPerLine: true } ],
'prefer-const': 2,
'prefer-rest-params': 2,
'prefer-spread': 2,
'prefer-template': 2,
'quotes': [ 2, 'single', { avoidEscape: true } ],
'semi': [ 2, 'always' ],
'semi-spacing': 2,
'space-before-blocks': 2,
'space-before-function-paren': [ 2, 'never' ],
'space-in-parens': [ 2, 'never' ],
'spaced-comment': [ 2, 'always' ],
'strict': 0,
'valid-typeof': 2,
'yoda': 2
}
};
......@@ -40,7 +40,7 @@ const numCpus = os.cpus().length;
gulp.task('rtpcapabilities', () =>
{
let supportedRtpCapabilities = require('./lib/supportedRtpCapabilities');
const supportedRtpCapabilities = require('./lib/supportedRtpCapabilities');
return gulp.src('worker/src/RTC/Room.cpp')
// Let's generate valid syntax as expected by clang-format rules.
......@@ -60,7 +60,7 @@ gulp.task('lint:node', () =>
gulp.task('lint:worker', () =>
{
let src = workerFiles.concat(
const src = workerFiles.concat(
// Remove Ragel generated files.
'!worker/src/Utils/IP.cpp'
);
......@@ -71,7 +71,7 @@ gulp.task('lint:worker', () =>
gulp.task('format:worker', () =>
{
let src = workerFiles.concat(
const src = workerFiles.concat(
// Remove Ragel generated files.
'!worker/src/Utils/IP.cpp'
);
......
......@@ -124,7 +124,7 @@ class Channel extends EventEmitter
// binary event with its binary data.
else
{
let msg = this._lastBinaryNotification;
const msg = this._lastBinaryNotification;
// Reset.
this._lastBinaryNotification = null;
......@@ -164,7 +164,7 @@ class Channel extends EventEmitter
logger.debug('close()');
// Close every pending sent.
for (let sent of this._pendingSent.values())
for (const sent of this._pendingSent.values())
{
sent.close();
}
......@@ -190,12 +190,12 @@ class Channel extends EventEmitter
request(method, internal, data)
{
let id = utils.randomNumber();
const id = utils.randomNumber();
logger.debug('request() [method:%s, id:%s]', method, id);
let request = { id, method, internal, data };
let ns = netstring.nsWrite(JSON.stringify(request));
const request = { id, method, internal, data };
const ns = netstring.nsWrite(JSON.stringify(request));
if (Buffer.byteLength(ns) > NS_MAX_SIZE)
return Promise.reject(new Error('request too big'));
......@@ -212,18 +212,18 @@ class Channel extends EventEmitter
return new Promise((pResolve, pReject) =>
{
let sent =
const sent =
{
resolve: (data) =>
resolve : (data2) =>
{
if (!this._pendingSent.delete(id))
return;
clearTimeout(sent.timer);
pResolve(data);
pResolve(data2);
},
reject: (error) =>
reject : (error) =>
{
if (!this._pendingSent.delete(id))
return;
......@@ -232,7 +232,7 @@ class Channel extends EventEmitter
pReject(error);
},
timer: setTimeout(() =>
timer : setTimeout(() =>
{
if (!this._pendingSent.delete(id))
return;
......@@ -240,7 +240,7 @@ class Channel extends EventEmitter
pReject(new Error('request timeout'));
}, REQUEST_TIMEOUT),
close: () =>
close : () =>
{
clearTimeout(sent.timer);
pReject(new errors.InvalidStateError('Channel closed'));
......@@ -259,7 +259,7 @@ class Channel extends EventEmitter
// If a Response, retrieve its associated Request.
if (msg.id)
{
let sent = this._pendingSent.get(msg.id);
const sent = this._pendingSent.get(msg.id);
if (!sent)
{
......
......@@ -62,10 +62,10 @@ class Peer extends EventEmitter
case 'newrtpsender':
{
let associatedRtpReceiver = this._sandbox.getRtpReceiverById(
const associatedRtpReceiver = this._sandbox.getRtpReceiverById(
data.associatedRtpReceiverId);
let internal =
const internal2 =
{
roomId : this._internal.roomId,
peerId : this._internal.peerId,
......@@ -73,7 +73,7 @@ class Peer extends EventEmitter
transportId : null
};
let data2 =
const data2 =
{
kind : data.kind,
peer : this,
......@@ -83,7 +83,7 @@ class Peer extends EventEmitter
};
// Create a RtpSender instance.
let rtpSender = new RtpSender(internal, data2, this._channel);
const rtpSender = new RtpSender(internal2, data2, this._channel);
// Store the RtpSender instance and remove it when closed.
this._rtpSenders.add(rtpSender);
......@@ -169,19 +169,19 @@ class Peer extends EventEmitter
this._channel.removeAllListeners(this._internal.peerId);
// Close every Transport.
for (let transport of this._transports)
for (const transport of this._transports)
{
transport.close(undefined, true);
}
// Close every RtpReceiver.
for (let rtpReceiver of this._rtpReceivers)
for (const rtpReceiver of this._rtpReceivers)
{
rtpReceiver.close(undefined, true);
}
// Close every RtpSender.
for (let rtpSender of this._rtpSenders)
for (const rtpSender of this._rtpSenders)
{
rtpSender.close();
}
......@@ -194,9 +194,9 @@ class Peer extends EventEmitter
{
logger.debug('"peer.close" request succeeded');
})
.catch((error) =>
.catch((error2) =>
{
logger.error('"peer.close" request failed: %s', error);
logger.error('"peer.close" request failed: %s', error2);
});
}
......@@ -284,7 +284,7 @@ class Peer extends EventEmitter
if (this._closed)
return Promise.reject(new errors.InvalidStateError('Peer closed'));
let internal =
const internal =
{
roomId : this._internal.roomId,
peerId : this._internal.peerId,
......@@ -297,7 +297,7 @@ class Peer extends EventEmitter
logger.debug('"peer.createTransport" request succeeded');
// Create a Transport instance.
let transport = new Transport(internal, data, this._channel);
const transport = new Transport(internal, data, this._channel);
// Store the Transport instance and remove it when closed.
this._transports.add(transport);
......@@ -349,7 +349,7 @@ class Peer extends EventEmitter
if (!this._transports.has(transport))
throw new Error('transport not found');
let internal =
const internal =
{
roomId : this._internal.roomId,
peerId : this._internal.peerId,
......@@ -357,7 +357,7 @@ class Peer extends EventEmitter
transportId : transport._internal.transportId
};
let data =
const data =
{
kind : kind,
peer : this,
......@@ -365,13 +365,13 @@ class Peer extends EventEmitter
};
// Create a RtpReceiver instance.
let rtpReceiver = new RtpReceiver(internal, data, this._channel);
const rtpReceiver = new RtpReceiver(internal, data, this._channel);
// Store the RtpReceiver instance and remove it when closed.
this._rtpReceivers.add(rtpReceiver);
rtpReceiver.on('close', () => this._rtpReceivers.delete(rtpReceiver));
let options =
const options =
{
kind : kind
};
......
......@@ -37,7 +37,7 @@ class Room extends EventEmitter
this._closed = false;
// Subscribe to notifications.
this._channel.on(this._internal.roomId, (event, data) =>
this._channel.on(this._internal.roomId, (event, data2) =>
{
switch (event)
{
......@@ -49,27 +49,27 @@ class Room extends EventEmitter
case 'audiolevels':
{
let entries = data.entries;
let data2 = [];
const entries = data2.entries;
const data3 = [];
for (let entry of entries)
for (const entry of entries)
{
let rtpReceiverId = entry[0];
let audioLevel = entry[1];
let rtpReceiver = this._rtpReceivers.get(rtpReceiverId);
const rtpReceiverId = entry[0];
const audioLevel = entry[1];
const rtpReceiver = this._rtpReceivers.get(rtpReceiverId);
if (!rtpReceiver)
continue;
let peer = rtpReceiver.peer;
const peer = rtpReceiver.peer;
if (!peer)
continue;
data2.push({ peer, rtpReceiver, audioLevel });
data3.push({ peer, rtpReceiver, audioLevel });
}
let orderedEntries = data2.sort((a, b) =>
const orderedEntries = data3.sort((a, b) =>
{
if (a.audioLevel > b.audioLevel)
return -1;
......@@ -186,7 +186,7 @@ class Room extends EventEmitter
this._channel.removeAllListeners(this._internal.roomId);
// Close every Peer.
for (let peer of this._peers.values())
for (const peer of this._peers.values())
{
peer.close(undefined, true);
}
......@@ -199,9 +199,9 @@ class Room extends EventEmitter
{
logger.debug('"room.close" request succeeded');
})
.catch((error) =>
.catch((error2) =>
{
logger.error('"room.close" request failed: %s', error);
logger.error('"room.close" request failed: %s', error2);
});
}
......@@ -271,14 +271,14 @@ class Room extends EventEmitter
if (this._peers.has(peerName))
throw new Error(`peer already exists [peerName:"${peerName}"]`);
let peerId = utils.randomNumber();
let internal =
const peerId = utils.randomNumber();
const internal =
{
roomId : this._internal.roomId,
peerId : peerId,
peerName : peerName
};
let sandbox =
const sandbox =
{
getRtpReceiverById : (rtpReceiverId) =>
{
......@@ -287,7 +287,7 @@ class Room extends EventEmitter
};
// Create a Peer instance.
let peer = new Peer(internal, this._channel, sandbox);
const peer = new Peer(internal, this._channel, sandbox);
// Store the Peer instance and remove it when closed.
this._peers.set(peerName, peer);
......@@ -335,7 +335,7 @@ class Room extends EventEmitter
_setCapabilities(capabilities)
{
for (let kind of KINDS)
for (const kind of KINDS)
{
this._capabilities[kind] =
{
......@@ -344,9 +344,9 @@ class Room extends EventEmitter
fecMechanisms : []
};
let kindCapabilities = this._capabilities[kind];
const kindCapabilities = this._capabilities[kind];
for (let codec of capabilities.codecs)
for (const codec of capabilities.codecs)
{
if (codec.kind === kind)
{
......@@ -354,7 +354,7 @@ class Room extends EventEmitter
}
else if (codec.kind === '')
{
let clonedCodec = utils.clone(codec);
const clonedCodec = utils.clone(codec);
clonedCodec.kind = kind;
kindCapabilities.codecs.push(clonedCodec);
......@@ -364,7 +364,7 @@ class Room extends EventEmitter
// Ignore if there are no media codecs of this kind.
if (kindCapabilities.codecs.length > 0)
{
for (let headerExtension of capabilities.headerExtensions)
for (const headerExtension of capabilities.headerExtensions)
{
if (headerExtension.kind === kind)
{
......@@ -372,7 +372,7 @@ class Room extends EventEmitter
}
else if (headerExtension.kind === '')
{
let clonedHeaderExtension = utils.clone(headerExtension);
const clonedHeaderExtension = utils.clone(headerExtension);
clonedHeaderExtension.kind = kind;
kindCapabilities.headerExtensions.push(clonedHeaderExtension);
......
......@@ -35,7 +35,7 @@ class RtpReceiver extends EventEmitter
this._closed = false;
// Subscribe to notifications.
this._channel.on(this._internal.rtpReceiverId, (event, data, buffer) =>
this._channel.on(this._internal.rtpReceiverId, (event, data2, buffer) =>
{
switch (event)
{
......@@ -54,8 +54,8 @@ class RtpReceiver extends EventEmitter
case 'rtpobject':
{
// Append the binary buffer into `object.payload`.
data.object.payload = buffer;
this.emit('rtpobject', data.object);
data2.object.payload = buffer;
this.emit('rtpobject', data2.object);
break;
}
......@@ -207,9 +207,9 @@ class RtpReceiver extends EventEmitter
{
logger.debug('"rtpReceiver.close" request succeeded');
})
.catch((error) =>
.catch((error2) =>
{
logger.error('"rtpReceiver.close" request failed: %s', error);
logger.error('"rtpReceiver.close" request failed: %s', error2);
});
}
......@@ -263,7 +263,7 @@ class RtpReceiver extends EventEmitter
{
logger.debug('"rtpReceiver.receive" request succeeded');
let hadParameters = !!this._data.rtpParameters;
const hadParameters = Boolean(this._data.rtpParameters);
this._data.rtpParameters = data;
......@@ -308,7 +308,7 @@ class RtpReceiver extends EventEmitter
if (transport.closed)
return Promise.reject(new errors.InvalidStateError('transport is closed'));
let previousTransportId = this._internal.transportId;
const previousTransportId = this._internal.transportId;
this._internal.transportId = transport._internal.transportId;
......
......@@ -37,7 +37,7 @@ class RtpSender extends EventEmitter
this._closed = false;
// Subscribe to notifications.
this._channel.on(this._internal.rtpSenderId, (event, data) =>
this._channel.on(this._internal.rtpSenderId, (event, data2) =>
{
switch (event)
{
......@@ -49,16 +49,16 @@ class RtpSender extends EventEmitter
case 'parameterschange':
{
this._data.rtpParameters = data.rtpParameters;
this._data.active = data.active;
this.emit('parameterschange', data.rtpParameters, data.active);
this._data.rtpParameters = data2.rtpParameters;
this._data.active = data2.active;
this.emit('parameterschange', data2.rtpParameters, data2.active);
break;
}
case 'activechange':
{
this._data.active = data.active;
this.emit('activechange', data.active);
this._data.active = data2.active;
this.emit('activechange', data2.active);
break;
}
......@@ -181,7 +181,7 @@ class RtpSender extends EventEmitter
if (transport.closed)
return Promise.reject(new errors.InvalidStateError('transport is closed'));
let previousTransportId = this._internal.transportId;
const previousTransportId = this._internal.transportId;
this._internal.transportId = transport._internal.transportId;
......@@ -224,7 +224,7 @@ class RtpSender extends EventEmitter
return this._channel.request('rtpSender.disable', this._internal,
{
disabled : false,
emit : !!options.emit
emit : Boolean(options.emit)
})
.then(() =>
{
......@@ -258,7 +258,7 @@ class RtpSender extends EventEmitter
return this._channel.request('rtpSender.disable', this._internal,
{
disabled : true,
emit : !!options.emit
emit : Boolean(options.emit)
})
.then(() =>
{
......
......@@ -33,9 +33,9 @@ class Server extends EventEmitter
super();
this.setMaxListeners(Infinity);
let serverId = utils.randomString();
const serverId = utils.randomString();
const parameters = [];
let numWorkers = DEFAULT_NUM_WORKERS;
let parameters = [];
// Set of Worker instances.
this._workers = new Set();
......@@ -84,13 +84,13 @@ class Server extends EventEmitter
// Remove rtcMinPort/rtcMaxPort (will be added per worker).
let totalRtcMinPort = options.rtcMinPort;
let totalRtcMaxPort = options.rtcMaxPort;
const totalRtcMinPort = options.rtcMinPort;
const totalRtcMaxPort = options.rtcMaxPort;
delete options.rtcMinPort;
delete options.rtcMaxPort;
for (let key of Object.keys(options))
for (const key of Object.keys(options))
{
if (!check.includes(VALID_WORKER_PARAMETERS, key))
{
......@@ -102,7 +102,7 @@ class Server extends EventEmitter
switch (key)
{
case 'logTags':
for (let tag of options.logTags)
for (const tag of options.logTags)
{
parameters.push(`--logTag=${String(tag).trim()}`);
}
......@@ -116,14 +116,14 @@ class Server extends EventEmitter
// Create Worker instances.
for (let i = 1; i <= numWorkers; i++)
{
let workerId = serverId + '#' + i;
let workerParameters = parameters.slice(0);
const workerId = `${serverId}#${i}`;
const workerParameters = parameters.slice(0);
// Distribute RTC ports for each worker.
let rtcMinPort = totalRtcMinPort;
let rtcMaxPort = totalRtcMaxPort;
let numPorts = Math.floor((rtcMaxPort - rtcMinPort) / numWorkers);
const numPorts = Math.floor((rtcMaxPort - rtcMinPort) / numWorkers);
rtcMinPort = rtcMinPort + (numPorts * (i - 1));
rtcMaxPort = rtcMinPort + numPorts;
......@@ -164,7 +164,7 @@ class Server extends EventEmitter
logger.error('close() [error:%s]', error);
// Close every Worker.
for (let worker of this._workers)
for (const worker of this._workers)
{
worker.close();
}
......@@ -184,9 +184,9 @@ class Server extends EventEmitter
if (this._closed)
return Promise.reject(new errors.InvalidStateError('Server closed'));
let promises = [];
const promises = [];
for (let worker of this._workers)
for (const worker of this._workers)
{
promises.push(worker.dump());
}
......@@ -194,7 +194,7 @@ class Server extends EventEmitter
return Promise.all(promises)
.then((datas) =>
{
let json =
const json =
{
workers : datas
};
......@@ -217,9 +217,9 @@ class Server extends EventEmitter
if (this._closed)
return Promise.reject(new errors.InvalidStateError('Server closed'));
let promises = [];
const promises = [];
for (let worker of this._workers)
for (const worker of this._workers)
{
promises.push(worker.updateSettings(options));
}
......@@ -239,7 +239,7 @@ class Server extends EventEmitter
if (this._closed)
return Promise.reject(new errors.InvalidStateError('Server closed'));
let worker = this._getRandomWorker();
const worker = this._getRandomWorker();
return worker.createRoom(options)
.then((room) =>
......@@ -270,7 +270,7 @@ class Server extends EventEmitter
_getRandomWorker()
{
let array = Array.from(this._workers);
const array = Array.from(this._workers);
return array[array.length * Math.random() << 0];
}
......
......@@ -61,7 +61,7 @@ class Transport extends EventEmitter
this._closed = false;
// Subscribe to notifications.
this._channel.on(this._internal.transportId, (event, data) =>
this._channel.on(this._internal.transportId, (event, data2) =>
{
switch (event)
{
......@@ -73,27 +73,27 @@ class Transport extends EventEmitter
case 'iceselectedtuplechange':
{
this._data.iceSelectedTuple = data.iceSelectedTuple;
this._data.iceSelectedTuple = data2.iceSelectedTuple;
// Emit it to the app.
this.emit(event, data.iceSelectedTuple);
this.emit(event, data2.iceSelectedTuple);
break;
}
case 'icestatechange':
{
this._data.iceState = data.iceState;
this._data.iceState = data2.iceState;
// Emit it to the app.
this.emit(event, data.iceState);
this.emit(event, data2.iceState);
break;
}
case 'dtlsstatechange':
{
this._data.dtlsState = data.dtlsState;
if (data.dtlsState === 'connected')
this._data.dtlsRemoteCert = data.dtlsRemoteCert;
this._data.dtlsState = data2.dtlsState;
if (data2.dtlsState === 'connected')
this._data.dtlsRemoteCert = data2.dtlsRemoteCert;
// Emit it to the app.
this.emit(event, data.dtlsState);
this.emit(event, data2.dtlsState);
break;
}
......@@ -185,9 +185,9 @@ class Transport extends EventEmitter
{
logger.debug('"transport.close" request succeeded');
})
.catch((error) =>
.catch((error2) =>
{
logger.error('"transport.close" request failed: %s', error);
logger.error('"transport.close" request failed: %s', error2);
});
}
......@@ -267,7 +267,7 @@ class Transport extends EventEmitter
if (this._closed)
return Promise.reject(new errors.InvalidStateError('Transport closed'));
let options = { bitrate };
const options = { bitrate };
// Send Channel request.
return this._channel.request('transport.setMaxBitrate', this._internal, options)
......
......@@ -41,10 +41,11 @@ class Worker extends EventEmitter
super();
this.setMaxListeners(Infinity);
let spawnArgs = [ id ].concat(parameters);
let spawnOptions =
const spawnArgs = [ id ].concat(parameters);
const spawnOptions =
{
detached : false,
/*
* fd 0 (stdin) : Just ignore it.
* fd 1 (stdout) : Pipe it for 3rd libraries in the worker.
......@@ -52,7 +53,7 @@ class Worker extends EventEmitter
* fd 2 (stderr) : Same as stdout.
* fd 3 (channel) : Channel fd.
*/
stdio : [ 'ignore', 'pipe', 'pipe', 'pipe' ]
stdio : [ 'ignore', 'pipe', 'pipe', 'pipe' ]
};
// Create the mediasoup-worker child process.
......@@ -67,7 +68,7 @@ class Worker extends EventEmitter
// Be ready for 3rd party worker libraries logging to stdout.
this._child.stdout.on('data', (buffer) =>
{
for (let line of buffer.toString('utf8').split('\n'))
for (const line of buffer.toString('utf8').split('\n'))
{
if (line)
logger.debug(`mediasoup-worker's stdout: ${line}`);
......@@ -77,10 +78,13 @@ class Worker extends EventEmitter
// In case of a worker bug, mediasoup will call abort() and log to stderr.
this._child.stderr.on('data', (buffer) =>
{
for (let line of buffer.toString('utf8').split('\n'))
for (const line of buffer.toString('utf8').split('\n'))
{
if (line)
{
// eslint-disable-next-line no-console
console.error(`mediasoup-worker's stderr: ${line}`);
}
}
});
......@@ -112,7 +116,7 @@ class Worker extends EventEmitter
logger.error('close() [error:%s]', error);
// Close every Room.
for (let room of this._rooms)
for (const room of this._rooms)
{
room.close(undefined, true);
}
......@@ -176,7 +180,7 @@ class Worker extends EventEmitter
{
logger.debug('createRoom() [options:%o]', options);
let internal =
const internal =
{
roomId : utils.randomNumber()
};
......@@ -187,7 +191,7 @@ class Worker extends EventEmitter
logger.debug('"worker.createRoom" request succeeded');
// Create a Room instance.
let room = new Room(internal, data, this._channel);
const room = new Room(internal, data, this._channel);
// Store the Room instance and remove it when closed.
this._rooms.add(room);
......
......@@ -2,7 +2,7 @@
function createErrorClass(name)
{
let klass = class extends Error
const klass = class extends Error
{
constructor(message)
{
......
......@@ -10,20 +10,22 @@ class Logger
{
if (prefix)
{
this._debug = debug(APP_NAME + ':' + prefix);
this._warn = debug(APP_NAME + ':WARN:' + prefix);
this._error = debug(APP_NAME + ':ERROR:' + prefix);
this._debug = debug(`${APP_NAME}:${prefix}`);
this._warn = debug(`${APP_NAME}:WARN:${prefix}`);
this._error = debug(`${APP_NAME}:ERROR:${prefix}`);
}
else
{
this._debug = debug(APP_NAME);
this._warn = debug(APP_NAME + ':WARN');
this._error = debug(APP_NAME + ':ERROR');
this._warn = debug(`${APP_NAME}:WARN`);
this._error = debug(`${APP_NAME}:ERROR`);
}
/* eslint-disable no-console */
this._debug.log = console.info.bind(console);
this._warn.log = console.warn.bind(console);
this._error.log = console.error.bind(console);
/* eslint-enable no-console */
}
get debug()
......
......@@ -9,7 +9,7 @@ const PKG = require('../package.json');
logger.debug('%s version %s', PKG.name, PKG.version);
// Set of Server instances.
let servers = new Set();
const servers = new Set();
module.exports =
{
......@@ -40,7 +40,7 @@ module.exports =
{
logger.debug('Server() [options:%o]', options);
let server = new Server(options);
const server = new Server(options);
// Store the Server instance and remove it when closed.
servers.add(server);
......@@ -52,18 +52,18 @@ module.exports =
/**
* Export mediasoup custom errors.
*/
errors: errors,
errors : errors,
/**
* Export the webrtc module.
*/
webrtc: webrtc
webrtc : webrtc
};
// On process exit close all the Servers.
process.on('exit', () =>
{
for (let server of servers)
for (const server of servers)
{
server.close();
}
......@@ -74,7 +74,15 @@ process.on('exit', () =>
process.on('unhandledRejection', (reason) =>
{
if (reason instanceof Error)
logger.error('"unhandledRejection" event due to a Promise being rejected with no error handler:\n%s', reason.stack);
{
logger.error(
'"unhandledRejection" event due to a Promise being rejected with no error handler:\n%s',
reason.stack);
}
else
logger.error('"unhandledRejection" event due to a Promise being rejected with no error handler [reason:%o]', reason);
{
logger.error(
'"unhandledRejection" event due to a Promise being rejected with no error handler [reason:%o]',
reason);
}
});
'use strict';
let supportedRtpCapabilities =
const supportedRtpCapabilities =
{
codecs :
[
......@@ -126,15 +126,15 @@ let supportedRtpCapabilities =
clockRate : 90000,
rtcpFeedback :
[
{ type: 'nack' }, // Locally consumed.
{ type: 'nack', parameter: 'pli' }, // Bypassed.
{ type: 'nack', parameter: 'sli' }, // Bypassed.
{ type: 'nack' }, // Locally consumed.
{ type: 'nack', parameter: 'pli' }, // Bypassed.
{ type: 'nack', parameter: 'sli' }, // Bypassed.
{ type: 'nack', parameter: 'rpsi' }, // Bypassed.
{ type: 'nack', parameter: 'app' }, // Bypassed.
{ type: 'ccm', parameter: 'fir' }, // Bypassed.
{ type: 'ack', parameter: 'rpsi' }, // Bypassed.
{ type: 'ack', parameter: 'app' }, // Bypassed.
{ type: 'goog-remb' } // Locally generated.
{ type: 'nack', parameter: 'app' }, // Bypassed.
{ type: 'ccm', parameter: 'fir' }, // Bypassed.
{ type: 'ack', parameter: 'rpsi' }, // Bypassed.
{ type: 'ack', parameter: 'app' }, // Bypassed.
{ type: 'goog-remb' } // Locally generated.
]
},
{
......@@ -143,57 +143,57 @@ let supportedRtpCapabilities =
clockRate : 90000,
rtcpFeedback :
[
{ type: 'nack' },
{ type: 'nack', parameter: 'pli' },
{ type: 'nack', parameter: 'sli' },
{ type: 'nack' },
{ type: 'nack', parameter: 'pli' },
{ type: 'nack', parameter: 'sli' },
{ type: 'nack', parameter: 'rpsi' },
{ type: 'nack', parameter: 'app' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'ack', parameter: 'rpsi' },
{ type: 'ack', parameter: 'app' },
{ type: 'goog-remb' }
{ type: 'nack', parameter: 'app' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'ack', parameter: 'rpsi' },
{ type: 'ack', parameter: 'app' },
{ type: 'goog-remb' }
]
},
{
kind : 'video',
name : 'video/H264',
clockRate : 90000,
parameters :
kind : 'video',
name : 'video/H264',
clockRate : 90000,
parameters :
{
packetizationMode : 0
},
rtcpFeedback :
[
{ type: 'nack' },
{ type: 'nack', parameter: 'pli' },
{ type: 'nack', parameter: 'sli' },
{ type: 'nack' },
{ type: 'nack', parameter: 'pli' },
{ type: 'nack', parameter: 'sli' },
{ type: 'nack', parameter: 'rpsi' },
{ type: 'nack', parameter: 'app' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'ack', parameter: 'rpsi' },
{ type: 'ack', parameter: 'app' },
{ type: 'goog-remb' }
{ type: 'nack', parameter: 'app' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'ack', parameter: 'rpsi' },
{ type: 'ack', parameter: 'app' },
{ type: 'goog-remb' }
]
},
{
kind : 'video',
name : 'video/H264',
clockRate : 90000,
parameters :
kind : 'video',
name : 'video/H264',
clockRate : 90000,
parameters :
{
packetizationMode : 1
},
rtcpFeedback :
[
{ type: 'nack' },
{ type: 'nack', parameter: 'pli' },
{ type: 'nack', parameter: 'sli' },
{ type: 'nack' },
{ type: 'nack', parameter: 'pli' },
{ type: 'nack', parameter: 'sli' },
{ type: 'nack', parameter: 'rpsi' },
{ type: 'nack', parameter: 'app' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'ack', parameter: 'rpsi' },
{ type: 'ack', parameter: 'app' },
{ type: 'goog-remb' }
{ type: 'nack', parameter: 'app' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'ack', parameter: 'rpsi' },
{ type: 'ack', parameter: 'app' },
{ type: 'goog-remb' }
]
},
{
......@@ -202,15 +202,15 @@ let supportedRtpCapabilities =
clockRate : 90000,
rtcpFeedback :
[
{ type: 'nack' },
{ type: 'nack', parameter: 'pli' },
{ type: 'nack', parameter: 'sli' },
{ type: 'nack' },
{ type: 'nack', parameter: 'pli' },
{ type: 'nack', parameter: 'sli' },
{ type: 'nack', parameter: 'rpsi' },
{ type: 'nack', parameter: 'app' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'ack', parameter: 'rpsi' },
{ type: 'ack', parameter: 'app' },
{ type: 'goog-remb' }
{ type: 'nack', parameter: 'app' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'ack', parameter: 'rpsi' },
{ type: 'ack', parameter: 'app' },
{ type: 'goog-remb' }
]
}
],
......
......@@ -13,28 +13,28 @@ const randomNumberGenerator = randomNumber.generator(
// In ORTC, codec parameters use camelCase but that provides zero benefit.
// Let keep them for backward compatibility.
const ORTC_TO_SDP_PARAMETERS = new Map([
const ORTC_TO_SDP_PARAMETERS = new Map([
// OPUS parameters.
// https://tools.ietf.org/html/draft-ietf-payload-rtp-opus
[ 'maxPlaybackRate', 'maxplaybackrate' ],
[ 'maxPlaybackRate', 'maxplaybackrate' ],
[ 'spropMaxCaptureRate', 'sprop-maxcapturerate' ],
[ 'maxAverageBitrate', 'maxaveragebitrate' ],
[ 'useInbandFec', 'useinbandfec' ],
[ 'useDtx', 'usedtx' ],
[ 'maxAverageBitrate', 'maxaveragebitrate' ],
[ 'useInbandFec', 'useinbandfec' ],
[ 'useDtx', 'usedtx' ],
// FLEXFEC parameters.
// https://tools.ietf.org/html/draft-ietf-payload-flexible-fec-scheme
[ 'l', 'L' ],
[ 'd', 'D' ],
[ 'toP', 'ToP' ]
[ 'l', 'L' ],
[ 'd', 'D' ],
[ 'toP', 'ToP' ]
]);
// Covert ORTC codec parameters to lowercase.
const ORTC_TO_SDP_PARAMETERS_LOWERCASE = new Map();
for (let pair of ORTC_TO_SDP_PARAMETERS)
for (const pair of ORTC_TO_SDP_PARAMETERS)
{
let key = pair[0];
let value = pair[1];
const key = pair[0];
const value = pair[1];
ORTC_TO_SDP_PARAMETERS_LOWERCASE.set(key.toLowerCase(), value);
}
......@@ -46,7 +46,7 @@ module.exports =
return randomatic('a', length || 8);
},
randomNumber: randomNumberGenerator,
randomNumber : randomNumberGenerator,
clone(obj)
{
......@@ -66,7 +66,7 @@ module.exports =
if (typeof param !== 'string' || !param)
throw new TypeError('wrong argument');
let wellKnownParam = ORTC_TO_SDP_PARAMETERS_LOWERCASE.get(param.toLowerCase());
const wellKnownParam = ORTC_TO_SDP_PARAMETERS_LOWERCASE.get(param.toLowerCase());
if (wellKnownParam)
return wellKnownParam;
......@@ -75,7 +75,7 @@ module.exports =
for (let i = 0, len = param.length; i < len; i++)
{
let c = param[i];
const c = param[i];
if (c === c.toLowerCase())
{
......
......@@ -164,7 +164,7 @@ class RTCPeerConnectionCommon extends EventEmitter
// First set peer's capabilities.
.then(() =>
{
let capabilities = sdpUtils.descToCapabilities(desc.parsed);
const capabilities = sdpUtils.descToCapabilities(desc.parsed);
return this._peer.setCapabilities(capabilities);
})
......@@ -249,7 +249,7 @@ class RTCPeerConnectionCommon extends EventEmitter
this._busy = false;
// Create an offer.
let localDescription = this._createLocalDescription('offer');
const localDescription = this._createLocalDescription('offer');
// Update flag.
this._initialOfferCreated = true;
......@@ -282,7 +282,7 @@ class RTCPeerConnectionCommon extends EventEmitter
}
// Create an answer.
let localDescription = this._createLocalDescription('answer');
const localDescription = this._createLocalDescription('answer');
// Resolve with it.
return Promise.resolve(localDescription);
......@@ -302,7 +302,7 @@ class RTCPeerConnectionCommon extends EventEmitter
if (!this._peer.capabilities)
return Promise.reject(new InvalidStateError('capabilities not yet set'));
let remoteDescription = desc;
const remoteDescription = desc;
let newSignalingState;
switch (remoteDescription.type)
......@@ -491,7 +491,7 @@ class RTCPeerConnectionCommon extends EventEmitter
if (this.closed)
return Promise.reject(new InvalidStateError('closed'));
let transport = this._peer.transports[0];
const transport = this._peer.transports[0];
return Promise.resolve()
// First change ufrag/pwd of the Transport.
......
......@@ -115,9 +115,9 @@ class RTCRtpTransceiver
toObjectMedia(type)
{
let transport = this._transport;
let capabilities = this._capabilities;
let objMedia = {};
const transport = this._transport;
const capabilities = this._capabilities;
const objMedia = {};
let closed = this.closed;
// m= line.
......@@ -146,9 +146,9 @@ class RTCRtpTransceiver
{
objMedia.candidates = [];
for (let candidate of transport.iceLocalCandidates)
for (const candidate of transport.iceLocalCandidates)
{
let objCandidate = {};
const objCandidate = {};
// mediasoup does not support non rtcp-mux so candidates component is
// always RTP (1).
......@@ -190,7 +190,7 @@ class RTCRtpTransceiver
objMedia.fmtp = [];
// Array of payload types.
let payloads = [];
const payloads = [];
// Codecs.
let codecs;
......@@ -201,15 +201,15 @@ class RTCRtpTransceiver
else
codecs = capabilities.codecs;
for (let codec of codecs)
for (const codec of codecs)
{
if (codec.kind && codec.kind !== this._kind)
continue;
payloads.push(codec.payloadType);
let codecSubtype = codec.name.split('/')[1];
let rtp =
const codecSubtype = codec.name.split('/')[1];
const rtp =
{
payload : codec.payloadType,
codec : codecSubtype,
......@@ -224,15 +224,15 @@ class RTCRtpTransceiver
// If codec has parameters add them into a=fmtp attributes.
if (codec.parameters)
{
let paramFmtp =
const paramFmtp =
{
payload : codec.payloadType,
config : ''
};
for (let key of Object.keys(codec.parameters))
for (const key of Object.keys(codec.parameters))
{
let normalizedKey = utils.paramToSDP(key);
const normalizedKey = utils.paramToSDP(key);
if (paramFmtp.config)
paramFmtp.config += ';';
......@@ -246,7 +246,7 @@ class RTCRtpTransceiver
// Set RTCP feedback.
if (codec.rtcpFeedback)
{
for (let fb of codec.rtcpFeedback)
for (const fb of codec.rtcpFeedback)
{
objMedia.rtcpFb.push(
{
......@@ -284,7 +284,7 @@ class RTCRtpTransceiver
if (this._sender.rtpParameters.userParameters.msid)
objMedia.msid = this._sender.rtpParameters.userParameters.msid;
for (let encoding of this._sender.rtpParameters.encodings)
for (const encoding of this._sender.rtpParameters.encodings)
{
objMedia.ssrcs.push(
{
......@@ -307,7 +307,7 @@ class RTCRtpTransceiver
objMedia.ssrcGroups.push(
{
semantics : 'FID',
ssrcs : [encoding.ssrc, encoding.rtx.ssrc].join(' ')
ssrcs : [ encoding.ssrc, encoding.rtx.ssrc ].join(' ')
});
}
}
......@@ -321,7 +321,7 @@ class RTCRtpTransceiver
// If a RtpSender, take the header extensions from it.
if (this._sender)
{
for (let headerExtension of this._sender.rtpParameters.headerExtensions)
for (const headerExtension of this._sender.rtpParameters.headerExtensions)
{
objMedia.ext.push(
{
......@@ -333,7 +333,7 @@ class RTCRtpTransceiver
// Otherwise take them from peer's capabilities.
else
{
for (let headerExtension of capabilities.headerExtensions)
for (const headerExtension of capabilities.headerExtensions)
{
if (headerExtension.kind && headerExtension.kind !== this._kind)
continue;
......
......@@ -7,16 +7,16 @@ module.exports =
descToCapabilities(parsed)
{
// Map of RtpCodecParameters indexed by payload type.
let mapCodecs = new Map();
const mapCodecs = new Map();
// RtpHeaderExtensions.
let headerExtensions = [];
const headerExtensions = [];
for (let parsedMedia of parsed.media)
for (const parsedMedia of parsed.media)
{
// Media kind.
let kind = parsedMedia.type;
const kind = parsedMedia.type;
for (let rtp of parsedMedia.rtp)
for (const rtp of parsedMedia.rtp)
{
// Ignore feature codecs.
switch (rtp.codec.toLowerCase())
......@@ -29,8 +29,8 @@ module.exports =
}
// TODO: This will fail for kind:depth and video/vp8, but who knows?
let codecMime = kind + '/' + rtp.codec;
let codec =
const codecMime = `${kind}/${rtp.codec}`;
const codec =
{
kind : kind,
name : codecMime,
......@@ -48,10 +48,10 @@ module.exports =
if (parsedMedia.fmtp)
{
for (let fmtp of parsedMedia.fmtp)
for (const fmtp of parsedMedia.fmtp)
{
let params = sdpTransform.parseFmtpConfig(fmtp.config);
let codec = mapCodecs.get(fmtp.payload);
const params = sdpTransform.parseFmtpConfig(fmtp.config);
const codec = mapCodecs.get(fmtp.payload);
if (!codec)
continue;
......@@ -62,9 +62,9 @@ module.exports =
if (parsedMedia.rtcpFb)
{
for (let fb of parsedMedia.rtcpFb)
for (const fb of parsedMedia.rtcpFb)
{
let codec = mapCodecs.get(fb.payload);
const codec = mapCodecs.get(fb.payload);
if (!codec)
continue;
......@@ -79,11 +79,11 @@ module.exports =
if (Array.isArray(parsedMedia.ext))
{
for (let ext of parsedMedia.ext)
for (const ext of parsedMedia.ext)
{
let preferredId = ext.value;
let uri = ext.uri;
let headerExtension =
const preferredId = ext.value;
const uri = ext.uri;
const headerExtension =
{
kind : kind,
uri : uri,
......@@ -95,7 +95,7 @@ module.exports =
for (let i=0, len=headerExtensions.length; i<len; i++)
{
let savedHeaderExtension = headerExtensions[i];
const savedHeaderExtension = headerExtensions[i];
if (
headerExtension.kind === savedHeaderExtension.kind &&
......@@ -112,11 +112,11 @@ module.exports =
}
}
let capabilities =
const capabilities =
{
codecs : Array.from(mapCodecs.values()),
headerExtensions : headerExtensions,
fecMechanisms : [] // TODO
fecMechanisms : [] // TODO
};
return capabilities;
......@@ -127,7 +127,7 @@ module.exports =
let media;
// If the first media (i.e. audio) is inactive, it has no DTLS stuff so iterate.
for (let m of parsed.media)
for (const m of parsed.media)
{
if (m.setup)
{
......@@ -140,7 +140,7 @@ module.exports =
return null;
// NOTE: Firefox uses global fingerprint attribute.
let remoteFingerprint = media.fingerprint || parsed.fingerprint;
const remoteFingerprint = media.fingerprint || parsed.fingerprint;
let remoteDtlsRole;
switch (media.setup)
......@@ -153,7 +153,7 @@ module.exports =
break;
}
let remoteDtlsParameters =
const remoteDtlsParameters =
{
role : remoteDtlsRole,
fingerprint :
......@@ -168,15 +168,15 @@ module.exports =
descToRtpHeaderExtensionParameters(parsedMedia)
{
let headerExtensions = [];
const headerExtensions = [];
if (!Array.isArray(parsedMedia.ext))
return headerExtensions;
for (let ext of parsedMedia.ext)
for (const ext of parsedMedia.ext)
{
let id = ext.value;
let uri = ext.uri;
const id = ext.value;
const uri = ext.uri;
headerExtensions.push(
{
......@@ -193,27 +193,28 @@ module.exports =
*/
getPlanBSsrcs(parsedMedia)
{
let singleSsrcs = new Set();
let simulcastSsrcs = new Set();
let rtxSsrcs = new Set();
let ssrcs = [];
const singleSsrcs = new Set();
const simulcastSsrcs = new Set();
const rtxSsrcs = new Set();
const ssrcs = [];
// Simulcast/RTX.
if (Array.isArray(parsedMedia.ssrcGroups))
{
for (let group of parsedMedia.ssrcGroups)
for (const group of parsedMedia.ssrcGroups)
{
switch (group.semantics)
{
case 'SIM':
{
let simulcast = [];
const simulcast = [];
for (let ssrc of group.ssrcs.split(' '))
for (const ssrc of group.ssrcs.split(' '))
{
ssrc = Number(ssrc);
simulcastSsrcs.add(ssrc);
simulcast.push(ssrc);
const ssrc2 = Number(ssrc);
simulcastSsrcs.add(ssrc2);
simulcast.push(ssrc2);
}
ssrcs.push(simulcast);
......@@ -223,13 +224,14 @@ module.exports =
case 'FID':
{
let rtx = [];
const rtx = [];
for (let ssrc of group.ssrcs.split(' '))
for (const ssrc of group.ssrcs.split(' '))
{
ssrc = Number(ssrc);
rtxSsrcs.add(ssrc);
rtx.push(ssrc);
const ssrc2 = Number(ssrc);
rtxSsrcs.add(ssrc2);
rtx.push(ssrc2);
}
ssrcs.push(rtx);
......@@ -243,9 +245,9 @@ module.exports =
// Single streams.
if (Array.isArray(parsedMedia.ssrcs))
{
for (let ssrcObj of parsedMedia.ssrcs)
for (const ssrcObj of parsedMedia.ssrcs)
{
let ssrc = ssrcObj.id;
const ssrc = ssrcObj.id;
if (simulcastSsrcs.has(ssrc) || singleSsrcs.has(ssrc) || rtxSsrcs.has(ssrc))
continue;
......@@ -260,7 +262,7 @@ module.exports =
getPlanBTrackInfo(parsedMedia, ssrc)
{
let info =
const info =
{
cname : null,
msid : null,
......@@ -274,7 +276,7 @@ module.exports =
if (Array.isArray(ssrc))
ssrc = ssrc[0];
for (let ssrcObj of parsedMedia.ssrcs)
for (const ssrcObj of parsedMedia.ssrcs)
{
if (ssrcObj.id !== ssrc)
continue;
......
......@@ -12,7 +12,7 @@ class RTCSessionDescription
*/
constructor(descriptionInitDict)
{
let type = descriptionInitDict.type;
const type = descriptionInitDict.type;
switch (type)
{
......
差异被折叠。
{
"name": "mediasoup",
"version": "1.2.8",
"version": "2.0.0-alpha",
"description": "Cutting Edge WebRTC Video Conferencing",
"author": "Iñaki Baz Castillo <ibc@aliax.net> (https://inakibaz.me)",
"contributors": [
......@@ -30,15 +30,16 @@
},
"main": "lib/mediasoup.js",
"dependencies": {
"check-types": "^7.2.0",
"check-types": "^7.3.0",
"clone": "^2.1.1",
"debug": "^2.6.8",
"debug": "^3.0.0",
"netstring": "^0.3.0",
"random-number": "0.0.7",
"random-number": "0.0.9",
"randomatic": "^1.1.7",
"sdp-transform": "^2.3.0"
},
"devDependencies": {
"eslint": "^4.5.0",
"gulp": "github:gulpjs/gulp#4.0",
"gulp-clang-format": "^1.0.23",
"gulp-eslint": "^4.0.0",
......@@ -46,7 +47,7 @@
"gulp-replace": "^0.6.1",
"gulp-shell": "^0.6.3",
"gulp-touch-cmd": "0.0.1",
"tap": "^10.7.0"
"tap": "^10.7.2"
},
"optionalDependencies": {
"clang-tools-prebuilt": "^0.1.4"
......
......@@ -26,11 +26,11 @@ module.exports =
clockRate : 90000
},
{
kind : 'video',
name : 'video/h264',
clockRate : 90000,
kind : 'video',
name : 'video/h264',
clockRate : 90000,
payloadType : 112,
parameters :
parameters :
{
packetizationMode : 1
}
......@@ -68,14 +68,14 @@ module.exports =
clockRate : 90000,
rtcpFeedback :
[
{ type: 'nack' },
{ type: 'nack', parameter: 'pli' },
{ type: 'nack', parameter: 'sli' },
{ type: 'nack' },
{ type: 'nack', parameter: 'pli' },
{ type: 'nack', parameter: 'sli' },
{ type: 'nack', parameter: 'rpsi' },
{ type: 'nack', parameter: 'app' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'ack', parameter: 'rpsi' },
{ type: 'ack', parameter: 'app' }
{ type: 'nack', parameter: 'app' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'ack', parameter: 'rpsi' },
{ type: 'ack', parameter: 'app' }
]
},
{
......@@ -83,30 +83,30 @@ module.exports =
name : 'video/rtx',
payloadType : 97,
clockRate : 90000,
parameters :
parameters :
{
apt : 110
}
},
{
kind : 'video',
name : 'video/H264',
payloadType : 111,
clockRate : 90000,
parameters :
kind : 'video',
name : 'video/H264',
payloadType : 111,
clockRate : 90000,
parameters :
{
packetizationMode : 0
},
rtcpFeedback :
[
{ type: 'nack' },
{ type: 'nack', parameter: 'pli' },
{ type: 'nack', parameter: 'sli' },
{ type: 'nack' },
{ type: 'nack', parameter: 'pli' },
{ type: 'nack', parameter: 'sli' },
{ type: 'nack', parameter: 'rpsi' },
{ type: 'nack', parameter: 'app' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'ack', parameter: 'rpsi' },
{ type: 'ack', parameter: 'app' }
{ type: 'nack', parameter: 'app' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'ack', parameter: 'rpsi' },
{ type: 'ack', parameter: 'app' }
]
},
{
......@@ -120,24 +120,24 @@ module.exports =
}
},
{
kind : 'video',
name : 'video/H264',
payloadType : 112,
clockRate : 90000,
parameters :
kind : 'video',
name : 'video/H264',
payloadType : 112,
clockRate : 90000,
parameters :
{
packetizationMode : 1
},
rtcpFeedback :
[
{ type: 'nack' },
{ type: 'nack', parameter: 'pli' },
{ type: 'nack', parameter: 'sli' },
{ type: 'nack' },
{ type: 'nack', parameter: 'pli' },
{ type: 'nack', parameter: 'sli' },
{ type: 'nack', parameter: 'rpsi' },
{ type: 'nack', parameter: 'app' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'ack', parameter: 'rpsi' },
{ type: 'ack', parameter: 'app' }
{ type: 'nack', parameter: 'app' },
{ type: 'ccm', parameter: 'fir' },
{ type: 'ack', parameter: 'rpsi' },
{ type: 'ack', parameter: 'app' }
]
},
{
......
......@@ -7,7 +7,7 @@ const peerCapabilities = require('./data/options').peerCapabilities;
function initTest(t)
{
let server = mediasoup.Server();
const server = mediasoup.Server();
let peer;
t.tearDown(() => server.close());
......@@ -30,7 +30,7 @@ tap.test('peer.createTransport() with no options must succeed', { timeout: 2000
return initTest(t)
.then((data) =>
{
let peer = data.peer;
const peer = data.peer;
t.equal(peer.name, 'alice', 'peer.name must be "alice"');
......@@ -40,10 +40,10 @@ tap.test('peer.createTransport() with no options must succeed', { timeout: 2000
t.pass('peer.createTransport() succeeded');
return peer.dump()
.then((data) =>
.then((data2) =>
{
t.pass('peer.dump() succeeded');
t.equal(Object.keys(data.transports).length, 1, 'peer.dump() must retrieve one transport');
t.equal(Object.keys(data2.transports).length, 1, 'peer.dump() must retrieve one transport');
t.end();
})
.catch((error) => t.fail(`peer.dump() failed: ${error}`));
......@@ -56,7 +56,7 @@ tap.test('peer.createTransport() with no udp nor tcp must fail', { timeout: 2000
return initTest(t)
.then((data) =>
{
let peer = data.peer;
const peer = data.peer;
return peer.createTransport({ udp: false, tcp: false })
.then(() => t.fail('peer.createTransport() succeeded'))
......@@ -72,7 +72,7 @@ tap.test('peer.RtpReceiver() with valid transport must succeed', { timeout: 2000
return initTest(t)
.then((data) =>
{
let peer = data.peer;
const peer = data.peer;
let rtpReceiver;
return peer.createTransport({ tcp: false })
......@@ -87,10 +87,10 @@ tap.test('peer.RtpReceiver() with valid transport must succeed', { timeout: 2000
return peer.dump();
})
.then((data) =>
.then((data2) =>
{
t.pass('peer.dump() succeeded');
t.equal(Object.keys(data.rtpReceivers).length, 1, 'peer.dump() must retrieve one rtpReceiver');
t.equal(Object.keys(data2.rtpReceivers).length, 1, 'peer.dump() must retrieve one rtpReceiver');
t.same(peer.rtpReceivers[0], rtpReceiver, 'peer.rtpReceivers[0] must retrieve the previous rtpReceiver');
});
});
......@@ -101,7 +101,7 @@ tap.test('peer.RtpReceiver() with a closed transport must fail', { timeout: 2000
return initTest(t)
.then((data) =>
{
let peer = data.peer;
const peer = data.peer;
return peer.createTransport({ tcp: false })
.then((transport) =>
......@@ -125,7 +125,7 @@ tap.test('peer.RtpReceiver() with invalid kind must fail', { timeout: 2000 }, (t
return initTest(t)
.then((data) =>
{
let peer = data.peer;
const peer = data.peer;
return peer.createTransport({ tcp: false })
.then((transport) =>
......
......@@ -7,14 +7,14 @@ const peerOptions = require('./data/options').peerOptions;
tap.test('room.Peer() with peerName must succeed', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server();
const server = mediasoup.Server();
t.tearDown(() => server.close());
server.createRoom(roomOptions)
.then((room) =>
{
let peer = room.Peer('alice', peerOptions);
const peer = room.Peer('alice', peerOptions);
peer.on('close', (error) =>
{
......@@ -30,7 +30,7 @@ tap.test('room.Peer() with peerName must succeed', { timeout: 2000 }, (t) =>
tap.test('room.Peer() without peerName must fail', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server();
const server = mediasoup.Server();
t.tearDown(() => server.close());
......@@ -51,7 +51,7 @@ tap.test('room.Peer() without peerName must fail', { timeout: 2000 }, (t) =>
tap.test('room.Peer() with same peerName must fail', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server();
const server = mediasoup.Server();
t.tearDown(() => server.close());
......@@ -73,14 +73,14 @@ tap.test('room.Peer() with same peerName must fail', { timeout: 2000 }, (t) =>
tap.test('room.Peer() with same peerName must succeed if previous peer was closed before', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server();
const server = mediasoup.Server();
t.tearDown(() => server.close());
server.createRoom(roomOptions)
.then((room) =>
{
let peer1 = room.Peer('alice', peerOptions);
const peer1 = room.Peer('alice', peerOptions);
t.equal(room.getPeer('alice'), peer1, 'room.getPeer() must retrieve the first "alice"');
t.equal(room.peers.length, 1, 'room.peers must retrieve one peer');
......@@ -90,7 +90,7 @@ tap.test('room.Peer() with same peerName must succeed if previous peer was close
t.notOk(room.getPeer('alice'), 'room.getPeer() must retrieve nothing');
t.equal(room.peers.length, 0, 'room.peers must retrieve zero peers');
let peer2 = room.Peer('alice', peerOptions);
const peer2 = room.Peer('alice', peerOptions);
t.equal(room.getPeer('alice'), peer2, 'room.getPeer() must retrieve the new "alice"');
t.equal(room.peers.length, 1, 'room.peers must retrieve one peer');
......@@ -109,16 +109,16 @@ tap.test('room.Peer() with same peerName must succeed if previous peer was close
tap.test('room.peers must retrieve existing peers', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server();
const server = mediasoup.Server();
t.tearDown(() => server.close());
server.createRoom(roomOptions)
.then((room) =>
{
let alice = room.Peer('alice', peerOptions);
let bob = room.Peer('bob', peerOptions);
let carol = room.Peer('carol', peerOptions);
const alice = room.Peer('alice', peerOptions);
const bob = room.Peer('bob', peerOptions);
const carol = room.Peer('carol', peerOptions);
bob.close();
......@@ -131,7 +131,7 @@ tap.test('room.peers must retrieve existing peers', { timeout: 2000 }, (t) =>
tap.test('room.getCapabilities() must retrieve current room capabilities', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server();
const server = mediasoup.Server();
t.tearDown(() => server.close());
......@@ -148,7 +148,7 @@ tap.test('room.getCapabilities() must retrieve current room capabilities', { tim
tap.test('room.dump() must succeed', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server();
const server = mediasoup.Server();
t.tearDown(() => server.close());
......
差异被折叠。
......@@ -6,7 +6,7 @@ const roomOptions = require('./data/options').roomOptions;
tap.test('server.updateSettings() with no options must succeed', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server();
const server = mediasoup.Server();
t.tearDown(() => server.close());
......@@ -21,7 +21,7 @@ tap.test('server.updateSettings() with no options must succeed', { timeout: 2000
tap.test('server.updateSettings() with valid options must succeed', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server();
const server = mediasoup.Server();
t.tearDown(() => server.close());
......@@ -36,7 +36,7 @@ tap.test('server.updateSettings() with valid options must succeed', { timeout: 2
tap.test('server.updateSettings() with invalid options must fail', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server();
const server = mediasoup.Server();
t.tearDown(() => server.close());
......@@ -51,7 +51,7 @@ tap.test('server.updateSettings() with invalid options must fail', { timeout: 20
tap.test('server.updateSettings() in a closed server must fail', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server();
const server = mediasoup.Server();
t.tearDown(() => server.close());
......@@ -72,7 +72,7 @@ tap.test('server.updateSettings() in a closed server must fail', { timeout: 2000
tap.test('server.createRoom() must succeed', { _timeout: 2000 }, (t) =>
{
let server = mediasoup.Server();
const server = mediasoup.Server();
t.tearDown(() => server.close());
......@@ -95,7 +95,7 @@ tap.test('server.createRoom() must succeed', { _timeout: 2000 }, (t) =>
tap.test('server.createRoom() in a closed server must fail', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server();
const server = mediasoup.Server();
server.close();
......@@ -111,7 +111,7 @@ tap.test('server.createRoom() in a closed server must fail', { timeout: 2000 },
tap.test('server.dump() must succeed', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server({ numWorkers: 2 });
const server = mediasoup.Server({ numWorkers: 2 });
t.tearDown(() => server.close());
......
......@@ -6,7 +6,7 @@ const roomOptions = require('./data/options').roomOptions;
function initTest(t)
{
let server = mediasoup.Server();
const server = mediasoup.Server();
let peer;
t.tearDown(() => server.close());
......@@ -29,7 +29,7 @@ tap.test('transport.setRemoteDtlsParameters() with "server" role must succeed',
return initTest(t)
.then((data) =>
{
let transport = data.transport;
const transport = data.transport;
t.equal(transport.dtlsLocalParameters.role, 'auto', 'default local DTLS role must be "auto"');
......@@ -49,10 +49,10 @@ tap.test('transport.setRemoteDtlsParameters() with "server" role must succeed',
return transport.dump();
})
.then((data) =>
.then((data2) =>
{
t.pass('transport.dump() succeeded');
t.equal(data.dtlsLocalParameters.role, 'client', 'local DTLS role must be "client"');
t.equal(data2.dtlsLocalParameters.role, 'client', 'local DTLS role must be "client"');
});
});
});
......@@ -62,7 +62,7 @@ tap.test('transport.setRemoteDtlsParameters() with "auto" role must succeed', {
return initTest(t)
.then((data) =>
{
let transport = data.transport;
const transport = data.transport;
return transport.setRemoteDtlsParameters(
{
......@@ -80,10 +80,10 @@ tap.test('transport.setRemoteDtlsParameters() with "auto" role must succeed', {
return transport.dump();
})
.then((data) =>
.then((data2) =>
{
t.pass('transport.dump() succeeded');
t.equal(data.dtlsLocalParameters.role, 'client', 'local DTLS role must be "client"');
t.equal(data2.dtlsLocalParameters.role, 'client', 'local DTLS role must be "client"');
});
});
});
......@@ -93,7 +93,7 @@ tap.test('transport.setRemoteDtlsParameters() with no role must succeed', { time
return initTest(t)
.then((data) =>
{
let transport = data.transport;
const transport = data.transport;
return transport.setRemoteDtlsParameters(
{
......@@ -110,10 +110,10 @@ tap.test('transport.setRemoteDtlsParameters() with no role must succeed', { time
return transport.dump();
})
.then((data) =>
.then((data2) =>
{
t.pass('transport.dump() succeeded');
t.equal(data.dtlsLocalParameters.role, 'client', 'local DTLS role must be "client"');
t.equal(data2.dtlsLocalParameters.role, 'client', 'local DTLS role must be "client"');
});
});
});
......@@ -123,7 +123,7 @@ tap.test('transport.setRemoteDtlsParameters() with invalid role must fail', { ti
return initTest(t)
.then((data) =>
{
let transport = data.transport;
const transport = data.transport;
return transport.setRemoteDtlsParameters(
{
......@@ -148,7 +148,7 @@ tap.test('transport.setRemoteDtlsParameters() without fingerprint must fail', {
return initTest(t)
.then((data) =>
{
let transport = data.transport;
const transport = data.transport;
return transport.setRemoteDtlsParameters(
{
......@@ -165,7 +165,7 @@ tap.test('transport.setRemoteDtlsParameters() without fingerprint must fail', {
tap.test('transport.close() must succeed', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server();
const server = mediasoup.Server();
t.plan(6);
t.tearDown(() => server.close());
......@@ -173,7 +173,7 @@ tap.test('transport.close() must succeed', { timeout: 2000 }, (t) =>
server.createRoom(roomOptions)
.then((room) =>
{
let peer = room.Peer('alice');
const peer = room.Peer('alice');
peer.createTransport({ tcp: false })
.then((transport) =>
......@@ -192,7 +192,7 @@ tap.test('transport.close() must succeed', { timeout: 2000 }, (t) =>
t.pass('peer.dump() succeeded');
t.equal(Object.keys(data.transports).length, 0, 'peer.dump() must retrieve zero transports');
})
.catch((error) => t.fail(`peer.dump() failed: ${error}`));
.catch((error2) => t.fail(`peer.dump() failed: ${error2}`));
});
setTimeout(() => transport.close(), 100);
......@@ -203,7 +203,7 @@ tap.test('transport.close() must succeed', { timeout: 2000 }, (t) =>
tap.test('create transport in a server with rtcAnnouncedIPv4', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server(
const server = mediasoup.Server(
{
rtcIPv4 : true,
rtcIPv6 : false,
......@@ -224,8 +224,8 @@ tap.test('create transport in a server with rtcAnnouncedIPv4', { timeout: 2000 }
})
.then((transport) =>
{
let candidates = transport.iceLocalCandidates;
let candidate = candidates[0];
const candidates = transport.iceLocalCandidates;
const candidate = candidates[0];
t.equal(candidates.length, 1, 'transport has 1 ICE local candidate');
t.equal(candidate.protocol, 'udp', 'candidate.protocol must be udp');
......@@ -238,8 +238,8 @@ tap.test('create transport in a server with rtcAnnouncedIPv4', { timeout: 2000 }
})
.then((transport) =>
{
let candidates = transport.iceLocalCandidates;
let candidate = candidates[0];
const candidates = transport.iceLocalCandidates;
const candidate = candidates[0];
t.equal(candidates.length, 1, 'transport has 1 ICE local candidate');
t.equal(candidate.protocol, 'tcp', 'candidate.protocol must be tcp');
......
......@@ -6,7 +6,7 @@ const mediasoup = require('../');
tap.test('mediasoup.Server() with no options must succeed', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server();
const server = mediasoup.Server();
server.on('close', (error) =>
{
......@@ -19,7 +19,7 @@ tap.test('mediasoup.Server() with no options must succeed', { timeout: 2000 }, (
tap.test('mediasoup.Server() with valid options must succeed', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server(
const server = mediasoup.Server(
{
numWorkers : 1,
logLevel : 'warn'
......@@ -36,7 +36,7 @@ tap.test('mediasoup.Server() with valid options must succeed', { timeout: 2000 }
tap.test('mediasoup.Server() with valid DTLS certificate must succeed', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server(
const server = mediasoup.Server(
{
numWorkers : 1,
dtlsCertificateFile : path.join(__dirname, 'data', 'dtls-cert.pem'),
......@@ -54,7 +54,7 @@ tap.test('mediasoup.Server() with valid DTLS certificate must succeed', { timeou
tap.test('mediasoup.Server() with wrong options must fail', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server({ logLevel: 'WRONG_VALUE' });
const server = mediasoup.Server({ logLevel: 'WRONG_VALUE' });
server.on('close', (error) =>
{
......@@ -65,7 +65,7 @@ tap.test('mediasoup.Server() with wrong options must fail', { timeout: 2000 }, (
tap.test('mediasoup.Server() with non existing rtcIPv4 IP must fail', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server({ rtcIPv4: '1.2.3.4' });
const server = mediasoup.Server({ rtcIPv4: '1.2.3.4' });
server.on('close', (error) =>
{
......@@ -76,7 +76,7 @@ tap.test('mediasoup.Server() with non existing rtcIPv4 IP must fail', { timeout:
tap.test('mediasoup.Server() with too narrow RTC ports range must fail', { timeout: 2000 }, (t) =>
{
let server = mediasoup.Server({ rtcMinPort: 2000, rtcMaxPort: 2050 });
const server = mediasoup.Server({ rtcMinPort: 2000, rtcMaxPort: 2050 });
server.on('close', (error) =>
{
......
差异被折叠。
......@@ -5,14 +5,14 @@ module.exports = function(funcs)
return new Promise((resolve, reject) =>
{
let i = 0;
let len = funcs.length;
const len = funcs.length;
function next()
{
if (i >= len)
return resolve();
let func = funcs[i];
const func = funcs[i];
func()
.then(() =>
......
......@@ -2,6 +2,9 @@
Please do not submit pull requests changing the `version.hpp`
or the single-include `catch.hpp` file, these are changed
only when a new release is made.
Before submitting a PR you should probably read the contributor documentation
at docs/contributing.md. It will tell you how to properly test your changes.
-->
......
......@@ -11,25 +11,25 @@ matrix:
apt:
sources: ['llvm-toolchain-precise', 'ubuntu-toolchain-r-test']
packages: ['clang']
env: COMPILER='clang++' BUILD_TYPE='Release' CPP11=0
env: COMPILER='clang++' BUILD_TYPE='Release'
- os: linux
compiler: clang
addons: *clang34
env: COMPILER='clang++' BUILD_TYPE='Debug' CPP11=0
env: COMPILER='clang++' BUILD_TYPE='Debug'
- os: linux
compiler: clang
addons: &clang35
apt:
sources: ['llvm-toolchain-precise-3.5', 'ubuntu-toolchain-r-test']
packages: ['clang-3.5']
env: COMPILER='clang++-3.5' BUILD_TYPE='Release' CPP11=0
env: COMPILER='clang++-3.5' BUILD_TYPE='Release'
- os: linux
compiler: clang
addons: *clang35
env: COMPILER='clang++-3.5' BUILD_TYPE='Debug' CPP11=0
env: COMPILER='clang++-3.5' BUILD_TYPE='Debug'
- os: linux
......@@ -38,12 +38,12 @@ matrix:
apt:
sources: ['llvm-toolchain-precise-3.6', 'ubuntu-toolchain-r-test']
packages: ['clang-3.6']
env: COMPILER='clang++-3.6' BUILD_TYPE='Release' CPP11=0
env: COMPILER='clang++-3.6' BUILD_TYPE='Release'
- os: linux
compiler: clang
addons: *clang36
env: COMPILER='clang++-3.6' BUILD_TYPE='Debug' CPP11=0
env: COMPILER='clang++-3.6' BUILD_TYPE='Debug'
- os: linux
......@@ -52,12 +52,12 @@ matrix:
apt:
sources: ['llvm-toolchain-precise-3.7', 'ubuntu-toolchain-r-test']
packages: ['clang-3.7']
env: COMPILER='clang++-3.7' BUILD_TYPE='Release' CPP11=0
env: COMPILER='clang++-3.7' BUILD_TYPE='Release'
- os: linux
compiler: clang
addons: *clang37
env: COMPILER='clang++-3.7' BUILD_TYPE='Debug' CPP11=0
env: COMPILER='clang++-3.7' BUILD_TYPE='Debug'
- os: linux
......@@ -66,12 +66,12 @@ matrix:
apt:
sources: ['llvm-toolchain-precise-3.8', 'ubuntu-toolchain-r-test']
packages: ['clang-3.8']
env: COMPILER='clang++-3.8' BUILD_TYPE='Release' CPP11=0
env: COMPILER='clang++-3.8' BUILD_TYPE='Release'
- os: linux
compiler: clang
addons: *clang38
env: COMPILER='clang++-3.8' BUILD_TYPE='Debug' CPP11=0
env: COMPILER='clang++-3.8' BUILD_TYPE='Debug'
# 2/ Linux GCC Builds
......@@ -81,12 +81,12 @@ matrix:
apt:
sources: ['ubuntu-toolchain-r-test']
packages: ['g++-4.4']
env: COMPILER='g++-4.4' BUILD_TYPE='Release' CPP11=0
env: COMPILER='g++-4.4' BUILD_TYPE='Release'
- os: linux
compiler: gcc
addons: *gcc44
env: COMPILER='g++-4.4' BUILD_TYPE='Debug' CPP11=0
env: COMPILER='g++-4.4' BUILD_TYPE='Debug'
- os: linux
......@@ -95,12 +95,12 @@ matrix:
apt:
sources: ['ubuntu-toolchain-r-test']
packages: ['g++-4.7']
env: COMPILER='g++-4.7' BUILD_TYPE='Release' CPP11=0
env: COMPILER='g++-4.7' BUILD_TYPE='Release'
- os: linux
compiler: gcc
addons: *gcc47
env: COMPILER='g++-4.7' BUILD_TYPE='Debug' CPP11=0
env: COMPILER='g++-4.7' BUILD_TYPE='Debug'
- os: linux
......@@ -109,12 +109,12 @@ matrix:
apt:
sources: ['ubuntu-toolchain-r-test']
packages: ['g++-4.8']
env: COMPILER='g++-4.8' BUILD_TYPE='Release' CPP11=0
env: COMPILER='g++-4.8' BUILD_TYPE='Release'
- os: linux
compiler: gcc
addons: *gcc48
env: COMPILER='g++-4.8' BUILD_TYPE='Debug' CPP11=0
env: COMPILER='g++-4.8' BUILD_TYPE='Debug'
- os: linux
......@@ -123,12 +123,12 @@ matrix:
apt:
sources: ['ubuntu-toolchain-r-test']
packages: ['g++-4.9']
env: COMPILER='g++-4.9' BUILD_TYPE='Release' CPP11=0
env: COMPILER='g++-4.9' BUILD_TYPE='Release'
- os: linux
compiler: gcc
addons: *gcc49
env: COMPILER='g++-4.9' BUILD_TYPE='Debug' CPP11=0
env: COMPILER='g++-4.9' BUILD_TYPE='Debug'
- os: linux
......@@ -137,12 +137,12 @@ matrix:
apt:
sources: ['ubuntu-toolchain-r-test']
packages: ['g++-5']
env: COMPILER='g++-5' BUILD_TYPE='Release' CPP11=0
env: COMPILER='g++-5' BUILD_TYPE='Release'
- os: linux
compiler: gcc
addons: *gcc5
env: COMPILER='g++-5' BUILD_TYPE='Debug' CPP11=0
env: COMPILER='g++-5' BUILD_TYPE='Debug'
- os: linux
......@@ -151,20 +151,17 @@ matrix:
apt:
sources: ['ubuntu-toolchain-r-test']
packages: ['g++-6']
env: COMPILER='g++-6' BUILD_TYPE='Release' CPP11=0
env: COMPILER='g++-6' BUILD_TYPE='Release'
- os: linux
compiler: gcc
addons: *gcc6
env: COMPILER='g++-6' BUILD_TYPE='Debug' CPP11=0
env: COMPILER='g++-6' BUILD_TYPE='Debug'
# 3a/ Linux C++11 GCC builds
- os: linux
compiler: gcc
addons: &gcc48
apt:
sources: ['ubuntu-toolchain-r-test']
packages: ['g++-4.8']
addons: *gcc48
env: COMPILER='g++-4.8' BUILD_TYPE='Release' CPP11=1
- os: linux
......@@ -175,10 +172,7 @@ matrix:
# 3b/ Linux C++11 Clang builds
- os: linux
compiler: clang
addons: &clang38
apt:
sources: ['llvm-toolchain-precise-3.8', 'ubuntu-toolchain-r-test']
packages: ['clang-3.8']
addons: *clang38
env: COMPILER='clang++-3.8' BUILD_TYPE='Release' CPP11=1
- os: linux
......@@ -186,27 +180,69 @@ matrix:
addons: *clang38
env: COMPILER='clang++-3.8' BUILD_TYPE='Debug' CPP11=1
# 4a/ Linux C++14 GCC builds
- os: linux
compiler: gcc
addons: *gcc6
env: COMPILER='g++-6' BUILD_TYPE='Release' CPP14=1
- os: linux
compiler: gcc
addons: *gcc6
env: COMPILER='g++-6' BUILD_TYPE='Debug' CPP14=1
# 4b/ Linux C++14 Clang builds
# - os: linux
# compiler: clang
# addons: *clang38
# env: COMPILER='clang++-3.8' BUILD_TYPE='Release' CPP14=1
#
# - os: linux
# compiler: clang
# addons: *clang38
# env: COMPILER='clang++-3.8' BUILD_TYPE='Debug' CPP14=1
# 4/ OSX Clang Builds
# 5/ OSX Clang Builds
- os: osx
osx_image: xcode7.3
compiler: clang
env: COMPILER='clang++' BUILD_TYPE='Debug' CPP11=0
env: COMPILER='clang++' BUILD_TYPE='Debug'
- os: osx
osx_image: xcode7.3
compiler: clang
env: COMPILER='clang++' BUILD_TYPE='Release' CPP11=0
env: COMPILER='clang++' BUILD_TYPE='Release'
- os: osx
osx_image: xcode8
compiler: clang
env: COMPILER='clang++' BUILD_TYPE='Debug'
- os: osx
osx_image: xcode8
compiler: clang
env: COMPILER='clang++' BUILD_TYPE='Release'
- os: osx
osx_image: xcode8
compiler: clang
env: COMPILER='clang++' BUILD_TYPE='Debug' USE_CPP11=1
- os: osx
osx_image: xcode8
compiler: clang
env: COMPILER='clang++' BUILD_TYPE='Release' USE_CPP11=1
- os: osx
osx_image: xcode8
compiler: clang
env: COMPILER='clang++' BUILD_TYPE='Debug' CPP11=0
env: COMPILER='clang++' BUILD_TYPE='Debug' USE_CPP14=1
- os: osx
osx_image: xcode8
compiler: clang
env: COMPILER='clang++' BUILD_TYPE='Release' CPP11=0
env: COMPILER='clang++' BUILD_TYPE='Release' USE_CPP14=1
install:
......@@ -218,13 +254,13 @@ install:
mkdir cmake && travis_retry wget --no-check-certificate --quiet -O - ${CMAKE_URL} | tar --strip-components=1 -xz -C cmake
export PATH=${DEPS_DIR}/cmake/bin:${PATH}
elif [[ "${TRAVIS_OS_NAME}" == "osx" ]]; then
which cmake || brew install cmake
which cmake || brew install cmake
fi
before_script:
- export CXX=${COMPILER}
- cd ${TRAVIS_BUILD_DIR}
- cmake -H. -BBuild -DCMAKE_BUILD_TYPE=${BUILD_TYPE} -Wdev -DUSE_CPP11=${CPP11}
- cmake -H. -BBuild -DCMAKE_BUILD_TYPE=${BUILD_TYPE} -Wdev -DUSE_CPP11=${CPP11} -DUSE_CPP14=${CPP14}
- cd Build
script:
......
......@@ -19,6 +19,10 @@ elseif(USE_CPP14)
set(CMAKE_CXX_FLAGS "-std=c++14 ${CMAKE_CXX_FLAGS}")
endif()
if(USE_WMAIN)
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /ENTRY:wmainCRTStartup")
endif()
#checks that the given hard-coded list contains all headers + sources in the given folder
function(CheckFileList LIST_VAR FOLDER)
set(MESSAGE " should be added to the variable ${LIST_VAR}")
......@@ -55,6 +59,7 @@ set(TEST_SOURCES
${SELF_TEST_DIR}/CmdLineTests.cpp
${SELF_TEST_DIR}/CompilationTests.cpp
${SELF_TEST_DIR}/ConditionTests.cpp
${SELF_TEST_DIR}/DecompositionTests.cpp
${SELF_TEST_DIR}/EnumToString.cpp
${SELF_TEST_DIR}/ExceptionTests.cpp
${SELF_TEST_DIR}/GeneratorTests.cpp
......@@ -245,28 +250,35 @@ SOURCE_GROUP("Benchmarks" FILES ${BENCH_SOURCES})
# configure the executable
include_directories(${HEADER_DIR})
add_executable(SelfTest ${TEST_SOURCES} ${IMPL_SOURCES} ${HEADERS})
add_executable(Benchmark ${BENCH_SOURCES} ${HEADERS})
# Add desired warnings
if ( CMAKE_CXX_COMPILER_ID MATCHES "Clang|AppleClang|GNU" )
target_compile_options( SelfTest PRIVATE -Wall -Wextra )
target_compile_options( Benchmark PRIVATE -Wall -Wextra )
endif()
if ( CMAKE_CXX_COMPILER_ID MATCHES "MSVC" )
target_compile_options( SelfTest PRIVATE /W4 /w44265 /WX )
target_compile_options( Benchmark PRIVATE /W4 )
endif()
# Projects consuming Catch via ExternalProject_Add might want to use install step
# without building all of our selftests.
if (NOT NO_SELFTEST)
add_executable(SelfTest ${TEST_SOURCES} ${IMPL_SOURCES} ${HEADERS})
add_executable(Benchmark ${BENCH_SOURCES} ${HEADERS})
# Add desired warnings
if ( CMAKE_CXX_COMPILER_ID MATCHES "Clang|AppleClang|GNU" )
target_compile_options( SelfTest PRIVATE -Wall -Wextra )
target_compile_options( Benchmark PRIVATE -Wall -Wextra )
endif()
if ( CMAKE_CXX_COMPILER_ID MATCHES "MSVC" )
target_compile_options( SelfTest PRIVATE /W4 /w44265 /WX )
target_compile_options( Benchmark PRIVATE /W4 )
endif()
# configure unit tests via CTest
enable_testing()
add_test(NAME RunTests COMMAND SelfTest)
add_test(NAME ListTests COMMAND SelfTest --list-tests)
set_tests_properties(ListTests PROPERTIES PASS_REGULAR_EXPRESSION "[0-9]+ test cases")
# configure unit tests via CTest
enable_testing()
add_test(NAME RunTests COMMAND SelfTest)
add_test(NAME ListTags COMMAND SelfTest --list-tags)
set_tests_properties(ListTags PROPERTIES PASS_REGULAR_EXPRESSION "[0-9]+ tags")
add_test(NAME ListTests COMMAND SelfTest --list-tests)
set_tests_properties(ListTests PROPERTIES PASS_REGULAR_EXPRESSION "[0-9]+ test cases")
endif() # !NO_SELFTEST
add_test(NAME ListTags COMMAND SelfTest --list-tags)
set_tests_properties(ListTags PROPERTIES PASS_REGULAR_EXPRESSION "[0-9]+ tags")
install(DIRECTORY "single_include/" DESTINATION "include/catch/")
install(DIRECTORY "single_include/" DESTINATION "include/catch")
......@@ -3,8 +3,9 @@
[![Github Releases](https://img.shields.io/github/release/philsquared/catch.svg)](https://github.com/philsquared/catch/releases)
[![Build Status](https://travis-ci.org/philsquared/Catch.svg?branch=master)](https://travis-ci.org/philsquared/Catch)
[![Build status](https://ci.appveyor.com/api/projects/status/hrtk60hv6tw6fght/branch/master?svg=true)](https://ci.appveyor.com/project/philsquared/catch/branch/master)
[![Try online](https://img.shields.io/badge/try-online-blue.svg)](https://wandbox.org/permlink/IJ0n8142H2DROPIm)
<a href="https://github.com/philsquared/Catch/releases/download/v1.8.2/catch.hpp">The latest, single header, version can be downloaded directly using this link</a>
<a href="https://github.com/philsquared/Catch/releases/download/v1.9.7/catch.hpp">The latest, single header, version can be downloaded directly using this link</a>
## What's the Catch?
......@@ -21,3 +22,7 @@ This documentation comprises these three parts:
* Issues and bugs can be raised on the [Issue tracker on GitHub](https://github.com/philsquared/Catch/issues)
* For discussion or questions please use [the dedicated Google Groups forum](https://groups.google.com/forum/?fromgroups#!forum/catch-forum)
* See [who else is using Catch](docs/opensource-users.md)
## Help us out
We're currently running [a survey](https://www.surveymonkey.co.uk/r/TLLYQJW) to help us shape the future of Catch.
Please take a few moments to fill it out (there's only ten questions).
# version string format -- This will be overwritten later anyway
version: "{build}"
# Disable the dead branch for v2 development
branches:
except:
- develop-v2
os:
- Visual Studio 2013
- Visual Studio 2017
- Visual Studio 2015
- Visual Studio 2013
environment:
matrix:
- additional_flags: "/permissive- /std:c++latest"
wmain: 0
- additional_flags: ""
wmain: 0
- additional_flags: "/D_UNICODE /DUNICODE"
wmain: 1
matrix:
exclude:
-
additional_flags: "/permissive- /std:c++latest"
os: Visual Studio 2015
-
additional_flags: "/permissive- /std:c++latest"
os: Visual Studio 2013
init:
- git config --global core.autocrlf input
......@@ -31,8 +47,8 @@ configuration:
#Cmake will autodetect the compiler, but we set the arch
before_build:
- echo Running cmake...
- cmake -H. -BBuild -A%PLATFORM%
- set CXXFLAGS=%additional_flags%
- cmake -H. -BBuild -A%PLATFORM% -DUSE_WMAIN=%wmain%
# build with MSBuild
build:
......
#!/usr/bin/env python
from conans import ConanFile
class CatchConan(ConanFile):
name = "Catch"
version = "1.9.7"
description = "A modern, C++-native, header-only, framework for unit-tests, TDD and BDD"
author = "philsquared"
generators = "cmake"
exports_sources = "single_include/*"
url = "https://github.com/philsquared/Catch"
license = "Boost Software License - Version 1.0. http://www.boost.org/LICENSE_1_0.txt"
def package(self):
self.copy(pattern="catch.hpp", src="single_include", dst="include")
#==================================================================================================#
# supported macros #
# - TEST_CASE, #
# - SCENARIO, #
# - TEST_CASE_METHOD, #
# - CATCH_TEST_CASE, #
# - CATCH_SCENARIO, #
# - CATCH_TEST_CASE_METHOD. #
# #
# Usage #
# 1. make sure this module is in the path or add this otherwise: #
# set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake.modules/") #
# 2. make sure that you've enabled testing option for the project by the call: #
# enable_testing() #
# 3. add the lines to the script for testing target (sample CMakeLists.txt): #
# project(testing_target) #
# set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake.modules/") #
# enable_testing() #
# #
# find_path(CATCH_INCLUDE_DIR "catch.hpp") #
# include_directories(${INCLUDE_DIRECTORIES} ${CATCH_INCLUDE_DIR}) #
# #
# file(GLOB SOURCE_FILES "*.cpp") #
# add_executable(${PROJECT_NAME} ${SOURCE_FILES}) #
# #
# include(ParseAndAddCatchTests) #
# ParseAndAddCatchTests(${PROJECT_NAME}) #
# #
# The following variables affect the behavior of the script: #
# #
# PARSE_CATCH_TESTS_VERBOSE (Default OFF) #
# -- enables debug messages #
# PARSE_CATCH_TESTS_NO_HIDDEN_TESTS (Default OFF) #
# -- excludes tests marked with [!hide], [.] or [.foo] tags #
# PARSE_CATCH_TESTS_ADD_FIXTURE_IN_TEST_NAME (Default ON) #
# -- adds fixture class name to the test name #
# PARSE_CATCH_TESTS_ADD_TARGET_IN_TEST_NAME (Default ON) #
# -- adds cmake target name to the test name #
# #
#==================================================================================================#
cmake_minimum_required(VERSION 2.8.8)
option(PARSE_CATCH_TESTS_VERBOSE "Print Catch to CTest parser debug messages" OFF)
option(PARSE_CATCH_TESTS_NO_HIDDEN_TESTS "Exclude tests with [!hide], [.] or [.foo] tags" OFF)
option(PARSE_CATCH_TESTS_ADD_FIXTURE_IN_TEST_NAME "Add fixture class name to the test name" ON)
option(PARSE_CATCH_TESTS_ADD_TARGET_IN_TEST_NAME "Add target name to the test name" ON)
function(PrintDebugMessage)
if(PARSE_CATCH_TESTS_VERBOSE)
message(STATUS "ParseAndAddCatchTests: ${ARGV}")
endif()
endfunction()
# This removes the contents between
# - block comments (i.e. /* ... */)
# - full line comments (i.e. // ... )
# contents have been read into '${CppCode}'.
# !keep partial line comments
function(RemoveComments CppCode)
string(ASCII 2 CMakeBeginBlockComment)
string(ASCII 3 CMakeEndBlockComment)
string(REGEX REPLACE "/\\*" "${CMakeBeginBlockComment}" ${CppCode} "${${CppCode}}")
string(REGEX REPLACE "\\*/" "${CMakeEndBlockComment}" ${CppCode} "${${CppCode}}")
string(REGEX REPLACE "${CMakeBeginBlockComment}[^${CMakeEndBlockComment}]*${CMakeEndBlockComment}" "" ${CppCode} "${${CppCode}}")
string(REGEX REPLACE "\n[ \t]*//+[^\n]+" "\n" ${CppCode} "${${CppCode}}")
set(${CppCode} "${${CppCode}}" PARENT_SCOPE)
endfunction()
# Worker function
function(ParseFile SourceFile TestTarget)
# According to CMake docs EXISTS behavior is well-defined only for full paths.
get_filename_component(SourceFile ${SourceFile} ABSOLUTE)
if(NOT EXISTS ${SourceFile})
message(WARNING "Cannot find source file: ${SourceFile}")
return()
endif()
PrintDebugMessage("parsing ${SourceFile}")
file(STRINGS ${SourceFile} Contents NEWLINE_CONSUME)
# Remove block and fullline comments
RemoveComments(Contents)
# Find definition of test names
string(REGEX MATCHALL "[ \t]*(CATCH_)?(TEST_CASE_METHOD|SCENARIO|TEST_CASE)[ \t]*\\([^\)]+\\)+[ \t\n]*{+[ \t]*(//[^\n]*[Tt][Ii][Mm][Ee][Oo][Uu][Tt][ \t]*[0-9]+)*" Tests "${Contents}")
foreach(TestName ${Tests})
# Strip newlines
string(REGEX REPLACE "\\\\\n|\n" "" TestName "${TestName}")
# Get test type and fixture if applicable
string(REGEX MATCH "(CATCH_)?(TEST_CASE_METHOD|SCENARIO|TEST_CASE)[ \t]*\\([^,^\"]*" TestTypeAndFixture "${TestName}")
string(REGEX MATCH "(CATCH_)?(TEST_CASE_METHOD|SCENARIO|TEST_CASE)" TestType "${TestTypeAndFixture}")
string(REPLACE "${TestType}(" "" TestFixture "${TestTypeAndFixture}")
# Get string parts of test definition
string(REGEX MATCHALL "\"+([^\\^\"]|\\\\\")+\"+" TestStrings "${TestName}")
# Strip wrapping quotation marks
string(REGEX REPLACE "^\"(.*)\"$" "\\1" TestStrings "${TestStrings}")
string(REPLACE "\";\"" ";" TestStrings "${TestStrings}")
# Validate that a test name and tags have been provided
list(LENGTH TestStrings TestStringsLength)
if(TestStringsLength GREATER 2 OR TestStringsLength LESS 1)
message(FATAL_ERROR "You must provide a valid test name and tags for all tests in ${SourceFile}")
endif()
# Assign name and tags
list(GET TestStrings 0 Name)
if("${TestType}" STREQUAL "SCENARIO")
set(Name "Scenario: ${Name}")
endif()
if(PARSE_CATCH_TESTS_ADD_FIXTURE_IN_TEST_NAME AND TestFixture)
set(CTestName "${TestFixture}:${Name}")
else()
set(CTestName "${Name}")
endif()
if(PARSE_CATCH_TESTS_ADD_TARGET_IN_TEST_NAME)
set(CTestName "${TestTarget}:${CTestName}")
endif()
# add target to labels to enable running all tests added from this target
set(Labels ${TestTarget})
if(TestStringsLength EQUAL 2)
list(GET TestStrings 1 Tags)
string(TOLOWER "${Tags}" Tags)
# remove target from labels if the test is hidden
if("${Tags}" MATCHES ".*\\[!?(hide|\\.)\\].*")
list(REMOVE_ITEM Labels ${TestTarget})
endif()
string(REPLACE "]" ";" Tags "${Tags}")
string(REPLACE "[" "" Tags "${Tags}")
endif()
list(APPEND Labels ${Tags})
list(FIND Labels "!hide" IndexOfHideLabel)
set(HiddenTagFound OFF)
foreach(label ${Labels})
string(REGEX MATCH "^!hide|^\\." result ${label})
if(result)
set(HiddenTagFound ON)
break()
endif(result)
endforeach(label)
if(PARSE_CATCH_TESTS_NO_HIDDEN_TESTS AND ${HiddenTagFound})
PrintDebugMessage("Skipping test \"${CTestName}\" as it has [!hide], [.] or [.foo] label")
else()
PrintDebugMessage("Adding test \"${CTestName}\"")
if(Labels)
PrintDebugMessage("Setting labels to ${Labels}")
endif()
# Add the test and set its properties
add_test(NAME "\"${CTestName}\"" COMMAND ${TestTarget} ${Name} ${AdditionalCatchParameters})
set_tests_properties("\"${CTestName}\"" PROPERTIES FAIL_REGULAR_EXPRESSION "No tests ran"
LABELS "${Labels}")
endif()
endforeach()
endfunction()
# entry point
function(ParseAndAddCatchTests TestTarget)
PrintDebugMessage("Started parsing ${TestTarget}")
get_target_property(SourceFiles ${TestTarget} SOURCES)
PrintDebugMessage("Found the following sources: ${SourceFiles}")
foreach(SourceFile ${SourceFiles})
ParseFile(${SourceFile} ${TestTarget})
endforeach()
PrintDebugMessage("Finished parsing ${TestTarget}")
endfunction()
These are the currently documented areas of the framework. There is more to come.
Before looking at this material be sure to read the [tutorial](tutorial.md)
To get the most out of Catch, start with the [tutorial](tutorial.md).
Once you're up and running consider the following reference material.
Writing tests:
* [Assertion macros](assertions.md)
* [Matchers](matchers.md)
* [Logging macros](logging.md)
* [Test cases and sections](test-cases-and-sections.md)
* [Test fixtures](test-fixtures.md)
* [Supplying your own main()](own-main.md)
* [Reporters](reporters.md)
* [Event Listeners](event-listeners.md)
* [Configuration](configuration.md)
Fine tuning:
* [Supplying your own main()](own-main.md)
* [Compile-time configuration](configuration.md)
* [String Conversions](tostring.md)
Running:
* [Command line](command-line.md)
* [Build systems](build-systems.md)
* [CI and Build system integration](build-systems.md)
FAQ:
* [Why are my tests slow to compile?](slow-compiles.md)
* [Known limitations](limitations.md)
Other
Other:
* [Why Catch?](why-catch.md)
* [Open Source Projects using Catch](opensource-users.md)
* [Contributing](contributing.md)
......
......@@ -95,7 +95,7 @@ Expects that an exception (of any type) is be thrown during evaluation of the ex
* **REQUIRE_THROWS_AS(** _expression_, _exception type_ **)** and
* **CHECK_THROWS_AS(** _expression_, _exception type_ **)**
Expects that an exception of the _specified type_ is thrown during evaluation of the expression.
Expects that an exception of the _specified type_ is thrown during evaluation of the expression. Note that the _exception type_ is used verbatim and you should include (const) reference.
* **REQUIRE_THROWS_WITH(** _expression_, _string or string matcher_ **)** and
* **CHECK_THROWS_WITH(** _expression_, _string or string matcher_ **)**
......@@ -131,6 +131,11 @@ To support Matchers a slightly different form is used. Matchers have [their own
Matchers can be composed using `&&`, `||` and `!` operators.
## Thread Safety
Currently assertions in Catch are not thread safe.
For more details, along with workarounds, see the section on [the limitations page](limitations.md#thread-safe-assertions).
---
[Home](Readme.md)
\ No newline at end of file
# Integration with build systems
# CI and build system integration
Build Systems may refer to low-level tools, like CMake, or larger systems that run on servers, like Jenkins or TeamCity. This page will talk about both.
......@@ -56,8 +56,26 @@ Because of the incremental nature of Catch's test suites and ability to run spec
## CMake
You can use the following CMake script to automatically fetch Catch from github and configure it as an external project:
In general we recommend "vendoring" Catch's single-include releases inside your own repository. If you do this, the following example shows a minimal CMake project:
```CMake
cmake_minimum_required(VERSION 3.0)
project(cmake_test)
# Prepare "Catch" library for other executables
set(CATCH_INCLUDE_DIR ${CMAKE_CURRENT_SOURCE_DIR}/catch)
add_library(Catch INTERFACE)
target_include_directories(Catch INTERFACE ${CATCH_INCLUDE_DIR})
# Make test executable
set(TEST_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp)
add_executable(tests ${TEST_SOURCES})
target_link_libraries(tests Catch)
```
Note that it assumes that the path to the Catch's header is `catch/catch.hpp` from the `CMakeLists.txt` file.
You can also use the following CMake snippet to automatically fetch the entire Catch repository from github and configure it as an external project:
```CMake
cmake_minimum_required(VERSION 2.8.8)
project(catch_builder CXX)
......@@ -90,6 +108,36 @@ include_directories(${CATCH_INCLUDE_DIR} ${COMMON_INCLUDES})
enable_testing(true) # Enables unit-testing.
```
The advantage of this approach is that you can always automatically update Catch to the latest release. The disadvantage is that it means bringing in lot more than you need.
### Automatic test registration
If you are also using ctest, `contrib/ParseAndAddCatchTests.cmake` is a CMake script that attempts to parse your test files and automatically register all test cases, using tags as labels. This means that these
```cpp
TEST_CASE("Test1", "[unit]") {
int a = 1;
int b = 2;
REQUIRE(a == b);
}
TEST_CASE("Test2") {
int a = 1;
int b = 2;
REQUIRE(a == b);
}
TEST_CASE("Test3", "[a][b][c]") {
int a = 1;
int b = 2;
REQUIRE(a == b);
}
```
would be registered as 3 tests, `Test1`, `Test2` and `Test3`, and ctest 4 labels would be created, `a`, `b`, `c` and `unit`.
### CodeCoverage module (GCOV, LCOV...)
If you are using GCOV tool to get testing coverage of your code, and are not sure how to integrate it with CMake and Catch, there should be an external example over at https://github.com/fkromer/catch_cmake_coverage
---
[Home](Readme.md)
\ No newline at end of file
[Home](Readme.md)
# Commercial users of Catch
As well as [Open Source](opensource-users.md) users Catch is widely used within proprietary code bases too. Many companies like to keep this
information internal, and that's fine, but if you're more open it would be great if we could list the names of as
many organisations as possible that use Catch somewhere in their codebase. Enterprise environments often tend to be
far more conservative in their tool adoption - and being aware that other companies are using Catch can ease the
path in.
As well as [Open Source](opensource-users.md) users Catch is widely used within proprietary code bases too.
Many organisations like to keep this information internal, and that's fine,
but if you're more open it would be great if we could list the names of as
many organisations as possible that use Catch somewhere in their codebase.
Enterprise environments often tend to be far more conservative in their tool adoption -
and being aware that other companies are using Catch can ease the path in.
So if you are aware of Catch usage in your organisation, and are fairly confident there is no issue with sharing this
fact then please let us know - either directly, via a PR or [issue](https://github.com/philsquared/Catch/issues), or on the [forums](https://groups.google.com/forum/?fromgroups#!forum/catch-forum).
fact then please let us know - either directly, via a PR or
[issue](https://github.com/philsquared/Catch/issues), or on the [forums](https://groups.google.com/forum/?fromgroups#!forum/catch-forum).
- Bloomberg
- NASA
- [Inscopix Inc.](https://www.inscopix.com/)
......@@ -43,26 +43,34 @@ By default a console width of 80 is assumed but this can be controlled by defini
CATCH_CONFIG_NOSTDOUT
Catch does not use ```std::cout``` and ```std::cerr``` directly but gets them from ```Catch::cout()``` and ```Catch::cerr()``` respectively. If the above identifier is defined these functions are left unimplemented and you must implement them yourself. Their signatures are:
Catch does not use ```std::cout```, ```std::cerr``` and ```std::clog``` directly but gets them from ```Catch::cout()```, ```Catch::cerr()``` and ```Catch::clog``` respectively. If the above identifier is defined these functions are left unimplemented and you must implement them yourself. Their signatures are:
std::ostream& cout();
std::ostream& cerr();
std::ostream& clog();
This can be useful on certain platforms that do not provide ```std::cout``` and ```std::cerr```, such as certain embedded systems.
This can be useful on certain platforms that do not provide the standard iostreams, such as certain embedded systems.
# Default reporter
CATCH_CONFIG_DEFAULT_REPORTER <reporter>
The default reporter (reporter used when no reporters are explicitly specified) can be overriden during compilation time by using the above macro. Note that desired value of the macro is a C string and quotes have to be escaped during compilation: `clang++ test.cpp -DCATCH_CONFIG_DEFAULT_REPORTER=\"xml\"`.
# C++ conformance toggles
CATCH_CONFIG_CPP11_NULLPTR // nullptr is supported?
CATCH_CONFIG_CPP11_NOEXCEPT // noexcept is supported?
CATCH_CONFIG_CPP11_GENERATED_METHODS // delete and default keywords for methods
CATCH_CONFIG_CPP11_IS_ENUM // std::is_enum is supported?
CATCH_CONFIG_CPP11_TUPLE // std::tuple is supported
CATCH_CONFIG_VARIADIC_MACROS // Usually pre-C++11 compiler extensions are sufficient
CATCH_CONFIG_CPP11_LONG_LONG // generates overloads for the long long type
CATCH_CONFIG_CPP11_OVERRIDE // CATCH_OVERRIDE expands to override (for virtual function implementations)
CATCH_CONFIG_CPP11_UNIQUE_PTR // Use std::unique_ptr instead of std::auto_ptr
CATCH_CONFIG_CPP11_SHUFFLE // Use std::shuffle instead of std::random_shuffle
CATCH_CONFIG_CPP11_TYPE_TRAITS // Use std::enable_if and <type_traits>
CATCH_CONFIG_CPP11_NULLPTR // nullptr is supported?
CATCH_CONFIG_CPP11_NOEXCEPT // noexcept is supported?
CATCH_CONFIG_CPP11_GENERATED_METHODS // delete and default keywords for methods
CATCH_CONFIG_CPP11_IS_ENUM // std::is_enum is supported?
CATCH_CONFIG_CPP11_TUPLE // std::tuple is supported
CATCH_CONFIG_VARIADIC_MACROS // Usually pre-C++11 compiler extensions are sufficient
CATCH_CONFIG_CPP11_LONG_LONG // generates overloads for the long long type
CATCH_CONFIG_CPP11_OVERRIDE // CATCH_OVERRIDE expands to override (for virtual function implementations)
CATCH_CONFIG_CPP11_UNIQUE_PTR // Use std::unique_ptr instead of std::auto_ptr
CATCH_CONFIG_CPP11_SHUFFLE // Use std::shuffle instead of std::random_shuffle
CATCH_CONFIG_CPP11_TYPE_TRAITS // Use std::enable_if and <type_traits>
CATCH_CONFIG_CPP11_STREAM_INSERTABLE_CHECK // Use C++11 expression SFINAE to check if class can be inserted to std::ostream
Catch has some basic compiler detection that will attempt to select the appropriate mix of these macros. However being incomplete - and often without access to the respective compilers - this detection tends to be conservative.
So overriding control is given to the user. If a compiler supports a feature (and Catch does not already detect it) then one or more of these may be defined to enable it (or suppress it, in some cases). If you do do this please raise an issue, specifying your compiler version (ideally with an idea of how to detect it) and stating that it has such support.
......@@ -70,24 +78,51 @@ You may also suppress any of these features by using the `_NO_` form, e.g. `CATC
All C++11 support can be disabled with `CATCH_CONFIG_NO_CPP11`
## `CATCH_CONFIG_CPP11_STREAM_INSERTABLE_CHECK`
This flag is off by default, but allows you to resolve problems caused by types with private base class that are streamable, but the classes themselves are not. Without it, the following code will cause a compilation error:
```cpp
#define CATCH_CONFIG_MAIN
#include <catch.hpp>
struct A {};
std::ostream &operator<< (std::ostream &o, const A &v) { return o << 0; }
struct B : private A {
bool operator==(int){ return true;}
};
B f ();
std::ostream g ();
TEST_CASE ("Error in streamable check") {
B x;
REQUIRE (x == 4);
}
```
# Other toggles
CATCH_CONFIG_COUNTER // Use __COUNTER__ to generate unique names for test cases
CATCH_CONFIG_WINDOWS_SEH // Enable SEH handling on Windows
CATCH_CONFIG_FAST_COMPILE // Sacrifices some (extremely minor) features for compilation speed
CATCH_CONFIG_FAST_COMPILE // Sacrifices some (rather minor) features for compilation speed
CATCH_CONFIG_POSIX_SIGNALS // Enable handling POSIX signals
CATCH_CONFIG_WINDOWS_CRTDBG // Enable leak checking using Windows's CRT Debug Heap
Currently Catch enables `CATCH_CONFIG_WINDOWS_SEH` only when compiled with MSVC, because some versions of MinGW do not have the necessary Win32 API support.
At this moment, `CATCH_CONFIG_FAST_COMPILE` changes only the behaviour of the `-b` (`--break`) flag, making it break into debugger in a stack frame *below* the actual test, unlike the default behaviour, where the break into debugger occurs in the same stack frame as the actual test. `CATCH_CONFIG_FAST_COMPILE` has to be either defined, or not defined, in all translation units that are linked into single test binary, or the behaviour of setting `-b` flag will be unpredictable.
`CATCH_CONFIG_POSIX_SIGNALS` is on by default, except when Catch is compiled under `Cygwin`, where it is disabled by default (but can be force-enabled by defining `CATCH_CONFIG_POSIX_SIGNALS`).
`CATCH_CONFIG_WINDOWS_CRTDBG` is off by default. If enabled, Windows's CRT is used to check for memory leaks, and displays them after the tests finish running.
Just as with the C++11 conformance toggles, these toggles can be disabled by using `_NO_` form of the toggle, e.g. `CATCH_CONFIG_NO_WINDOWS_SEH`.
## `CATCH_CONFIG_FAST_COMPILE`
Defining this flag speeds up compilation of test files by ~20%, by making 2 changes:
* The `-b` (`--break`) flag no longer makes Catch break into debugger in the same stack frame as the failed test, but rather in a stack frame *below*.
* The `REQUIRE` family of macros (`REQUIRE`, `REQUIRE_FALSE` and `REQUIRE_THAT`) no longer uses local try-catch block. This disables exception translation, but should not lead to false negatives.
`CATCH_CONFIG_FAST_COMPILE` has to be either defined, or not defined, in all translation units that are linked into single test binary, or the behaviour of setting `-b` flag and throwing unexpected exceptions will be unpredictable.
# Windows header clutter
On Windows Catch includes `windows.h`. To minimize global namespace clutter in the implementation file, it defines `NOMINMAX` and `WIN32_LEAN_AND_MEAN` before including it. You can control this behaviour via two macros:
......
......@@ -18,8 +18,8 @@ Ongoing development is currently on _master_. At some point an integration branc
_Users_ of Catch primarily use the single header version. _Maintainers_ should work with the full source (which is still,
primarily, in headers). This can be found in the `include` folder. There are a set of test files, currently under
`projects/SelfTest`. The test app can be built via CMake from the `CMakeLists.txt` file in the root, or you can generate
project files for Visual Studio, XCode, and others (instructions in the `projects` folder). If you have access to CLion
that can work with the CMake file directly.
project files for Visual Studio, XCode, and others (instructions in the `projects` folder). If you have access to CLion,
it can work with the CMake file directly.
As well as the runtime test files you'll also see a `SurrogateCpps` directory under `projects/SelfTest`.
This contains a set of .cpp files that each `#include` a single header.
......@@ -34,6 +34,25 @@ __When submitting a pull request please do not include changes to the single inc
as these are managed by the scripts!__
## Testing your changes
Obviously all changes to Catch's code should be tested. If you added new functionality, you should add tests covering and
showcasing it. Even if you have only made changes to Catch internals (ie you implemented some performance improvements),
you should still test your changes.
This means 3 things
* Compiling Catch's SelfTest project -- code that does not compile is evidently incorrect. Obviously, you are not expected to
have access to all compilers and platforms Catch supports, Catch's CI pipeline will compile your code using supported compilers
once you open a PR.
* Running the SelfTest binary. There should be no unexpected failures on simple run.
* Running Catch's approval tests. Approval tests compare current output of the SelfTest binary in various configurations against
known good output. Catch's repository provides utility scripts `approvalTests.py` to help you with this. It needs to be passed
the SelfTest binary compiled with your changes, like so: `$ ./scripts/approvalTests.py clang-build/SelfTest`. The output should
be fairly self-explanatory.
*this document is still in-progress...*
---
......
......@@ -31,7 +31,7 @@ struct MyListener : Catch::TestEventListenerBase {
// Perform some setup before a test case is run
}
virtual void testCaseEnded( TestCaseStats const& testCaseStats ) override {
virtual void testCaseEnded( Catch::TestCaseStats const& testCaseStats ) override {
// Tear-down after a test case is run
}
};
......@@ -70,4 +70,4 @@ just look in the source code to see what fields are available.
---
[Home](Readme.md)
\ No newline at end of file
[Home](Readme.md)
# Logging macros
Additional messages can be logged during a test case.
Additional messages can be logged during a test case. Note that the messages are scoped and thus will not be reported if failure occurs in scope preceding the message declaration. An example:
```cpp
TEST_CASE("Foo") {
INFO("Test case start");
for (int i = 0; i < 2; ++i) {
INFO("The number is " << i);
CHECK(i == 0);
}
}
TEST_CASE("Bar") {
INFO("Test case start");
for (int i = 0; i < 2; ++i) {
INFO("The number is " << i);
CHECK(i == i);
}
CHECK(false);
}
```
When the `CHECK` fails in the "Foo" test case, then two messages will be printed.
```
Test case start
The number is 1
```
When the last `CHECK` fails in the "Bar" test case, then only one message will be printed: `Test case start`.
## Streaming macros
......
......@@ -13,6 +13,7 @@ which consists of either a single matcher or one or more matchers combined using
For example, to assert that a string ends with a certain substring:
```c++
using Catch::Matchers::EndsWith; // or Catch::EndsWith
std::string str = getStringFromSomewhere();
REQUIRE_THAT( str, EndsWith( "as a service" ) );
```
......@@ -34,7 +35,7 @@ REQUIRE_THAT( str,
```
## Built in matchers
Currently Catch has some string matchers and some vector matchers.
Currently Catch has some string matchers and some vector matchers. They are in the `Catch::Matchers` and `Catch` namespaces.
The string matchers are `StartsWith`, `EndsWith`, `Contains` and `Equals`. Each of them also takes an optional second argument, that decides case sensitivity (by-default, they are case sensitive).
The vector matchers are `Contains`, `VectorContains` and `Equals`. `VectorContains` looks for a single element in the matched vector, `Contains` looks for a set (vector) of elements inside the matched vector.
......
# Open Source projects using Catch
Catch is great for open source. With it's [liberal license](../LICENSE_1_0.txt) and single-header, dependency-free, distribution
Catch is great for open source. With it's [liberal license](../LICENSE.txt) and single-header, dependency-free, distribution
it's easy to just drop the header into your project and start writing tests - what's not to like?
As a result Catch is now being used in many Open Source projects, including some quite well known ones.
......@@ -34,9 +34,18 @@ A, single-header, JSON parsing library that takes advantage of what C++ has to o
### [MNMLSTC Core](https://github.com/mnmlstc/core)
a small and easy to use C++11 library that adds a functionality set that will be available in C++14 and later, as well as some useful additions
### [nanodbc](https://github.com/lexicalunit/nanodbc/)
A small C++ library wrapper for the native C ODBC API.
### [Nonius](https://github.com/libnonius/nonius)
A header-only framework for benchmarking small snippets of C++ code.
### [SOCI](https://github.com/SOCI/soci)
The C++ Database Access Library
### [polymorphic_value](https://github.com/jbcoe/polymorphic_value)
A polymorphic value-type for C++
### [Ppconsul](https://github.com/oliora/ppconsul)
A C++ client library for Consul. Consul is a distributed tool for discovering and configuring services in your infrastructure
......@@ -46,6 +55,9 @@ A library of algorithms for values-distributed-in-time
### [Trompeloeil](https://github.com/rollbear/trompeloeil)
A thread safe header only mocking framework for C++14
### [args](https://github.com/Taywee/args)
A simple header-only C++ argument parser library.
## Applications & Tools
### [ArangoDB](https://github.com/arangodb/arangodb)
......@@ -54,6 +66,9 @@ ArangoDB is a native multi-model database with flexible data models for document
### [MAME](https://github.com/mamedev/mame)
MAME originally stood for Multiple Arcade Machine Emulator
### [Newsbeuter](https://github.com/akrennmair/newsbeuter)
Newsbeuter is an open-source RSS/Atom feed reader for text terminals.
### [Standardese](https://github.com/foonathan/standardese)
Standardese aims to be a nextgen Doxygen
......
# 1.9.7
### Fixes
* Various warnings from clang-tidy, Resharper-C++ and PVS Studio have been addressed (#957)
* Dynamically generated sections are now properly reported (#963)
* Writes to `std::clog` are redirected for reporters (#989)
* Previously only `std::cerr` writes were redirected
* Interleaved writes to `std::cerr` and `std::clog` are combined properly
* Assertions failed before signals/structured exceptions fails test case are properly reported as failed (#990)
### Improvements
* Catch's runtime overhead has been decreased further (#940)
* Added support for IBM i ILE c++ compiler (#976)
* This means that AS/400 is now supported.
* The default reporter can be configured at compile time (#978)
* That is, the reporter used if no reporter is explicitly specified
### Other
* `ParseAndAddCatchTests` cmake script has couple new customization options
# 1.9.6
### Improvements
* Catch's runtime overhead has been significantly decreased (#937, #939)
* Added `--list-extra-info` cli option (#934).
* It lists all tests together with extra information, ie filename, line number and description.
# 1.9.5
### Fixes
* Truthy expressions are now reconstructed properly, not as booleans (#914)
* Various warnings are no longer erroneously suppressed in test files (files that include `catch.hpp`, but do not define `CATCH_CONFIG_MAIN` or `CATCH_CONFIG_RUNNER`) (#871)
* Catch no longer fails to link when main is compiled as C++, but linked against Objective-C (#855)
* Fixed incorrect gcc version detection when deciding to use `__COUNTER__` (#928)
* Previously any GCC with minor version less than 3 would be incorrectly classified as not supporting `__COUNTER__`.
* Suppressed C4996 warning caused by upcoming updated to MSVC 2017, marking `std::uncaught_exception` as deprecated. (#927)
### Improvements
* CMake integration script now incorporates debug messages and registers tests in an improved way (#911)
* Various documentation improvements
# 1.9.4
### Fixes
* `CATCH_FAIL` macro no longer causes compilation error without variadic macro support
* `INFO` messages are no longer cleared after being reported once
### Improvements and minor changes
* Catch now uses `wmain` when compiled under Windows and `UNICODE` is defined.
* Note that Catch still officially supports only ASCII
# 1.9.3
### Fixes
* Completed the fix for (lack of) uint64_t in earlier Visual Studios
# 1.9.2
### Improvements and minor changes
* All of `Approx`'s member functions now accept strong typedefs in C++11 mode (#888)
* Previously `Approx::scale`, `Approx::epsilon`, `Approx::margin` and `Approx::operator()` didn't.
### Fixes
* POSIX signals are now disabled by default under QNX (#889)
* QNX does not support current enough (2001) POSIX specification
* JUnit no longer counts exceptions as failures if given test case is marked as ok to fail.
* `Catch::Option` should now have its storage properly aligned.
* Catch no longer attempts to define `uint64_t` on windows (#862)
* This was causing trouble when compiled under Cygwin
### Other
* Catch is now compiled under MSVC 2017 using `std:c++latest` (C++17 mode) in CI
* We now provide cmake script that autoregisters Catch tests into ctest.
* See `contrib` folder.
# 1.9.1
### Fixes
* Unexpected exceptions are no longer ignored by default (#885, #887)
# 1.9.0
### Improvements and minor changes
* Catch no longer attempts to ensure the exception type passed by user in `REQUIRE_THROWS_AS` is a constant reference.
* It was causing trouble when `REQUIRE_THROWS_AS` was used inside templated functions
* This actually reverts changes made in v1.7.2
* Catch's `Version` struct should no longer be double freed when multiple instances of Catch tests are loaded into single program (#858)
* It is now a static variable in an inline function instead of being an `extern`ed struct.
* Attempt to register invalid tag or tag alias now throws instead of calling `exit()`.
* Because this happen before entering main, it still aborts execution
* Further improvements to this are coming
* `CATCH_CONFIG_FAST_COMPILE` now speeds-up compilation of `REQUIRE*` assertions by further ~15%.
* The trade-off is disabling translation of unexpected exceptions into text.
* When Catch is compiled using C++11, `Approx` is now constructible with anything that can be explicitly converted to `double`.
* Captured messages are now printed on unexpected exceptions
### Fixes:
* Clang's `-Wexit-time-destructors` should be suppressed for Catch's internals
* GCC's `-Wparentheses` is now suppressed for all TU's that include `catch.hpp`.
* This is functionally a revert of changes made in 1.8.0, where we tried using `_Pragma` based suppression. This should have kept the suppression local to Catch's assertions, but bugs in GCC's handling of `_Pragma`s in C++ mode meant that it did not always work.
* You can now tell Catch to use C++11-based check when checking whether a type can be streamed to output.
* This fixes cases when an unstreamable type has streamable private base (#877)
* [Details can be found in documentation](configuration.md#catch_config_cpp11_stream_insertable_check)
### Other notes:
* We have added VS 2017 to our CI
* Work on Catch 2 should start soon
# 1.8.2
......@@ -29,6 +150,7 @@
* Clara no longer assumes first argument (binary name) is always present (#729)
* If it is missing, empty string is used as default.
* Clara no longer reads 1 character past argument string (#830)
* Regression in Objective-C bindings (Matchers) fixed (#854)
### Other notes:
......@@ -49,7 +171,7 @@ Cygwin issue with `gettimeofday` - `#define` was not early enough
* Matchers have new, simpler (and documented) interface.
* Catch provides string and vector matchers.
* For details see [Matchers documentation](docs/matchers.md).
* For details see [Matchers documentation](matchers.md).
* Changed console reporter test duration reporting format (#322)
* Old format: `Some simple comparisons between doubles completed in 0.000123s`
* New format: `xxx.123s: Some simple comparisons between doubles` _(There will always be exactly 3 decimal places)_
......@@ -63,7 +185,7 @@ Cygwin issue with `gettimeofday` - `#define` was not early enough
* For details see [documentation about integrating with build systems](build-systems.md).
* XML reporter now reports filename as part of the `Section` and `TestCase` tags.
* `Approx` now supports an optional margin of absolute error
* It has also received [new documentation](docs/assertions.md).
* It has also received [new documentation](assertions.md).
### Fixes
* Silenced C4312 ("conversion from int to 'ClassName *") warnings in the evaluate layer.
......@@ -106,7 +228,7 @@ Other:
### Fixes:
* Fixed inconsistency in defining `NOMINMAX` and `WIN32_LEAN_AND_MEAN` inside `catch.hpp`.
* Fixed SEH-related compilation error under older MinGW compilers, by making Windows SEH handling opt-in for compilers other than MSVC.
* For specifics, look into the [documentation](docs/configuration.md).
* For specifics, look into the [documentation](configuration.md).
* Fixed compilation error under MinGW caused by improper compiler detection.
* Fixed XML reporter sometimes leaving an empty output file when a test ends with signal/structured exception.
* Fixed XML reporter not reporting captured stdout/stderr.
......@@ -120,7 +242,7 @@ Other:
* Microbenchmark focused on Catch's overhead went from ~3.4s to ~0.7s.
* Real world test using [JSON for Modern C++](https://github.com/nlohmann/json)'s test suite went from ~6m 25s to ~4m 14s.
* Catch can now run specific sections within test cases.
* For now the support is only basic (no wildcards or tags), for details see the [documentation](docs/command-line.md).
* For now the support is only basic (no wildcards or tags), for details see the [documentation](command-line.md).
* Catch now supports SEH on Windows as well as signals on Linux.
* After receiving a signal, Catch reports failing assertion and then passes the signal onto the previous handler.
* Approx can be used to compare values against strong typedefs (available in C++11 mode only).
......@@ -157,7 +279,7 @@ Other:
* Approval tests can now be run on Windows
* CMake will now warn if a file is present in the `include` folder but not is not enumerated as part of the project
* Catch now defines `NOMINMAX` and `WIN32_LEAN_AND_MEAN` before including `windows.h`
* This can be disabled if needed, see [documentation](docs/configuration.md) for details.
* This can be disabled if needed, see [documentation](configuration.md) for details.
## 1.6.0
......
# How to release
When enough changes have accumulated, it is time to release new version of Catch. This document describes the proces in doing so, that no steps are forgotten. Note that all referenced scripts can be found in the `scripts/` directory.
## Neccessary steps
These steps are neccessary and have to be performed before each new release. They serve to make sure that the new release is correct and linked-to from the standard places.
### Approval testing
Catch's releases are primarily validated against output from previous release, stored in `projects/SelfTest/Baselines`. To validate current sources, build the SelfTest binary and pass it to the `approvalTests.py` script: `approvalTests.py <path/to/SelfTest>`.
There should be no differences, as Approval tests should be updated when changes to Catch are made, but if there are, then they need to be manually reviewed and either approved (using `approve.py`) or Catch requires other fixes.
### Incrementing version number
Catch uses a variant of [semantic versioning](http://semver.org/), with breaking API changes (and thus major version increments) being very rare. Thus, the release will usually increment the patch version, when it only contains couple of bugfixes, or minor version, when it contains new functionality, or larger changes in implementation of current functionality.
After deciding which part of version number should be incremented, you can use one of the `*Release.py` scripts to perform the required changes to Catch.
### Generate updated single-include header
After updating version number, regenerate single-include header using `generateSingleHeader.py`.
### Release notes
Once a release is ready, release notes need to be written. They should summarize changes done since last release. For rough idea of expected notes see previous releases. Once written, release notes should be placed in `docs/release-notes.md`.
### Commit and push update to GitHub
After version number is incremented, single-include header is regenerated and release notes are updated, changes should be commited and pushed to GitHub.
### Release on GitHub
After pushing changes to GitHub, GitHub release *needs* to be created. Tag version and release title should be same as the new version, description should contain the release notes for the current release. Single header version of `catch.hpp` *needs* to be attached as a binary, as that is where the official download link links to. Preferably it should use linux line endings.
## Optional steps
The following steps are optional, and do not have to be performed when releasing new version of Catch. However, they are *should* happen, but they can happen the next day without losing anything significant.
### vcpkg update
Catch is maintaining its own port in Microsoft's package manager [vcpkg](https://github.com/Microsoft/vcpkg). This means that when new version of Catch is released, it should be posted there as well. `updateVcpkgPackage.py` can do a lot of neccessary work for you, it creates a branch and commits neccessary changes. You should review these changes, push and open a PR against vcpkg's upstream.
Note that the script assumes you have your fork of vcpkg checked out in a directory next to the directory where you have checked out Catch, like so:
```
GitHub
Catch
vcpkg
```
### Wandbox update
Recently we also included a link to wandbox with preloaded Catch on the main page. Strictly speaking it is unneccessary to update this after every release, Catch usually does not change that much between versions, but it should be kept up to date anyway.
# Reporters
Catch has a modular reporting system and comes bundled with a handful of useful reporters built in.
You can also write your own reporters.
## Using different reporters
The reporter to use can easily be controlled from the command line.
To specify a reporter use [`-r` or `--reporter`](command-line.md#choosing-a-reporter-to-use), followed by the name of the reporter, e.g.:
```
-r xml
```
If you don't specify a reporter then the console reporter is used by default.
There are four reporters built in to the single include:
* `console` writes as lines of text, formatted to a typical terminal width, with colours if a capable terminal is detected.
* `compact` similar to `console` but optimised for minimal output - each entry on one line
* `junit` writes xml that corresponds to Ant's [junitreport](http://help.catchsoftware.com/display/ET/JUnit+Format) target. Useful for build systems that understand Junit. If you are using Jenkins with Catch 1.x, you can improve quality of output by applying changes in [#923](https://github.com/philsquared/Catch/pull/923).
Because of the way the junit format is structured the run must complete before anything is written.
* `xml` writes an xml format tailored to Catch. Unlike `junit` this is a streaming format so results are delivered progressively.
There are a few additional reporters, for specific build systems, in the Catch repository (in `include\reporters`) which you can `#include` in your project if you would like to make use of them.
Do this in one source file - typically the same one you have `CATCH_CONFIG_MAIN` or `CATCH_CONFIG_RUNNER`.
* `teamcity` writes the native, streaming, format that [TeamCity](https://www.jetbrains.com/teamcity/) understands.
Use this when building as part of a TeamCity build to see results as they happen.
* `tap` writes in the TAP ([Test Anything Protocol](https://en.wikipedia.org/wiki/Test_Anything_Protocol)) format.
* `automake` writes in a format that correspond to [automake .trs](https://www.gnu.org/software/automake/manual/html_node/Log-files-generation-and-test-results-recording.html) files
You see what reporters are available from the command line by running with `--list-reporters`.
By default all these reports are written to stdout, but can be redirected to a file with [`-o` or `--out`](command-line.md#sending-output-to-a-file)
## Writing your own reporter
You can write your own custom reporter and register it with Catch.
At time of writing the interface is subject to some changes so is not, yet, documented here.
If you are determined you shouldn't have too much trouble working it out from the existing implementations -
but do keep in mind upcoming changes (these will be minor, simplifying, changes such as not needing to forward calls to the base class).
---
[Home](Readme.md)
\ No newline at end of file
......@@ -28,7 +28,7 @@ The tag expression, ```"[widget]"``` selects A, B & D. ```"[gadget]"``` selects
For more detail on command line selection see [the command line docs](command-line.md#specifying-which-tests-to-run)
Tag names are not case sensitive.
Tag names are not case sensitive and can contain any ASCII characters. This means that tags `[tag with spaces]` and `[I said "good day"]` are both allowed tags and can be filtered on. Escapes are not supported however and `[\]]` is not a valid tag.
### Special Tags
......
......@@ -16,16 +16,7 @@ std::ostream& operator << ( std::ostream& os, T const& value ) {
(where ```T``` is your type and ```convertMyTypeToString``` is where you'll write whatever code is necessary to make your type printable - it doesn't have to be in another function).
You should put this function in the same namespace as your type.
Alternatively you may prefer to write it as a member function:
```
std::ostream& T::operator << ( std::ostream& os ) const {
os << convertMyTypeToString( *this );
return os;
}
```
You should put this function in the same namespace as your type and it has to be declared before including Catch's header.
## Catch::toString overload
......@@ -39,11 +30,12 @@ namespace Catch {
}
```
Again ```T``` is your type and ```convertMyTypeToString``` is where you'll write whatever code is necessary to make your type printable. Note that the function must be in the Catch namespace, which itself must be in the global namespace.
Again ```T``` is your type and ```convertMyTypeToString``` is where you'll write whatever code is necessary to make your type printable. Note that the function must be in the Catch namespace, which itself must be in the global namespace and must be declared _before_ Catch's header is included.
## Catch::StringMaker<T> specialisation
**Please note that overloading `Catch::toString` is currently considered legacy and will not be supported in the next major version of Catch.**
There are some cases where overloading toString does not work as expected. Specialising StringMaker<T> gives you more precise, and reliable, control - but at the cost of slightly more code and complexity:
## Catch::StringMaker<T> specialisation
Another way of telling Catch how to convert a type to string is specialising `Catch::StringMaker` template. This allows you to have separate way of stringifying types for Catch, than you have for writing it to a stream and also doesn't require you to declare it before including Catch's header.
```
namespace Catch {
......
差异被折叠。
File mode changed from 100644 to 100755
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论