Skip to content
This repository has been archived by the owner on Sep 21, 2022. It is now read-only.

Allow to run tests in subset of browsers #138

Merged
merged 2 commits into from
Apr 6, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions doc/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@ one test completely (green color in report), partially (yellow) or was not captu
* `--root-url`, `-r` – use specified URL instead of `rootUrl` setting from config file.
* `--grid-url`, `-g` – use specified URL instead of `gridUrl` setting from config file.
* `--grep PATTERN` – execute only suites with names that match the regular expression pattern.
* `--browser ID` — execute suite only for specified browser id. Can be used multiple times.
Can be also specified with `GEMINI_BROWSERS` environment variable. If both CLI option
and env variable are set, CLI has precedence.
* `--help` – display help message.
* `--version` – display version.

Expand Down
3 changes: 3 additions & 0 deletions doc/commands.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,9 @@ gemini test --reporter flat --reporter html [пути к файлам с тес
* `--root-url`, `-r` – использовать другой URL вместо указанного в поле `rootUrl` конфигурационного файла;
* `--grid-url`, `-g` – использовать другой URL вместо указанного в поле `gridUrl` конфигурационного файла;
* `--grep PATTERN` – исполнять только те наборы, название которых соответствуют регулярному выражению;
* `--browser ID` — исполнять наборы только в заданном браузере. Опцию можно указать несколько раз;
Может быть также задана переменной среды `GEMINI_BROWSERS`. В случае, если задана и опция и переменная среды
будет использована опция.
* `--help` – отобразить справку;
* `--version` – отобразить текущую версию.

Expand Down
4 changes: 4 additions & 0 deletions doc/programmatic-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,8 @@ reporter).
* `grep` – regular expression to filter suites to run. By default, all tests
will be executed. If this option is set, only suites with name matching the
pattern will be executed.
* `browsers` — array of browser ids to execute tests in. By default, tests are
executed in all browsers, specified in config.

Returns promise that resolve to a stats object with following keys:

Expand All @@ -118,6 +120,8 @@ new temp directory will be created.
* `grep` – regular expression to filter suites to run. By default, all tests
will be executed. If this option is set, only suites with name matching the
pattern will be executed.
* `browsers` — array of browser ids to execute tests in. By default, tests are
executed in all browsers, specified in config.

Returns promise that resolve to a stats object with following keys:

Expand Down
4 changes: 4 additions & 0 deletions doc/programmatic-api.ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ state.shouldSkip({browserName: 'firefox', version: '25.0'});
Параметры:
* `reporters` – массив инструментов создания отчёта. Каждый элемент массива может быть представлен или строкой (используется встроенный инструментарий создания отчетов), или reporter-функцией (для создания нестандартных отчетов).
* `grep` – регулярное выражение для фильтрации запускаемых тестовых наборов. По умолчанию, запускаются все тесты. Если данный параметр передан, запускаются только наборы с названиями, соответствующими заданному паттерну.
* `browsers` — массив идентификаторов браузеров, в которых должны быть запущены тесты. По умолчанию, тесты запускаются во всех браузерах,
указанных в файле настроек.

В результате возвращает `promise`, соответствующий объекту со следующими ключами:

Expand All @@ -95,6 +97,8 @@ state.shouldSkip({browserName: 'firefox', version: '25.0'});
* `reporters` – массив инструментов создания отчёта. Каждый элемент массива может быть представлен или строкой (используется встроенный инструментарий создания отчетов), или reporter-функцией (для создания нестандартных отчетов).
* `tempDir` – директория для хранения временных изображений (текущего состояния). По умолчанию создаётся новая временная папка.
* `grep` – регулярное выражение для фильтрации запускаемых тестовых наборов. По умолчанию, запускаются все тесты. Если данный параметр передан, запускаются только наборы с названиями, соответствующими заданному паттерну.
* `browsers` — массив идентификаторов браузеров, в которых должны быть запущены тесты. По умолчанию, тесты запускаются во всех браузерах,
указанных в файле настроек.

В результате возвращает `promise`, соответствующий объекту со следующими ключами:

