提交 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 = module.exports =
{ {
extends : [ 'eslint:recommended' ], env:
parserOptions :
{ {
ecmaVersion : 6, es6: true,
sourceType : 'module', node: true
ecmaFeatures : },
extends:
[
'eslint:recommended'
],
settings: {},
parserOptions:
{ {
impliedStrict : true ecmaVersion: 6,
sourceType: 'module',
ecmaFeatures:
{
impliedStrict: true
} }
}, },
env : rules:
{ {
'es6' : true, 'array-bracket-spacing': [ 2, 'always',
'node' : true
},
'rules' :
{ {
'comma-dangle' : 2, objectsInArrays: true,
'comma-spacing' : [ 2, { before: false, after: true } ], arraysInArrays: true
'max-len' : }],
[ 'arrow-parens': [ 2, 'always' ],
2, '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,
{ {
code : 100, singleLine:
ignoreStrings : true, {
ignoreUrls : true, beforeColon: false,
ignoreTemplateLiterals : true, afterColon: true
tabWidth : 2, },
ignoreComments : true multiLine:
{
beforeColon: true,
afterColon: true,
align: 'colon'
} }
], }],
'no-console' : 0, 'keyword-spacing': 2,
'no-constant-condition' : 2, 'linebreak-style': [ 2, 'unix' ],
'no-control-regex' : 2, 'lines-around-comment': [ 2,
'no-dupe-args' : 2, {
'no-dupe-keys' : 2, allowBlockStart: true,
'no-duplicate-case' : 2, allowObjectStart: true,
'no-empty' : 0, beforeBlockComment: true,
'no-empty-character-class' : 2, beforeLineComment: false
'no-ex-assign' : 2, }],
'no-extra-boolean-cast' : 2, 'max-len': [ 2, 90,
'no-extra-parens' : [ 2, 'all', { nestedBinaryExpressions: false } ], {
'no-extra-semi' : 2, tabWidth: 2,
'no-func-assign' : 2, comments: 110,
'no-inner-declarations' : 2, ignoreUrls: true,
'no-invalid-regexp' : 2, ignoreStrings: true,
'no-irregular-whitespace' : 2, ignoreTemplateLiterals: true,
'no-loop-func' : 2, ignoreRegExpLiterals: true
'no-negated-in-lhs' : 2, }],
'no-obj-calls' : 2, 'newline-after-var': 2,
'no-prototype-builtins' : 2, 'newline-before-return': 2,
'no-regex-spaces' : 2, 'newline-per-chained-call': 2,
'no-sparse-arrays' : 2, 'no-alert': 2,
'no-undef' : 2, 'no-caller': 2,
'no-unexpected-multiline' : 2, 'no-case-declarations': 2,
'no-unreachable' : 2, 'no-catch-shadow': 2,
'no-unsafe-finally' : 2, 'no-class-assign': 2,
'no-unused-vars' : [ 2, { vars: 'all', args: 'after-used' }], 'no-confusing-arrow': 2,
'no-multi-spaces' : 0, 'no-console': 2,
'no-whitespace-before-property' : 2, 'no-const-assign': 2,
'quotes' : [ 2, 'single', { avoidEscape: true } ], 'no-debugger': 2,
'semi' : [ 2, 'always' ], 'no-dupe-args': 2,
'space-before-blocks' : 2, 'no-dupe-keys': 2,
'space-before-function-paren' : [ 2, 'never' ], 'no-duplicate-case': 2,
'space-in-parens' : [ 2, 'never' ], 'no-div-regex': 2,
'spaced-comment' : [ 2, 'always' ], 'no-empty': [ 2, { allowEmptyCatch: true } ],
'use-isnan' : 2, 'no-empty-pattern': 2,
'valid-typeof' : 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; ...@@ -40,7 +40,7 @@ const numCpus = os.cpus().length;
gulp.task('rtpcapabilities', () => gulp.task('rtpcapabilities', () =>
{ {
let supportedRtpCapabilities = require('./lib/supportedRtpCapabilities'); const supportedRtpCapabilities = require('./lib/supportedRtpCapabilities');
return gulp.src('worker/src/RTC/Room.cpp') return gulp.src('worker/src/RTC/Room.cpp')
// Let's generate valid syntax as expected by clang-format rules. // Let's generate valid syntax as expected by clang-format rules.
...@@ -60,7 +60,7 @@ gulp.task('lint:node', () => ...@@ -60,7 +60,7 @@ gulp.task('lint:node', () =>
gulp.task('lint:worker', () => gulp.task('lint:worker', () =>
{ {
let src = workerFiles.concat( const src = workerFiles.concat(
// Remove Ragel generated files. // Remove Ragel generated files.
'!worker/src/Utils/IP.cpp' '!worker/src/Utils/IP.cpp'
); );
...@@ -71,7 +71,7 @@ gulp.task('lint:worker', () => ...@@ -71,7 +71,7 @@ gulp.task('lint:worker', () =>
gulp.task('format:worker', () => gulp.task('format:worker', () =>
{ {
let src = workerFiles.concat( const src = workerFiles.concat(
// Remove Ragel generated files. // Remove Ragel generated files.
'!worker/src/Utils/IP.cpp' '!worker/src/Utils/IP.cpp'
); );
......
...@@ -124,7 +124,7 @@ class Channel extends EventEmitter ...@@ -124,7 +124,7 @@ class Channel extends EventEmitter
// binary event with its binary data. // binary event with its binary data.
else else
{ {
let msg = this._lastBinaryNotification; const msg = this._lastBinaryNotification;
// Reset. // Reset.
this._lastBinaryNotification = null; this._lastBinaryNotification = null;
...@@ -164,7 +164,7 @@ class Channel extends EventEmitter ...@@ -164,7 +164,7 @@ class Channel extends EventEmitter
logger.debug('close()'); logger.debug('close()');
// Close every pending sent. // Close every pending sent.
for (let sent of this._pendingSent.values()) for (const sent of this._pendingSent.values())
{ {
sent.close(); sent.close();
} }
...@@ -190,12 +190,12 @@ class Channel extends EventEmitter ...@@ -190,12 +190,12 @@ class Channel extends EventEmitter
request(method, internal, data) request(method, internal, data)
{ {
let id = utils.randomNumber(); const id = utils.randomNumber();
logger.debug('request() [method:%s, id:%s]', method, id); logger.debug('request() [method:%s, id:%s]', method, id);
let request = { id, method, internal, data }; const request = { id, method, internal, data };
let ns = netstring.nsWrite(JSON.stringify(request)); const ns = netstring.nsWrite(JSON.stringify(request));
if (Buffer.byteLength(ns) > NS_MAX_SIZE) if (Buffer.byteLength(ns) > NS_MAX_SIZE)
return Promise.reject(new Error('request too big')); return Promise.reject(new Error('request too big'));
...@@ -212,18 +212,18 @@ class Channel extends EventEmitter ...@@ -212,18 +212,18 @@ class Channel extends EventEmitter
return new Promise((pResolve, pReject) => return new Promise((pResolve, pReject) =>
{ {
let sent = const sent =
{ {
resolve: (data) => resolve : (data2) =>
{ {
if (!this._pendingSent.delete(id)) if (!this._pendingSent.delete(id))
return; return;
clearTimeout(sent.timer); clearTimeout(sent.timer);
pResolve(data); pResolve(data2);
}, },
reject: (error) => reject : (error) =>
{ {
if (!this._pendingSent.delete(id)) if (!this._pendingSent.delete(id))
return; return;
...@@ -232,7 +232,7 @@ class Channel extends EventEmitter ...@@ -232,7 +232,7 @@ class Channel extends EventEmitter
pReject(error); pReject(error);
}, },
timer: setTimeout(() => timer : setTimeout(() =>
{ {
if (!this._pendingSent.delete(id)) if (!this._pendingSent.delete(id))
return; return;
...@@ -240,7 +240,7 @@ class Channel extends EventEmitter ...@@ -240,7 +240,7 @@ class Channel extends EventEmitter
pReject(new Error('request timeout')); pReject(new Error('request timeout'));
}, REQUEST_TIMEOUT), }, REQUEST_TIMEOUT),
close: () => close : () =>
{ {
clearTimeout(sent.timer); clearTimeout(sent.timer);
pReject(new errors.InvalidStateError('Channel closed')); pReject(new errors.InvalidStateError('Channel closed'));
...@@ -259,7 +259,7 @@ class Channel extends EventEmitter ...@@ -259,7 +259,7 @@ class Channel extends EventEmitter
// If a Response, retrieve its associated Request. // If a Response, retrieve its associated Request.
if (msg.id) if (msg.id)
{ {
let sent = this._pendingSent.get(msg.id); const sent = this._pendingSent.get(msg.id);
if (!sent) if (!sent)
{ {
......
...@@ -62,10 +62,10 @@ class Peer extends EventEmitter ...@@ -62,10 +62,10 @@ class Peer extends EventEmitter
case 'newrtpsender': case 'newrtpsender':
{ {
let associatedRtpReceiver = this._sandbox.getRtpReceiverById( const associatedRtpReceiver = this._sandbox.getRtpReceiverById(
data.associatedRtpReceiverId); data.associatedRtpReceiverId);
let internal = const internal2 =
{ {
roomId : this._internal.roomId, roomId : this._internal.roomId,
peerId : this._internal.peerId, peerId : this._internal.peerId,
...@@ -73,7 +73,7 @@ class Peer extends EventEmitter ...@@ -73,7 +73,7 @@ class Peer extends EventEmitter
transportId : null transportId : null
}; };
let data2 = const data2 =
{ {
kind : data.kind, kind : data.kind,
peer : this, peer : this,
...@@ -83,7 +83,7 @@ class Peer extends EventEmitter ...@@ -83,7 +83,7 @@ class Peer extends EventEmitter
}; };
// Create a RtpSender instance. // 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. // Store the RtpSender instance and remove it when closed.
this._rtpSenders.add(rtpSender); this._rtpSenders.add(rtpSender);
...@@ -169,19 +169,19 @@ class Peer extends EventEmitter ...@@ -169,19 +169,19 @@ class Peer extends EventEmitter
this._channel.removeAllListeners(this._internal.peerId); this._channel.removeAllListeners(this._internal.peerId);
// Close every Transport. // Close every Transport.
for (let transport of this._transports) for (const transport of this._transports)
{ {
transport.close(undefined, true); transport.close(undefined, true);
} }
// Close every RtpReceiver. // Close every RtpReceiver.
for (let rtpReceiver of this._rtpReceivers) for (const rtpReceiver of this._rtpReceivers)
{ {
rtpReceiver.close(undefined, true); rtpReceiver.close(undefined, true);
} }
// Close every RtpSender. // Close every RtpSender.
for (let rtpSender of this._rtpSenders) for (const rtpSender of this._rtpSenders)
{ {
rtpSender.close(); rtpSender.close();
} }
...@@ -194,9 +194,9 @@ class Peer extends EventEmitter ...@@ -194,9 +194,9 @@ class Peer extends EventEmitter
{ {
logger.debug('"peer.close" request succeeded'); 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 ...@@ -284,7 +284,7 @@ class Peer extends EventEmitter
if (this._closed) if (this._closed)
return Promise.reject(new errors.InvalidStateError('Peer closed')); return Promise.reject(new errors.InvalidStateError('Peer closed'));
let internal = const internal =
{ {
roomId : this._internal.roomId, roomId : this._internal.roomId,
peerId : this._internal.peerId, peerId : this._internal.peerId,
...@@ -297,7 +297,7 @@ class Peer extends EventEmitter ...@@ -297,7 +297,7 @@ class Peer extends EventEmitter
logger.debug('"peer.createTransport" request succeeded'); logger.debug('"peer.createTransport" request succeeded');
// Create a Transport instance. // 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. // Store the Transport instance and remove it when closed.
this._transports.add(transport); this._transports.add(transport);
...@@ -349,7 +349,7 @@ class Peer extends EventEmitter ...@@ -349,7 +349,7 @@ class Peer extends EventEmitter
if (!this._transports.has(transport)) if (!this._transports.has(transport))
throw new Error('transport not found'); throw new Error('transport not found');
let internal = const internal =
{ {
roomId : this._internal.roomId, roomId : this._internal.roomId,
peerId : this._internal.peerId, peerId : this._internal.peerId,
...@@ -357,7 +357,7 @@ class Peer extends EventEmitter ...@@ -357,7 +357,7 @@ class Peer extends EventEmitter
transportId : transport._internal.transportId transportId : transport._internal.transportId
}; };
let data = const data =
{ {
kind : kind, kind : kind,
peer : this, peer : this,
...@@ -365,13 +365,13 @@ class Peer extends EventEmitter ...@@ -365,13 +365,13 @@ class Peer extends EventEmitter
}; };
// Create a RtpReceiver instance. // 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. // Store the RtpReceiver instance and remove it when closed.
this._rtpReceivers.add(rtpReceiver); this._rtpReceivers.add(rtpReceiver);
rtpReceiver.on('close', () => this._rtpReceivers.delete(rtpReceiver)); rtpReceiver.on('close', () => this._rtpReceivers.delete(rtpReceiver));
let options = const options =
{ {
kind : kind kind : kind
}; };
......
...@@ -37,7 +37,7 @@ class Room extends EventEmitter ...@@ -37,7 +37,7 @@ class Room extends EventEmitter
this._closed = false; this._closed = false;
// Subscribe to notifications. // Subscribe to notifications.
this._channel.on(this._internal.roomId, (event, data) => this._channel.on(this._internal.roomId, (event, data2) =>
{ {
switch (event) switch (event)
{ {
...@@ -49,27 +49,27 @@ class Room extends EventEmitter ...@@ -49,27 +49,27 @@ class Room extends EventEmitter
case 'audiolevels': case 'audiolevels':
{ {
let entries = data.entries; const entries = data2.entries;
let data2 = []; const data3 = [];
for (let entry of entries) for (const entry of entries)
{ {
let rtpReceiverId = entry[0]; const rtpReceiverId = entry[0];
let audioLevel = entry[1]; const audioLevel = entry[1];
let rtpReceiver = this._rtpReceivers.get(rtpReceiverId); const rtpReceiver = this._rtpReceivers.get(rtpReceiverId);
if (!rtpReceiver) if (!rtpReceiver)
continue; continue;
let peer = rtpReceiver.peer; const peer = rtpReceiver.peer;
if (!peer) if (!peer)
continue; 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) if (a.audioLevel > b.audioLevel)
return -1; return -1;
...@@ -186,7 +186,7 @@ class Room extends EventEmitter ...@@ -186,7 +186,7 @@ class Room extends EventEmitter
this._channel.removeAllListeners(this._internal.roomId); this._channel.removeAllListeners(this._internal.roomId);
// Close every Peer. // Close every Peer.
for (let peer of this._peers.values()) for (const peer of this._peers.values())
{ {
peer.close(undefined, true); peer.close(undefined, true);
} }
...@@ -199,9 +199,9 @@ class Room extends EventEmitter ...@@ -199,9 +199,9 @@ class Room extends EventEmitter
{ {
logger.debug('"room.close" request succeeded'); 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 ...@@ -271,14 +271,14 @@ class Room extends EventEmitter
if (this._peers.has(peerName)) if (this._peers.has(peerName))
throw new Error(`peer already exists [peerName:"${peerName}"]`); throw new Error(`peer already exists [peerName:"${peerName}"]`);
let peerId = utils.randomNumber(); const peerId = utils.randomNumber();
let internal = const internal =
{ {
roomId : this._internal.roomId, roomId : this._internal.roomId,
peerId : peerId, peerId : peerId,
peerName : peerName peerName : peerName
}; };
let sandbox = const sandbox =
{ {
getRtpReceiverById : (rtpReceiverId) => getRtpReceiverById : (rtpReceiverId) =>
{ {
...@@ -287,7 +287,7 @@ class Room extends EventEmitter ...@@ -287,7 +287,7 @@ class Room extends EventEmitter
}; };
// Create a Peer instance. // 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. // Store the Peer instance and remove it when closed.
this._peers.set(peerName, peer); this._peers.set(peerName, peer);
...@@ -335,7 +335,7 @@ class Room extends EventEmitter ...@@ -335,7 +335,7 @@ class Room extends EventEmitter
_setCapabilities(capabilities) _setCapabilities(capabilities)
{ {
for (let kind of KINDS) for (const kind of KINDS)
{ {
this._capabilities[kind] = this._capabilities[kind] =
{ {
...@@ -344,9 +344,9 @@ class Room extends EventEmitter ...@@ -344,9 +344,9 @@ class Room extends EventEmitter
fecMechanisms : [] 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) if (codec.kind === kind)
{ {
...@@ -354,7 +354,7 @@ class Room extends EventEmitter ...@@ -354,7 +354,7 @@ class Room extends EventEmitter
} }
else if (codec.kind === '') else if (codec.kind === '')
{ {
let clonedCodec = utils.clone(codec); const clonedCodec = utils.clone(codec);
clonedCodec.kind = kind; clonedCodec.kind = kind;
kindCapabilities.codecs.push(clonedCodec); kindCapabilities.codecs.push(clonedCodec);
...@@ -364,7 +364,7 @@ class Room extends EventEmitter ...@@ -364,7 +364,7 @@ class Room extends EventEmitter
// Ignore if there are no media codecs of this kind. // Ignore if there are no media codecs of this kind.
if (kindCapabilities.codecs.length > 0) if (kindCapabilities.codecs.length > 0)
{ {
for (let headerExtension of capabilities.headerExtensions) for (const headerExtension of capabilities.headerExtensions)
{ {
if (headerExtension.kind === kind) if (headerExtension.kind === kind)
{ {
...@@ -372,7 +372,7 @@ class Room extends EventEmitter ...@@ -372,7 +372,7 @@ class Room extends EventEmitter
} }
else if (headerExtension.kind === '') else if (headerExtension.kind === '')
{ {
let clonedHeaderExtension = utils.clone(headerExtension); const clonedHeaderExtension = utils.clone(headerExtension);
clonedHeaderExtension.kind = kind; clonedHeaderExtension.kind = kind;
kindCapabilities.headerExtensions.push(clonedHeaderExtension); kindCapabilities.headerExtensions.push(clonedHeaderExtension);
......
...@@ -35,7 +35,7 @@ class RtpReceiver extends EventEmitter ...@@ -35,7 +35,7 @@ class RtpReceiver extends EventEmitter
this._closed = false; this._closed = false;
// Subscribe to notifications. // Subscribe to notifications.
this._channel.on(this._internal.rtpReceiverId, (event, data, buffer) => this._channel.on(this._internal.rtpReceiverId, (event, data2, buffer) =>
{ {
switch (event) switch (event)
{ {
...@@ -54,8 +54,8 @@ class RtpReceiver extends EventEmitter ...@@ -54,8 +54,8 @@ class RtpReceiver extends EventEmitter
case 'rtpobject': case 'rtpobject':
{ {
// Append the binary buffer into `object.payload`. // Append the binary buffer into `object.payload`.
data.object.payload = buffer; data2.object.payload = buffer;
this.emit('rtpobject', data.object); this.emit('rtpobject', data2.object);
break; break;
} }
...@@ -207,9 +207,9 @@ class RtpReceiver extends EventEmitter ...@@ -207,9 +207,9 @@ class RtpReceiver extends EventEmitter
{ {
logger.debug('"rtpReceiver.close" request succeeded'); 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 ...@@ -263,7 +263,7 @@ class RtpReceiver extends EventEmitter
{ {
logger.debug('"rtpReceiver.receive" request succeeded'); logger.debug('"rtpReceiver.receive" request succeeded');
let hadParameters = !!this._data.rtpParameters; const hadParameters = Boolean(this._data.rtpParameters);
this._data.rtpParameters = data; this._data.rtpParameters = data;
...@@ -308,7 +308,7 @@ class RtpReceiver extends EventEmitter ...@@ -308,7 +308,7 @@ class RtpReceiver extends EventEmitter
if (transport.closed) if (transport.closed)
return Promise.reject(new errors.InvalidStateError('transport is 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; this._internal.transportId = transport._internal.transportId;
......
...@@ -37,7 +37,7 @@ class RtpSender extends EventEmitter ...@@ -37,7 +37,7 @@ class RtpSender extends EventEmitter
this._closed = false; this._closed = false;
// Subscribe to notifications. // Subscribe to notifications.
this._channel.on(this._internal.rtpSenderId, (event, data) => this._channel.on(this._internal.rtpSenderId, (event, data2) =>
{ {
switch (event) switch (event)
{ {
...@@ -49,16 +49,16 @@ class RtpSender extends EventEmitter ...@@ -49,16 +49,16 @@ class RtpSender extends EventEmitter
case 'parameterschange': case 'parameterschange':
{ {
this._data.rtpParameters = data.rtpParameters; this._data.rtpParameters = data2.rtpParameters;
this._data.active = data.active; this._data.active = data2.active;
this.emit('parameterschange', data.rtpParameters, data.active); this.emit('parameterschange', data2.rtpParameters, data2.active);
break; break;
} }
case 'activechange': case 'activechange':
{ {
this._data.active = data.active; this._data.active = data2.active;
this.emit('activechange', data.active); this.emit('activechange', data2.active);
break; break;
} }
...@@ -181,7 +181,7 @@ class RtpSender extends EventEmitter ...@@ -181,7 +181,7 @@ class RtpSender extends EventEmitter
if (transport.closed) if (transport.closed)
return Promise.reject(new errors.InvalidStateError('transport is 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; this._internal.transportId = transport._internal.transportId;
...@@ -224,7 +224,7 @@ class RtpSender extends EventEmitter ...@@ -224,7 +224,7 @@ class RtpSender extends EventEmitter
return this._channel.request('rtpSender.disable', this._internal, return this._channel.request('rtpSender.disable', this._internal,
{ {
disabled : false, disabled : false,
emit : !!options.emit emit : Boolean(options.emit)
}) })
.then(() => .then(() =>
{ {
...@@ -258,7 +258,7 @@ class RtpSender extends EventEmitter ...@@ -258,7 +258,7 @@ class RtpSender extends EventEmitter
return this._channel.request('rtpSender.disable', this._internal, return this._channel.request('rtpSender.disable', this._internal,
{ {
disabled : true, disabled : true,
emit : !!options.emit emit : Boolean(options.emit)
}) })
.then(() => .then(() =>
{ {
......
...@@ -33,9 +33,9 @@ class Server extends EventEmitter ...@@ -33,9 +33,9 @@ class Server extends EventEmitter
super(); super();
this.setMaxListeners(Infinity); this.setMaxListeners(Infinity);
let serverId = utils.randomString(); const serverId = utils.randomString();
const parameters = [];
let numWorkers = DEFAULT_NUM_WORKERS; let numWorkers = DEFAULT_NUM_WORKERS;
let parameters = [];
// Set of Worker instances. // Set of Worker instances.
this._workers = new Set(); this._workers = new Set();
...@@ -84,13 +84,13 @@ class Server extends EventEmitter ...@@ -84,13 +84,13 @@ class Server extends EventEmitter
// Remove rtcMinPort/rtcMaxPort (will be added per worker). // Remove rtcMinPort/rtcMaxPort (will be added per worker).
let totalRtcMinPort = options.rtcMinPort; const totalRtcMinPort = options.rtcMinPort;
let totalRtcMaxPort = options.rtcMaxPort; const totalRtcMaxPort = options.rtcMaxPort;
delete options.rtcMinPort; delete options.rtcMinPort;
delete options.rtcMaxPort; delete options.rtcMaxPort;
for (let key of Object.keys(options)) for (const key of Object.keys(options))
{ {
if (!check.includes(VALID_WORKER_PARAMETERS, key)) if (!check.includes(VALID_WORKER_PARAMETERS, key))
{ {
...@@ -102,7 +102,7 @@ class Server extends EventEmitter ...@@ -102,7 +102,7 @@ class Server extends EventEmitter
switch (key) switch (key)
{ {
case 'logTags': case 'logTags':
for (let tag of options.logTags) for (const tag of options.logTags)
{ {
parameters.push(`--logTag=${String(tag).trim()}`); parameters.push(`--logTag=${String(tag).trim()}`);
} }
...@@ -116,14 +116,14 @@ class Server extends EventEmitter ...@@ -116,14 +116,14 @@ class Server extends EventEmitter
// Create Worker instances. // Create Worker instances.
for (let i = 1; i <= numWorkers; i++) for (let i = 1; i <= numWorkers; i++)
{ {
let workerId = serverId + '#' + i; const workerId = `${serverId}#${i}`;
let workerParameters = parameters.slice(0); const workerParameters = parameters.slice(0);
// Distribute RTC ports for each worker. // Distribute RTC ports for each worker.
let rtcMinPort = totalRtcMinPort; let rtcMinPort = totalRtcMinPort;
let rtcMaxPort = totalRtcMaxPort; let rtcMaxPort = totalRtcMaxPort;
let numPorts = Math.floor((rtcMaxPort - rtcMinPort) / numWorkers); const numPorts = Math.floor((rtcMaxPort - rtcMinPort) / numWorkers);
rtcMinPort = rtcMinPort + (numPorts * (i - 1)); rtcMinPort = rtcMinPort + (numPorts * (i - 1));
rtcMaxPort = rtcMinPort + numPorts; rtcMaxPort = rtcMinPort + numPorts;
...@@ -164,7 +164,7 @@ class Server extends EventEmitter ...@@ -164,7 +164,7 @@ class Server extends EventEmitter
logger.error('close() [error:%s]', error); logger.error('close() [error:%s]', error);
// Close every Worker. // Close every Worker.
for (let worker of this._workers) for (const worker of this._workers)
{ {
worker.close(); worker.close();
} }
...@@ -184,9 +184,9 @@ class Server extends EventEmitter ...@@ -184,9 +184,9 @@ class Server extends EventEmitter
if (this._closed) if (this._closed)
return Promise.reject(new errors.InvalidStateError('Server 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()); promises.push(worker.dump());
} }
...@@ -194,7 +194,7 @@ class Server extends EventEmitter ...@@ -194,7 +194,7 @@ class Server extends EventEmitter
return Promise.all(promises) return Promise.all(promises)
.then((datas) => .then((datas) =>
{ {
let json = const json =
{ {
workers : datas workers : datas
}; };
...@@ -217,9 +217,9 @@ class Server extends EventEmitter ...@@ -217,9 +217,9 @@ class Server extends EventEmitter
if (this._closed) if (this._closed)
return Promise.reject(new errors.InvalidStateError('Server 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)); promises.push(worker.updateSettings(options));
} }
...@@ -239,7 +239,7 @@ class Server extends EventEmitter ...@@ -239,7 +239,7 @@ class Server extends EventEmitter
if (this._closed) if (this._closed)
return Promise.reject(new errors.InvalidStateError('Server closed')); return Promise.reject(new errors.InvalidStateError('Server closed'));
let worker = this._getRandomWorker(); const worker = this._getRandomWorker();
return worker.createRoom(options) return worker.createRoom(options)
.then((room) => .then((room) =>
...@@ -270,7 +270,7 @@ class Server extends EventEmitter ...@@ -270,7 +270,7 @@ class Server extends EventEmitter
_getRandomWorker() _getRandomWorker()
{ {
let array = Array.from(this._workers); const array = Array.from(this._workers);
return array[array.length * Math.random() << 0]; return array[array.length * Math.random() << 0];
} }
......
...@@ -61,7 +61,7 @@ class Transport extends EventEmitter ...@@ -61,7 +61,7 @@ class Transport extends EventEmitter
this._closed = false; this._closed = false;
// Subscribe to notifications. // Subscribe to notifications.
this._channel.on(this._internal.transportId, (event, data) => this._channel.on(this._internal.transportId, (event, data2) =>
{ {
switch (event) switch (event)
{ {
...@@ -73,27 +73,27 @@ class Transport extends EventEmitter ...@@ -73,27 +73,27 @@ class Transport extends EventEmitter
case 'iceselectedtuplechange': case 'iceselectedtuplechange':
{ {
this._data.iceSelectedTuple = data.iceSelectedTuple; this._data.iceSelectedTuple = data2.iceSelectedTuple;
// Emit it to the app. // Emit it to the app.
this.emit(event, data.iceSelectedTuple); this.emit(event, data2.iceSelectedTuple);
break; break;
} }
case 'icestatechange': case 'icestatechange':
{ {
this._data.iceState = data.iceState; this._data.iceState = data2.iceState;
// Emit it to the app. // Emit it to the app.
this.emit(event, data.iceState); this.emit(event, data2.iceState);
break; break;
} }
case 'dtlsstatechange': case 'dtlsstatechange':
{ {
this._data.dtlsState = data.dtlsState; this._data.dtlsState = data2.dtlsState;
if (data.dtlsState === 'connected') if (data2.dtlsState === 'connected')
this._data.dtlsRemoteCert = data.dtlsRemoteCert; this._data.dtlsRemoteCert = data2.dtlsRemoteCert;
// Emit it to the app. // Emit it to the app.
this.emit(event, data.dtlsState); this.emit(event, data2.dtlsState);
break; break;
} }
...@@ -185,9 +185,9 @@ class Transport extends EventEmitter ...@@ -185,9 +185,9 @@ class Transport extends EventEmitter
{ {
logger.debug('"transport.close" request succeeded'); 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 ...@@ -267,7 +267,7 @@ class Transport extends EventEmitter
if (this._closed) if (this._closed)
return Promise.reject(new errors.InvalidStateError('Transport closed')); return Promise.reject(new errors.InvalidStateError('Transport closed'));
let options = { bitrate }; const options = { bitrate };
// Send Channel request. // Send Channel request.
return this._channel.request('transport.setMaxBitrate', this._internal, options) return this._channel.request('transport.setMaxBitrate', this._internal, options)
......
...@@ -41,10 +41,11 @@ class Worker extends EventEmitter ...@@ -41,10 +41,11 @@ class Worker extends EventEmitter
super(); super();
this.setMaxListeners(Infinity); this.setMaxListeners(Infinity);
let spawnArgs = [ id ].concat(parameters); const spawnArgs = [ id ].concat(parameters);
let spawnOptions = const spawnOptions =
{ {
detached : false, detached : false,
/* /*
* fd 0 (stdin) : Just ignore it. * fd 0 (stdin) : Just ignore it.
* fd 1 (stdout) : Pipe it for 3rd libraries in the worker. * fd 1 (stdout) : Pipe it for 3rd libraries in the worker.
...@@ -67,7 +68,7 @@ class Worker extends EventEmitter ...@@ -67,7 +68,7 @@ class Worker extends EventEmitter
// Be ready for 3rd party worker libraries logging to stdout. // Be ready for 3rd party worker libraries logging to stdout.
this._child.stdout.on('data', (buffer) => 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) if (line)
logger.debug(`mediasoup-worker's stdout: ${line}`); logger.debug(`mediasoup-worker's stdout: ${line}`);
...@@ -77,11 +78,14 @@ class Worker extends EventEmitter ...@@ -77,11 +78,14 @@ class Worker extends EventEmitter
// In case of a worker bug, mediasoup will call abort() and log to stderr. // In case of a worker bug, mediasoup will call abort() and log to stderr.
this._child.stderr.on('data', (buffer) => 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) if (line)
{
// eslint-disable-next-line no-console
console.error(`mediasoup-worker's stderr: ${line}`); console.error(`mediasoup-worker's stderr: ${line}`);
} }
}
}); });
// Set child process events. // Set child process events.
...@@ -112,7 +116,7 @@ class Worker extends EventEmitter ...@@ -112,7 +116,7 @@ class Worker extends EventEmitter
logger.error('close() [error:%s]', error); logger.error('close() [error:%s]', error);
// Close every Room. // Close every Room.
for (let room of this._rooms) for (const room of this._rooms)
{ {
room.close(undefined, true); room.close(undefined, true);
} }
...@@ -176,7 +180,7 @@ class Worker extends EventEmitter ...@@ -176,7 +180,7 @@ class Worker extends EventEmitter
{ {
logger.debug('createRoom() [options:%o]', options); logger.debug('createRoom() [options:%o]', options);
let internal = const internal =
{ {
roomId : utils.randomNumber() roomId : utils.randomNumber()
}; };
...@@ -187,7 +191,7 @@ class Worker extends EventEmitter ...@@ -187,7 +191,7 @@ class Worker extends EventEmitter
logger.debug('"worker.createRoom" request succeeded'); logger.debug('"worker.createRoom" request succeeded');
// Create a Room instance. // 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. // Store the Room instance and remove it when closed.
this._rooms.add(room); this._rooms.add(room);
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
function createErrorClass(name) function createErrorClass(name)
{ {
let klass = class extends Error const klass = class extends Error
{ {
constructor(message) constructor(message)
{ {
......
...@@ -10,20 +10,22 @@ class Logger ...@@ -10,20 +10,22 @@ class Logger
{ {
if (prefix) if (prefix)
{ {
this._debug = debug(APP_NAME + ':' + prefix); this._debug = debug(`${APP_NAME}:${prefix}`);
this._warn = debug(APP_NAME + ':WARN:' + prefix); this._warn = debug(`${APP_NAME}:WARN:${prefix}`);
this._error = debug(APP_NAME + ':ERROR:' + prefix); this._error = debug(`${APP_NAME}:ERROR:${prefix}`);
} }
else else
{ {
this._debug = debug(APP_NAME); this._debug = debug(APP_NAME);
this._warn = debug(APP_NAME + ':WARN'); this._warn = debug(`${APP_NAME}:WARN`);
this._error = debug(APP_NAME + ':ERROR'); this._error = debug(`${APP_NAME}:ERROR`);
} }
/* eslint-disable no-console */
this._debug.log = console.info.bind(console); this._debug.log = console.info.bind(console);
this._warn.log = console.warn.bind(console); this._warn.log = console.warn.bind(console);
this._error.log = console.error.bind(console); this._error.log = console.error.bind(console);
/* eslint-enable no-console */
} }
get debug() get debug()
......
...@@ -9,7 +9,7 @@ const PKG = require('../package.json'); ...@@ -9,7 +9,7 @@ const PKG = require('../package.json');
logger.debug('%s version %s', PKG.name, PKG.version); logger.debug('%s version %s', PKG.name, PKG.version);
// Set of Server instances. // Set of Server instances.
let servers = new Set(); const servers = new Set();
module.exports = module.exports =
{ {
...@@ -40,7 +40,7 @@ module.exports = ...@@ -40,7 +40,7 @@ module.exports =
{ {
logger.debug('Server() [options:%o]', options); 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. // Store the Server instance and remove it when closed.
servers.add(server); servers.add(server);
...@@ -52,18 +52,18 @@ module.exports = ...@@ -52,18 +52,18 @@ module.exports =
/** /**
* Export mediasoup custom errors. * Export mediasoup custom errors.
*/ */
errors: errors, errors : errors,
/** /**
* Export the webrtc module. * Export the webrtc module.
*/ */
webrtc: webrtc webrtc : webrtc
}; };
// On process exit close all the Servers. // On process exit close all the Servers.
process.on('exit', () => process.on('exit', () =>
{ {
for (let server of servers) for (const server of servers)
{ {
server.close(); server.close();
} }
...@@ -74,7 +74,15 @@ process.on('exit', () => ...@@ -74,7 +74,15 @@ process.on('exit', () =>
process.on('unhandledRejection', (reason) => process.on('unhandledRejection', (reason) =>
{ {
if (reason instanceof Error) 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 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'; 'use strict';
let supportedRtpCapabilities = const supportedRtpCapabilities =
{ {
codecs : codecs :
[ [
......
...@@ -31,10 +31,10 @@ const ORTC_TO_SDP_PARAMETERS = new Map([ ...@@ -31,10 +31,10 @@ const ORTC_TO_SDP_PARAMETERS = new Map([
// Covert ORTC codec parameters to lowercase. // Covert ORTC codec parameters to lowercase.
const ORTC_TO_SDP_PARAMETERS_LOWERCASE = new Map(); 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]; const key = pair[0];
let value = pair[1]; const value = pair[1];
ORTC_TO_SDP_PARAMETERS_LOWERCASE.set(key.toLowerCase(), value); ORTC_TO_SDP_PARAMETERS_LOWERCASE.set(key.toLowerCase(), value);
} }
...@@ -46,7 +46,7 @@ module.exports = ...@@ -46,7 +46,7 @@ module.exports =
return randomatic('a', length || 8); return randomatic('a', length || 8);
}, },
randomNumber: randomNumberGenerator, randomNumber : randomNumberGenerator,
clone(obj) clone(obj)
{ {
...@@ -66,7 +66,7 @@ module.exports = ...@@ -66,7 +66,7 @@ module.exports =
if (typeof param !== 'string' || !param) if (typeof param !== 'string' || !param)
throw new TypeError('wrong argument'); 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) if (wellKnownParam)
return wellKnownParam; return wellKnownParam;
...@@ -75,7 +75,7 @@ module.exports = ...@@ -75,7 +75,7 @@ module.exports =
for (let i = 0, len = param.length; i < len; i++) for (let i = 0, len = param.length; i < len; i++)
{ {
let c = param[i]; const c = param[i];
if (c === c.toLowerCase()) if (c === c.toLowerCase())
{ {
......
...@@ -164,7 +164,7 @@ class RTCPeerConnectionCommon extends EventEmitter ...@@ -164,7 +164,7 @@ class RTCPeerConnectionCommon extends EventEmitter
// First set peer's capabilities. // First set peer's capabilities.
.then(() => .then(() =>
{ {
let capabilities = sdpUtils.descToCapabilities(desc.parsed); const capabilities = sdpUtils.descToCapabilities(desc.parsed);
return this._peer.setCapabilities(capabilities); return this._peer.setCapabilities(capabilities);
}) })
...@@ -249,7 +249,7 @@ class RTCPeerConnectionCommon extends EventEmitter ...@@ -249,7 +249,7 @@ class RTCPeerConnectionCommon extends EventEmitter
this._busy = false; this._busy = false;
// Create an offer. // Create an offer.
let localDescription = this._createLocalDescription('offer'); const localDescription = this._createLocalDescription('offer');
// Update flag. // Update flag.
this._initialOfferCreated = true; this._initialOfferCreated = true;
...@@ -282,7 +282,7 @@ class RTCPeerConnectionCommon extends EventEmitter ...@@ -282,7 +282,7 @@ class RTCPeerConnectionCommon extends EventEmitter
} }
// Create an answer. // Create an answer.
let localDescription = this._createLocalDescription('answer'); const localDescription = this._createLocalDescription('answer');
// Resolve with it. // Resolve with it.
return Promise.resolve(localDescription); return Promise.resolve(localDescription);
...@@ -302,7 +302,7 @@ class RTCPeerConnectionCommon extends EventEmitter ...@@ -302,7 +302,7 @@ class RTCPeerConnectionCommon extends EventEmitter
if (!this._peer.capabilities) if (!this._peer.capabilities)
return Promise.reject(new InvalidStateError('capabilities not yet set')); return Promise.reject(new InvalidStateError('capabilities not yet set'));
let remoteDescription = desc; const remoteDescription = desc;
let newSignalingState; let newSignalingState;
switch (remoteDescription.type) switch (remoteDescription.type)
...@@ -491,7 +491,7 @@ class RTCPeerConnectionCommon extends EventEmitter ...@@ -491,7 +491,7 @@ class RTCPeerConnectionCommon extends EventEmitter
if (this.closed) if (this.closed)
return Promise.reject(new InvalidStateError('closed')); return Promise.reject(new InvalidStateError('closed'));
let transport = this._peer.transports[0]; const transport = this._peer.transports[0];
return Promise.resolve() return Promise.resolve()
// First change ufrag/pwd of the Transport. // First change ufrag/pwd of the Transport.
......
...@@ -115,9 +115,9 @@ class RTCRtpTransceiver ...@@ -115,9 +115,9 @@ class RTCRtpTransceiver
toObjectMedia(type) toObjectMedia(type)
{ {
let transport = this._transport; const transport = this._transport;
let capabilities = this._capabilities; const capabilities = this._capabilities;
let objMedia = {}; const objMedia = {};
let closed = this.closed; let closed = this.closed;
// m= line. // m= line.
...@@ -146,9 +146,9 @@ class RTCRtpTransceiver ...@@ -146,9 +146,9 @@ class RTCRtpTransceiver
{ {
objMedia.candidates = []; 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 // mediasoup does not support non rtcp-mux so candidates component is
// always RTP (1). // always RTP (1).
...@@ -190,7 +190,7 @@ class RTCRtpTransceiver ...@@ -190,7 +190,7 @@ class RTCRtpTransceiver
objMedia.fmtp = []; objMedia.fmtp = [];
// Array of payload types. // Array of payload types.
let payloads = []; const payloads = [];
// Codecs. // Codecs.
let codecs; let codecs;
...@@ -201,15 +201,15 @@ class RTCRtpTransceiver ...@@ -201,15 +201,15 @@ class RTCRtpTransceiver
else else
codecs = capabilities.codecs; codecs = capabilities.codecs;
for (let codec of codecs) for (const codec of codecs)
{ {
if (codec.kind && codec.kind !== this._kind) if (codec.kind && codec.kind !== this._kind)
continue; continue;
payloads.push(codec.payloadType); payloads.push(codec.payloadType);
let codecSubtype = codec.name.split('/')[1]; const codecSubtype = codec.name.split('/')[1];
let rtp = const rtp =
{ {
payload : codec.payloadType, payload : codec.payloadType,
codec : codecSubtype, codec : codecSubtype,
...@@ -224,15 +224,15 @@ class RTCRtpTransceiver ...@@ -224,15 +224,15 @@ class RTCRtpTransceiver
// If codec has parameters add them into a=fmtp attributes. // If codec has parameters add them into a=fmtp attributes.
if (codec.parameters) if (codec.parameters)
{ {
let paramFmtp = const paramFmtp =
{ {
payload : codec.payloadType, payload : codec.payloadType,
config : '' 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) if (paramFmtp.config)
paramFmtp.config += ';'; paramFmtp.config += ';';
...@@ -246,7 +246,7 @@ class RTCRtpTransceiver ...@@ -246,7 +246,7 @@ class RTCRtpTransceiver
// Set RTCP feedback. // Set RTCP feedback.
if (codec.rtcpFeedback) if (codec.rtcpFeedback)
{ {
for (let fb of codec.rtcpFeedback) for (const fb of codec.rtcpFeedback)
{ {
objMedia.rtcpFb.push( objMedia.rtcpFb.push(
{ {
...@@ -284,7 +284,7 @@ class RTCRtpTransceiver ...@@ -284,7 +284,7 @@ class RTCRtpTransceiver
if (this._sender.rtpParameters.userParameters.msid) if (this._sender.rtpParameters.userParameters.msid)
objMedia.msid = 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( objMedia.ssrcs.push(
{ {
...@@ -307,7 +307,7 @@ class RTCRtpTransceiver ...@@ -307,7 +307,7 @@ class RTCRtpTransceiver
objMedia.ssrcGroups.push( objMedia.ssrcGroups.push(
{ {
semantics : 'FID', semantics : 'FID',
ssrcs : [encoding.ssrc, encoding.rtx.ssrc].join(' ') ssrcs : [ encoding.ssrc, encoding.rtx.ssrc ].join(' ')
}); });
} }
} }
...@@ -321,7 +321,7 @@ class RTCRtpTransceiver ...@@ -321,7 +321,7 @@ class RTCRtpTransceiver
// If a RtpSender, take the header extensions from it. // If a RtpSender, take the header extensions from it.
if (this._sender) if (this._sender)
{ {
for (let headerExtension of this._sender.rtpParameters.headerExtensions) for (const headerExtension of this._sender.rtpParameters.headerExtensions)
{ {
objMedia.ext.push( objMedia.ext.push(
{ {
...@@ -333,7 +333,7 @@ class RTCRtpTransceiver ...@@ -333,7 +333,7 @@ class RTCRtpTransceiver
// Otherwise take them from peer's capabilities. // Otherwise take them from peer's capabilities.
else else
{ {
for (let headerExtension of capabilities.headerExtensions) for (const headerExtension of capabilities.headerExtensions)
{ {
if (headerExtension.kind && headerExtension.kind !== this._kind) if (headerExtension.kind && headerExtension.kind !== this._kind)
continue; continue;
......
...@@ -7,16 +7,16 @@ module.exports = ...@@ -7,16 +7,16 @@ module.exports =
descToCapabilities(parsed) descToCapabilities(parsed)
{ {
// Map of RtpCodecParameters indexed by payload type. // Map of RtpCodecParameters indexed by payload type.
let mapCodecs = new Map(); const mapCodecs = new Map();
// RtpHeaderExtensions. // RtpHeaderExtensions.
let headerExtensions = []; const headerExtensions = [];
for (let parsedMedia of parsed.media) for (const parsedMedia of parsed.media)
{ {
// Media kind. // 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. // Ignore feature codecs.
switch (rtp.codec.toLowerCase()) switch (rtp.codec.toLowerCase())
...@@ -29,8 +29,8 @@ module.exports = ...@@ -29,8 +29,8 @@ module.exports =
} }
// TODO: This will fail for kind:depth and video/vp8, but who knows? // TODO: This will fail for kind:depth and video/vp8, but who knows?
let codecMime = kind + '/' + rtp.codec; const codecMime = `${kind}/${rtp.codec}`;
let codec = const codec =
{ {
kind : kind, kind : kind,
name : codecMime, name : codecMime,
...@@ -48,10 +48,10 @@ module.exports = ...@@ -48,10 +48,10 @@ module.exports =
if (parsedMedia.fmtp) if (parsedMedia.fmtp)
{ {
for (let fmtp of parsedMedia.fmtp) for (const fmtp of parsedMedia.fmtp)
{ {
let params = sdpTransform.parseFmtpConfig(fmtp.config); const params = sdpTransform.parseFmtpConfig(fmtp.config);
let codec = mapCodecs.get(fmtp.payload); const codec = mapCodecs.get(fmtp.payload);
if (!codec) if (!codec)
continue; continue;
...@@ -62,9 +62,9 @@ module.exports = ...@@ -62,9 +62,9 @@ module.exports =
if (parsedMedia.rtcpFb) 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) if (!codec)
continue; continue;
...@@ -79,11 +79,11 @@ module.exports = ...@@ -79,11 +79,11 @@ module.exports =
if (Array.isArray(parsedMedia.ext)) if (Array.isArray(parsedMedia.ext))
{ {
for (let ext of parsedMedia.ext) for (const ext of parsedMedia.ext)
{ {
let preferredId = ext.value; const preferredId = ext.value;
let uri = ext.uri; const uri = ext.uri;
let headerExtension = const headerExtension =
{ {
kind : kind, kind : kind,
uri : uri, uri : uri,
...@@ -95,7 +95,7 @@ module.exports = ...@@ -95,7 +95,7 @@ module.exports =
for (let i=0, len=headerExtensions.length; i<len; i++) for (let i=0, len=headerExtensions.length; i<len; i++)
{ {
let savedHeaderExtension = headerExtensions[i]; const savedHeaderExtension = headerExtensions[i];
if ( if (
headerExtension.kind === savedHeaderExtension.kind && headerExtension.kind === savedHeaderExtension.kind &&
...@@ -112,7 +112,7 @@ module.exports = ...@@ -112,7 +112,7 @@ module.exports =
} }
} }
let capabilities = const capabilities =
{ {
codecs : Array.from(mapCodecs.values()), codecs : Array.from(mapCodecs.values()),
headerExtensions : headerExtensions, headerExtensions : headerExtensions,
...@@ -127,7 +127,7 @@ module.exports = ...@@ -127,7 +127,7 @@ module.exports =
let media; let media;
// If the first media (i.e. audio) is inactive, it has no DTLS stuff so iterate. // 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) if (m.setup)
{ {
...@@ -140,7 +140,7 @@ module.exports = ...@@ -140,7 +140,7 @@ module.exports =
return null; return null;
// NOTE: Firefox uses global fingerprint attribute. // NOTE: Firefox uses global fingerprint attribute.
let remoteFingerprint = media.fingerprint || parsed.fingerprint; const remoteFingerprint = media.fingerprint || parsed.fingerprint;
let remoteDtlsRole; let remoteDtlsRole;
switch (media.setup) switch (media.setup)
...@@ -153,7 +153,7 @@ module.exports = ...@@ -153,7 +153,7 @@ module.exports =
break; break;
} }
let remoteDtlsParameters = const remoteDtlsParameters =
{ {
role : remoteDtlsRole, role : remoteDtlsRole,
fingerprint : fingerprint :
...@@ -168,15 +168,15 @@ module.exports = ...@@ -168,15 +168,15 @@ module.exports =
descToRtpHeaderExtensionParameters(parsedMedia) descToRtpHeaderExtensionParameters(parsedMedia)
{ {
let headerExtensions = []; const headerExtensions = [];
if (!Array.isArray(parsedMedia.ext)) if (!Array.isArray(parsedMedia.ext))
return headerExtensions; return headerExtensions;
for (let ext of parsedMedia.ext) for (const ext of parsedMedia.ext)
{ {
let id = ext.value; const id = ext.value;
let uri = ext.uri; const uri = ext.uri;
headerExtensions.push( headerExtensions.push(
{ {
...@@ -193,27 +193,28 @@ module.exports = ...@@ -193,27 +193,28 @@ module.exports =
*/ */
getPlanBSsrcs(parsedMedia) getPlanBSsrcs(parsedMedia)
{ {
let singleSsrcs = new Set(); const singleSsrcs = new Set();
let simulcastSsrcs = new Set(); const simulcastSsrcs = new Set();
let rtxSsrcs = new Set(); const rtxSsrcs = new Set();
let ssrcs = []; const ssrcs = [];
// Simulcast/RTX. // Simulcast/RTX.
if (Array.isArray(parsedMedia.ssrcGroups)) if (Array.isArray(parsedMedia.ssrcGroups))
{ {
for (let group of parsedMedia.ssrcGroups) for (const group of parsedMedia.ssrcGroups)
{ {
switch (group.semantics) switch (group.semantics)
{ {
case 'SIM': case 'SIM':
{ {
let simulcast = []; const simulcast = [];
for (let ssrc of group.ssrcs.split(' ')) for (const ssrc of group.ssrcs.split(' '))
{ {
ssrc = Number(ssrc); const ssrc2 = Number(ssrc);
simulcastSsrcs.add(ssrc);
simulcast.push(ssrc); simulcastSsrcs.add(ssrc2);
simulcast.push(ssrc2);
} }
ssrcs.push(simulcast); ssrcs.push(simulcast);
...@@ -223,13 +224,14 @@ module.exports = ...@@ -223,13 +224,14 @@ module.exports =
case 'FID': case 'FID':
{ {
let rtx = []; const rtx = [];
for (let ssrc of group.ssrcs.split(' ')) for (const ssrc of group.ssrcs.split(' '))
{ {
ssrc = Number(ssrc); const ssrc2 = Number(ssrc);
rtxSsrcs.add(ssrc);
rtx.push(ssrc); rtxSsrcs.add(ssrc2);
rtx.push(ssrc2);
} }
ssrcs.push(rtx); ssrcs.push(rtx);
...@@ -243,9 +245,9 @@ module.exports = ...@@ -243,9 +245,9 @@ module.exports =
// Single streams. // Single streams.
if (Array.isArray(parsedMedia.ssrcs)) 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)) if (simulcastSsrcs.has(ssrc) || singleSsrcs.has(ssrc) || rtxSsrcs.has(ssrc))
continue; continue;
...@@ -260,7 +262,7 @@ module.exports = ...@@ -260,7 +262,7 @@ module.exports =
getPlanBTrackInfo(parsedMedia, ssrc) getPlanBTrackInfo(parsedMedia, ssrc)
{ {
let info = const info =
{ {
cname : null, cname : null,
msid : null, msid : null,
...@@ -274,7 +276,7 @@ module.exports = ...@@ -274,7 +276,7 @@ module.exports =
if (Array.isArray(ssrc)) if (Array.isArray(ssrc))
ssrc = ssrc[0]; ssrc = ssrc[0];
for (let ssrcObj of parsedMedia.ssrcs) for (const ssrcObj of parsedMedia.ssrcs)
{ {
if (ssrcObj.id !== ssrc) if (ssrcObj.id !== ssrc)
continue; continue;
......
...@@ -12,7 +12,7 @@ class RTCSessionDescription ...@@ -12,7 +12,7 @@ class RTCSessionDescription
*/ */
constructor(descriptionInitDict) constructor(descriptionInitDict)
{ {
let type = descriptionInitDict.type; const type = descriptionInitDict.type;
switch (type) switch (type)
{ {
......
差异被折叠。
{ {
"name": "mediasoup", "name": "mediasoup",
"version": "1.2.8", "version": "2.0.0-alpha",
"description": "Cutting Edge WebRTC Video Conferencing", "description": "Cutting Edge WebRTC Video Conferencing",
"author": "Iñaki Baz Castillo <ibc@aliax.net> (https://inakibaz.me)", "author": "Iñaki Baz Castillo <ibc@aliax.net> (https://inakibaz.me)",
"contributors": [ "contributors": [
...@@ -30,15 +30,16 @@ ...@@ -30,15 +30,16 @@
}, },
"main": "lib/mediasoup.js", "main": "lib/mediasoup.js",
"dependencies": { "dependencies": {
"check-types": "^7.2.0", "check-types": "^7.3.0",
"clone": "^2.1.1", "clone": "^2.1.1",
"debug": "^2.6.8", "debug": "^3.0.0",
"netstring": "^0.3.0", "netstring": "^0.3.0",
"random-number": "0.0.7", "random-number": "0.0.9",
"randomatic": "^1.1.7", "randomatic": "^1.1.7",
"sdp-transform": "^2.3.0" "sdp-transform": "^2.3.0"
}, },
"devDependencies": { "devDependencies": {
"eslint": "^4.5.0",
"gulp": "github:gulpjs/gulp#4.0", "gulp": "github:gulpjs/gulp#4.0",
"gulp-clang-format": "^1.0.23", "gulp-clang-format": "^1.0.23",
"gulp-eslint": "^4.0.0", "gulp-eslint": "^4.0.0",
...@@ -46,7 +47,7 @@ ...@@ -46,7 +47,7 @@
"gulp-replace": "^0.6.1", "gulp-replace": "^0.6.1",
"gulp-shell": "^0.6.3", "gulp-shell": "^0.6.3",
"gulp-touch-cmd": "0.0.1", "gulp-touch-cmd": "0.0.1",
"tap": "^10.7.0" "tap": "^10.7.2"
}, },
"optionalDependencies": { "optionalDependencies": {
"clang-tools-prebuilt": "^0.1.4" "clang-tools-prebuilt": "^0.1.4"
......
...@@ -7,7 +7,7 @@ const peerCapabilities = require('./data/options').peerCapabilities; ...@@ -7,7 +7,7 @@ const peerCapabilities = require('./data/options').peerCapabilities;
function initTest(t) function initTest(t)
{ {
let server = mediasoup.Server(); const server = mediasoup.Server();
let peer; let peer;
t.tearDown(() => server.close()); t.tearDown(() => server.close());
...@@ -30,7 +30,7 @@ tap.test('peer.createTransport() with no options must succeed', { timeout: 2000 ...@@ -30,7 +30,7 @@ tap.test('peer.createTransport() with no options must succeed', { timeout: 2000
return initTest(t) return initTest(t)
.then((data) => .then((data) =>
{ {
let peer = data.peer; const peer = data.peer;
t.equal(peer.name, 'alice', 'peer.name must be "alice"'); 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 ...@@ -40,10 +40,10 @@ tap.test('peer.createTransport() with no options must succeed', { timeout: 2000
t.pass('peer.createTransport() succeeded'); t.pass('peer.createTransport() succeeded');
return peer.dump() return peer.dump()
.then((data) => .then((data2) =>
{ {
t.pass('peer.dump() succeeded'); 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(); t.end();
}) })
.catch((error) => t.fail(`peer.dump() failed: ${error}`)); .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 ...@@ -56,7 +56,7 @@ tap.test('peer.createTransport() with no udp nor tcp must fail', { timeout: 2000
return initTest(t) return initTest(t)
.then((data) => .then((data) =>
{ {
let peer = data.peer; const peer = data.peer;
return peer.createTransport({ udp: false, tcp: false }) return peer.createTransport({ udp: false, tcp: false })
.then(() => t.fail('peer.createTransport() succeeded')) .then(() => t.fail('peer.createTransport() succeeded'))
...@@ -72,7 +72,7 @@ tap.test('peer.RtpReceiver() with valid transport must succeed', { timeout: 2000 ...@@ -72,7 +72,7 @@ tap.test('peer.RtpReceiver() with valid transport must succeed', { timeout: 2000
return initTest(t) return initTest(t)
.then((data) => .then((data) =>
{ {
let peer = data.peer; const peer = data.peer;
let rtpReceiver; let rtpReceiver;
return peer.createTransport({ tcp: false }) return peer.createTransport({ tcp: false })
...@@ -87,10 +87,10 @@ tap.test('peer.RtpReceiver() with valid transport must succeed', { timeout: 2000 ...@@ -87,10 +87,10 @@ tap.test('peer.RtpReceiver() with valid transport must succeed', { timeout: 2000
return peer.dump(); return peer.dump();
}) })
.then((data) => .then((data2) =>
{ {
t.pass('peer.dump() succeeded'); 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'); 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 ...@@ -101,7 +101,7 @@ tap.test('peer.RtpReceiver() with a closed transport must fail', { timeout: 2000
return initTest(t) return initTest(t)
.then((data) => .then((data) =>
{ {
let peer = data.peer; const peer = data.peer;
return peer.createTransport({ tcp: false }) return peer.createTransport({ tcp: false })
.then((transport) => .then((transport) =>
...@@ -125,7 +125,7 @@ tap.test('peer.RtpReceiver() with invalid kind must fail', { timeout: 2000 }, (t ...@@ -125,7 +125,7 @@ tap.test('peer.RtpReceiver() with invalid kind must fail', { timeout: 2000 }, (t
return initTest(t) return initTest(t)
.then((data) => .then((data) =>
{ {
let peer = data.peer; const peer = data.peer;
return peer.createTransport({ tcp: false }) return peer.createTransport({ tcp: false })
.then((transport) => .then((transport) =>
......
...@@ -7,14 +7,14 @@ const peerOptions = require('./data/options').peerOptions; ...@@ -7,14 +7,14 @@ const peerOptions = require('./data/options').peerOptions;
tap.test('room.Peer() with peerName must succeed', { timeout: 2000 }, (t) => tap.test('room.Peer() with peerName must succeed', { timeout: 2000 }, (t) =>
{ {
let server = mediasoup.Server(); const server = mediasoup.Server();
t.tearDown(() => server.close()); t.tearDown(() => server.close());
server.createRoom(roomOptions) server.createRoom(roomOptions)
.then((room) => .then((room) =>
{ {
let peer = room.Peer('alice', peerOptions); const peer = room.Peer('alice', peerOptions);
peer.on('close', (error) => peer.on('close', (error) =>
{ {
...@@ -30,7 +30,7 @@ tap.test('room.Peer() with peerName must succeed', { timeout: 2000 }, (t) => ...@@ -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) => tap.test('room.Peer() without peerName must fail', { timeout: 2000 }, (t) =>
{ {
let server = mediasoup.Server(); const server = mediasoup.Server();
t.tearDown(() => server.close()); t.tearDown(() => server.close());
...@@ -51,7 +51,7 @@ tap.test('room.Peer() without peerName must fail', { timeout: 2000 }, (t) => ...@@ -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) => tap.test('room.Peer() with same peerName must fail', { timeout: 2000 }, (t) =>
{ {
let server = mediasoup.Server(); const server = mediasoup.Server();
t.tearDown(() => server.close()); t.tearDown(() => server.close());
...@@ -73,14 +73,14 @@ tap.test('room.Peer() with same peerName must fail', { timeout: 2000 }, (t) => ...@@ -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) => 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()); t.tearDown(() => server.close());
server.createRoom(roomOptions) server.createRoom(roomOptions)
.then((room) => .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.getPeer('alice'), peer1, 'room.getPeer() must retrieve the first "alice"');
t.equal(room.peers.length, 1, 'room.peers must retrieve one peer'); 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 ...@@ -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.notOk(room.getPeer('alice'), 'room.getPeer() must retrieve nothing');
t.equal(room.peers.length, 0, 'room.peers must retrieve zero peers'); 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.getPeer('alice'), peer2, 'room.getPeer() must retrieve the new "alice"');
t.equal(room.peers.length, 1, 'room.peers must retrieve one peer'); 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 ...@@ -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) => tap.test('room.peers must retrieve existing peers', { timeout: 2000 }, (t) =>
{ {
let server = mediasoup.Server(); const server = mediasoup.Server();
t.tearDown(() => server.close()); t.tearDown(() => server.close());
server.createRoom(roomOptions) server.createRoom(roomOptions)
.then((room) => .then((room) =>
{ {
let alice = room.Peer('alice', peerOptions); const alice = room.Peer('alice', peerOptions);
let bob = room.Peer('bob', peerOptions); const bob = room.Peer('bob', peerOptions);
let carol = room.Peer('carol', peerOptions); const carol = room.Peer('carol', peerOptions);
bob.close(); bob.close();
...@@ -131,7 +131,7 @@ tap.test('room.peers must retrieve existing peers', { timeout: 2000 }, (t) => ...@@ -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) => tap.test('room.getCapabilities() must retrieve current room capabilities', { timeout: 2000 }, (t) =>
{ {
let server = mediasoup.Server(); const server = mediasoup.Server();
t.tearDown(() => server.close()); t.tearDown(() => server.close());
...@@ -148,7 +148,7 @@ tap.test('room.getCapabilities() must retrieve current room capabilities', { tim ...@@ -148,7 +148,7 @@ tap.test('room.getCapabilities() must retrieve current room capabilities', { tim
tap.test('room.dump() must succeed', { timeout: 2000 }, (t) => tap.test('room.dump() must succeed', { timeout: 2000 }, (t) =>
{ {
let server = mediasoup.Server(); const server = mediasoup.Server();
t.tearDown(() => server.close()); t.tearDown(() => server.close());
......
...@@ -8,7 +8,7 @@ const promiseSeries = require('./utils/promiseSeries'); ...@@ -8,7 +8,7 @@ const promiseSeries = require('./utils/promiseSeries');
function initTest(t) function initTest(t)
{ {
let server = mediasoup.Server(); const server = mediasoup.Server();
let peer; let peer;
t.tearDown(() => server.close()); t.tearDown(() => server.close());
...@@ -35,9 +35,9 @@ tap.test('rtpReceiver.receive() with no encodings must succeed', { timeout: 2000 ...@@ -35,9 +35,9 @@ tap.test('rtpReceiver.receive() with no encodings must succeed', { timeout: 2000
return initTest(t) return initTest(t)
.then((data) => .then((data) =>
{ {
let peer = data.peer; const peer = data.peer;
let transport = data.transport; const transport = data.transport;
let rtpReceiver = peer.RtpReceiver('audio', transport); const rtpReceiver = peer.RtpReceiver('audio', transport);
t.equal(rtpReceiver.peer, peer, 'associated peer must match'); t.equal(rtpReceiver.peer, peer, 'associated peer must match');
...@@ -56,7 +56,7 @@ tap.test('rtpReceiver.receive() with no encodings must succeed', { timeout: 2000 ...@@ -56,7 +56,7 @@ tap.test('rtpReceiver.receive() with no encodings must succeed', { timeout: 2000
{ {
t.pass('rtpReceiver.receive() succeeded'); t.pass('rtpReceiver.receive() succeeded');
let rtpParameters = rtpReceiver.rtpParameters; const rtpParameters = rtpReceiver.rtpParameters;
t.assert(rtpParameters.encodings, 'computed rtpParameters has encodings'); t.assert(rtpParameters.encodings, 'computed rtpParameters has encodings');
t.equal(rtpParameters.encodings.length, 1, 'encodings has 1 encoding'); t.equal(rtpParameters.encodings.length, 1, 'encodings has 1 encoding');
...@@ -71,9 +71,9 @@ tap.test('rtpReceiver.receive() with encodings without codecPayloadType must suc ...@@ -71,9 +71,9 @@ tap.test('rtpReceiver.receive() with encodings without codecPayloadType must suc
return initTest(t) return initTest(t)
.then((data) => .then((data) =>
{ {
let peer = data.peer; const peer = data.peer;
let transport = data.transport; const transport = data.transport;
let rtpReceiver = peer.RtpReceiver('video', transport); const rtpReceiver = peer.RtpReceiver('video', transport);
return rtpReceiver.receive( return rtpReceiver.receive(
{ {
...@@ -112,7 +112,7 @@ tap.test('rtpReceiver.receive() with encodings without codecPayloadType must suc ...@@ -112,7 +112,7 @@ tap.test('rtpReceiver.receive() with encodings without codecPayloadType must suc
{ {
t.pass('rtpReceiver.receive() succeeded'); t.pass('rtpReceiver.receive() succeeded');
let rtpParameters = rtpReceiver.rtpParameters; const rtpParameters = rtpReceiver.rtpParameters;
t.equal(rtpParameters.encodings.length, 3, 'computed rtpParameters has 3 encodings'); t.equal(rtpParameters.encodings.length, 3, 'computed rtpParameters has 3 encodings');
t.equal(rtpParameters.encodings[0].codecPayloadType, 110, 'first encoding has codecPayloadType 110'); t.equal(rtpParameters.encodings[0].codecPayloadType, 110, 'first encoding has codecPayloadType 110');
...@@ -128,10 +128,10 @@ tap.test('rtpReceiver.receive() with full rtpParameters must succeed', { timeout ...@@ -128,10 +128,10 @@ tap.test('rtpReceiver.receive() with full rtpParameters must succeed', { timeout
return initTest(t) return initTest(t)
.then((data) => .then((data) =>
{ {
let peer = data.peer; const peer = data.peer;
let transport = data.transport; const transport = data.transport;
let rtpReceiver = peer.RtpReceiver('video', transport); const rtpReceiver = peer.RtpReceiver('video', transport);
let rtpParameters = const rtpParameters =
{ {
muxId : 'abcd', muxId : 'abcd',
codecs : codecs :
...@@ -226,11 +226,11 @@ tap.test('two rtpReceiver.receive() over the same transport sharing PT values mu ...@@ -226,11 +226,11 @@ tap.test('two rtpReceiver.receive() over the same transport sharing PT values mu
return initTest(t) return initTest(t)
.then((data) => .then((data) =>
{ {
let peer = data.peer; const peer = data.peer;
let transport = data.transport; const transport = data.transport;
let rtpReceiver1 = peer.RtpReceiver('audio', transport); const rtpReceiver1 = peer.RtpReceiver('audio', transport);
let rtpReceiver2 = peer.RtpReceiver('audio', transport); const rtpReceiver2 = peer.RtpReceiver('audio', transport);
let promises = []; const promises = [];
promises.push(rtpReceiver1.receive( promises.push(rtpReceiver1.receive(
{ {
...@@ -285,9 +285,9 @@ tap.test('rtpReceiver.receive() without rtpParameters must fail', { timeout: 200 ...@@ -285,9 +285,9 @@ tap.test('rtpReceiver.receive() without rtpParameters must fail', { timeout: 200
return initTest(t) return initTest(t)
.then((data) => .then((data) =>
{ {
let peer = data.peer; const peer = data.peer;
let transport = data.transport; const transport = data.transport;
let rtpReceiver = peer.RtpReceiver('audio', transport); const rtpReceiver = peer.RtpReceiver('audio', transport);
return rtpReceiver.receive() return rtpReceiver.receive()
.then(() => t.fail('rtpReceiver.receive() succeeded')) .then(() => t.fail('rtpReceiver.receive() succeeded'))
...@@ -303,10 +303,10 @@ tap.test('rtpReceiver.receive() with wrong codecs must fail', { timeout: 2000 }, ...@@ -303,10 +303,10 @@ tap.test('rtpReceiver.receive() with wrong codecs must fail', { timeout: 2000 },
return initTest(t) return initTest(t)
.then((data) => .then((data) =>
{ {
let peer = data.peer; const peer = data.peer;
let transport = data.transport; const transport = data.transport;
let rtpReceiver = peer.RtpReceiver('audio', transport); const rtpReceiver = peer.RtpReceiver('audio', transport);
let funcs = []; const funcs = [];
funcs.push(function() funcs.push(function()
{ {
...@@ -510,10 +510,10 @@ tap.test('rtpReceiver.receive() with wrong encodings must fail', { timeout: 2000 ...@@ -510,10 +510,10 @@ tap.test('rtpReceiver.receive() with wrong encodings must fail', { timeout: 2000
return initTest(t) return initTest(t)
.then((data) => .then((data) =>
{ {
let peer = data.peer; const peer = data.peer;
let transport = data.transport; const transport = data.transport;
let rtpReceiver = peer.RtpReceiver('audio', transport); const rtpReceiver = peer.RtpReceiver('audio', transport);
let funcs = []; const funcs = [];
funcs.push(function() funcs.push(function()
{ {
...@@ -550,11 +550,11 @@ tap.test('two rtpReceiver.receive() over the same transport sharing PT values mu ...@@ -550,11 +550,11 @@ tap.test('two rtpReceiver.receive() over the same transport sharing PT values mu
return initTest(t) return initTest(t)
.then((data) => .then((data) =>
{ {
let peer = data.peer; const peer = data.peer;
let transport = data.transport; const transport = data.transport;
let rtpReceiver1 = peer.RtpReceiver('audio', transport); const rtpReceiver1 = peer.RtpReceiver('audio', transport);
let rtpReceiver2 = peer.RtpReceiver('audio', transport); const rtpReceiver2 = peer.RtpReceiver('audio', transport);
let promises = []; const promises = [];
promises.push(rtpReceiver1.receive( promises.push(rtpReceiver1.receive(
{ {
...@@ -598,10 +598,10 @@ tap.test('rtpReceiver.receive() should produce the expected RTP listener routing ...@@ -598,10 +598,10 @@ tap.test('rtpReceiver.receive() should produce the expected RTP listener routing
return initTest(t) return initTest(t)
.then((data) => .then((data) =>
{ {
let peer = data.peer; const peer = data.peer;
let transport = data.transport; const transport = data.transport;
let rtpReceiver = peer.RtpReceiver('audio', transport); const rtpReceiver = peer.RtpReceiver('audio', transport);
let funcs = []; const funcs = [];
funcs.push(function() funcs.push(function()
{ {
...@@ -620,11 +620,11 @@ tap.test('rtpReceiver.receive() should produce the expected RTP listener routing ...@@ -620,11 +620,11 @@ tap.test('rtpReceiver.receive() should produce the expected RTP listener routing
{ {
return transport.dump(); return transport.dump();
}) })
.then((data) => .then((data2) =>
{ {
let id = rtpReceiver._internal.rtpReceiverId; const id = rtpReceiver._internal.rtpReceiverId;
t.same(data.rtpListener, t.same(data2.rtpListener,
{ {
muxIdTable : {}, muxIdTable : {},
ptTable : ptTable :
...@@ -660,11 +660,11 @@ tap.test('rtpReceiver.receive() should produce the expected RTP listener routing ...@@ -660,11 +660,11 @@ tap.test('rtpReceiver.receive() should produce the expected RTP listener routing
{ {
return transport.dump(); return transport.dump();
}) })
.then((data) => .then((data2) =>
{ {
let id = rtpReceiver._internal.rtpReceiverId; const id = rtpReceiver._internal.rtpReceiverId;
t.same(data.rtpListener, t.same(data2.rtpListener,
{ {
muxIdTable : muxIdTable :
{ {
...@@ -713,11 +713,11 @@ tap.test('rtpReceiver.receive() should produce the expected RTP listener routing ...@@ -713,11 +713,11 @@ tap.test('rtpReceiver.receive() should produce the expected RTP listener routing
{ {
return transport.dump(); return transport.dump();
}) })
.then((data) => .then((data2) =>
{ {
let id = rtpReceiver._internal.rtpReceiverId; const id = rtpReceiver._internal.rtpReceiverId;
t.same(data.rtpListener, t.same(data2.rtpListener,
{ {
muxIdTable : {}, muxIdTable : {},
ptTable : ptTable :
...@@ -767,11 +767,11 @@ tap.test('rtpReceiver.receive() should produce the expected RTP listener routing ...@@ -767,11 +767,11 @@ tap.test('rtpReceiver.receive() should produce the expected RTP listener routing
{ {
return transport.dump(); return transport.dump();
}) })
.then((data) => .then((data2) =>
{ {
let id = rtpReceiver._internal.rtpReceiverId; const id = rtpReceiver._internal.rtpReceiverId;
t.same(data.rtpListener, t.same(data2.rtpListener,
{ {
muxIdTable : {}, muxIdTable : {},
ptTable : {}, ptTable : {},
...@@ -824,11 +824,11 @@ tap.test('rtpReceiver.receive() should produce the expected RTP listener routing ...@@ -824,11 +824,11 @@ tap.test('rtpReceiver.receive() should produce the expected RTP listener routing
{ {
return transport.dump(); return transport.dump();
}) })
.then((data) => .then((data2) =>
{ {
let id = rtpReceiver._internal.rtpReceiverId; const id = rtpReceiver._internal.rtpReceiverId;
t.same(data.rtpListener, t.same(data2.rtpListener,
{ {
muxIdTable : {}, muxIdTable : {},
ptTable : ptTable :
...@@ -856,9 +856,9 @@ tap.test('rtpReceiver.close() must succeed', { timeout: 2000 }, (t) => ...@@ -856,9 +856,9 @@ tap.test('rtpReceiver.close() must succeed', { timeout: 2000 }, (t) =>
return initTest(t) return initTest(t)
.then((data) => .then((data) =>
{ {
let peer = data.peer; const peer = data.peer;
let transport = data.transport; const transport = data.transport;
let rtpReceiver = peer.RtpReceiver('audio', transport); const rtpReceiver = peer.RtpReceiver('audio', transport);
setTimeout(() => rtpReceiver.close(), 100); setTimeout(() => rtpReceiver.close(), 100);
......
...@@ -6,7 +6,7 @@ const roomOptions = require('./data/options').roomOptions; ...@@ -6,7 +6,7 @@ const roomOptions = require('./data/options').roomOptions;
tap.test('server.updateSettings() with no options must succeed', { timeout: 2000 }, (t) => tap.test('server.updateSettings() with no options must succeed', { timeout: 2000 }, (t) =>
{ {
let server = mediasoup.Server(); const server = mediasoup.Server();
t.tearDown(() => server.close()); t.tearDown(() => server.close());
...@@ -21,7 +21,7 @@ tap.test('server.updateSettings() with no options must succeed', { timeout: 2000 ...@@ -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) => tap.test('server.updateSettings() with valid options must succeed', { timeout: 2000 }, (t) =>
{ {
let server = mediasoup.Server(); const server = mediasoup.Server();
t.tearDown(() => server.close()); t.tearDown(() => server.close());
...@@ -36,7 +36,7 @@ tap.test('server.updateSettings() with valid options must succeed', { timeout: 2 ...@@ -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) => tap.test('server.updateSettings() with invalid options must fail', { timeout: 2000 }, (t) =>
{ {
let server = mediasoup.Server(); const server = mediasoup.Server();
t.tearDown(() => server.close()); t.tearDown(() => server.close());
...@@ -51,7 +51,7 @@ tap.test('server.updateSettings() with invalid options must fail', { timeout: 20 ...@@ -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) => 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()); t.tearDown(() => server.close());
...@@ -72,7 +72,7 @@ tap.test('server.updateSettings() in a closed server must fail', { timeout: 2000 ...@@ -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) => tap.test('server.createRoom() must succeed', { _timeout: 2000 }, (t) =>
{ {
let server = mediasoup.Server(); const server = mediasoup.Server();
t.tearDown(() => server.close()); t.tearDown(() => server.close());
...@@ -95,7 +95,7 @@ tap.test('server.createRoom() must succeed', { _timeout: 2000 }, (t) => ...@@ -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) => tap.test('server.createRoom() in a closed server must fail', { timeout: 2000 }, (t) =>
{ {
let server = mediasoup.Server(); const server = mediasoup.Server();
server.close(); server.close();
...@@ -111,7 +111,7 @@ tap.test('server.createRoom() in a closed server must fail', { timeout: 2000 }, ...@@ -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) => 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()); t.tearDown(() => server.close());
......
...@@ -6,7 +6,7 @@ const roomOptions = require('./data/options').roomOptions; ...@@ -6,7 +6,7 @@ const roomOptions = require('./data/options').roomOptions;
function initTest(t) function initTest(t)
{ {
let server = mediasoup.Server(); const server = mediasoup.Server();
let peer; let peer;
t.tearDown(() => server.close()); t.tearDown(() => server.close());
...@@ -29,7 +29,7 @@ tap.test('transport.setRemoteDtlsParameters() with "server" role must succeed', ...@@ -29,7 +29,7 @@ tap.test('transport.setRemoteDtlsParameters() with "server" role must succeed',
return initTest(t) return initTest(t)
.then((data) => .then((data) =>
{ {
let transport = data.transport; const transport = data.transport;
t.equal(transport.dtlsLocalParameters.role, 'auto', 'default local DTLS role must be "auto"'); 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', ...@@ -49,10 +49,10 @@ tap.test('transport.setRemoteDtlsParameters() with "server" role must succeed',
return transport.dump(); return transport.dump();
}) })
.then((data) => .then((data2) =>
{ {
t.pass('transport.dump() succeeded'); 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', { ...@@ -62,7 +62,7 @@ tap.test('transport.setRemoteDtlsParameters() with "auto" role must succeed', {
return initTest(t) return initTest(t)
.then((data) => .then((data) =>
{ {
let transport = data.transport; const transport = data.transport;
return transport.setRemoteDtlsParameters( return transport.setRemoteDtlsParameters(
{ {
...@@ -80,10 +80,10 @@ tap.test('transport.setRemoteDtlsParameters() with "auto" role must succeed', { ...@@ -80,10 +80,10 @@ tap.test('transport.setRemoteDtlsParameters() with "auto" role must succeed', {
return transport.dump(); return transport.dump();
}) })
.then((data) => .then((data2) =>
{ {
t.pass('transport.dump() succeeded'); 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 ...@@ -93,7 +93,7 @@ tap.test('transport.setRemoteDtlsParameters() with no role must succeed', { time
return initTest(t) return initTest(t)
.then((data) => .then((data) =>
{ {
let transport = data.transport; const transport = data.transport;
return transport.setRemoteDtlsParameters( return transport.setRemoteDtlsParameters(
{ {
...@@ -110,10 +110,10 @@ tap.test('transport.setRemoteDtlsParameters() with no role must succeed', { time ...@@ -110,10 +110,10 @@ tap.test('transport.setRemoteDtlsParameters() with no role must succeed', { time
return transport.dump(); return transport.dump();
}) })
.then((data) => .then((data2) =>
{ {
t.pass('transport.dump() succeeded'); 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 ...@@ -123,7 +123,7 @@ tap.test('transport.setRemoteDtlsParameters() with invalid role must fail', { ti
return initTest(t) return initTest(t)
.then((data) => .then((data) =>
{ {
let transport = data.transport; const transport = data.transport;
return transport.setRemoteDtlsParameters( return transport.setRemoteDtlsParameters(
{ {
...@@ -148,7 +148,7 @@ tap.test('transport.setRemoteDtlsParameters() without fingerprint must fail', { ...@@ -148,7 +148,7 @@ tap.test('transport.setRemoteDtlsParameters() without fingerprint must fail', {
return initTest(t) return initTest(t)
.then((data) => .then((data) =>
{ {
let transport = data.transport; const transport = data.transport;
return transport.setRemoteDtlsParameters( return transport.setRemoteDtlsParameters(
{ {
...@@ -165,7 +165,7 @@ tap.test('transport.setRemoteDtlsParameters() without fingerprint must fail', { ...@@ -165,7 +165,7 @@ tap.test('transport.setRemoteDtlsParameters() without fingerprint must fail', {
tap.test('transport.close() must succeed', { timeout: 2000 }, (t) => tap.test('transport.close() must succeed', { timeout: 2000 }, (t) =>
{ {
let server = mediasoup.Server(); const server = mediasoup.Server();
t.plan(6); t.plan(6);
t.tearDown(() => server.close()); t.tearDown(() => server.close());
...@@ -173,7 +173,7 @@ tap.test('transport.close() must succeed', { timeout: 2000 }, (t) => ...@@ -173,7 +173,7 @@ tap.test('transport.close() must succeed', { timeout: 2000 }, (t) =>
server.createRoom(roomOptions) server.createRoom(roomOptions)
.then((room) => .then((room) =>
{ {
let peer = room.Peer('alice'); const peer = room.Peer('alice');
peer.createTransport({ tcp: false }) peer.createTransport({ tcp: false })
.then((transport) => .then((transport) =>
...@@ -192,7 +192,7 @@ tap.test('transport.close() must succeed', { timeout: 2000 }, (t) => ...@@ -192,7 +192,7 @@ tap.test('transport.close() must succeed', { timeout: 2000 }, (t) =>
t.pass('peer.dump() succeeded'); t.pass('peer.dump() succeeded');
t.equal(Object.keys(data.transports).length, 0, 'peer.dump() must retrieve zero transports'); 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); setTimeout(() => transport.close(), 100);
...@@ -203,7 +203,7 @@ tap.test('transport.close() must succeed', { timeout: 2000 }, (t) => ...@@ -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) => tap.test('create transport in a server with rtcAnnouncedIPv4', { timeout: 2000 }, (t) =>
{ {
let server = mediasoup.Server( const server = mediasoup.Server(
{ {
rtcIPv4 : true, rtcIPv4 : true,
rtcIPv6 : false, rtcIPv6 : false,
...@@ -224,8 +224,8 @@ tap.test('create transport in a server with rtcAnnouncedIPv4', { timeout: 2000 } ...@@ -224,8 +224,8 @@ tap.test('create transport in a server with rtcAnnouncedIPv4', { timeout: 2000 }
}) })
.then((transport) => .then((transport) =>
{ {
let candidates = transport.iceLocalCandidates; const candidates = transport.iceLocalCandidates;
let candidate = candidates[0]; const candidate = candidates[0];
t.equal(candidates.length, 1, 'transport has 1 ICE local candidate'); t.equal(candidates.length, 1, 'transport has 1 ICE local candidate');
t.equal(candidate.protocol, 'udp', 'candidate.protocol must be udp'); 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 } ...@@ -238,8 +238,8 @@ tap.test('create transport in a server with rtcAnnouncedIPv4', { timeout: 2000 }
}) })
.then((transport) => .then((transport) =>
{ {
let candidates = transport.iceLocalCandidates; const candidates = transport.iceLocalCandidates;
let candidate = candidates[0]; const candidate = candidates[0];
t.equal(candidates.length, 1, 'transport has 1 ICE local candidate'); t.equal(candidates.length, 1, 'transport has 1 ICE local candidate');
t.equal(candidate.protocol, 'tcp', 'candidate.protocol must be tcp'); t.equal(candidate.protocol, 'tcp', 'candidate.protocol must be tcp');
......
...@@ -6,7 +6,7 @@ const mediasoup = require('../'); ...@@ -6,7 +6,7 @@ const mediasoup = require('../');
tap.test('mediasoup.Server() with no options must succeed', { timeout: 2000 }, (t) => tap.test('mediasoup.Server() with no options must succeed', { timeout: 2000 }, (t) =>
{ {
let server = mediasoup.Server(); const server = mediasoup.Server();
server.on('close', (error) => server.on('close', (error) =>
{ {
...@@ -19,7 +19,7 @@ tap.test('mediasoup.Server() with no options must succeed', { timeout: 2000 }, ( ...@@ -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) => tap.test('mediasoup.Server() with valid options must succeed', { timeout: 2000 }, (t) =>
{ {
let server = mediasoup.Server( const server = mediasoup.Server(
{ {
numWorkers : 1, numWorkers : 1,
logLevel : 'warn' logLevel : 'warn'
...@@ -36,7 +36,7 @@ tap.test('mediasoup.Server() with valid options must succeed', { timeout: 2000 } ...@@ -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) => tap.test('mediasoup.Server() with valid DTLS certificate must succeed', { timeout: 2000 }, (t) =>
{ {
let server = mediasoup.Server( const server = mediasoup.Server(
{ {
numWorkers : 1, numWorkers : 1,
dtlsCertificateFile : path.join(__dirname, 'data', 'dtls-cert.pem'), dtlsCertificateFile : path.join(__dirname, 'data', 'dtls-cert.pem'),
...@@ -54,7 +54,7 @@ tap.test('mediasoup.Server() with valid DTLS certificate must succeed', { timeou ...@@ -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) => 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) => server.on('close', (error) =>
{ {
...@@ -65,7 +65,7 @@ tap.test('mediasoup.Server() with wrong options must fail', { timeout: 2000 }, ( ...@@ -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) => 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) => server.on('close', (error) =>
{ {
...@@ -76,7 +76,7 @@ tap.test('mediasoup.Server() with non existing rtcIPv4 IP must fail', { timeout: ...@@ -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) => 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) => server.on('close', (error) =>
{ {
......
差异被折叠。
...@@ -5,14 +5,14 @@ module.exports = function(funcs) ...@@ -5,14 +5,14 @@ module.exports = function(funcs)
return new Promise((resolve, reject) => return new Promise((resolve, reject) =>
{ {
let i = 0; let i = 0;
let len = funcs.length; const len = funcs.length;
function next() function next()
{ {
if (i >= len) if (i >= len)
return resolve(); return resolve();
let func = funcs[i]; const func = funcs[i];
func() func()
.then(() => .then(() =>
......
...@@ -2,6 +2,9 @@ ...@@ -2,6 +2,9 @@
Please do not submit pull requests changing the `version.hpp` Please do not submit pull requests changing the `version.hpp`
or the single-include `catch.hpp` file, these are changed or the single-include `catch.hpp` file, these are changed
only when a new release is made. 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,12 +11,12 @@ matrix: ...@@ -11,12 +11,12 @@ matrix:
apt: apt:
sources: ['llvm-toolchain-precise', 'ubuntu-toolchain-r-test'] sources: ['llvm-toolchain-precise', 'ubuntu-toolchain-r-test']
packages: ['clang'] packages: ['clang']
env: COMPILER='clang++' BUILD_TYPE='Release' CPP11=0 env: COMPILER='clang++' BUILD_TYPE='Release'
- os: linux - os: linux
compiler: clang compiler: clang
addons: *clang34 addons: *clang34
env: COMPILER='clang++' BUILD_TYPE='Debug' CPP11=0 env: COMPILER='clang++' BUILD_TYPE='Debug'
- os: linux - os: linux
compiler: clang compiler: clang
...@@ -24,12 +24,12 @@ matrix: ...@@ -24,12 +24,12 @@ matrix:
apt: apt:
sources: ['llvm-toolchain-precise-3.5', 'ubuntu-toolchain-r-test'] sources: ['llvm-toolchain-precise-3.5', 'ubuntu-toolchain-r-test']
packages: ['clang-3.5'] packages: ['clang-3.5']
env: COMPILER='clang++-3.5' BUILD_TYPE='Release' CPP11=0 env: COMPILER='clang++-3.5' BUILD_TYPE='Release'
- os: linux - os: linux
compiler: clang compiler: clang
addons: *clang35 addons: *clang35
env: COMPILER='clang++-3.5' BUILD_TYPE='Debug' CPP11=0 env: COMPILER='clang++-3.5' BUILD_TYPE='Debug'
- os: linux - os: linux
...@@ -38,12 +38,12 @@ matrix: ...@@ -38,12 +38,12 @@ matrix:
apt: apt:
sources: ['llvm-toolchain-precise-3.6', 'ubuntu-toolchain-r-test'] sources: ['llvm-toolchain-precise-3.6', 'ubuntu-toolchain-r-test']
packages: ['clang-3.6'] packages: ['clang-3.6']
env: COMPILER='clang++-3.6' BUILD_TYPE='Release' CPP11=0 env: COMPILER='clang++-3.6' BUILD_TYPE='Release'
- os: linux - os: linux
compiler: clang compiler: clang
addons: *clang36 addons: *clang36
env: COMPILER='clang++-3.6' BUILD_TYPE='Debug' CPP11=0 env: COMPILER='clang++-3.6' BUILD_TYPE='Debug'
- os: linux - os: linux
...@@ -52,12 +52,12 @@ matrix: ...@@ -52,12 +52,12 @@ matrix:
apt: apt:
sources: ['llvm-toolchain-precise-3.7', 'ubuntu-toolchain-r-test'] sources: ['llvm-toolchain-precise-3.7', 'ubuntu-toolchain-r-test']
packages: ['clang-3.7'] packages: ['clang-3.7']
env: COMPILER='clang++-3.7' BUILD_TYPE='Release' CPP11=0 env: COMPILER='clang++-3.7' BUILD_TYPE='Release'
- os: linux - os: linux
compiler: clang compiler: clang
addons: *clang37 addons: *clang37
env: COMPILER='clang++-3.7' BUILD_TYPE='Debug' CPP11=0 env: COMPILER='clang++-3.7' BUILD_TYPE='Debug'
- os: linux - os: linux
...@@ -66,12 +66,12 @@ matrix: ...@@ -66,12 +66,12 @@ matrix:
apt: apt:
sources: ['llvm-toolchain-precise-3.8', 'ubuntu-toolchain-r-test'] sources: ['llvm-toolchain-precise-3.8', 'ubuntu-toolchain-r-test']
packages: ['clang-3.8'] packages: ['clang-3.8']
env: COMPILER='clang++-3.8' BUILD_TYPE='Release' CPP11=0 env: COMPILER='clang++-3.8' BUILD_TYPE='Release'
- os: linux - os: linux
compiler: clang compiler: clang
addons: *clang38 addons: *clang38
env: COMPILER='clang++-3.8' BUILD_TYPE='Debug' CPP11=0 env: COMPILER='clang++-3.8' BUILD_TYPE='Debug'
# 2/ Linux GCC Builds # 2/ Linux GCC Builds
...@@ -81,12 +81,12 @@ matrix: ...@@ -81,12 +81,12 @@ matrix:
apt: apt:
sources: ['ubuntu-toolchain-r-test'] sources: ['ubuntu-toolchain-r-test']
packages: ['g++-4.4'] packages: ['g++-4.4']
env: COMPILER='g++-4.4' BUILD_TYPE='Release' CPP11=0 env: COMPILER='g++-4.4' BUILD_TYPE='Release'
- os: linux - os: linux
compiler: gcc compiler: gcc
addons: *gcc44 addons: *gcc44
env: COMPILER='g++-4.4' BUILD_TYPE='Debug' CPP11=0 env: COMPILER='g++-4.4' BUILD_TYPE='Debug'
- os: linux - os: linux
...@@ -95,12 +95,12 @@ matrix: ...@@ -95,12 +95,12 @@ matrix:
apt: apt:
sources: ['ubuntu-toolchain-r-test'] sources: ['ubuntu-toolchain-r-test']
packages: ['g++-4.7'] packages: ['g++-4.7']
env: COMPILER='g++-4.7' BUILD_TYPE='Release' CPP11=0 env: COMPILER='g++-4.7' BUILD_TYPE='Release'
- os: linux - os: linux
compiler: gcc compiler: gcc
addons: *gcc47 addons: *gcc47
env: COMPILER='g++-4.7' BUILD_TYPE='Debug' CPP11=0 env: COMPILER='g++-4.7' BUILD_TYPE='Debug'
- os: linux - os: linux
...@@ -109,12 +109,12 @@ matrix: ...@@ -109,12 +109,12 @@ matrix:
apt: apt:
sources: ['ubuntu-toolchain-r-test'] sources: ['ubuntu-toolchain-r-test']
packages: ['g++-4.8'] packages: ['g++-4.8']
env: COMPILER='g++-4.8' BUILD_TYPE='Release' CPP11=0 env: COMPILER='g++-4.8' BUILD_TYPE='Release'
- os: linux - os: linux
compiler: gcc compiler: gcc
addons: *gcc48 addons: *gcc48
env: COMPILER='g++-4.8' BUILD_TYPE='Debug' CPP11=0 env: COMPILER='g++-4.8' BUILD_TYPE='Debug'
- os: linux - os: linux
...@@ -123,12 +123,12 @@ matrix: ...@@ -123,12 +123,12 @@ matrix:
apt: apt:
sources: ['ubuntu-toolchain-r-test'] sources: ['ubuntu-toolchain-r-test']
packages: ['g++-4.9'] packages: ['g++-4.9']
env: COMPILER='g++-4.9' BUILD_TYPE='Release' CPP11=0 env: COMPILER='g++-4.9' BUILD_TYPE='Release'
- os: linux - os: linux
compiler: gcc compiler: gcc
addons: *gcc49 addons: *gcc49
env: COMPILER='g++-4.9' BUILD_TYPE='Debug' CPP11=0 env: COMPILER='g++-4.9' BUILD_TYPE='Debug'
- os: linux - os: linux
...@@ -137,12 +137,12 @@ matrix: ...@@ -137,12 +137,12 @@ matrix:
apt: apt:
sources: ['ubuntu-toolchain-r-test'] sources: ['ubuntu-toolchain-r-test']
packages: ['g++-5'] packages: ['g++-5']
env: COMPILER='g++-5' BUILD_TYPE='Release' CPP11=0 env: COMPILER='g++-5' BUILD_TYPE='Release'
- os: linux - os: linux
compiler: gcc compiler: gcc
addons: *gcc5 addons: *gcc5
env: COMPILER='g++-5' BUILD_TYPE='Debug' CPP11=0 env: COMPILER='g++-5' BUILD_TYPE='Debug'
- os: linux - os: linux
...@@ -151,20 +151,17 @@ matrix: ...@@ -151,20 +151,17 @@ matrix:
apt: apt:
sources: ['ubuntu-toolchain-r-test'] sources: ['ubuntu-toolchain-r-test']
packages: ['g++-6'] packages: ['g++-6']
env: COMPILER='g++-6' BUILD_TYPE='Release' CPP11=0 env: COMPILER='g++-6' BUILD_TYPE='Release'
- os: linux - os: linux
compiler: gcc compiler: gcc
addons: *gcc6 addons: *gcc6
env: COMPILER='g++-6' BUILD_TYPE='Debug' CPP11=0 env: COMPILER='g++-6' BUILD_TYPE='Debug'
# 3a/ Linux C++11 GCC builds # 3a/ Linux C++11 GCC builds
- os: linux - os: linux
compiler: gcc compiler: gcc
addons: &gcc48 addons: *gcc48
apt:
sources: ['ubuntu-toolchain-r-test']
packages: ['g++-4.8']
env: COMPILER='g++-4.8' BUILD_TYPE='Release' CPP11=1 env: COMPILER='g++-4.8' BUILD_TYPE='Release' CPP11=1
- os: linux - os: linux
...@@ -175,10 +172,7 @@ matrix: ...@@ -175,10 +172,7 @@ matrix:
# 3b/ Linux C++11 Clang builds # 3b/ Linux C++11 Clang builds
- os: linux - os: linux
compiler: clang compiler: clang
addons: &clang38 addons: *clang38
apt:
sources: ['llvm-toolchain-precise-3.8', 'ubuntu-toolchain-r-test']
packages: ['clang-3.8']
env: COMPILER='clang++-3.8' BUILD_TYPE='Release' CPP11=1 env: COMPILER='clang++-3.8' BUILD_TYPE='Release' CPP11=1
- os: linux - os: linux
...@@ -186,27 +180,69 @@ matrix: ...@@ -186,27 +180,69 @@ matrix:
addons: *clang38 addons: *clang38
env: COMPILER='clang++-3.8' BUILD_TYPE='Debug' CPP11=1 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 - os: osx
osx_image: xcode7.3 osx_image: xcode7.3
compiler: clang compiler: clang
env: COMPILER='clang++' BUILD_TYPE='Debug' CPP11=0 env: COMPILER='clang++' BUILD_TYPE='Debug'
- os: osx - os: osx
osx_image: xcode7.3 osx_image: xcode7.3
compiler: clang 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 - os: osx
osx_image: xcode8 osx_image: xcode8
compiler: clang compiler: clang
env: COMPILER='clang++' BUILD_TYPE='Debug' CPP11=0 env: COMPILER='clang++' BUILD_TYPE='Debug' USE_CPP14=1
- os: osx - os: osx
osx_image: xcode8 osx_image: xcode8
compiler: clang compiler: clang
env: COMPILER='clang++' BUILD_TYPE='Release' CPP11=0 env: COMPILER='clang++' BUILD_TYPE='Release' USE_CPP14=1
install: install:
...@@ -224,7 +260,7 @@ install: ...@@ -224,7 +260,7 @@ install:
before_script: before_script:
- export CXX=${COMPILER} - export CXX=${COMPILER}
- cd ${TRAVIS_BUILD_DIR} - 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 - cd Build
script: script:
......
...@@ -19,6 +19,10 @@ elseif(USE_CPP14) ...@@ -19,6 +19,10 @@ elseif(USE_CPP14)
set(CMAKE_CXX_FLAGS "-std=c++14 ${CMAKE_CXX_FLAGS}") set(CMAKE_CXX_FLAGS "-std=c++14 ${CMAKE_CXX_FLAGS}")
endif() 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 #checks that the given hard-coded list contains all headers + sources in the given folder
function(CheckFileList LIST_VAR FOLDER) function(CheckFileList LIST_VAR FOLDER)
set(MESSAGE " should be added to the variable ${LIST_VAR}") set(MESSAGE " should be added to the variable ${LIST_VAR}")
...@@ -55,6 +59,7 @@ set(TEST_SOURCES ...@@ -55,6 +59,7 @@ set(TEST_SOURCES
${SELF_TEST_DIR}/CmdLineTests.cpp ${SELF_TEST_DIR}/CmdLineTests.cpp
${SELF_TEST_DIR}/CompilationTests.cpp ${SELF_TEST_DIR}/CompilationTests.cpp
${SELF_TEST_DIR}/ConditionTests.cpp ${SELF_TEST_DIR}/ConditionTests.cpp
${SELF_TEST_DIR}/DecompositionTests.cpp
${SELF_TEST_DIR}/EnumToString.cpp ${SELF_TEST_DIR}/EnumToString.cpp
${SELF_TEST_DIR}/ExceptionTests.cpp ${SELF_TEST_DIR}/ExceptionTests.cpp
${SELF_TEST_DIR}/GeneratorTests.cpp ${SELF_TEST_DIR}/GeneratorTests.cpp
...@@ -245,28 +250,35 @@ SOURCE_GROUP("Benchmarks" FILES ${BENCH_SOURCES}) ...@@ -245,28 +250,35 @@ SOURCE_GROUP("Benchmarks" FILES ${BENCH_SOURCES})
# configure the executable # configure the executable
include_directories(${HEADER_DIR}) include_directories(${HEADER_DIR})
add_executable(SelfTest ${TEST_SOURCES} ${IMPL_SOURCES} ${HEADERS})
add_executable(Benchmark ${BENCH_SOURCES} ${HEADERS})
# Add desired warnings # Projects consuming Catch via ExternalProject_Add might want to use install step
if ( CMAKE_CXX_COMPILER_ID MATCHES "Clang|AppleClang|GNU" ) # 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( SelfTest PRIVATE -Wall -Wextra )
target_compile_options( Benchmark PRIVATE -Wall -Wextra ) target_compile_options( Benchmark PRIVATE -Wall -Wextra )
endif() endif()
if ( CMAKE_CXX_COMPILER_ID MATCHES "MSVC" ) if ( CMAKE_CXX_COMPILER_ID MATCHES "MSVC" )
target_compile_options( SelfTest PRIVATE /W4 /w44265 /WX ) target_compile_options( SelfTest PRIVATE /W4 /w44265 /WX )
target_compile_options( Benchmark PRIVATE /W4 ) target_compile_options( Benchmark PRIVATE /W4 )
endif() 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 add_test(NAME ListTags COMMAND SelfTest --list-tags)
enable_testing() set_tests_properties(ListTags PROPERTIES PASS_REGULAR_EXPRESSION "[0-9]+ tags")
add_test(NAME RunTests COMMAND SelfTest)
add_test(NAME ListTests COMMAND SelfTest --list-tests) endif() # !NO_SELFTEST
set_tests_properties(ListTests PROPERTIES PASS_REGULAR_EXPRESSION "[0-9]+ test cases")
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 @@ ...@@ -3,8 +3,9 @@
[![Github Releases](https://img.shields.io/github/release/philsquared/catch.svg)](https://github.com/philsquared/catch/releases) [![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://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) [![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? ## What's the Catch?
...@@ -21,3 +22,7 @@ This documentation comprises these three parts: ...@@ -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) * 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) * 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) * 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 string format -- This will be overwritten later anyway
version: "{build}" version: "{build}"
# Disable the dead branch for v2 development
branches:
except:
- develop-v2
os: os:
- Visual Studio 2013 - Visual Studio 2017
- Visual Studio 2015 - 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: init:
- git config --global core.autocrlf input - git config --global core.autocrlf input
...@@ -31,8 +47,8 @@ configuration: ...@@ -31,8 +47,8 @@ configuration:
#Cmake will autodetect the compiler, but we set the arch #Cmake will autodetect the compiler, but we set the arch
before_build: before_build:
- echo Running cmake... - set CXXFLAGS=%additional_flags%
- cmake -H. -BBuild -A%PLATFORM% - cmake -H. -BBuild -A%PLATFORM% -DUSE_WMAIN=%wmain%
# build with MSBuild # build with MSBuild
build: 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. To get the most out of Catch, start with the [tutorial](tutorial.md).
Once you're up and running consider the following reference material.
Before looking at this material be sure to read the [tutorial](tutorial.md)
Writing tests:
* [Assertion macros](assertions.md) * [Assertion macros](assertions.md)
* [Matchers](matchers.md) * [Matchers](matchers.md)
* [Logging macros](logging.md) * [Logging macros](logging.md)
* [Test cases and sections](test-cases-and-sections.md) * [Test cases and sections](test-cases-and-sections.md)
* [Test fixtures](test-fixtures.md) * [Test fixtures](test-fixtures.md)
* [Supplying your own main()](own-main.md) * [Reporters](reporters.md)
* [Event Listeners](event-listeners.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) * [String Conversions](tostring.md)
Running:
* [Command line](command-line.md) * [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) * [Why are my tests slow to compile?](slow-compiles.md)
* [Known limitations](limitations.md) * [Known limitations](limitations.md)
Other Other:
* [Why Catch?](why-catch.md) * [Why Catch?](why-catch.md)
* [Open Source Projects using Catch](opensource-users.md) * [Open Source Projects using Catch](opensource-users.md)
* [Contributing](contributing.md) * [Contributing](contributing.md)
......
...@@ -95,7 +95,7 @@ Expects that an exception (of any type) is be thrown during evaluation of the ex ...@@ -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 * **REQUIRE_THROWS_AS(** _expression_, _exception type_ **)** and
* **CHECK_THROWS_AS(** _expression_, _exception type_ **)** * **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 * **REQUIRE_THROWS_WITH(** _expression_, _string or string matcher_ **)** and
* **CHECK_THROWS_WITH(** _expression_, _string or string matcher_ **)** * **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 ...@@ -131,6 +131,11 @@ To support Matchers a slightly different form is used. Matchers have [their own
Matchers can be composed using `&&`, `||` and `!` operators. 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) [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. 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 ...@@ -56,8 +56,26 @@ Because of the incremental nature of Catch's test suites and ability to run spec
## CMake ## 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
cmake_minimum_required(VERSION 2.8.8) cmake_minimum_required(VERSION 2.8.8)
project(catch_builder CXX) project(catch_builder CXX)
...@@ -90,6 +108,36 @@ include_directories(${CATCH_INCLUDE_DIR} ${COMMON_INCLUDES}) ...@@ -90,6 +108,36 @@ include_directories(${CATCH_INCLUDE_DIR} ${COMMON_INCLUDES})
enable_testing(true) # Enables unit-testing. 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) [Home](Readme.md)
# Commercial users of Catch # 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 As well as [Open Source](opensource-users.md) users Catch is widely used within proprietary code bases too.
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 like to keep this information internal, and that's fine,
many organisations as possible that use Catch somewhere in their codebase. Enterprise environments often tend to be but if you're more open it would be great if we could list the names of as
far more conservative in their tool adoption - and being aware that other companies are using Catch can ease the many organisations as possible that use Catch somewhere in their codebase.
path in. 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 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 - Bloomberg
- NASA
- [Inscopix Inc.](https://www.inscopix.com/)
...@@ -43,12 +43,19 @@ By default a console width of 80 is assumed but this can be controlled by defini ...@@ -43,12 +43,19 @@ By default a console width of 80 is assumed but this can be controlled by defini
CATCH_CONFIG_NOSTDOUT 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& cout();
std::ostream& cerr(); 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 # C++ conformance toggles
...@@ -63,6 +70,7 @@ This can be useful on certain platforms that do not provide ```std::cout``` and ...@@ -63,6 +70,7 @@ This can be useful on certain platforms that do not provide ```std::cout``` and
CATCH_CONFIG_CPP11_UNIQUE_PTR // Use std::unique_ptr instead of std::auto_ptr 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_SHUFFLE // Use std::shuffle instead of std::random_shuffle
CATCH_CONFIG_CPP11_TYPE_TRAITS // Use std::enable_if and <type_traits> 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. 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. 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 ...@@ -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` 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 # Other toggles
CATCH_CONFIG_COUNTER // Use __COUNTER__ to generate unique names for test cases CATCH_CONFIG_COUNTER // Use __COUNTER__ to generate unique names for test cases
CATCH_CONFIG_WINDOWS_SEH // Enable SEH handling on Windows 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_POSIX_SIGNALS // Enable handling POSIX signals
CATCH_CONFIG_WINDOWS_CRTDBG // Enable leak checking using Windows's CRT Debug Heap 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. 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_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. `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`. 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 # 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: 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 ...@@ -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, _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 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 `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 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. 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`. 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. 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 ...@@ -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!__ 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...* *this document is still in-progress...*
--- ---
......
...@@ -31,7 +31,7 @@ struct MyListener : Catch::TestEventListenerBase { ...@@ -31,7 +31,7 @@ struct MyListener : Catch::TestEventListenerBase {
// Perform some setup before a test case is run // 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 // Tear-down after a test case is run
} }
}; };
......
# Logging macros # 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 ## Streaming macros
......
...@@ -13,6 +13,7 @@ which consists of either a single matcher or one or more matchers combined using ...@@ -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: For example, to assert that a string ends with a certain substring:
```c++ ```c++
using Catch::Matchers::EndsWith; // or Catch::EndsWith
std::string str = getStringFromSomewhere(); std::string str = getStringFromSomewhere();
REQUIRE_THAT( str, EndsWith( "as a service" ) ); REQUIRE_THAT( str, EndsWith( "as a service" ) );
``` ```
...@@ -34,7 +35,7 @@ REQUIRE_THAT( str, ...@@ -34,7 +35,7 @@ REQUIRE_THAT( str,
``` ```
## Built in matchers ## 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 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. 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 # 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? 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. 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 ...@@ -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) ### [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 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) ### [SOCI](https://github.com/SOCI/soci)
The C++ Database Access Library 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) ### [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 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 ...@@ -46,6 +55,9 @@ A library of algorithms for values-distributed-in-time
### [Trompeloeil](https://github.com/rollbear/trompeloeil) ### [Trompeloeil](https://github.com/rollbear/trompeloeil)
A thread safe header only mocking framework for C++14 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 ## Applications & Tools
### [ArangoDB](https://github.com/arangodb/arangodb) ### [ArangoDB](https://github.com/arangodb/arangodb)
...@@ -54,6 +66,9 @@ ArangoDB is a native multi-model database with flexible data models for document ...@@ -54,6 +66,9 @@ ArangoDB is a native multi-model database with flexible data models for document
### [MAME](https://github.com/mamedev/mame) ### [MAME](https://github.com/mamedev/mame)
MAME originally stood for Multiple Arcade Machine Emulator 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](https://github.com/foonathan/standardese)
Standardese aims to be a nextgen Doxygen 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 # 1.8.2
...@@ -29,6 +150,7 @@ ...@@ -29,6 +150,7 @@
* Clara no longer assumes first argument (binary name) is always present (#729) * Clara no longer assumes first argument (binary name) is always present (#729)
* If it is missing, empty string is used as default. * If it is missing, empty string is used as default.
* Clara no longer reads 1 character past argument string (#830) * Clara no longer reads 1 character past argument string (#830)
* Regression in Objective-C bindings (Matchers) fixed (#854)
### Other notes: ### Other notes:
...@@ -49,7 +171,7 @@ Cygwin issue with `gettimeofday` - `#define` was not early enough ...@@ -49,7 +171,7 @@ Cygwin issue with `gettimeofday` - `#define` was not early enough
* Matchers have new, simpler (and documented) interface. * Matchers have new, simpler (and documented) interface.
* Catch provides string and vector matchers. * 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) * Changed console reporter test duration reporting format (#322)
* Old format: `Some simple comparisons between doubles completed in 0.000123s` * 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)_ * 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 ...@@ -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). * 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. * XML reporter now reports filename as part of the `Section` and `TestCase` tags.
* `Approx` now supports an optional margin of absolute error * `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 ### Fixes
* Silenced C4312 ("conversion from int to 'ClassName *") warnings in the evaluate layer. * Silenced C4312 ("conversion from int to 'ClassName *") warnings in the evaluate layer.
...@@ -106,7 +228,7 @@ Other: ...@@ -106,7 +228,7 @@ Other:
### Fixes: ### Fixes:
* Fixed inconsistency in defining `NOMINMAX` and `WIN32_LEAN_AND_MEAN` inside `catch.hpp`. * 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. * 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 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 sometimes leaving an empty output file when a test ends with signal/structured exception.
* Fixed XML reporter not reporting captured stdout/stderr. * Fixed XML reporter not reporting captured stdout/stderr.
...@@ -120,7 +242,7 @@ Other: ...@@ -120,7 +242,7 @@ Other:
* Microbenchmark focused on Catch's overhead went from ~3.4s to ~0.7s. * 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. * 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. * 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. * 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. * 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). * Approx can be used to compare values against strong typedefs (available in C++11 mode only).
...@@ -157,7 +279,7 @@ Other: ...@@ -157,7 +279,7 @@ Other:
* Approval tests can now be run on Windows * 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 * 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` * 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 ## 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 ...@@ -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) 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 ### Special Tags
......
...@@ -16,16 +16,7 @@ std::ostream& operator << ( std::ostream& os, T const& value ) { ...@@ -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). (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. You should put this function in the same namespace as your type and it has to be declared before including Catch's header.
Alternatively you may prefer to write it as a member function:
```
std::ostream& T::operator << ( std::ostream& os ) const {
os << convertMyTypeToString( *this );
return os;
}
```
## Catch::toString overload ## Catch::toString overload
...@@ -39,11 +30,12 @@ namespace Catch { ...@@ -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 { namespace Catch {
......
...@@ -68,7 +68,7 @@ with expansion: ...@@ -68,7 +68,7 @@ with expansion:
0 == 1 0 == 1
``` ```
Note that we get the actual return value of Factorial(0) printed for us (0) - even though we used a natural expression with the == operator. That let's us immediately see what the problem is. Note that we get the actual return value of Factorial(0) printed for us (0) - even though we used a natural expression with the == operator. That lets us immediately see what the problem is.
Let's change the factorial function to: Let's change the factorial function to:
...@@ -80,7 +80,7 @@ unsigned int Factorial( unsigned int number ) { ...@@ -80,7 +80,7 @@ unsigned int Factorial( unsigned int number ) {
Now all the tests pass. Now all the tests pass.
Of course there are still more issues to do deal with. For example we'll hit problems when the return value starts to exceed the range of an unsigned int. With factorials that can happen quite quickly. You might want to add tests for such cases and decide how to handle them. We'll stop short of doing that here. Of course there are still more issues to deal with. For example we'll hit problems when the return value starts to exceed the range of an unsigned int. With factorials that can happen quite quickly. You might want to add tests for such cases and decide how to handle them. We'll stop short of doing that here.
## What did we do here? ## What did we do here?
......
...@@ -31,10 +31,14 @@ namespace Catch { ...@@ -31,10 +31,14 @@ namespace Catch {
return reporter; return reporter;
} }
#if !defined(CATCH_CONFIG_DEFAULT_REPORTER)
#define CATCH_CONFIG_DEFAULT_REPORTER "console"
#endif
Ptr<IStreamingReporter> makeReporter( Ptr<Config> const& config ) { Ptr<IStreamingReporter> makeReporter( Ptr<Config> const& config ) {
std::vector<std::string> reporters = config->getReporterNames(); std::vector<std::string> reporters = config->getReporterNames();
if( reporters.empty() ) if( reporters.empty() )
reporters.push_back( "console" ); reporters.push_back( CATCH_CONFIG_DEFAULT_REPORTER );
Ptr<IStreamingReporter> reporter; Ptr<IStreamingReporter> reporter;
for( std::vector<std::string>::const_iterator it = reporters.begin(), itEnd = reporters.end(); for( std::vector<std::string>::const_iterator it = reporters.begin(), itEnd = reporters.end();
...@@ -95,11 +99,11 @@ namespace Catch { ...@@ -95,11 +99,11 @@ namespace Catch {
if( lastSlash != std::string::npos ) if( lastSlash != std::string::npos )
filename = filename.substr( lastSlash+1 ); filename = filename.substr( lastSlash+1 );
std::string::size_type lastDot = filename.find_last_of( "." ); std::string::size_type lastDot = filename.find_last_of( '.' );
if( lastDot != std::string::npos ) if( lastDot != std::string::npos )
filename = filename.substr( 0, lastDot ); filename = filename.substr( 0, lastDot );
tags.insert( "#" + filename ); tags.insert( '#' + filename );
setTags( test, tags ); setTags( test, tags );
} }
} }
...@@ -125,7 +129,7 @@ namespace Catch { ...@@ -125,7 +129,7 @@ namespace Catch {
} }
void showHelp( std::string const& processName ) { void showHelp( std::string const& processName ) {
Catch::cout() << "\nCatch v" << libraryVersion << "\n"; Catch::cout() << "\nCatch v" << libraryVersion() << "\n";
m_cli.usage( Catch::cout(), processName ); m_cli.usage( Catch::cout(), processName );
Catch::cout() << "For more detail usage please see the project docs\n" << std::endl; Catch::cout() << "For more detail usage please see the project docs\n" << std::endl;
...@@ -166,6 +170,32 @@ namespace Catch { ...@@ -166,6 +170,32 @@ namespace Catch {
return returnCode; return returnCode;
} }
#if defined(WIN32) && defined(UNICODE)
int run( int argc, wchar_t const* const* const argv ) {
char **utf8Argv = new char *[ argc ];
for ( int i = 0; i < argc; ++i ) {
int bufSize = WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, NULL, 0, NULL, NULL );
utf8Argv[ i ] = new char[ bufSize ];
WideCharToMultiByte( CP_UTF8, 0, argv[i], -1, utf8Argv[i], bufSize, NULL, NULL );
}
int returnCode = applyCommandLine( argc, utf8Argv );
if( returnCode == 0 )
returnCode = run();
for ( int i = 0; i < argc; ++i )
delete [] utf8Argv[ i ];
delete [] utf8Argv;
return returnCode;
}
#endif
int run() { int run() {
if( m_configData.showHelp ) if( m_configData.showHelp )
return 0; return 0;
......
...@@ -151,7 +151,7 @@ namespace Tbc { ...@@ -151,7 +151,7 @@ namespace Tbc {
return oss.str(); return oss.str();
} }
inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) { friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) {
for( Text::const_iterator it = _text.begin(), itEnd = _text.end(); for( Text::const_iterator it = _text.begin(), itEnd = _text.end();
it != itEnd; ++it ) { it != itEnd; ++it ) {
if( it != _text.begin() ) if( it != _text.begin() )
......
...@@ -29,26 +29,26 @@ namespace Detail { ...@@ -29,26 +29,26 @@ namespace Detail {
m_value( value ) m_value( value )
{} {}
Approx( Approx const& other )
: m_epsilon( other.m_epsilon ),
m_margin( other.m_margin ),
m_scale( other.m_scale ),
m_value( other.m_value )
{}
static Approx custom() { static Approx custom() {
return Approx( 0 ); return Approx( 0 );
} }
Approx operator()( double value ) { #if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS)
Approx approx( value );
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
Approx operator()( T value ) {
Approx approx( static_cast<double>(value) );
approx.epsilon( m_epsilon ); approx.epsilon( m_epsilon );
approx.margin( m_margin ); approx.margin( m_margin );
approx.scale( m_scale ); approx.scale( m_scale );
return approx; return approx;
} }
#if defined(CATCH_CONFIG_CPP11_TYPE_TRAITS) template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
explicit Approx( T value ): Approx(static_cast<double>(value))
{}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator == ( const T& lhs, Approx const& rhs ) { friend bool operator == ( const T& lhs, Approx const& rhs ) {
// Thanks to Richard Harris for his help refining this formula // Thanks to Richard Harris for his help refining this formula
...@@ -76,29 +76,54 @@ namespace Detail { ...@@ -76,29 +76,54 @@ namespace Detail {
} }
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator <= ( T lhs, Approx const& rhs ) friend bool operator <= ( T lhs, Approx const& rhs ) {
{
return double(lhs) < rhs.m_value || lhs == rhs; return double(lhs) < rhs.m_value || lhs == rhs;
} }
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator <= ( Approx const& lhs, T rhs ) friend bool operator <= ( Approx const& lhs, T rhs ) {
{
return lhs.m_value < double(rhs) || lhs == rhs; return lhs.m_value < double(rhs) || lhs == rhs;
} }
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator >= ( T lhs, Approx const& rhs ) friend bool operator >= ( T lhs, Approx const& rhs ) {
{
return double(lhs) > rhs.m_value || lhs == rhs; return double(lhs) > rhs.m_value || lhs == rhs;
} }
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type> template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
friend bool operator >= ( Approx const& lhs, T rhs ) friend bool operator >= ( Approx const& lhs, T rhs ) {
{
return lhs.m_value > double(rhs) || lhs == rhs; return lhs.m_value > double(rhs) || lhs == rhs;
} }
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
Approx& epsilon( T newEpsilon ) {
m_epsilon = double(newEpsilon);
return *this;
}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
Approx& margin( T newMargin ) {
m_margin = double(newMargin);
return *this;
}
template <typename T, typename = typename std::enable_if<std::is_constructible<double, T>::value>::type>
Approx& scale( T newScale ) {
m_scale = double(newScale);
return *this;
}
#else #else
Approx operator()( double value ) {
Approx approx( value );
approx.epsilon( m_epsilon );
approx.margin( m_margin );
approx.scale( m_scale );
return approx;
}
friend bool operator == ( double lhs, Approx const& rhs ) { friend bool operator == ( double lhs, Approx const& rhs ) {
// Thanks to Richard Harris for his help refining this formula // Thanks to Richard Harris for his help refining this formula
bool relativeOK = std::fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( std::fabs(lhs), std::fabs(rhs.m_value) ) ); bool relativeOK = std::fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( std::fabs(lhs), std::fabs(rhs.m_value) ) );
...@@ -120,26 +145,21 @@ namespace Detail { ...@@ -120,26 +145,21 @@ namespace Detail {
return !operator==( rhs, lhs ); return !operator==( rhs, lhs );
} }
friend bool operator <= ( double lhs, Approx const& rhs ) friend bool operator <= ( double lhs, Approx const& rhs ) {
{
return lhs < rhs.m_value || lhs == rhs; return lhs < rhs.m_value || lhs == rhs;
} }
friend bool operator <= ( Approx const& lhs, double rhs ) friend bool operator <= ( Approx const& lhs, double rhs ) {
{
return lhs.m_value < rhs || lhs == rhs; return lhs.m_value < rhs || lhs == rhs;
} }
friend bool operator >= ( double lhs, Approx const& rhs ) friend bool operator >= ( double lhs, Approx const& rhs ) {
{
return lhs > rhs.m_value || lhs == rhs; return lhs > rhs.m_value || lhs == rhs;
} }
friend bool operator >= ( Approx const& lhs, double rhs ) friend bool operator >= ( Approx const& lhs, double rhs ) {
{
return lhs.m_value > rhs || lhs == rhs; return lhs.m_value > rhs || lhs == rhs;
} }
#endif
Approx& epsilon( double newEpsilon ) { Approx& epsilon( double newEpsilon ) {
m_epsilon = newEpsilon; m_epsilon = newEpsilon;
...@@ -155,6 +175,7 @@ namespace Detail { ...@@ -155,6 +175,7 @@ namespace Detail {
m_scale = newScale; m_scale = newScale;
return *this; return *this;
} }
#endif
std::string toString() const { std::string toString() const {
std::ostringstream oss; std::ostringstream oss;
......
...@@ -39,16 +39,18 @@ namespace Catch { ...@@ -39,16 +39,18 @@ namespace Catch {
struct AssertionInfo struct AssertionInfo
{ {
AssertionInfo() {} AssertionInfo();
AssertionInfo( std::string const& _macroName, AssertionInfo( char const * _macroName,
SourceLineInfo const& _lineInfo, SourceLineInfo const& _lineInfo,
std::string const& _capturedExpression, char const * _capturedExpression,
ResultDisposition::Flags _resultDisposition ); ResultDisposition::Flags _resultDisposition,
char const * _secondArg = "");
std::string macroName; char const * macroName;
SourceLineInfo lineInfo; SourceLineInfo lineInfo;
std::string capturedExpression; char const * capturedExpression;
ResultDisposition::Flags resultDisposition; ResultDisposition::Flags resultDisposition;
char const * secondArg;
}; };
struct AssertionResultData struct AssertionResultData
......
差异被折叠。
File mode changed from 100644 to 100755
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
差异被折叠。
Markdown 格式
0% 或
您添加了 0 人 到此讨论。请谨慎行事。
请先完成此评论的编辑!
请 注册 或者 后发表评论