Fixed unit/integration testing; fixed a few linting errors;

pull/72/head
Christoph Oberhofer 10 years ago
parent 38da5b0d41
commit 8668e79b63

@ -0,0 +1,75 @@
{
"settings" : {
"ecmascript": 6,
"jsx": true
},
"env": {
"browser": true,
"node": true
},
"ecmaFeatures": {
"blockBindings": true,
"forOf": true,
"blockBindings": true,
"defaultParams": true,
"globalReturn": false,
"modules": true,
"objectLiteralShorthandMethods": true,
"objectLiteralShorthandProperties": true,
"templateStrings": true,
"spread": true,
"jsx": true,
"arrowFunctions": true,
"classes": true,
"destructuring": true,
"objectLiteralComputedProperties": true
},
"globals": {},
"rules": {
"no-unused-expressions": 1,
"no-extra-boolean-cast": 1,
"no-multi-spaces": 2,
"no-underscore-dangle": 0,
"comma-dangle": 2,
"camelcase": 0,
"curly": 2,
"eqeqeq": 2,
"guard-for-in": 2,
"wrap-iife": 0,
"no-use-before-define": [1, "nofunc"],
"new-cap": 2,
"quotes": 0,
"strict": 0,
"no-caller": 2,
"no-empty": 1,
"no-new": 2,
"no-plusplus": 0,
"no-unused-vars": 1,
"no-trailing-spaces": 2,
// STYLE
"max-params": [2, 7],
"key-spacing": [1, {
beforeColon: false,
afterColon: true
}],
"indent": [2, 4],
"brace-style": [2, "1tbs"],
"comma-spacing": [2, {before: false, after: true}],
"comma-style": [2, "last"],
"consistent-this": [1, "self"],
"eol-last": 0,
"new-cap": 0,
"new-parens": 2,
"no-array-constructor": 2,
"no-mixed-spaces-and-tabs": 2,
"no-multiple-empty-lines": 2,
"semi-spacing": 2,
"no-spaced-func": 1,
"padded-blocks": [2, "never"],
"semi": [2, "always"],
"space-after-keywords": [2, "always"],
"space-infix-ops": 2,
"max-len" : [1, 120]
}
}

@ -1,5 +1,4 @@
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
@ -10,26 +9,14 @@ module.exports = function(grunt) {
integration: {
configFile: 'karma-integration.conf.js'
}
},
jshint : {
all : ['Gruntfile.js', 'src/*.js']
}
});
// Load the plugin that provides the "uglify" task.
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-requirejs');
grunt.loadNpmTasks('grunt-karma');
grunt.loadTasks('tasks');
grunt.registerTask('build', ['check', 'requirejs']);
grunt.registerTask('check', ['jshint']);
grunt.registerTask('dist', ['build', 'uglify', 'uglyasm']);
grunt.registerTask('test', ['karma']);
grunt.registerTask('integrationtest', ['karma:integration']);
grunt.registerTask('default', ['build']);
};

35
dist/quagga.js vendored