Expand Down
7 changes: 7 additions & 0 deletions lib/cli/common.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,13 @@ exports.common = function() {
return new RegExp(value, 'i');
})
.end()
.opt()
.name('browsers')
.long('browser')
.short('b')
.long('Execute tests only in specified browsers')
.arr()
.end()
.arg()
.name('testFiles')
.title('Paths to files or directories, containing tests')
Expand Down
3 changes: 2 additions & 1 deletion lib/cli/gather.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ module.exports = function() {
.then(function(gemini) {
return gemini.gather(args.testFiles, {
reporters: [flatReporter],
grep: opts.grep
grep: opts.grep,
browsers: opts.browsers
});
})
.then(function(stats) {
Expand Down
3 changes: 2 additions & 1 deletion lib/cli/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ module.exports = function() {
.then(function(gemini) {
return gemini.test(args.testFiles, {
reporters: opts.reporters,
grep: opts.grep
grep: opts.grep,
browsers: opts.browsers
});
})
.then(function(stats) {
Expand Down
20 changes: 20 additions & 0 deletions lib/gemini.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ var path = require('path'),
publicApi = require('./public-api'),

exposeTestsApi = require('./tests-api'),

GeminiError = require('./errors/gemini-error'),
Image = require('./image');

var DEFAULT_CFG_NAME = '.gemini.yml',
Expand Down Expand Up @@ -40,16 +42,34 @@ function Gemini(config, overrides) {
options = options || {};
options.reporters = options.reporters || [];

var envBrowsers = process.env.GEMINI_BROWSERS? process.env.GEMINI_BROWSERS.split(',') : null;
options.browsers = options.browsers || envBrowsers;

if (options.grep) {
runnerInstance.setGrepPattern(options.grep);
}
if (options.browsers) {
validateBrowsers(options.browsers);
runnerInstance.setTestBrowsers(options.browsers);
}
return _this.readTests(paths)
.then(function(rootSuite) {
options.reporters.forEach(applyReporter.bind(null, runnerInstance));
return runnerInstance.run(rootSuite);
});
}

function validateBrowsers(browsers) {
var browserIds = _this.browserIds;
browsers.forEach(function(id) {
if (browserIds.indexOf(id) === -1) {
throw new GeminiError('Unknown browser id: ' + id,
'Use one of the browser ids specified in config file: ' +
browserIds.join(', '));
}
});
}

this.readTests = function(paths) {
paths = paths || [getDefaultSpecsDir()];
return pathUtils.expandPaths(paths)
Expand Down
2 changes: 1 addition & 1 deletion lib/reporters/flat.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ module.exports = function(runner) {
browserSuites[data.browserId].pop();
});

//for test command
//for test command
runner.on('endTest', function(result) {
if (result.equal) {
reportSuccess(result);
Expand Down
16 changes: 15 additions & 1 deletion lib/runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ module.exports = inherit(EventEmitter, {
this._grepPattern = pattern;
},

setTestBrowsers: function(browsers) {
this._testBrowsers = browsers;
},

run: function(rootSuite) {
var _this = this;
this._stats = new Stats();
Expand Down Expand Up @@ -56,7 +60,7 @@ module.exports = inherit(EventEmitter, {

_runBrowsers: function(suites) {
var _this = this;
return q.all(Object.keys(this.config.browsers).map(function(browserId) {
return q.all(this._getBrowsersToLaunch().map(function(browserId) {
return _this.browserLauncher.launch(browserId)
.then(function(browser) {
_this.emit('startBrowser', {browserId: browser.id});
Expand All @@ -73,6 +77,16 @@ module.exports = inherit(EventEmitter, {
}));
},

_getBrowsersToLaunch: function() {
var ids = Object.keys(this.config.browsers);
if (this._testBrowsers) {
return ids.filter(function(browserId) {
return this._testBrowsers.indexOf(browserId) !== -1;
}, this);
}
return ids;
},

_runSuitesInBrowser: function(suites, browser) {
var _this = this;
return promiseUtils.seqMap(suites, function(suite) {
Expand Down
16 changes: 15 additions & 1 deletion test/runner.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ describe('runner', function() {
});
});

it('should launch each browser in config', function() {
it('should launch each browser in config if testBrowsers are not set', function() {
this.runner.config.browsers = {
browser1: {browserName: 'browser1', version: '1'},
browser2: {browserName: 'browser2'}
Expand All @@ -130,6 +130,20 @@ describe('runner', function() {
}.bind(this));
});

it('should launch only browsers specified in testBrowsers', function() {
this.runner.config.browsers = {
browser1: {browserName: 'browser1', version: '1'},
browser2: {browserName: 'browser2'}
};
this.runner.setTestBrowsers(['browser1']);

addState(this.suite, 'state');
return this.runner.run(this.root).then(function() {
sinon.assert.calledWith(this.launcher.launch, 'browser1');
sinon.assert.neverCalledWith(this.launcher.launch, 'browser2');
}.bind(this));
});

it('should emit `startBrowser` event when starting browser', function() {
this.runner.config.browsers = {
browser: {browserName: 'name'}
Expand Down