@ -589,12 +589,9 @@ return /******/ (function(modules) { // webpackBootstrap
'use strict';
Object.defineProperty(exports, '__esModule', {
value: true
});
if (typeof window !== 'undefined') {
window.requestAnimFrame = (function () {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function ( /* function FrameRequestCallback */callback, /* DOMElement Element */element) {
return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function ( /* function FrameRequestCallback */callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
@ -612,9 +609,6 @@ return /******/ (function(modules) { // webpackBootstrap
return al * bl + (ah * bl + al * bh << 16 >>> 0) | 0;
};
exports['default'] = {};
module.exports = exports['default'];
/***/ },
/* 3 */
/***/ function(module, exports, __webpack_require__) {
@ -7456,9 +7450,6 @@ return /******/ (function(modules) { // webpackBootstrap
/* 20 */
/***/ function(module, exports, __webpack_require__) {
/* jshint undef: true, unused: true, browser:true, devel: true */
/* global define */
'use strict';
Object.defineProperty(exports, '__esModule', {
@ -7692,7 +7683,6 @@ return /******/ (function(modules) { // webpackBootstrap
patch;
for (i = 0; i < _numPatches.x; i++) {
for (j = 0; j < _numPatches.y; j++) {
x = _subImageWrapper.size.x * i;
y = _subImageWrapper.size.y * j;
@ -7849,7 +7839,6 @@ return /******/ (function(modules) { // webpackBootstrap
function describePatch(moments, patchPos, x, y) {
var k,
avg,
sum = 0,
eligibleMoments = [],
matchingMoments,
patch,
@ -7866,7 +7855,6 @@ return /******/ (function(modules) { // webpackBootstrap
// if at least 2 moments are found which have at least minComponentWeights covered
if (eligibleMoments.length >= 2) {
sum = eligibleMoments.length;
matchingMoments = similarMoments(eligibleMoments);
avg = 0;
// determine the similarity of the moments
@ -8775,6 +8763,7 @@ return /******/ (function(modules) { // webpackBootstrap
} else if (typeof readerConfig === 'string') {
reader = readerConfig;
}
console.log("Before registering reader: ", reader);
_barcodeReaders.push(new readers[reader](config));
});
console.log("Registered Readers: " + _barcodeReaders.map(function (reader) {
@ -9104,7 +9093,6 @@ return /******/ (function(modules) { // webpackBootstrap
* @param {Object} result {line, min, max}
*/
Bresenham.toBinaryLine = function (result) {
var min = result.min,
max = result.max,
line = result.line,
@ -9364,8 +9352,7 @@ return /******/ (function(modules) { // webpackBootstrap
rawResult = [],
decodedCodes = [],
shiftNext = false,
unshift,
lastCharacterWasPrintable;
unshift;
if (startInfo === null) {
return null;
@ -9431,9 +9418,6 @@ return /******/ (function(modules) { // webpackBootstrap
if (code.code < 96) {
result.push(String.fromCharCode(32 + code.code));
} else {
if (code.code != self.STOP_CODE) {
lastCharacterWasPrintable = false;
}
switch (code.code) {
case self.CODE_SHIFT:
shiftNext = true;
@ -9472,7 +9456,7 @@ return /******/ (function(modules) { // webpackBootstrap
done = true;
}
if (unshift) {
codeset = codeset == self.CODE_A ? self.CODE_B : self.CODE_A;
codeset = codeset === self.CODE_A ? self.CODE_B : self.CODE_A;
}
}
@ -9489,7 +9473,7 @@ return /******/ (function(modules) { // webpackBootstrap
// checksum
// Does not work correctly yet!!! startcode - endcode?
checksum -= multiplier * rawResult[rawResult.length - 1];
if (checksum % 103 != rawResult[rawResult.length - 1]) {
if (checksum % 103 !== rawResult[rawResult.length - 1]) {
return null;
}
@ -10281,7 +10265,6 @@ return /******/ (function(modules) { // webpackBootstrap
counter[counterPos]++;
} else {
if (counterPos === counter.length - 1) {
// find start pattern
if (self._toPattern(counter) === self.ASTERISK) {
whiteSpaceMustStart = Math.floor(Math.max(0, patternStart - (i - patternStart) / 4));
@ -10708,15 +10691,15 @@ return /******/ (function(modules) { // webpackBootstrap
UPCReader.prototype._decode = function () {
var result = _ean_reader2["default"].prototype._decode.call(this);
console.log("result", result);
if (result && result.code && result.code.length === 13 && result.code.charAt(0) === "0") {
result.code = result.code.substring(1);
return result;
}
return null;
};
exports["default"] = _ean_reader2["default"];
exports["default"] = UPCReader;
module.exports = exports["default"];
/***/ },
@ -12901,9 +12884,9 @@ return /******/ (function(modules) { // webpackBootstrap
if (typeof MediaStreamTrack !== 'undefined' && typeof MediaStreamTrack.getSources !== 'undefined') {
MediaStreamTrack.getSources(function (sourceInfos) {
var videoSourceId;
for (var i = 0; i != sourceInfos.length; ++i) {
for (var i = 0; i < sourceInfos.length; ++i) {
var sourceInfo = sourceInfos[i];
if (sourceInfo.kind == "video" && sourceInfo.facing == videoConstraints.facing) {
if (sourceInfo.kind === "video" && sourceInfo.facing === videoConstraints.facing) {
videoSourceId = sourceInfo.id;
}
}

2
dist/quagga.map vendored

File diff suppressed because one or more lines are too long

@ -101,7 +101,7 @@
&copy; Copyright by Christoph Oberhofer
</p>
</footer>
<script src="../src/vendor/jquery-1.9.0.min.js" type="text/javascript"></script>
<script src="vendor/jquery-1.9.0.min.js" type="text/javascript"></script>
<script src="../dist/quagga.js" type="text/javascript"></script>
<script src="file_input.js" type="text/javascript"></script>
</body>

@ -1,25 +1,36 @@
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha', 'requirejs', 'chai', 'sinon', 'sinon-chai'],
frameworks: ['mocha', 'chai', 'sinon', 'sinon-chai'],
files: [
'test-main.js',
'src/typedefs.js',
{pattern: 'node_modules/async/lib/async.js', included: false},
{pattern: 'node_modules/gl-matrix/dist/gl-matrix-min.js', included: false},
{pattern: 'src/*.js', included: false},
{pattern: 'spec/**/*integration.spec.js', included: false},
{pattern: 'test/**/*.*', included: false}
'test/test-main-integration.js',
{pattern: 'test/integration/**/*.js', included: false},
{pattern: 'test/fixtures/**/*.*', included: false}
],
preprocessors: {
'test/test-main-integration.js': ['webpack']
},
webpack: {
module: {
preLoaders: [
{
test: /\.js$/,
exclude: [
/node_modules/
],
loader: 'babel'
}
]
}
},
plugins: [
'karma-chrome-launcher',
'karma-mocha',
'karma-requirejs',
'karma-chai',
'karma-sinon',
'karma-sinon-chai'
'karma-sinon-chai',
require('karma-webpack')
],
reporters: ['progress'],
port: 9876,

@ -1,31 +1,46 @@
var path = require('path');
module.exports = function(config) {
config.set({
basePath: '',
frameworks: ['mocha', 'requirejs', 'chai', 'sinon', 'sinon-chai'],
frameworks: ['source-map-support', 'mocha', 'chai', 'sinon', 'sinon-chai'],
files: [
'test-main.js',
'src/typedefs.js',
{pattern: 'node_modules/async/lib/async.js', included: false},
{pattern: 'node_modules/gl-matrix/dist/gl-matrix-min.js', included: false},
{pattern: 'src/*.js', included: false},
{pattern: 'spec/**/*.js', included: false},
{pattern: 'test/**/*.*', included: false}
'test/test-main.js',
{pattern: 'test/spec/**/*.js', included: false}
],
preprocessors: {
'test/test-main.js': ['webpack']
},
webpack: {
module: {
preLoaders: [
{
test: /\.js$/,
exclude: [
'spec/**/*integration.spec.js'
/node_modules/
],
preprocessors: {
'src/*.js': ['coverage']
loader: 'babel'
},
{
test: /\.js$/,
include: [
path.resolve('src')
],
exclude: /node_modules/,
loader: 'isparta'
}
]
}
},
plugins: [
'karma-chrome-launcher',
'karma-coverage',
'karma-mocha',
'karma-requirejs',
'karma-chai',
'karma-sinon',
'karma-sinon-chai',
'karma-phantomjs-launcher'
'karma-source-map-support',
require('karma-webpack')
],
reporters: ['progress', 'coverage'],
port: 9876,

@ -10,12 +10,14 @@
"babel-eslint": "^4.1.3",
"babel-loader": "^5.3.2",
"chai": "^3.2.0",
"core-js": "^1.2.1",
"grunt": "^0.4.5",
"grunt-contrib-jshint": "^0.11.3",
"grunt-contrib-nodeunit": "^0.4.1",
"grunt-contrib-uglify": "^0.9.2",
"grunt-karma": "^0.12.1",
"grunt-requirejs": "^0.4.2",
"isparta-loader": "^1.0.0",
"karma": "^0.13.9",
"karma-chai": "0.1.0",
"karma-chrome-launcher": "^0.2.0",
@ -25,6 +27,8 @@
"karma-requirejs": "~0.2.2",
"karma-sinon": "^1.0.4",
"karma-sinon-chai": "~0.2.0",
"karma-source-map-support": "^1.1.0",
"karma-webpack": "^1.7.0",
"mocha": "^2.3.2",
"sinon": "^1.16.1",
"webpack": "^1.12.2",

@ -1,53 +0,0 @@
define(['array_helper'], function(ArrayHelper){
describe('init', function() {
it('initializes an array with the given value', function() {
var input = [0, 0, 0];
ArrayHelper.init(input, 5);
expect(input).to.deep.equal([5, 5, 5]);
});
});
describe('shuffle', function() {
before(function() {
sinon.stub(Math, 'random').returns(0.5);
});
after(function() {
sinon.restore(Math);
});
it('shuffles the content of an array', function() {
var input = [1, 2, 3];
expect(ArrayHelper.shuffle(input)).to.deep.equal([3, 1, 2]);
});
});
describe('toPointList', function() {
it('converts an Array to a List of poitns', function() {
var input = [[1, 2], [2, 2], [3, 2]];
expect(ArrayHelper.toPointList(input)).to.equal("[[1,2],\r\n[2,2],\r\n[3,2]]");
});
});
describe('threshold', function() {
it('returns all elements above the given threshold', function() {
var input = [1, 2, 3];
expect(ArrayHelper.threshold(input, 2, function(score) {
return score * 1.5;
})).to.deep.equal([2, 3]);
});
});
describe('maxIndex', function() {
it('gets the index of the biggest element in the array', function() {
var input = [1, 2, 3];
expect(ArrayHelper.maxIndex(input)).to.equal(2);
});
});
describe('max', function() {
it('gets the biggest element in the array', function() {
var input = [1, 3, 2];
expect(ArrayHelper.max(input)).to.equal(3);
});
});
});

@ -1,131 +0,0 @@
define(['barcode_locator', 'config', 'html_utils'],
function(BarcodeLocator, Config, HtmlUtils){
describe('checkImageConstraints', function() {
var config,
inputStream,
imageSize,
streamConfig = {};
beforeEach(function() {
imageSize = {
x: 640, y: 480
};
config = HtmlUtils.mergeObjects({}, Config);
inputStream = {
getWidth: function() {
return imageSize.x;
},
getHeight: function() {
return imageSize.y;
},
setWidth: function() {},
setHeight: function() {},
setTopRight: function() {},
setCanvasSize: function() {},
getConfig: function() {
return streamConfig;
}
};
sinon.stub(inputStream, "setWidth", function(width) {
imageSize.x = width;
});
sinon.stub(inputStream, "setHeight", function(height) {
imageSize.y = height;
});
sinon.stub(inputStream, "setTopRight");
sinon.stub(inputStream, "setCanvasSize");
});
afterEach(function() {
inputStream.setWidth.restore();
inputStream.setHeight.restore();
});
it('should not adjust the image-size if not needed', function() {
var expected = {x: imageSize.x, y: imageSize.y};
BarcodeLocator.checkImageConstraints(inputStream, config.locator);
expect(inputStream.getWidth()).to.be.equal(expected.x);
expect(inputStream.getHeight()).to.be.equal(expected.y);
});
it('should adjust the image-size', function() {
var expected = {x: imageSize.x, y: imageSize.y};
config.locator.halfSample = true;
imageSize.y += 1;
BarcodeLocator.checkImageConstraints(inputStream, config.locator);
expect(inputStream.getWidth()).to.be.equal(expected.x);
expect(inputStream.getHeight()).to.be.equal(expected.y);
});
it('should adjust the image-size', function() {
var expected = {x: imageSize.x, y: imageSize.y};
imageSize.y += 1;
config.locator.halfSample = false;
BarcodeLocator.checkImageConstraints(inputStream, config.locator);
expect(inputStream.getHeight()).to.be.equal(expected.y);
expect(inputStream.getWidth()).to.be.equal(expected.x);
});
it("should take the defined area into account", function() {
var expectedSize = {
x: 420,
y: 315
},
expectedTopRight = {
x: 115,
y: 52
},
expectedCanvasSize = {
x: 640,
y: 480
};
streamConfig.area = {
top: "11%",
right: "15%",
bottom: "20%",
left: "18%"
};
config.locator.halfSample = false;
BarcodeLocator.checkImageConstraints(inputStream, config.locator);
expect(inputStream.getHeight()).to.be.equal(expectedSize.y);
expect(inputStream.getWidth()).to.be.equal(expectedSize.x);
expect(inputStream.setTopRight.getCall(0).args[0]).to.deep.equal(expectedTopRight);
expect(inputStream.setCanvasSize.getCall(0).args[0]).to.deep.equal(expectedCanvasSize);
});
it("should return the original size if set to full image", function() {
var expectedSize = {
x: 640,
y: 480
},
expectedTopRight = {
x: 0,
y: 0
},
expectedCanvasSize = {
x: 640,
y: 480
};
streamConfig.area = {
top: "0%",
right: "0%",
bottom: "0%",
left: "0%"
};
config.locator.halfSample = false;
BarcodeLocator.checkImageConstraints(inputStream, config.locator);
expect(inputStream.getHeight()).to.be.equal(expectedSize.y);
expect(inputStream.getWidth()).to.be.equal(expectedSize.x);
expect(inputStream.setTopRight.getCall(0).args[0]).to.deep.equal(expectedTopRight);
expect(inputStream.setCanvasSize.getCall(0).args[0]).to.deep.equal(expectedCanvasSize);
});
});
});

@ -1,123 +0,0 @@
define(['camera_access'], function(CameraAccess){
var originalURL,
originalMediaStreamTrack,
video,
stream;
beforeEach(function() {
var tracks = [{
stop: function() {}
}];
originalURL = window.URL;
originalMediaStreamTrack = window.MediaStreamTrack;
window.MediaStreamTrack = {};
window.URL = null;
stream = {
getVideoTracks: function() {
return tracks;
}
};
sinon.spy(tracks[0], "stop");
video = {
src: null,
addEventListener: function() {
},
removeEventListener: function() {
},
play: function() {
},
videoWidth: 320,
videoHeight: 480
};
sinon.stub(video, "addEventListener", function(event, cb) {
cb();
});
sinon.stub(video, "play");
});
afterEach(function() {
window.URL = originalURL;
window.MediaStreamTrack = originalMediaStreamTrack;
});
describe('success', function() {
beforeEach(function() {
sinon.stub(navigator, "getUserMedia", function(constraints, success) {
success(stream);
});
});
afterEach(function() {
navigator.getUserMedia.restore();
});
describe('request', function () {
it('should request the camera', function (done) {
CameraAccess.request(video, {}, function () {
expect(navigator.getUserMedia.calledOnce).to.equal(true);
expect(video.src).to.deep.equal(stream);
done();
});
});
});
describe('release', function () {
it('should release the camera', function (done) {
CameraAccess.request(video, {}, function () {
expect(video.src).to.deep.equal(stream);
CameraAccess.release();
expect(video.src.getVideoTracks()).to.have.length(1);
expect(video.src.getVideoTracks()[0].stop.calledOnce).to.equal(true);
done();
});
});
});
});
describe('failure', function() {
describe("permission denied", function(){
before(function() {
sinon.stub(navigator, "getUserMedia", function(constraints, success, failure) {
failure(new Error());
});
});
after(function() {
navigator.getUserMedia.restore();
});
it('should throw if getUserMedia not available', function(done) {
CameraAccess.request(video, {}, function(err) {
expect(err).to.be.defined;
done();
});
});
});
describe("not available", function(){
var originalGetUserMedia;
before(function() {
originalGetUserMedia = navigator.getUserMedia;
navigator.getUserMedia = undefined;
});
after(function() {
navigator.getUserMedia = originalGetUserMedia;
});
it('should throw if getUserMedia not available', function(done) {
CameraAccess.request(video, {}, function(err) {
expect(err).to.be.defined;
done();
});
});
});
});
});

@ -1,145 +0,0 @@
define(['cv_utils'], function(CVUtils){
describe('imageRef', function() {
it('gets the image Reference for a coordinate', function() {
var res = CVUtils.imageRef(1, 2);
expect(res.x).to.equal(1);
expect(res.y).to.equal(2);
expect(res.toVec2()[0]).to.equal(1);
});
});
describe('calculatePatchSize', function() {
it('should not throw an error in case of valid image size', function() {
var expected = {x: 32, y: 32},
patchSize = CVUtils.calculatePatchSize("medium", {x: 640, y: 480});
expect(patchSize).to.be.deep.equal(expected);
});
it('should thow an error if image size it not valid', function() {
var expected = {x: 32, y: 32},
patchSize = CVUtils.calculatePatchSize("medium", {x: 640, y: 480});
expect(patchSize).to.be.deep.equal(expected);
});
});
describe('_parseCSSDimensionValues', function() {
it("should convert a percentual value correctly", function() {
var expected = {
value: 10,
unit: "%"
},
result = CVUtils._parseCSSDimensionValues("10%");
expect(result).to.be.deep.equal(expected);
});
it("should convert a 0% value correctly", function() {
var expected = {
value: 100,
unit: "%"
},
result = CVUtils._parseCSSDimensionValues("100%");
expect(result).to.be.deep.equal(expected);
});
it("should convert a 100% value correctly", function() {
var expected = {
value: 0,
unit: "%"
},
result = CVUtils._parseCSSDimensionValues("0%");
expect(result).to.be.deep.equal(expected);
});
it("should convert a pixel value to percentage", function() {
var expected = {
value: 26.3,
unit: "%"
},
result = CVUtils._parseCSSDimensionValues("26.3px");
console.log(result);
expect(result).to.be.deep.equal(expected);
});
});
describe("_dimensionsConverters", function(){
var context;
beforeEach(function() {
context = {
width: 640,
height: 480
};
});
it("should convert a top-value correclty", function() {
var expected = 48,
result = CVUtils._dimensionsConverters.top({value: 10, unit: "%"}, context);
expect(result).to.be.equal(expected);
});
it("should convert a right-value correclty", function() {
var expected = 640 - 128,
result = CVUtils._dimensionsConverters.right({value: 20, unit: "%"}, context);
expect(result).to.be.equal(expected);
});
it("should convert a bottom-value correclty", function() {
var expected = 480 - 77,
result = CVUtils._dimensionsConverters.bottom({value: 16, unit: "%"}, context);
expect(result).to.be.equal(expected);
});
it("should convert a left-value correclty", function() {
var expected = 57,
result = CVUtils._dimensionsConverters.left({value: 9, unit: "%"}, context);
expect(result).to.be.equal(expected);
});
});
describe("computeImageArea", function() {
it("should calculate an image-area", function() {
var expected = {
sx: 115,
sy: 48,
sw: 429,
sh: 336
},
result = CVUtils.computeImageArea(640, 480, {
top: "10%",
right: "15%",
bottom: "20%",
left: "18%"
});
expect(result).to.be.deep.equal(expected);
});
it("should calculate full image-area", function() {
var expected = {
sx: 0,
sy: 0,
sw: 640,
sh: 480
},
result = CVUtils.computeImageArea(640, 480, {
top: "0%",
right: "0%",
bottom: "0%",
left: "0%"
});
expect(result).to.be.deep.equal(expected);
});
});
});

@ -1,114 +0,0 @@
define(['events'], function(Events){
beforeEach(function() {
Events.unsubscribe();
});
describe("subscribe", function() {
it("should call one callback for a single event", function() {
var callbackA = sinon.stub(),
callbackB = sinon.stub();
Events.subscribe("test", callbackA);
Events.subscribe("test", callbackB);
Events.publish("test");
expect(callbackA.calledOnce).to.be.equal(true);
expect(callbackB.calledOnce).to.be.equal(true);
});
it("should call one callback twice if published twice", function() {
var callback = sinon.stub();
Events.subscribe("test", callback);
Events.publish("test");
Events.publish("test");
expect(callback.calledTwice).to.be.equal(true);
});
it("should call the callback asynchronuously", function(done) {
var test = {
callback: function() {
}
};
sinon.stub(test, "callback", function() {
expect(test.callback.calledOnce).to.be.true;
done();
});
Events.subscribe("test", test.callback, true);
Events.publish("test");
expect(test.callback.called).to.be.false;
});
});
describe("once", function() {
it("should call the callback once, even when published twice", function() {
var callbackA = sinon.stub(),
callbackB = sinon.stub();
Events.once("test", callbackA);
Events.subscribe("test", callbackB);
Events.publish("test");
Events.publish("test");
expect(callbackA.calledOnce).to.be.equal(true);
expect(callbackB.calledTwice).to.be.equal(true);
});
});
describe("unsubscribe", function() {
it("should unsubscribe all callbacks from a single event", function() {
var callbackA = sinon.stub(),
callbackB = sinon.stub(),
callbackC = sinon.stub();
Events.subscribe("test", callbackA);
Events.subscribe("test", callbackB);
Events.subscribe("testC", callbackC);
Events.publish("test");
expect(callbackC.called).to.be.equal(false);
expect(callbackA.calledOnce).to.be.equal(true);
expect(callbackB.calledOnce).to.be.equal(true);
Events.publish("testC");
expect(callbackC.calledOnce).to.be.equal(true);
expect(callbackA.calledOnce).to.be.equal(true);
expect(callbackB.calledOnce).to.be.equal(true);
Events.unsubscribe("test");
Events.publish("test");
expect(callbackC.calledOnce).to.be.equal(true);
expect(callbackA.calledOnce).to.be.equal(true);
expect(callbackB.calledOnce).to.be.equal(true);
});
it("should unsubscribe a single callback from a single event", function() {
var callbackA = sinon.stub(),
callbackB = sinon.stub();
Events.subscribe("test", callbackA);
Events.subscribe("test", callbackB);
Events.publish("test");
expect(callbackA.calledOnce).to.be.equal(true);
expect(callbackB.calledOnce).to.be.equal(true);
Events.unsubscribe("test", callbackB);
Events.publish("test");
expect(callbackA.calledTwice).to.be.equal(true);
expect(callbackB.calledOnce).to.be.equal(true);
});
});
});

@ -1,248 +0,0 @@
define(['quagga', 'async'], function(Quagga, async) {
describe('decodeSingle', function () {
var baseFolder = "base/test/fixtures/";
function generateConfig() {
return {
inputStream: {
size: 640
},
locator: {
patchSize: "medium",
halfSample: true
},
numOfWorkers: 0,
decoder: {
readers: ["ean_reader"]
},
locate: true,
src: null
};
}
this.timeout(10000);
function _runTestSet(testSet, config) {
var readers = config.decoder.readers.slice(),
format,
folder;
if (typeof readers[0] === 'string'){
format = readers[0];
} else {
format = readers[0].format;
}
folder = baseFolder + format.split('_').slice(0, -1).join('_') + "/";
it('should decode ' + folder + " correctly", function(done) {
async.eachSeries(testSet, function (sample, callback) {
config.src = folder + sample.name;
config.readers = readers;
Quagga.decodeSingle(config, function(result) {
console.log(sample.name);
expect(result.codeResult.code).to.equal(sample.result);
expect(result.codeResult.format).to.equal(sample.format);
callback();
});
}, function() {
done();
});
});
}
describe("EAN", function() {
var config = generateConfig(),
testSet = [
{"name": "image-001.jpg", "result": "3574660239843"},
{"name": "image-002.jpg", "result": "8032754490297"},
{"name": "image-003.jpg", "result": "4006209700068"},
/* {"name": "image-004.jpg", "result": "9002233139084"}, */
/* {"name": "image-005.jpg", "result": "8004030044005"}, */
{"name": "image-006.jpg", "result": "4003626011159"},
{"name": "image-007.jpg", "result": "2111220009686"},
{"name": "image-008.jpg", "result": "9000275609022"},
{"name": "image-009.jpg", "result": "9004593978587"},
{"name": "image-010.jpg", "result": "9002244845578"}
];
testSet.forEach(function(sample) {
sample.format = "ean_13";
});
config.decoder.readers = ['ean_reader'];
_runTestSet(testSet, config);
});
describe("Code128", function() {
var config = generateConfig(),
testSet = [
{"name": "image-001.jpg", "result": "0001285112001000040801"},
// {"name": "image-002.jpg", "result": "FANAVF1461710"},
// {"name": "image-003.jpg", "result": "673023"},
// {"name": "image-004.jpg", "result": "010210150301625334"},
{"name": "image-005.jpg", "result": "419055603900009001012999"},
{"name": "image-006.jpg", "result": "419055603900009001012999"},
{"name": "image-007.jpg", "result": "T 000003552345"},
{"name": "image-008.jpg", "result": "FANAVF1461710"},
{"name": "image-009.jpg", "result": "0001285112001000040801"},
{"name": "image-010.jpg", "result": "673023"}
];
testSet.forEach(function(sample) {
sample.format = "code_128";
});
config.decoder.readers = ['code_128_reader'];
_runTestSet(testSet, config);
});
describe("Code39", function() {
var config = generateConfig(),
testSet = [
{"name": "image-001.jpg", "result": "B3% $DAD$"},
{"name": "image-003.jpg", "result": "CODE39"},
{"name": "image-004.jpg", "result": "QUAGGAJS"},
/* {"name": "image-005.jpg", "result": "CODE39"}, */
{"name": "image-006.jpg", "result": "2/4-8/16-32"},
{"name": "image-007.jpg", "result": "2/4-8/16-32"},
{"name": "image-008.jpg", "result": "CODE39"},
{"name": "image-009.jpg", "result": "2/4-8/16-32"},
{"name": "image-010.jpg", "result": "CODE39"}
];
testSet.forEach(function(sample) {
sample.format = "code_39";
});
config.decoder.readers = ['code_39_reader'];
_runTestSet(testSet, config);
});
describe("EAN-8", function() {
var config = generateConfig(),
testSet = [
{"name": "image-001.jpg", "result": "42191605"},
{"name": "image-002.jpg", "result": "42191605"},
{"name": "image-003.jpg", "result": "90311208"},
{"name": "image-004.jpg", "result": "24057257"},
{"name": "image-005.jpg", "result": "90162602"},
{"name": "image-006.jpg", "result": "24036153"},
{"name": "image-007.jpg", "result": "42176817"},
{"name": "image-008.jpg", "result": "42191605"},
{"name": "image-009.jpg", "result": "42242215"},
{"name": "image-010.jpg", "result": "42184799"}
];
testSet.forEach(function(sample) {
sample.format = "ean_8";
});
config.decoder.readers = ['ean_8_reader'];
_runTestSet(testSet, config);
});
describe("UPC", function() {
var config = generateConfig(),
testSet = [
{"name": "image-001.jpg", "result": "882428015268"},
{"name": "image-002.jpg", "result": "882428015268"},
{"name": "image-003.jpg", "result": "882428015084"},
{"name": "image-004.jpg", "result": "882428015343"},
{"name": "image-005.jpg", "result": "882428015343"},
/* {"name": "image-006.jpg", "result": "882428015046"}, */
{"name": "image-007.jpg", "result": "882428015084"},
{"name": "image-008.jpg", "result": "882428015046"},
{"name": "image-009.jpg", "result": "039047013551"},
{"name": "image-010.jpg", "result": "039047013551"}
];
testSet.forEach(function(sample) {
sample.format = "upc_a";
});
config.decoder.readers = ['upc_reader'];
_runTestSet(testSet, config);
});
describe("UPC-E", function() {
var config = generateConfig(),
testSet = [
{"name": "image-001.jpg", "result": "04965802"},
{"name": "image-002.jpg", "result": "04965802"},
{"name": "image-003.jpg", "result": "03897425"},
{"name": "image-004.jpg", "result": "05096893"},
{"name": "image-005.jpg", "result": "05096893"},
{"name": "image-006.jpg", "result": "05096893"},
{"name": "image-007.jpg", "result": "03897425"},
{"name": "image-008.jpg", "result": "01264904"},
/*{"name": "image-009.jpg", "result": "01264904"},*/
{"name": "image-010.jpg", "result": "01264904"}
];
testSet.forEach(function(sample) {
sample.format = "upc_e";
});
config.decoder.readers = ['upc_e_reader'];
_runTestSet(testSet, config);
});
describe("Codabar", function() {
var config = generateConfig(),
testSet = [
{"name": "image-001.jpg", "result": "A10/53+17-70D"},
{"name": "image-002.jpg", "result": "B546745735B"},
{"name": "image-003.jpg", "result": "C$399.95A"},
{"name": "image-004.jpg", "result": "B546745735B"},
{"name": "image-005.jpg", "result": "C$399.95A"},
{"name": "image-006.jpg", "result": "B546745735B"},
{"name": "image-007.jpg", "result": "C$399.95A"},
{"name": "image-008.jpg", "result": "A16:9/4:3/3:2D"},
{"name": "image-009.jpg", "result": "C$399.95A"},
{"name": "image-010.jpg", "result": "C$399.95A"}
];
testSet.forEach(function(sample) {
sample.format = "codabar";
});
config.decoder.readers = ['codabar_reader'];
_runTestSet(testSet, config);
});
describe("I2of5 with localization", function() {
var config = {
inputStream: {
size: 800,
singleChannel: false
},
locator: {
patchSize: "small",
halfSample: false
},
numOfWorkers: 0,
decoder: {
readers: ["i2of5_reader"],
},
locate: true,
src: null
}, testSet = [
{"name": "image-001.jpg", "result": "2167361334"},
{"name": "image-002.jpg", "result": "2167361334"},
{"name": "image-003.jpg", "result": "2167361334"},
{"name": "image-004.jpg", "result": "2167361334"},
{"name": "image-005.jpg", "result": "2167361334"}
];
testSet.forEach(function(sample) {
sample.format = "i2of5";
});
_runTestSet(testSet, config);
});
});
});

@ -1,103 +0,0 @@
define(['result_collector', 'image_debug'], function(ResultCollector, ImageDebug) {
var canvasMock,
imageSize,
config;
beforeEach(function() {
imageSize = {x: 320, y: 240};
config = {
capture: true,
capacity: 20,
blacklist: [{code: "3574660239843", format: "ean_13"}],
filter: function(codeResult) {
return true;
}
};
canvasMock = {
getContext: function() {
return {};
},
toDataURL: sinon.spy(),
width: 0,
height: 0
};
sinon.stub(document, "createElement", function(type) {
if (type === "canvas") {
return canvasMock;
}
});
});
afterEach(function() {
document.createElement.restore();
});
describe('create', function () {
it("should return a new collector", function() {
ResultCollector.create(config);
expect(document.createElement.calledOnce).to.be.equal(true);
expect(document.createElement.getCall(0).args[0]).to.equal("canvas");
});
});
describe('addResult', function() {
beforeEach(function() {
sinon.stub(ImageDebug, "drawImage", function() {});
});
afterEach(function() {
ImageDebug.drawImage.restore();
});
it("should not add result if capacity is full", function(){
config.capacity = 1;
var collector = ResultCollector.create(config);
collector.addResult([], imageSize, {});
collector.addResult([], imageSize, {});
collector.addResult([], imageSize, {});
expect(collector.getResults()).to.have.length(1);
});
it("should only add results which match constraints", function(){
var collector = ResultCollector.create(config),
results;
collector.addResult([], imageSize, {code: "423423443", format: "ean_13"});
collector.addResult([], imageSize, {code: "3574660239843", format: "ean_13"});
collector.addResult([], imageSize, {code: "3574660239843", format: "code_128"});
results = collector.getResults();
expect(results).to.have.length(2);
results.forEach(function(result) {
expect(result).not.to.deep.equal(config.blacklist[0]);
});
});
it("should add result if no filter is set", function() {
delete config.filter;
var collector = ResultCollector.create(config);
collector.addResult([], imageSize, {code: "423423443", format: "ean_13"});
expect(collector.getResults()).to.have.length(1);
});
it("should not add results if filter returns false", function() {
config.filter = function(){ return false };
var collector = ResultCollector.create(config);
collector.addResult([], imageSize, {code: "423423443", format: "ean_13"});
expect(collector.getResults()).to.have.length(0);
});
it("should add result if no blacklist is set", function() {
delete config.blacklist;
var collector = ResultCollector.create(config);
collector.addResult([], imageSize, {code: "3574660239843", format: "ean_13"});
expect(collector.getResults()).to.have.length(1);
});
});
});

@ -82,10 +82,11 @@ export default {
} else if (typeof readerConfig === 'string') {
reader = readerConfig;
}
console.log("Before registering reader: ", reader);
_barcodeReaders.push(new readers[reader](config));
});
console.log("Registered Readers: " + _barcodeReaders
.map(function(reader) {return JSON.stringify({format: reader.FORMAT, config: reader.config});})
.map((reader) => JSON.stringify({format: reader.FORMAT, config: reader.config}))
.join(', '));
}
@ -130,7 +131,8 @@ export default {
// check if inside image
extendLine(ext);
while (ext > 1 && (!inputImageWrapper.inImageWithBorder(line[0], 0) || !inputImageWrapper.inImageWithBorder(line[1], 0))) {
while (ext > 1 && (!inputImageWrapper.inImageWithBorder(line[0], 0)
|| !inputImageWrapper.inImageWithBorder(line[1], 0))) {
ext -= Math.ceil(ext / 2);
extendLine(-ext);
}

@ -1,6 +1,3 @@
/* jshint undef: true, unused: true, browser:true, devel: true */
/* global define */
import ImageWrapper from './image_wrapper';
import CVUtils from './cv_utils';
import Rasterizer from './rasterizer';
@ -57,8 +54,11 @@ function initBuffers() {
_labelImageWrapper = new ImageWrapper(_patchSize, undefined, Array, true);
skeletonImageData = new ArrayBuffer(64 * 1024);
_subImageWrapper = new ImageWrapper(_patchSize, new Uint8Array(skeletonImageData, 0, _patchSize.x * _patchSize.y));
_skelImageWrapper = new ImageWrapper(_patchSize, new Uint8Array(skeletonImageData, _patchSize.x * _patchSize.y * 3, _patchSize.x * _patchSize.y), undefined, true);
_subImageWrapper = new ImageWrapper(_patchSize,
new Uint8Array(skeletonImageData, 0, _patchSize.x * _patchSize.y));
_skelImageWrapper = new ImageWrapper(_patchSize,
new Uint8Array(skeletonImageData, _patchSize.x * _patchSize.y * 3, _patchSize.x * _patchSize.y),
undefined, true);
_skeletonizer = skeletonizer(self, {
size: _patchSize.x
}, skeletonImageData);
@ -90,7 +90,18 @@ function initCanvas() {
* @returns {Array} The minimal bounding box
*/
function boxFromPatches(patches) {
var overAvg, i, j, patch, transMat, minx = _binaryImageWrapper.size.x, miny = _binaryImageWrapper.size.y, maxx = -_binaryImageWrapper.size.x, maxy = -_binaryImageWrapper.size.y, box, scale;
var overAvg,
i,
j,
patch,
transMat,
minx =
_binaryImageWrapper.size.x,
miny = _binaryImageWrapper.size.y,
maxx = -_binaryImageWrapper.size.x,
maxy = -_binaryImageWrapper.size.y,
box,
scale;
// draw all patches which are to be taken into consideration
overAvg = 0;
@ -193,7 +204,6 @@ function findPatches() {
patch;
for (i = 0; i < _numPatches.x; i++) {
for (j = 0; j < _numPatches.y; j++) {
x = _subImageWrapper.size.x * i;
y = _subImageWrapper.size.y * j;
@ -207,7 +217,8 @@ function findPatches() {
rasterResult = rasterizer.rasterize(0);
if (_config.showLabels) {
_labelImageWrapper.overlay(_canvasContainer.dom.binary, Math.floor(360 / rasterResult.count), {x : x, y : y});
_labelImageWrapper.overlay(_canvasContainer.dom.binary, Math.floor(360 / rasterResult.count),
{x: x, y: y});
}
// calculate moments from the skeletonized patch
@ -221,7 +232,8 @@ function findPatches() {
if (_config.showFoundPatches) {
for ( i = 0; i < patchesFound.length; i++) {
patch = patchesFound[i];
ImageDebug.drawRect(patch.pos, _subImageWrapper.size, _canvasContainer.ctx.binary, {color: "#99ff00", lineWidth: 2});
ImageDebug.drawRect(patch.pos, _subImageWrapper.size, _canvasContainer.ctx.binary,
{color: "#99ff00", lineWidth: 2});
}
}
@ -301,7 +313,8 @@ function findBoxes(topLabels, maxLabel) {
patch = patches[j];
hsv[0] = (topLabels[i].label / (maxLabel + 1)) * 360;
CVUtils.hsv2rgb(hsv, rgb);
ImageDebug.drawRect(patch.pos, _subImageWrapper.size, _canvasContainer.ctx.binary, {color: "rgb(" + rgb.join(",") + ")", lineWidth: 2});
ImageDebug.drawRect(patch.pos, _subImageWrapper.size, _canvasContainer.ctx.binary,
{color: "rgb(" + rgb.join(",") + ")", lineWidth: 2});
}
}
}
@ -349,7 +362,6 @@ function skeletonize(x, y) {
function describePatch(moments, patchPos, x, y) {
var k,
avg,
sum = 0,
eligibleMoments = [],
matchingMoments,
patch,
@ -366,7 +378,6 @@ function describePatch(moments, patchPos, x, y) {
// if at least 2 moments are found which have at least minComponentWeights covered
if (eligibleMoments.length >= 2) {
sum = eligibleMoments.length;
matchingMoments = similarMoments(eligibleMoments);
avg = 0;
// determine the similarity of the moments
@ -376,7 +387,9 @@ function describePatch(moments, patchPos, x, y) {
// Only two of the moments are allowed not to fit into the equation
// add the patch to the set
if (matchingMoments.length > 1 && matchingMoments.length >= (eligibleMoments.length / 4) * 3 && matchingMoments.length > moments.length / 4) {
if (matchingMoments.length > 1
&& matchingMoments.length >= (eligibleMoments.length / 4) * 3
&& matchingMoments.length > moments.length / 4) {
avg /= matchingMoments.length;
patch = {
index: patchPos[1] * _numPatches.x + patchPos[0],
@ -384,7 +397,12 @@ function describePatch(moments, patchPos, x, y) {
x: x,
y: y
},
box : [vec2.clone([x, y]), vec2.clone([x + _subImageWrapper.size.x, y]), vec2.clone([x + _subImageWrapper.size.x, y + _subImageWrapper.size.y]), vec2.clone([x, y + _subImageWrapper.size.y])],
box: [
vec2.clone([x, y]),
vec2.clone([x + _subImageWrapper.size.x, y]),
vec2.clone([x + _subImageWrapper.size.x, y + _subImageWrapper.size.y]),
vec2.clone([x, y + _subImageWrapper.size.y])
],
moments: matchingMoments,
rad: avg,
vec: vec2.clone([Math.cos(avg), Math.sin(avg)])
@ -420,10 +438,17 @@ function rasterizeAngularSimilarity(patchesFound) {
}
function trace(currentIdx) {
var x, y, currentPatch, patch, idx, dir, current = {
var x,
y,
currentPatch,
patch,
idx,
dir,
current = {
x: currentIdx % _patchLabelGrid.size.x,
y: (currentIdx / _patchLabelGrid.size.x) | 0
}, similarity;
},
similarity;
if (currentIdx < _patchLabelGrid.data.length) {
currentPatch = _imageToPatchGrid.data[currentIdx];
@ -477,7 +502,8 @@ function rasterizeAngularSimilarity(patchesFound) {
patch = _imageToPatchGrid.data[j];
hsv[0] = (_patchLabelGrid.data[j] / (label + 1)) * 360;
CVUtils.hsv2rgb(hsv, rgb);
ImageDebug.drawRect(patch.pos, _subImageWrapper.size, _canvasContainer.ctx.binary, {color: "rgb(" + rgb.join(",") + ")", lineWidth: 2});
ImageDebug.drawRect(patch.pos, _subImageWrapper.size, _canvasContainer.ctx.binary,
{color: "rgb(" + rgb.join(",") + ")", lineWidth: 2});
}
}
}

@ -110,7 +110,6 @@ Bresenham.toOtsuBinaryLine = function(result) {
* @param {Object} result {line, min, max}
*/
Bresenham.toBinaryLine = function(result) {
var min = result.min,
max = result.max,
line = result.line,

@ -83,9 +83,9 @@ function normalizeConstraints(config, cb) {
if ( typeof MediaStreamTrack !== 'undefined' && typeof MediaStreamTrack.getSources !== 'undefined') {
MediaStreamTrack.getSources(function(sourceInfos) {
var videoSourceId;
for (var i = 0; i != sourceInfos.length; ++i) {
for (var i = 0; i < sourceInfos.length; ++i) {
var sourceInfo = sourceInfos[i];
if (sourceInfo.kind == "video" && sourceInfo.facing == videoConstraints.facing) {
if (sourceInfo.kind === "video" && sourceInfo.facing === videoConstraints.facing) {
videoSourceId = sourceInfo.id;
}
}

@ -4,10 +4,12 @@ import {vec2} from 'gl-matrix';
*/
export default {
create: function(point, threshold) {
var points = [], center = {
var points = [],
center = {
rad: 0,
vec: vec2.clone([0, 0])
}, pointMap = {};
},
pointMap = {};
function init() {
add(point);

@ -8,7 +8,8 @@ function CodabarReader() {
var properties = {
ALPHABETH_STRING: {value: "0123456789-$:/.+ABCD"},
ALPHABET: {value: [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 45, 36, 58, 47, 46, 43, 65, 66, 67, 68]},
CHARACTER_ENCODINGS: {value: [0x003, 0x006, 0x009, 0x060, 0x012, 0x042, 0x021, 0x024, 0x030, 0x048, 0x00c, 0x018, 0x045, 0x051, 0x054, 0x015, 0x01A, 0x029, 0x00B, 0x00E]},
CHARACTER_ENCODINGS: {value: [0x003, 0x006, 0x009, 0x060, 0x012, 0x042, 0x021, 0x024, 0x030, 0x048, 0x00c, 0x018,
0x045, 0x051, 0x054, 0x015, 0x01A, 0x029, 0x00B, 0x00E]},
START_END: {value: [0x01A, 0x029, 0x00B, 0x00E]},
MIN_ENCODED_CHARS: {value: 4},
MAX_ACCEPTABLE: {value: 2.0},
@ -78,8 +79,10 @@ CodabarReader.prototype._decode = function() {
};
CodabarReader.prototype._verifyWhitespace = function(startCounter, endCounter) {
if ((startCounter - 1 <= 0) || this._counters[startCounter-1] >= (this._calculatePatternLength(startCounter) / 2.0)) {
if ((endCounter + 8 >= this._counters.length) || this._counters[endCounter+7] >= (this._calculatePatternLength(endCounter) / 2.0)) {
if ((startCounter - 1 <= 0)
|| this._counters[startCounter - 1] >= (this._calculatePatternLength(startCounter) / 2.0)) {
if ((endCounter + 8 >= this._counters.length)
|| this._counters[endCounter + 7] >= (this._calculatePatternLength(endCounter) / 2.0)) {
return true;
}
}

@ -247,8 +247,7 @@ Code128Reader.prototype._decode = function() {
rawResult = [],
decodedCodes = [],
shiftNext = false,
unshift,
lastCharacterWasPrintable;
unshift;
if (startInfo === null) {
return null;
@ -314,9 +313,6 @@ Code128Reader.prototype._decode = function() {
if (code.code < 96) {
result.push(String.fromCharCode(32 + code.code));
} else {
if (code.code != self.STOP_CODE) {
lastCharacterWasPrintable = false;
}
switch (code.code) {
case self.CODE_SHIFT:
shiftNext = true;
@ -355,7 +351,7 @@ Code128Reader.prototype._decode = function() {
done = true;
}
if (unshift) {
codeset = codeset == self.CODE_A ? self.CODE_B : self.CODE_A;
codeset = codeset === self.CODE_A ? self.CODE_B : self.CODE_A;
}
}
@ -372,7 +368,7 @@ Code128Reader.prototype._decode = function() {
// checksum
// Does not work correctly yet!!! startcode - endcode?
checksum -= multiplier * rawResult[rawResult.length - 1];
if (checksum % 103 != rawResult[rawResult.length - 1]) {
if (checksum % 103 !== rawResult[rawResult.length - 1]) {
return null;
}
@ -383,8 +379,6 @@ Code128Reader.prototype._decode = function() {
// remove last code from result (checksum)
result.splice(result.length - 1, 1);
return {
code: result.join(""),
start: startInfo.start,

@ -7,8 +7,12 @@ function Code39Reader() {
var properties = {
ALPHABETH_STRING: {value: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ-. *$/+%"},
ALPHABET: {value: [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 45, 46, 32, 42, 36, 47, 43, 37]},
CHARACTER_ENCODINGS: {value: [0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, 0x109, 0x049, 0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, 0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106, 0x046, 0x016, 0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, 0x0A8, 0x0A2, 0x08A, 0x02A]},
ALPHABET: {value: [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 45, 46, 32, 42, 36, 47, 43, 37]},
CHARACTER_ENCODINGS: {value: [0x034, 0x121, 0x061, 0x160, 0x031, 0x130, 0x070, 0x025, 0x124, 0x064, 0x109, 0x049,
0x148, 0x019, 0x118, 0x058, 0x00D, 0x10C, 0x04C, 0x01C, 0x103, 0x043, 0x142, 0x013, 0x112, 0x052, 0x007, 0x106,
0x046, 0x016, 0x181, 0x0C1, 0x1C0, 0x091, 0x190, 0x0D0, 0x085, 0x184, 0x0C4, 0x094, 0x0A8, 0x0A2, 0x08A, 0x02A
]},
ASTERISK: {value: 0x094},
FORMAT: {value: "code_39", writeable: false}
};
@ -179,7 +183,6 @@ Code39Reader.prototype._findStart = function() {
counter[counterPos]++;
} else {
if (counterPos === counter.length - 1) {
// find start pattern
if (self._toPattern(counter) === self.ASTERISK) {
whiteSpaceMustStart = Math.floor(Math.max(0, patternStart - ((i - patternStart) / 4)));

@ -10,12 +10,13 @@
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (/* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
function (/* function FrameRequestCallback */ callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
navigator.getUserMedia = navigator.getUserMedia ||
navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
}
Math.imul = Math.imul || function(a, b) {
@ -27,7 +28,3 @@
// the final |0 converts the unsigned value into a signed value
return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
};
export default {
}

@ -14,12 +14,12 @@ UPCReader.prototype.constructor = UPCReader;
UPCReader.prototype._decode = function() {
var result = EANReader.prototype._decode.call(this);
console.log("result", result);
if (result && result.code && result.code.length === 13 && result.code.charAt(0) === "0") {
result.code = result.code.substring(1);
return result;
}
return null;
};
export default EANReader;
export default UPCReader;

@ -1,55 +0,0 @@
var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;
var pathToModule = function(path) {
return path.replace(/^\/base\//, '').replace(/\.js$/, '');
};
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
allTestFiles.push(pathToModule(file));
}
});
require.config({
baseUrl: '/base',
paths: {
'array_helper': 'src/array_helper',
'cv_utils': 'src/cv_utils',
'typedefs': 'src/typedefs',
'cluster': 'src/cluster',
'camera_access': 'src/camera_access',
'events': 'src/events',
'html_utils': 'src/html_utils',
'quagga': 'src/quagga',
'barcode_decoder': 'src/barcode_decoder',
'barcode_locator': 'src/barcode_locator',
'barcode_reader': 'src/barcode_reader',
'bresenham': 'src/bresenham',
'codabar_reader': 'src/codabar_reader',
'code_39_reader': 'src/code_39_reader',
'code_39_vin_reader': 'src/code_39_vin_reader',
'code_128_reader': 'src/code_128_reader',
'config': 'src/config',
'ean_8_reader': 'src/ean_8_reader',
'ean_reader': 'src/ean_reader',
'frame_grabber': 'src/frame_grabber',
'image_debug': 'src/image_debug',
'image_loader': 'src/image_loader',
'image_wrapper': 'src/image_wrapper',
'input_stream': 'src/input_stream',
'rasterizer': 'src/rasterizer',
'skeletonizer': 'src/skeletonizer',
'subImage': 'src/subImage',
'tracer': 'src/tracer',
'upc_e_reader': 'src/upc_e_reader',
'upc_reader': 'src/upc_reader',
'async': 'node_modules/async/lib/async',
'gl-matrix': 'node_modules/gl-matrix/dist/gl-matrix-min',
'result_collector': 'src/result_collector',
'i2of5_reader': 'src/i2of5_reader'
},
deps: allTestFiles,
callback: window.__karma__.start
});

@ -0,0 +1,245 @@
const Quagga = require('../../src/quagga');
const async = require('async');
describe('decodeSingle', function () {
var baseFolder = "base/test/fixtures/";
function generateConfig() {
return {
inputStream: {
size: 640
},
locator: {
patchSize: "medium",
halfSample: true
},
numOfWorkers: 0,
decoder: {
readers: ["ean_reader"]
},
locate: true,
src: null
};
}
this.timeout(10000);
function _runTestSet(testSet, config) {
var readers = config.decoder.readers.slice(),
format,
folder;
if (typeof readers[0] === 'string'){
format = readers[0];
} else {
format = readers[0].format;
}
folder = baseFolder + format.split('_').slice(0, -1).join('_') + "/";
it('should decode ' + folder + " correctly", function(done) {
async.eachSeries(testSet, function (sample, callback) {
config.src = folder + sample.name;
config.readers = readers;
Quagga.decodeSingle(config, function(result) {
console.log(sample.name);
expect(result.codeResult.code).to.equal(sample.result);
expect(result.codeResult.format).to.equal(sample.format);
callback();
});
}, function() {
done();
});
});
}
describe("EAN", function() {
var config = generateConfig(),
testSet = [
{"name": "image-001.jpg", "result": "3574660239843"},
{"name": "image-002.jpg", "result": "8032754490297"},
{"name": "image-003.jpg", "result": "4006209700068"},
/* {"name": "image-004.jpg", "result": "9002233139084"}, */
/* {"name": "image-005.jpg", "result": "8004030044005"}, */
{"name": "image-006.jpg", "result": "4003626011159"},
{"name": "image-007.jpg", "result": "2111220009686"},
{"name": "image-008.jpg", "result": "9000275609022"},
{"name": "image-009.jpg", "result": "9004593978587"},
{"name": "image-010.jpg", "result": "9002244845578"}
];
testSet.forEach(function(sample) {
sample.format = "ean_13";
});
config.decoder.readers = ['ean_reader'];
_runTestSet(testSet, config);
});
describe("Code128", function() {
var config = generateConfig(),
testSet = [
{"name": "image-001.jpg", "result": "0001285112001000040801"},
// {"name": "image-002.jpg", "result": "FANAVF1461710"},
// {"name": "image-003.jpg", "result": "673023"},
// {"name": "image-004.jpg", "result": "010210150301625334"},
{"name": "image-005.jpg", "result": "419055603900009001012999"},
{"name": "image-006.jpg", "result": "419055603900009001012999"},
{"name": "image-007.jpg", "result": "T 000003552345"},
{"name": "image-008.jpg", "result": "FANAVF1461710"},
{"name": "image-009.jpg", "result": "0001285112001000040801"},
{"name": "image-010.jpg", "result": "673023"}
];
testSet.forEach(function(sample) {
sample.format = "code_128";
});
config.decoder.readers = ['code_128_reader'];
_runTestSet(testSet, config);
});
describe("Code39", function() {
var config = generateConfig(),
testSet = [
{"name": "image-001.jpg", "result": "B3% $DAD$"},
{"name": "image-003.jpg", "result": "CODE39"},
{"name": "image-004.jpg", "result": "QUAGGAJS"},
/* {"name": "image-005.jpg", "result": "CODE39"}, */
{"name": "image-006.jpg", "result": "2/4-8/16-32"},
{"name": "image-007.jpg", "result": "2/4-8/16-32"},
{"name": "image-008.jpg", "result": "CODE39"},
{"name": "image-009.jpg", "result": "2/4-8/16-32"},
{"name": "image-010.jpg", "result": "CODE39"}
];
testSet.forEach(function(sample) {
sample.format = "code_39";
});
config.decoder.readers = ['code_39_reader'];
_runTestSet(testSet, config);
});
describe("EAN-8", function() {
var config = generateConfig(),
testSet = [
{"name": "image-001.jpg", "result": "42191605"},
{"name": "image-002.jpg", "result": "42191605"},
{"name": "image-003.jpg", "result": "90311208"},
{"name": "image-004.jpg", "result": "24057257"},
{"name": "image-005.jpg", "result": "90162602"},
{"name": "image-006.jpg", "result": "24036153"},
{"name": "image-007.jpg", "result": "42176817"},
{"name": "image-008.jpg", "result": "42191605"},
{"name": "image-009.jpg", "result": "42242215"},
{"name": "image-010.jpg", "result": "42184799"}
];
testSet.forEach(function(sample) {
sample.format = "ean_8";
});
config.decoder.readers = ['ean_8_reader'];
_runTestSet(testSet, config);
});
describe("UPC", function() {
var config = generateConfig(),
testSet = [
{"name": "image-001.jpg", "result": "882428015268"},
{"name": "image-002.jpg", "result": "882428015268"},
{"name": "image-003.jpg", "result": "882428015084"},
{"name": "image-004.jpg", "result": "882428015343"},
{"name": "image-005.jpg", "result": "882428015343"},
/* {"name": "image-006.jpg", "result": "882428015046"}, */
{"name": "image-007.jpg", "result": "882428015084"},
{"name": "image-008.jpg", "result": "882428015046"},
{"name": "image-009.jpg", "result": "039047013551"},
{"name": "image-010.jpg", "result": "039047013551"}
];
testSet.forEach(function(sample) {
sample.format = "upc_a";
});
config.decoder.readers = ['upc_reader'];
_runTestSet(testSet, config);
});
describe("UPC-E", function() {
var config = generateConfig(),
testSet = [
{"name": "image-001.jpg", "result": "04965802"},
{"name": "image-002.jpg", "result": "04965802"},
{"name": "image-003.jpg", "result": "03897425"},
{"name": "image-004.jpg", "result": "05096893"},
{"name": "image-005.jpg", "result": "05096893"},
{"name": "image-006.jpg", "result": "05096893"},
{"name": "image-007.jpg", "result": "03897425"},
{"name": "image-008.jpg", "result": "01264904"},
/*{"name": "image-009.jpg", "result": "01264904"},*/
{"name": "image-010.jpg", "result": "01264904"}
];
testSet.forEach(function(sample) {
sample.format = "upc_e";
});
config.decoder.readers = ['upc_e_reader'];
_runTestSet(testSet, config);
});
describe("Codabar", function() {
var config = generateConfig(),
testSet = [
{"name": "image-001.jpg", "result": "A10/53+17-70D"},
{"name": "image-002.jpg", "result": "B546745735B"},
{"name": "image-003.jpg", "result": "C$399.95A"},
{"name": "image-004.jpg", "result": "B546745735B"},
{"name": "image-005.jpg", "result": "C$399.95A"},
{"name": "image-006.jpg", "result": "B546745735B"},
{"name": "image-007.jpg", "result": "C$399.95A"},
{"name": "image-008.jpg", "result": "A16:9/4:3/3:2D"},
{"name": "image-009.jpg", "result": "C$399.95A"},
{"name": "image-010.jpg", "result": "C$399.95A"}
];
testSet.forEach(function(sample) {
sample.format = "codabar";
});
config.decoder.readers = ['codabar_reader'];
_runTestSet(testSet, config);
});
describe("I2of5 with localization", function() {
var config = {
inputStream: {
size: 800,
singleChannel: false
},
locator: {
patchSize: "small",
halfSample: false
},
numOfWorkers: 0,
decoder: {
readers: ["i2of5_reader"]
},
locate: true,
src: null
},
testSet = [
{"name": "image-001.jpg", "result": "2167361334"},
{"name": "image-002.jpg", "result": "2167361334"},
{"name": "image-003.jpg", "result": "2167361334"},
{"name": "image-004.jpg", "result": "2167361334"},
{"name": "image-005.jpg", "result": "2167361334"}
];
testSet.forEach(function(sample) {
sample.format = "i2of5";
});
_runTestSet(testSet, config);
});
});

@ -0,0 +1,53 @@
const ArrayHelper = require('../../src/array_helper');
describe('init', function() {
it('initializes an array with the given value', function() {
var input = [0, 0, 0];
ArrayHelper.init(input, 5);
expect(input).to.deep.equal([5, 5, 5]);
});
});
describe('shuffle', function() {
before(function() {
sinon.stub(Math, 'random').returns(0.5);
});
after(function() {
sinon.restore(Math);
});
it('shuffles the content of an array', function() {
var input = [1, 2, 3];
expect(ArrayHelper.shuffle(input)).to.deep.equal([3, 1, 2]);
});
});
describe('toPointList', function() {
it('converts an Array to a List of poitns', function() {
var input = [[1, 2], [2, 2], [3, 2]];
expect(ArrayHelper.toPointList(input)).to.equal("[[1,2],\r\n[2,2],\r\n[3,2]]");
});
});
describe('threshold', function() {
it('returns all elements above the given threshold', function() {
var input = [1, 2, 3];
expect(ArrayHelper.threshold(input, 2, function(score) {
return score * 1.5;
})).to.deep.equal([2, 3]);
});
});
describe('maxIndex', function() {
it('gets the index of the biggest element in the array', function() {
var input = [1, 2, 3];
expect(ArrayHelper.maxIndex(input)).to.equal(2);
});
});
describe('max', function() {
it('gets the biggest element in the array', function() {
var input = [1, 3, 2];
expect(ArrayHelper.max(input)).to.equal(3);
});
});

@ -0,0 +1,130 @@
const BarcodeLocator = require('../../src/barcode_locator');
const Config = require('../../src/config');
const merge = require('lodash/object/merge');
describe('checkImageConstraints', function() {
var config,
inputStream,
imageSize,
streamConfig = {};
beforeEach(function() {
imageSize = {
x: 640, y: 480
};
config = merge({}, Config);
inputStream = {
getWidth: function() {
return imageSize.x;
},
getHeight: function() {
return imageSize.y;
},
setWidth: function() {},
setHeight: function() {},
setTopRight: function() {},
setCanvasSize: function() {},
getConfig: function() {
return streamConfig;
}
};
sinon.stub(inputStream, "setWidth", function(width) {
imageSize.x = width;
});
sinon.stub(inputStream, "setHeight", function(height) {
imageSize.y = height;
});
sinon.stub(inputStream, "setTopRight");
sinon.stub(inputStream, "setCanvasSize");
});
afterEach(function() {
inputStream.setWidth.restore();
inputStream.setHeight.restore();
});
it('should not adjust the image-size if not needed', function() {
var expected = {x: imageSize.x, y: imageSize.y};
BarcodeLocator.checkImageConstraints(inputStream, config.locator);
expect(inputStream.getWidth()).to.be.equal(expected.x);
expect(inputStream.getHeight()).to.be.equal(expected.y);
});
it('should adjust the image-size', function() {
var expected = {x: imageSize.x, y: imageSize.y};
config.locator.halfSample = true;
imageSize.y += 1;
BarcodeLocator.checkImageConstraints(inputStream, config.locator);
expect(inputStream.getWidth()).to.be.equal(expected.x);
expect(inputStream.getHeight()).to.be.equal(expected.y);
});
it('should adjust the image-size', function() {
var expected = {x: imageSize.x, y: imageSize.y};
imageSize.y += 1;
config.locator.halfSample = false;
BarcodeLocator.checkImageConstraints(inputStream, config.locator);
expect(inputStream.getHeight()).to.be.equal(expected.y);
expect(inputStream.getWidth()).to.be.equal(expected.x);
});
it("should take the defined area into account", function() {
var expectedSize = {
x: 420,
y: 315
},
expectedTopRight = {
x: 115,
y: 52
},
expectedCanvasSize = {
x: 640,
y: 480
};
streamConfig.area = {
top: "11%",
right: "15%",
bottom: "20%",
left: "18%"
};
config.locator.halfSample = false;
BarcodeLocator.checkImageConstraints(inputStream, config.locator);
expect(inputStream.getHeight()).to.be.equal(expectedSize.y);
expect(inputStream.getWidth()).to.be.equal(expectedSize.x);
expect(inputStream.setTopRight.getCall(0).args[0]).to.deep.equal(expectedTopRight);
expect(inputStream.setCanvasSize.getCall(0).args[0]).to.deep.equal(expectedCanvasSize);
});
it("should return the original size if set to full image", function() {
var expectedSize = {
x: 640,
y: 480
},
expectedTopRight = {
x: 0,
y: 0
},
expectedCanvasSize = {
x: 640,
y: 480
};
streamConfig.area = {
top: "0%",
right: "0%",
bottom: "0%",
left: "0%"
};
config.locator.halfSample = false;
BarcodeLocator.checkImageConstraints(inputStream, config.locator);
expect(inputStream.getHeight()).to.be.equal(expectedSize.y);
expect(inputStream.getWidth()).to.be.equal(expectedSize.x);
expect(inputStream.setTopRight.getCall(0).args[0]).to.deep.equal(expectedTopRight);
expect(inputStream.setCanvasSize.getCall(0).args[0]).to.deep.equal(expectedCanvasSize);
});
});

@ -0,0 +1,116 @@
const CameraAccess = require('../../src/camera_access');
var originalURL,
originalMediaStreamTrack,
video,
stream;
beforeEach(function() {
var tracks = [{
stop: function() {}
}];
originalURL = window.URL;
originalMediaStreamTrack = window.MediaStreamTrack;
window.MediaStreamTrack = {};
window.URL = null;
stream = {
getVideoTracks: function() {
return tracks;
}
};
sinon.spy(tracks[0], "stop");
video = {
src: null,
addEventListener: function() {},
removeEventListener: function() {},
play: function() {},
videoWidth: 320,
videoHeight: 480
};
sinon.stub(video, "addEventListener", function(event, cb) {
cb();
});
sinon.stub(video, "play");
});
afterEach(function() {
window.URL = originalURL;
window.MediaStreamTrack = originalMediaStreamTrack;
});
describe('success', function() {
beforeEach(function() {
sinon.stub(navigator, "getUserMedia", function(constraints, success) {
success(stream);
});
});
afterEach(function() {
navigator.getUserMedia.restore();
});
describe('request', function () {
it('should request the camera', function (done) {
CameraAccess.request(video, {}, function () {
expect(navigator.getUserMedia.calledOnce).to.equal(true);
expect(video.src).to.deep.equal(stream);
done();
});
});
});
describe('release', function () {
it('should release the camera', function (done) {
CameraAccess.request(video, {}, function () {
expect(video.src).to.deep.equal(stream);
CameraAccess.release();
expect(video.src.getVideoTracks()).to.have.length(1);
expect(video.src.getVideoTracks()[0].stop.calledOnce).to.equal(true);
done();
});
});
});
});
describe('failure', function() {
describe("permission denied", function(){
before(function() {
sinon.stub(navigator, "getUserMedia", function(constraints, success, failure) {
failure(new Error());
});
});
after(function() {
navigator.getUserMedia.restore();
});
it('should throw if getUserMedia not available', function(done) {
CameraAccess.request(video, {}, function(err) {
expect(err).to.be.defined;
done();
});
});
});
describe("not available", function(){
var originalGetUserMedia;
before(function() {
originalGetUserMedia = navigator.getUserMedia;
navigator.getUserMedia = undefined;
});
after(function() {
navigator.getUserMedia = originalGetUserMedia;
});
it('should throw if getUserMedia not available', function(done) {
CameraAccess.request(video, {}, function(err) {
expect(err).to.be.defined;
done();
});
});
});
});

@ -0,0 +1,144 @@
const CVUtils = require('../../src/cv_utils');
describe('imageRef', function() {
it('gets the image Reference for a coordinate', function() {
var res = CVUtils.imageRef(1, 2);
expect(res.x).to.equal(1);
expect(res.y).to.equal(2);
expect(res.toVec2()[0]).to.equal(1);
});
});
describe('calculatePatchSize', function() {
it('should not throw an error in case of valid image size', function() {
var expected = {x: 32, y: 32},
patchSize = CVUtils.calculatePatchSize("medium", {x: 640, y: 480});
expect(patchSize).to.be.deep.equal(expected);
});
it('should thow an error if image size it not valid', function() {
var expected = {x: 32, y: 32},
patchSize = CVUtils.calculatePatchSize("medium", {x: 640, y: 480});
expect(patchSize).to.be.deep.equal(expected);
});
});
describe('_parseCSSDimensionValues', function() {
it("should convert a percentual value correctly", function() {
var expected = {
value: 10,
unit: "%"
},
result = CVUtils._parseCSSDimensionValues("10%");
expect(result).to.be.deep.equal(expected);
});
it("should convert a 0% value correctly", function() {
var expected = {
value: 100,
unit: "%"
},
result = CVUtils._parseCSSDimensionValues("100%");
expect(result).to.be.deep.equal(expected);
});
it("should convert a 100% value correctly", function() {
var expected = {
value: 0,
unit: "%"
},
result = CVUtils._parseCSSDimensionValues("0%");
expect(result).to.be.deep.equal(expected);
});
it("should convert a pixel value to percentage", function() {
var expected = {
value: 26.3,
unit: "%"
},
result = CVUtils._parseCSSDimensionValues("26.3px");
console.log(result);
expect(result).to.be.deep.equal(expected);
});
});
describe("_dimensionsConverters", function(){
var context;
beforeEach(function() {
context = {
width: 640,
height: 480
};
});
it("should convert a top-value correclty", function() {
var expected = 48,
result = CVUtils._dimensionsConverters.top({value: 10, unit: "%"}, context);
expect(result).to.be.equal(expected);
});
it("should convert a right-value correclty", function() {
var expected = 640 - 128,
result = CVUtils._dimensionsConverters.right({value: 20, unit: "%"}, context);
expect(result).to.be.equal(expected);
});
it("should convert a bottom-value correclty", function() {
var expected = 480 - 77,
result = CVUtils._dimensionsConverters.bottom({value: 16, unit: "%"}, context);
expect(result).to.be.equal(expected);
});
it("should convert a left-value correclty", function() {
var expected = 57,
result = CVUtils._dimensionsConverters.left({value: 9, unit: "%"}, context);
expect(result).to.be.equal(expected);
});
});
describe("computeImageArea", function() {
it("should calculate an image-area", function() {
var expected = {
sx: 115,
sy: 48,
sw: 429,
sh: 336
},
result = CVUtils.computeImageArea(640, 480, {
top: "10%",
right: "15%",
bottom: "20%",
left: "18%"
});
expect(result).to.be.deep.equal(expected);
});
it("should calculate full image-area", function() {
var expected = {
sx: 0,
sy: 0,
sw: 640,
sh: 480
},
result = CVUtils.computeImageArea(640, 480, {
top: "0%",
right: "0%",
bottom: "0%",
left: "0%"
});
expect(result).to.be.deep.equal(expected);
});
});

@ -0,0 +1,114 @@
const Events = require('../../src/events');
beforeEach(function() {
Events.unsubscribe();
});
describe("subscribe", function() {
it("should call one callback for a single event", function() {
var callbackA = sinon.stub(),
callbackB = sinon.stub();
Events.subscribe("test", callbackA);
Events.subscribe("test", callbackB);
Events.publish("test");
expect(callbackA.calledOnce).to.be.equal(true);
expect(callbackB.calledOnce).to.be.equal(true);
});
it("should call one callback twice if published twice", function() {
var callback = sinon.stub();
Events.subscribe("test", callback);
Events.publish("test");
Events.publish("test");
expect(callback.calledTwice).to.be.equal(true);
});
it("should call the callback asynchronuously", function(done) {
var test = {
callback: function() {
}
};
sinon.stub(test, "callback", function() {
expect(test.callback.calledOnce).to.be.true;
done();
});
Events.subscribe("test", test.callback, true);
Events.publish("test");
expect(test.callback.called).to.be.false;
});
});
describe("once", function() {
it("should call the callback once, even when published twice", function() {
var callbackA = sinon.stub(),
callbackB = sinon.stub();
Events.once("test", callbackA);
Events.subscribe("test", callbackB);
Events.publish("test");
Events.publish("test");
expect(callbackA.calledOnce).to.be.equal(true);
expect(callbackB.calledTwice).to.be.equal(true);
});
});
describe("unsubscribe", function() {
it("should unsubscribe all callbacks from a single event", function() {
var callbackA = sinon.stub(),
callbackB = sinon.stub(),
callbackC = sinon.stub();
Events.subscribe("test", callbackA);
Events.subscribe("test", callbackB);
Events.subscribe("testC", callbackC);
Events.publish("test");
expect(callbackC.called).to.be.equal(false);
expect(callbackA.calledOnce).to.be.equal(true);
expect(callbackB.calledOnce).to.be.equal(true);
Events.publish("testC");
expect(callbackC.calledOnce).to.be.equal(true);
expect(callbackA.calledOnce).to.be.equal(true);
expect(callbackB.calledOnce).to.be.equal(true);
Events.unsubscribe("test");
Events.publish("test");
expect(callbackC.calledOnce).to.be.equal(true);
expect(callbackA.calledOnce).to.be.equal(true);
expect(callbackB.calledOnce).to.be.equal(true);
});
it("should unsubscribe a single callback from a single event", function() {
var callbackA = sinon.stub(),
callbackB = sinon.stub();
Events.subscribe("test", callbackA);
Events.subscribe("test", callbackB);
Events.publish("test");
expect(callbackA.calledOnce).to.be.equal(true);
expect(callbackB.calledOnce).to.be.equal(true);
Events.unsubscribe("test", callbackB);
Events.publish("test");
expect(callbackA.calledTwice).to.be.equal(true);
expect(callbackB.calledOnce).to.be.equal(true);
});
});

@ -0,0 +1,103 @@
const ResultCollector = require('../../src/result_collector');
const ImageDebug = require('../../src/image_debug');
var canvasMock,
imageSize,
config;
beforeEach(function() {
imageSize = {x: 320, y: 240};
config = {
capture: true,
capacity: 20,
blacklist: [{code: "3574660239843", format: "ean_13"}],
filter: function() {
return true;
}
};
canvasMock = {
getContext: function() {
return {};
},
toDataURL: sinon.spy(),
width: 0,
height: 0
};
sinon.stub(document, "createElement", function(type) {
if (type === "canvas") {
return canvasMock;
}
});
});
afterEach(function() {
document.createElement.restore();
});
describe('create', function () {
it("should return a new collector", function() {
ResultCollector.create(config);
expect(document.createElement.calledOnce).to.be.equal(true);
expect(document.createElement.getCall(0).args[0]).to.equal("canvas");
});
});
describe('addResult', function() {
beforeEach(function() {
sinon.stub(ImageDebug, "drawImage", function() {});
});
afterEach(function() {
ImageDebug.drawImage.restore();
});
it("should not add result if capacity is full", function(){
config.capacity = 1;
var collector = ResultCollector.create(config);
collector.addResult([], imageSize, {});
collector.addResult([], imageSize, {});
collector.addResult([], imageSize, {});
expect(collector.getResults()).to.have.length(1);
});
it("should only add results which match constraints", function(){
var collector = ResultCollector.create(config),
results;
collector.addResult([], imageSize, {code: "423423443", format: "ean_13"});
collector.addResult([], imageSize, {code: "3574660239843", format: "ean_13"});
collector.addResult([], imageSize, {code: "3574660239843", format: "code_128"});
results = collector.getResults();
expect(results).to.have.length(2);
results.forEach(function(result) {
expect(result).not.to.deep.equal(config.blacklist[0]);
});
});
it("should add result if no filter is set", function() {
delete config.filter;
var collector = ResultCollector.create(config);
collector.addResult([], imageSize, {code: "423423443", format: "ean_13"});
expect(collector.getResults()).to.have.length(1);
});
it("should not add results if filter returns false", function() {
config.filter = () => (false);
var collector = ResultCollector.create(config);
collector.addResult([], imageSize, {code: "423423443", format: "ean_13"});
expect(collector.getResults()).to.have.length(0);
});
it("should add result if no blacklist is set", function() {
delete config.blacklist;
var collector = ResultCollector.create(config);
collector.addResult([], imageSize, {code: "3574660239843", format: "ean_13"});
expect(collector.getResults()).to.have.length(1);
});
});

@ -0,0 +1,8 @@
require('events').EventEmitter.prototype._maxListeners = 0;
require('core-js/es5');
const testsContext = require.context("./integration", true, /.*js$/);
testsContext.keys().forEach(testsContext);
const componentsContext = require.context('../src/', true, /\.*js$/);
componentsContext.keys().forEach(componentsContext);

@ -0,0 +1,8 @@
require('events').EventEmitter.prototype._maxListeners = 0;
require('core-js/es5');
const testsContext = require.context("./spec", true, /.*js$/);
testsContext.keys().forEach(testsContext);
const componentsContext = require.context('../src/', true, /\.*js$/);
componentsContext.keys().forEach(componentsContext);
Loading…
Cancel
Save