<commit_before>'use strict';

/* global describe, it, before, after, expect, uniqueKey  */

var Promise = require('bluebird');
var Client  = require('..');
var _       = require('lodash');

var bucket = 'no-riak-test-kv';
var client = new Client();

describe('Key/Value operations', function () {
    before(function () {
        return client.setBucket({
            bucket: bucket,
            props: {
                allow_mult: true
            }
        });
    });

    it('put/get UTF8 string', function () {
        var str = '人人生而自由，在尊嚴和權利上一律平等。';
        return client.put({
            bucket: bucket,
            content: {
                value: str
            }
        })
        .then(function (result) {
            result.should.be.an('object').and.have.property('key').that.is.a('string');

            return client.get({
                bucket: bucket,
                key: result.key
            });
        })
        .then(function (result) {
            result.should.be.an('object');
            result.should.have.property('content').that.is.an('array');
            result.should.have.property('vclock').that.is.a('string');
            result.content.should.have.length(1);
            result.content[0].should.have.property('value');
            result.content[0].value.toString('utf8').should.be.eql(str);
            result.content[0].should.have.property('vtag').that.is.a('string');
            result.content[0].should.have.property('last_mod').that.is.a('number');
            result.content[0].should.have.property('last_mod_usecs').that.is.a('number');
        });
    });

    it('put - number - rejected', function () {
        return client.put({
            bucket: bucket,
            content: {
                value: 123
            }
        }).should.be.rejected;
    });

    it('put/get - plain object (autoJSON = true)', function () {
        var obj = {
            hello: 'world!'
        };
        return client.put({
            bucket: bucket,
            content: {
                value: obj
            }
        })
        .then(function (result) {
            result.should.be.an('object').and.have.property('key').that.is.a('string');

            return client.get({
                bucket: bucket,
                key: result.key
            });
        })
        .then(function (result) {
            result.should.be.an('object');
            result.should.have.property('content').that.is.an('array');
            result.should.have.property('vclock').that.is.a('string');
            result.content.should.have.length(1);
            result.content[0].should.have.property('value');
            result.content[0].value.should.be.eql(obj);
            result.content[0].should.have.property('vtag').that.is.a('string');
            result.content[0].should.have.property('last_mod').that.is.a('number');
            result.content[0].should.have.property('last_mod_usecs').that.is.a('number');
        });
    });

    it('put - plain object (autoJSON = false)', function () {
        var _client = new Client({
            autoJSON: false
        });

        return _client.put({
            bucket: bucket,
            content: {
                value: {
                    hello: 'world!'
                }
            }
        }).should.be.rejected;
    });

    it('put/get with specified key', function () {
        var key = uniqueKey('key');

        return client.put({
            bucket: bucket,
            key: key,
            content: {
                value: 'hello'
            }
        })
        .then(function (result) {
            expect(result).to.eql(null);

            return client.get({
                bucket: bucket,
                key: key
            });
        })
        .then(function (result) {
            result.should.be.an('object');
            result.should.have.property('content').that.is.an('array');
            result.content.should.have.length(1);
            result.content[0].should.have.property('value');
            result.content[0].value.toString().should.be.eql('hello');
        });
    });

    it('put twice without vclock - siblings (allow_mult=true)', function () {
        var key = uniqueKey('key');

        return client.put({
            bucket: bucket,
            key: key,
            content: {
                value: 'hello1'
            }
        })
        .then(function () {
            return client.put({
                bucket: bucket,
                key: key,
                content: {
                    value: 'hello2'
                }
            });
        })
        .then(function () {
            return client.get({
                bucket: bucket,
                key: key
            });
        })
        .then(function (result) {
            result.should.be.an('object');
            result.should.have.property('content').that.is.an('array');
            result.content.should.have.length(2);
            result.content[0].should.have.property('value');
            result.content[0].value.toString().should.be.eql('hello1');
            result.content[1].should.have.property('value');
            result.content[1].value.toString().should.be.eql('hello2');
        });
    });

    it('update twice - no siblings (allow_mult=true)', function () {
        var key = uniqueKey('key');

        return client.update({
            bucket: bucket,
            key: key,
            content: {
                value: 'hello1'
            }
        })
        .then(function () {
            return client.update({
                bucket: bucket,
                key: key,
                content: {
                    value: 'hello2'
                }
            });
        })
        .then(function () {
            return client.get({
                bucket: bucket,
                key: key
            });
        })
        .then(function (result) {
            result.should.be.an('object');
            result.should.have.property('content').that.is.an('array');
            result.content.should.have.length(1);
            result.content[0].should.have.property('value');
            result.content[0].value.toString().should.be.eql('hello2');
        });
    });

    it('listBuckets', function () {
        this.timeout(5000);
        return client.listBuckets()
        .then(function (result) {
            result.should.be.an('array');
            result.should.have.length.gt(0);
            result[0].should.be.a('string');
            result.should.include(bucket);
        });
    });

    it('listKeys', function () {
        var key = uniqueKey('key');

        return client.put({
            bucket: bucket,
            key: key,
            content: {
                value: 'hello'
            }
        })
        .then(function () {
            return client.listKeys({
                bucket: bucket
            });
        })
        .then(function (result) {
            result.should.be.an('array');
            result.should.have.length.gt(0);
            result[0].should.be.a('string');
            result.should.include(key);
        });
    });

    it('del - wrong key', function () {
        return client.del({
            bucket: bucket,
            key: 'no-such-key'
        }).should.eventually.eql(null);
    });

    it('del - wrong bucket', function () {
        return client.del({
            bucket: 'no-such-bucket',
            key: 'no-such-key'
        }).should.eventually.eql(null);
    });

    it('del', function () {
        var key = uniqueKey('key');

        return client.put({
            bucket: bucket,
            key: key,
            content: {
                value: 'hello'
            }
        })
        .then(function () {
            return client.del({
                bucket: bucket,
                key: key
            });
        })
        .delay(20) // easy way to avoid tobstones in a test (without using vclock)
        .then(function () {
            return client.get({
                bucket: bucket,
                key: key
            });
        }).should.eventually.be.eql(null);
    });

    it('2i search, with max_results/continuation', function () {
        var keys = [], indexValue = uniqueKey('index');

        return Promise.all(_.range(3).map(function (i) {
            keys[i] = uniqueKey('key');
            return client.put({
                bucket: bucket,
                key: keys[i],
                content: {
                    value: 'i' + i,
                    indexes: [{
                        key: 'no-riak-test_bin',
                        value: indexValue
                    }]
                }
            });
        }))
        .then(function () {
            return client.index({
                bucket: bucket,
                index: 'no-riak-test_bin',
                qtype: 0,
                max_results: 2,
                key: indexValue
            });
        })
        .spread(function (_keys, continuation) {
            _keys.should.be.an('array').and.have.length(2);
            continuation.should.be.a('string');

            return client.index({
                bucket: bucket,
                index: 'no-riak-test_bin',
                qtype: 0,
                max_results: 2,
                continuation: continuation,
                key: indexValue
            });
        })
        .spread(function (_keys, continuation) {
            _keys.should.be.an('array').and.have.length(1);
            expect(continuation).to.eql(null);
        });
    });

    it('2i search all at once', function () {
        var keys = [], indexValue = uniqueKey('index');
        return Promise.all(_.range(3).map(function (i) {
            keys[i] = uniqueKey('key');
            return client.put({
                bucket: bucket,
                key: keys[i],
                content: {
                    value: 'i' + i,
                    indexes: [{
                        key: 'no-riak-test_bin',
                        value: indexValue
                    }]
                }
            });
        }))
        .then(function () {
            return client.index({
                bucket: bucket,
                index: 'no-riak-test_bin',
                qtype: 0,
                key: indexValue
            });
        })
        .spread(function (_keys, continuation) {
            _keys.should.be.an('array').and.have.length(3);
            expect(continuation).to.eql(null);
        });
    });

    it('2i range query with return_terms=true', function () {
        var keys = [], indexValue = uniqueKey('index');
        return Promise.all(_.range(3).map(function (i) {
            keys[i] = uniqueKey('key');
            return client.put({
                bucket: bucket,
                key: keys[i],
                content: {
                    value: 'i' + i,
                    indexes: [{
                        key: 'no-riak-test_bin',
                        value: indexValue
                    }]
                }
            });
        }))
        .then(function () {
            return client.index({
                bucket: bucket,
                index: 'no-riak-test_bin',
                qtype: 1,
                return_terms: true,
                range_min: indexValue,
                range_max: indexValue
            });
        })
        .spread(function (results, continuation) {
            results.should.be.an('array').and.have.length(3);
            results[0].should.be.an('object');
            results[0].should.have.property('key');
            results[0].should.have.property('value');
            expect(continuation).to.eql(null);
        });
    });

    it('2i invalid query', function () {
        return client.index({
            bucket: bucket,
            index: 'no-riak-test_bin',
            qtype: 0
        }).should.be.rejectedWith('Invalid equality query');
    });

    it('map/reduce', function () {
        var keys = [];
        return Promise.all(_.range(3).map(function (i) {
            keys[i] = uniqueKey('key');
            return client.put({
                bucket: bucket,
                key: keys[i],
                content: {
                    value: {
                        num: i + 10
                    }
                }
            });
        }))
        .then(function () {
            return client.mapReduce({
                request: {
                    inputs: _.map(keys, function (k) { return [bucket, k]; }),
                    query: [{
                        map: { // this phase will return JSON decoded values for each input
                            source: 'function(v) { var d = Riak.mapValuesJson(v)[0]; return [d]; }',
                            language: 'javascript',
                            keep: true
                        }
                    }, { // this phase will return the `num` property of each value
                        reduce: {
                            source: 'function(values) { return values.map(function(v){ return v.num; }); }',
                            language: 'javascript',
                            keep: true
                        }
                    }, { // this phase will return a sum of all values
                        reduce: {
                            module: 'riak_kv_mapreduce',
                            function: 'reduce_sum',
                            language: 'erlang',
                            keep: true
                        }
                    }]
                }
            });
        })
        .then(function (results) {
            results.should.be.an('array').and.have.length(3); // each index in array is (phase number - 1), even if phase.keep was false

            results[0].should.be.an('array').and.have.length(3); // array of 1st phase results
            results[0].should.include({ num: 10 });

            results[1].should.be.an('array').and.have.length(3); // array of 2nd phase results
            results[1].should.include(10);

            results[2].should.be.an('array').and.have.length(1); // array of 3rd phase results
            results[2][0].should.be.eql(10 + 11 + 12);
        });
    });

    it('map/reduce - keep=false', function () {
        var keys = [];
        return Promise.all(_.range(3).map(function (i) {
            keys[i] = uniqueKey('key');
            return client.put({
                bucket: bucket,
                key: keys[i],
                content: {
                    value: {
                        num: i + 10
                    }
                }
            });
        }))
        .then(function () {
            return client.mapReduce({
                request: {
                    inputs: _.map(keys, function (k) { return [bucket, k]; }),
                    query: [{
                        map: {
                            source: 'function(v) { var d = Riak.mapValuesJson(v)[0]; return [d]; }',
                            language: 'javascript'
                        }
                    }, {
                        reduce: {
                            source: 'function(values) { return values.map(function(v){ return v.num; }); }',
                            language: 'javascript'
                        }
                    }, {
                        reduce: {
                            module: 'riak_kv_mapreduce',
                            function: 'reduce_sum',
                            language: 'erlang'
                        }
                    }]
                }
            });
        })
        .then(function (results) {
            results.should.be.an('array').and.have.length(3); // each index in array is (phase number - 1), even if phase.keep was false

            expect(results[0]).to.eql(undefined);
            expect(results[1]).to.eql(undefined);

            results[2].should.be.an('array').and.have.length(1); // array of 3rd phase results
            results[2][0].should.be.eql(10 + 11 + 12);
        });
    });

    it('set counter', function () {
        var key = uniqueKey('counter');
        return client.updateCounter({
            bucket: bucket,
            key: key,
            amount: 5,
            returnvalue: true
        })
        .then(function (value) {
            value.toNumber().should.be.eql(5);
        });
    });

    it('get counter', function () {
        var key = uniqueKey('counter');
        return client.updateCounter({
            bucket: bucket,
            key: key,
            amount: 5
        })
        .then(function () {
            return client.getCounter({
                bucket: bucket,
                key: key
            });
        })
        .then(function (value) {
            value.toNumber().should.be.eql(5);
        });
    });
});
<commit_msg>Test get() return null when key doesn't exit in Riak<commit_after>'use strict';

/* global describe, it, before, after, expect, uniqueKey  */

var Promise = require('bluebird');
var Client  = require('..');
var _       = require('lodash');

var bucket = 'no-riak-test-kv';
var client = new Client();

describe('Key/Value operations', function () {
    before(function () {
        return client.setBucket({
            bucket: bucket,
            props: {
                allow_mult: true
            }
        });
    });

    it('put/get UTF8 string', function () {
        var str = '人人生而自由，在尊嚴和權利上一律平等。';
        return client.put({
            bucket: bucket,
            content: {
                value: str
            }
        })
        .then(function (result) {
            result.should.be.an('object').and.have.property('key').that.is.a('string');

            return client.get({
                bucket: bucket,
                key: result.key
            });
        })
        .then(function (result) {
            result.should.be.an('object');
            result.should.have.property('content').that.is.an('array');
            result.should.have.property('vclock').that.is.a('string');
            result.content.should.have.length(1);
            result.content[0].should.have.property('value');
            result.content[0].value.toString('utf8').should.be.eql(str);
            result.content[0].should.have.property('vtag').that.is.a('string');
            result.content[0].should.have.property('last_mod').that.is.a('number');
            result.content[0].should.have.property('last_mod_usecs').that.is.a('number');
        });
    });

    it('put - number - rejected', function () {
        return client.put({
            bucket: bucket,
            content: {
                value: 123
            }
        }).should.be.rejected;
    });

    it('put/get - plain object (autoJSON = true)', function () {
        var obj = {
            hello: 'world!'
        };
        return client.put({
            bucket: bucket,
            content: {
                value: obj
            }
        })
        .then(function (result) {
            result.should.be.an('object').and.have.property('key').that.is.a('string');

            return client.get({
                bucket: bucket,
                key: result.key
            });
        })
        .then(function (result) {
            result.should.be.an('object');
            result.should.have.property('content').that.is.an('array');
            result.should.have.property('vclock').that.is.a('string');
            result.content.should.have.length(1);
            result.content[0].should.have.property('value');
            result.content[0].value.should.be.eql(obj);
            result.content[0].should.have.property('vtag').that.is.a('string');
            result.content[0].should.have.property('last_mod').that.is.a('number');
            result.content[0].should.have.property('last_mod_usecs').that.is.a('number');
        });
    });

    it('put - plain object (autoJSON = false)', function () {
        var _client = new Client({
            autoJSON: false
        });

        return _client.put({
            bucket: bucket,
            content: {
                value: {
                    hello: 'world!'
                }
            }
        }).should.be.rejected;
    });

    it('put/get with specified key', function () {
        var key = uniqueKey('key');

        return client.put({
            bucket: bucket,
            key: key,
            content: {
                value: 'hello'
            }
        })
        .then(function (result) {
            expect(result).to.eql(null);

            return client.get({
                bucket: bucket,
                key: key
            });
        })
        .then(function (result) {
            result.should.be.an('object');
            result.should.have.property('content').that.is.an('array');
            result.content.should.have.length(1);
            result.content[0].should.have.property('value');
            result.content[0].value.toString().should.be.eql('hello');
        });
    });

    it('get wrong key', function () {
        var key = uniqueKey('key');

        return client.get({
            bucket: bucket,
            key: key
        })
        .then(function (result) {
            expect(result).to.eql(null);
        });
    });

    it('put twice without vclock - siblings (allow_mult=true)', function () {
        var key = uniqueKey('key');

        return client.put({
            bucket: bucket,
            key: key,
            content: {
                value: 'hello1'
            }
        })
        .then(function () {
            return client.put({
                bucket: bucket,
                key: key,
                content: {
                    value: 'hello2'
                }
            });
        })
        .then(function () {
            return client.get({
                bucket: bucket,
                key: key
            });
        })
        .then(function (result) {
            result.should.be.an('object');
            result.should.have.property('content').that.is.an('array');
            result.content.should.have.length(2);
            result.content[0].should.have.property('value');
            result.content[0].value.toString().should.be.eql('hello1');
            result.content[1].should.have.property('value');
            result.content[1].value.toString().should.be.eql('hello2');
        });
    });

    it('update twice - no siblings (allow_mult=true)', function () {
        var key = uniqueKey('key');

        return client.update({
            bucket: bucket,
            key: key,
            content: {
                value: 'hello1'
            }
        })
        .then(function () {
            return client.update({
                bucket: bucket,
                key: key,
                content: {
                    value: 'hello2'
                }
            });
        })
        .then(function () {
            return client.get({
                bucket: bucket,
                key: key
            });
        })
        .then(function (result) {
            result.should.be.an('object');
            result.should.have.property('content').that.is.an('array');
            result.content.should.have.length(1);
            result.content[0].should.have.property('value');
            result.content[0].value.toString().should.be.eql('hello2');
        });
    });

    it('listBuckets', function () {
        this.timeout(5000);
        return client.listBuckets()
        .then(function (result) {
            result.should.be.an('array');
            result.should.have.length.gt(0);
            result[0].should.be.a('string');
            result.should.include(bucket);
        });
    });

    it('listKeys', function () {
        var key = uniqueKey('key');

        return client.put({
            bucket: bucket,
            key: key,
            content: {
                value: 'hello'
            }
        })
        .then(function () {
            return client.listKeys({
                bucket: bucket
            });
        })
        .then(function (result) {
            result.should.be.an('array');
            result.should.have.length.gt(0);
            result[0].should.be.a('string');
            result.should.include(key);
        });
    });

    it('del - wrong key', function () {
        return client.del({
            bucket: bucket,
            key: 'no-such-key'
        }).should.eventually.eql(null);
    });

    it('del - wrong bucket', function () {
        return client.del({
            bucket: 'no-such-bucket',
            key: 'no-such-key'
        }).should.eventually.eql(null);
    });

    it('del', function () {
        var key = uniqueKey('key');

        return client.put({
            bucket: bucket,
            key: key,
            content: {
                value: 'hello'
            }
        })
        .then(function () {
            return client.del({
                bucket: bucket,
                key: key
            });
        })
        .delay(20) // easy way to avoid tobstones in a test (without using vclock)
        .then(function () {
            return client.get({
                bucket: bucket,
                key: key
            });
        }).should.eventually.be.eql(null);
    });

    it('2i search, with max_results/continuation', function () {
        var keys = [], indexValue = uniqueKey('index');

        return Promise.all(_.range(3).map(function (i) {
            keys[i] = uniqueKey('key');
            return client.put({
                bucket: bucket,
                key: keys[i],
                content: {
                    value: 'i' + i,
                    indexes: [{
                        key: 'no-riak-test_bin',
                        value: indexValue
                    }]
                }
            });
        }))
        .then(function () {
            return client.index({
                bucket: bucket,
                index: 'no-riak-test_bin',
                qtype: 0,
                max_results: 2,
                key: indexValue
            });
        })
        .spread(function (_keys, continuation) {
            _keys.should.be.an('array').and.have.length(2);
            continuation.should.be.a('string');

            return client.index({
                bucket: bucket,
                index: 'no-riak-test_bin',
                qtype: 0,
                max_results: 2,
                continuation: continuation,
                key: indexValue
            });
        })
        .spread(function (_keys, continuation) {
            _keys.should.be.an('array').and.have.length(1);
            expect(continuation).to.eql(null);
        });
    });

    it('2i search all at once', function () {
        var keys = [], indexValue = uniqueKey('index');
        return Promise.all(_.range(3).map(function (i) {
            keys[i] = uniqueKey('key');
            return client.put({
                bucket: bucket,
                key: keys[i],
                content: {
                    value: 'i' + i,
                    indexes: [{
                        key: 'no-riak-test_bin',
                        value: indexValue
                    }]
                }
            });
        }))
        .then(function () {
            return client.index({
                bucket: bucket,
                index: 'no-riak-test_bin',
                qtype: 0,
                key: indexValue
            });
        })
        .spread(function (_keys, continuation) {
            _keys.should.be.an('array').and.have.length(3);
            expect(continuation).to.eql(null);
        });
    });

    it('2i range query with return_terms=true', function () {
        var keys = [], indexValue = uniqueKey('index');
        return Promise.all(_.range(3).map(function (i) {
            keys[i] = uniqueKey('key');
            return client.put({
                bucket: bucket,
                key: keys[i],
                content: {
                    value: 'i' + i,
                    indexes: [{
                        key: 'no-riak-test_bin',
                        value: indexValue
                    }]
                }
            });
        }))
        .then(function () {
            return client.index({
                bucket: bucket,
                index: 'no-riak-test_bin',
                qtype: 1,
                return_terms: true,
                range_min: indexValue,
                range_max: indexValue
            });
        })
        .spread(function (results, continuation) {
            results.should.be.an('array').and.have.length(3);
            results[0].should.be.an('object');
            results[0].should.have.property('key');
            results[0].should.have.property('value');
            expect(continuation).to.eql(null);
        });
    });

    it('2i invalid query', function () {
        return client.index({
            bucket: bucket,
            index: 'no-riak-test_bin',
            qtype: 0
        }).should.be.rejectedWith('Invalid equality query');
    });

    it('map/reduce', function () {
        var keys = [];
        return Promise.all(_.range(3).map(function (i) {
            keys[i] = uniqueKey('key');
            return client.put({
                bucket: bucket,
                key: keys[i],
                content: {
                    value: {
                        num: i + 10
                    }
                }
            });
        }))
        .then(function () {
            return client.mapReduce({
                request: {
                    inputs: _.map(keys, function (k) { return [bucket, k]; }),
                    query: [{
                        map: { // this phase will return JSON decoded values for each input
                            source: 'function(v) { var d = Riak.mapValuesJson(v)[0]; return [d]; }',
                            language: 'javascript',
                            keep: true
                        }
                    }, { // this phase will return the `num` property of each value
                        reduce: {
                            source: 'function(values) { return values.map(function(v){ return v.num; }); }',
                            language: 'javascript',
                            keep: true
                        }
                    }, { // this phase will return a sum of all values
                        reduce: {
                            module: 'riak_kv_mapreduce',
                            function: 'reduce_sum',
                            language: 'erlang',
                            keep: true
                        }
                    }]
                }
            });
        })
        .then(function (results) {
            results.should.be.an('array').and.have.length(3); // each index in array is (phase number - 1), even if phase.keep was false

            results[0].should.be.an('array').and.have.length(3); // array of 1st phase results
            results[0].should.include({ num: 10 });

            results[1].should.be.an('array').and.have.length(3); // array of 2nd phase results
            results[1].should.include(10);

            results[2].should.be.an('array').and.have.length(1); // array of 3rd phase results
            results[2][0].should.be.eql(10 + 11 + 12);
        });
    });

    it('map/reduce - keep=false', function () {
        var keys = [];
        return Promise.all(_.range(3).map(function (i) {
            keys[i] = uniqueKey('key');
            return client.put({
                bucket: bucket,
                key: keys[i],
                content: {
                    value: {
                        num: i + 10
                    }
                }
            });
        }))
        .then(function () {
            return client.mapReduce({
                request: {
                    inputs: _.map(keys, function (k) { return [bucket, k]; }),
                    query: [{
                        map: {
                            source: 'function(v) { var d = Riak.mapValuesJson(v)[0]; return [d]; }',
                            language: 'javascript'
                        }
                    }, {
                        reduce: {
                            source: 'function(values) { return values.map(function(v){ return v.num; }); }',
                            language: 'javascript'
                        }
                    }, {
                        reduce: {
                            module: 'riak_kv_mapreduce',
                            function: 'reduce_sum',
                            language: 'erlang'
                        }
                    }]
                }
            });
        })
        .then(function (results) {
            results.should.be.an('array').and.have.length(3); // each index in array is (phase number - 1), even if phase.keep was false

            expect(results[0]).to.eql(undefined);
            expect(results[1]).to.eql(undefined);

            results[2].should.be.an('array').and.have.length(1); // array of 3rd phase results
            results[2][0].should.be.eql(10 + 11 + 12);
        });
    });

    it('set counter', function () {
        var key = uniqueKey('counter');
        return client.updateCounter({
            bucket: bucket,
            key: key,
            amount: 5,
            returnvalue: true
        })
        .then(function (value) {
            value.toNumber().should.be.eql(5);
        });
    });

    it('get counter', function () {
        var key = uniqueKey('counter');
        return client.updateCounter({
            bucket: bucket,
            key: key,
            amount: 5
        })
        .then(function () {
            return client.getCounter({
                bucket: bucket,
                key: key
            });
        })
        .then(function (value) {
            value.toNumber().should.be.eql(5);
        });
    });
});
<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var hexdiff = require('hexer/diff');
var util = require('util');
var intoBufferResult = require('./interface').intoBufferResult;
var fromBufferResult = require('./interface').fromBufferResult;
var formatError = require('./interface').formatError;

module.exports.cases = testCases;

function testCases(rw, cases) {
    var self = function runTestCases(assert, done) {
        for (var i = 0; i < cases.length; i++) {
            var testCase;
            if (Array.isArray(cases[i])) {
                var value = cases[i][0];
                var bytes = cases[i][1];
                testCase = {
                    lengthTest: {
                        length: bytes.length,
                        value: value
                    },
                    writeTest: {
                        bytes: bytes,
                        value: value
                    },
                    readTest: {
                        bytes: bytes,
                        value: value
                    }
                };
            } else if (typeof cases[i] !== 'object') {
                throw new Error('invalid test case ' + i);
            } else {
                testCase = cases[i];
            }
            new RWTestCase(assert, rw, testCase).run();
        }
        (done || assert.end)();
    };
    self.assert = null;
    self.rw = null;
    return self;
}

function RWTestCase(assert, rw, testCase) {
    var self = this;
    self.assert = assert;
    self.rw = rw;
    self.testCase = testCase;
    self.hexdumpStream = process.stdout;
}

RWTestCase.prototype.run = function run() {
    var self = this;
    if (self.testCase.lengthTest) self.runLengthTest();
    if (self.testCase.writeTest) self.runWriteTest();
    if (self.testCase.readTest) self.runReadTest();
};

RWTestCase.prototype.runLengthTest = function runLengthTest() {
    var self = this;
    var testCase = self.testCase.lengthTest;
    var val = testCase.value;
    var res = self.rw.byteLength(val);
    if (res.err) {
        if (testCase.error) {
            self.assert.deepEqual(
                copyErr(res.err, testCase.error),
                testCase.error, 'expected length error');
        } else {
            self.assert.ifError(res.err, 'no length error');
        }
    } else if (testCase.error) {
        self.assert.fail('expected length error');
    } else {
        self.assert.deepEqual(res && res.length, testCase.length, util.format('length: %j', val));
    }
};

RWTestCase.prototype.runWriteTest = function runWriteTest() {
    var self = this;
    var testCase = self.testCase.writeTest;
    var val = testCase.value;
    var got = Buffer(testCase.bytes ? testCase.bytes.length : testCase.length || 0);
    got.fill(0);
    var res = intoBufferResult(self.rw, got, val);
    var err = res.error;
    if (err) {
        if (testCase.error) {
            self.assert.deepEqual(
                copyErr(err, testCase.error),
                testCase.error, 'expected write error');
        } else {
            self.hexdump('write error', err);
            self.assert.ifError(err, 'no write error');
        }
    } else if (testCase.error) {
        self.assert.fail('expected write error');
    } else {
        var desc = util.format('write: %j', val);
        var buf = Buffer(testCase.bytes);
        // istanbul ignore if
        if (got.toString('hex') !== buf.toString('hex')) {
            self.assert.comment('expected v actual:\n' +
                hexdiff(buf, got, {colored: true}));
            self.assert.fail(desc);
        } else {
            self.assert.pass(desc);
        }
    }
};

RWTestCase.prototype.runReadTest = function runReadTest() {
    var self = this;
    var testCase = self.testCase.readTest;
    var buffer = Buffer(testCase.bytes);
    var res = fromBufferResult(self.rw, buffer);
    var err = res.error;
    var got = res.value;
    if (err) {
        if (testCase.error) {
            self.assert.deepEqual(
                copyErr(err, testCase.error),
                testCase.error, 'expected read error');
        } else {
            // istanbul ignore else
            if (!got && err.buffer) got = err.buffer;
            // istanbul ignore else
            if (Buffer.isBuffer(got)) self.hexdump('read error', err);
            self.assert.ifError(err, 'no read error');
        }
    } else if (testCase.error) {
        self.assert.fail('expected read error');
    } else {
        var val = testCase.value;
        self.assert.deepEqual(got, val, util.format('read: %j', val));
        if (typeof val === 'object') {
            var gotConsName = got && got.constructor && got.constructor.name;
            var valConsName = val && val.constructor && val.constructor.name;
            self.assert.equal(gotConsName, valConsName,
                'expected ' + valConsName + ' constructor');
        }
    }
};

RWTestCase.prototype.hexdump = function hexdump(desc, err) {
    var self = this;
    var dump = util.format('%s: %s',
        desc, formatError(err, {color: true}));
    self.hexdumpStream.write(dump);
};

function copyErr(err, tmpl) {
    var out = {};
    // istanbul ignore else
    if (err) {
        Object.keys(tmpl).forEach(function(key) {
            out[key] = err[key];
        });
    }
    return out;
}
<commit_msg>TestRW: refactor hexdump -> dumpError<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

'use strict';

var hexdiff = require('hexer/diff');
var util = require('util');
var intoBufferResult = require('./interface').intoBufferResult;
var fromBufferResult = require('./interface').fromBufferResult;
var formatError = require('./interface').formatError;

module.exports.cases = testCases;

function testCases(rw, cases) {
    var self = function runTestCases(assert, done) {
        for (var i = 0; i < cases.length; i++) {
            var testCase;
            if (Array.isArray(cases[i])) {
                var value = cases[i][0];
                var bytes = cases[i][1];
                testCase = {
                    lengthTest: {
                        length: bytes.length,
                        value: value
                    },
                    writeTest: {
                        bytes: bytes,
                        value: value
                    },
                    readTest: {
                        bytes: bytes,
                        value: value
                    }
                };
            } else if (typeof cases[i] !== 'object') {
                throw new Error('invalid test case ' + i);
            } else {
                testCase = cases[i];
            }
            new RWTestCase(assert, rw, testCase).run();
        }
        (done || assert.end)();
    };
    self.assert = null;
    self.rw = null;
    return self;
}

function RWTestCase(assert, rw, testCase) {
    var self = this;
    self.assert = assert;
    self.rw = rw;
    self.testCase = testCase;
    self.hexdumpStream = process.stdout;
}

RWTestCase.prototype.run = function run() {
    var self = this;
    if (self.testCase.lengthTest) self.runLengthTest();
    if (self.testCase.writeTest) self.runWriteTest();
    if (self.testCase.readTest) self.runReadTest();
};

RWTestCase.prototype.runLengthTest = function runLengthTest() {
    var self = this;
    var testCase = self.testCase.lengthTest;
    var val = testCase.value;
    var res = self.rw.byteLength(val);
    if (res.err) {
        if (testCase.error) {
            self.assert.deepEqual(
                copyErr(res.err, testCase.error),
                testCase.error, 'expected length error');
        } else {
            self.assert.ifError(res.err, 'no length error');
        }
    } else if (testCase.error) {
        self.assert.fail('expected length error');
    } else {
        self.assert.deepEqual(res && res.length, testCase.length, util.format('length: %j', val));
    }
};

RWTestCase.prototype.runWriteTest = function runWriteTest() {
    var self = this;
    var testCase = self.testCase.writeTest;
    var val = testCase.value;
    var got = Buffer(testCase.bytes ? testCase.bytes.length : testCase.length || 0);
    got.fill(0);
    var res = intoBufferResult(self.rw, got, val);
    var err = res.error;
    if (err) {
        if (testCase.error) {
            self.assert.deepEqual(
                copyErr(err, testCase.error),
                testCase.error, 'expected write error');
        } else {
            self.assert.ifError(err, 'no write error');
            self.dumpError('write', err);
        }
    } else if (testCase.error) {
        self.assert.fail('expected write error');
    } else {
        var desc = util.format('write: %j', val);
        var buf = Buffer(testCase.bytes);
        // istanbul ignore if
        if (got.toString('hex') !== buf.toString('hex')) {
            self.assert.comment('expected v actual:\n' +
                hexdiff(buf, got, {colored: true}));
            self.assert.fail(desc);
        } else {
            self.assert.pass(desc);
        }
    }
};

RWTestCase.prototype.runReadTest = function runReadTest() {
    var self = this;
    var testCase = self.testCase.readTest;
    var buffer = Buffer(testCase.bytes);
    var res = fromBufferResult(self.rw, buffer);
    var err = res.error;
    var got = res.value;
    if (err) {
        if (testCase.error) {
            self.assert.deepEqual(
                copyErr(err, testCase.error),
                testCase.error, 'expected read error');
        } else {
            // istanbul ignore else
            if (!got && err.buffer) got = err.buffer;
            // istanbul ignore else
            self.assert.ifError(err, 'no read error');
            if (Buffer.isBuffer(got)) self.dumpError('read', err);
        }
    } else if (testCase.error) {
        self.assert.fail('expected read error');
    } else {
        var val = testCase.value;
        self.assert.deepEqual(got, val, util.format('read: %j', val));
        if (typeof val === 'object') {
            var gotConsName = got && got.constructor && got.constructor.name;
            var valConsName = val && val.constructor && val.constructor.name;
            self.assert.equal(gotConsName, valConsName,
                'expected ' + valConsName + ' constructor');
        }
    }
};

RWTestCase.prototype.dumpError = function dumpError(kind, err) {
    var self = this;
    var dump = util.format('%s error: %s',
        kind, formatError(err, {color: true}));
    self.hexdumpStream.write(dump);
};

function copyErr(err, tmpl) {
    var out = {};
    // istanbul ignore else
    if (err) {
        Object.keys(tmpl).forEach(function(key) {
            out[key] = err[key];
        });
    }
    return out;
}
<|endoftext|>


<commit_before>'use strict';

/*
 * AngularJS Toaster
 * Version: 0.4.5
 *
 * Copyright 2013 Jiri Kavulak.
 * All Rights Reserved.
 * Use, reproduction, distribution, and modification of this code is subject to the terms and
 * conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php
 *
 * Author: Jiri Kavulak
 * Related to project of John Papa and Hans Fjällemark
 */

angular.module('toaster', ['ngAnimate'])
.service('toaster', ['$rootScope', function ($rootScope) {
    this.pop = function (type, title, body, timeout, bodyOutputType, id) {
        var toast = {
            type: type,
            title: title,
            body: body,
            timeout: timeout,
            bodyOutputType: bodyOutputType,
            id: id
        };
        $rootScope.$broadcast('toaster-newToast', toast);
    };

    this.clear = function () {
        $rootScope.$broadcast('toaster-clearToasts');
    };
}])
.constant('toasterConfig', {
    'limit': 0,                   // limits max number of toasts
    'tap-to-dismiss': true,
    'newest-on-top': true,
    //'fade-in': 1000,            // done in css
    //'on-fade-in': undefined,    // not implemented
    //'fade-out': 1000,           // done in css
    // 'on-fade-out': undefined,  // not implemented
    //'extended-time-out': 1000,    // not implemented
    'time-out': 5000, // Set timeOut and extendedTimeout to 0 to make it sticky
    'icon-classes': {
        error: 'toast-error',
        info: 'toast-info',
        success: 'toast-success',
        warning: 'toast-warning'
    },
    'body-output-type': '', // Options: '', 'trustedHtml', 'template'
    'body-template': 'toasterBodyTmpl.html',
    'icon-class': 'toast-info',
    'position-class': 'toast-top-right',
    'title-class': 'toast-title',
    'message-class': 'toast-message',
    'default-id-prefix': '__toast-'
})
.directive('toasterContainer', ['$compile', '$timeout', '$sce', 'toasterConfig', 'toaster',
function ($compile, $timeout, $sce, toasterConfig, toaster) {
    return {
        replace: true,
        restrict: 'EA',
        scope: true, // creates an internal scope for this directive
        link: function (scope, elm, attrs) {

            var id = 0,
                mergedConfig;
            scope.toasters = [];

            if (attrs.toasterOptions) {
                mergedConfig = angular.extend({}, toasterConfig, scope.$eval(attrs.toasterOptions));
            }

            scope.config = {
                position: mergedConfig['position-class'],
                title: mergedConfig['title-class'],
                message: mergedConfig['message-class'],
                tap: mergedConfig['tap-to-dismiss']
            };

            scope.configureTimer = function configureTimer(toast) {
                var timeout = typeof (toast.timeout) == "number" ? toast.timeout : mergedConfig['time-out'];
                if (timeout > 0)
                    setTimeout(toast, timeout);
            };

            function addToast(toast) {
                toast.type = mergedConfig['icon-classes'][toast.type];
                if (!toast.type)
                    toast.type = mergedConfig['icon-class'];

                if (toast.id == null) {
                    toast.id = mergedConfig['default-id-prefix'] + id++;
                }

                // Set the toast.bodyOutputType to the default if it isn't set
                toast.bodyOutputType = toast.bodyOutputType || mergedConfig['body-output-type']
                switch (toast.bodyOutputType) {
                    case 'trustedHtml':
                        toast.html = $sce.trustAsHtml(toast.body);
                        break;
                    case 'template':
                        toast.bodyTemplate = toast.body || mergedConfig['body-template'];
                        break;
                }

                scope.configureTimer(toast);

                if (mergedConfig['newest-on-top'] === true) {
                    scope.toasters.unshift(toast);
                    if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) {
                        scope.toasters.pop();
                    }
                } else {
                    scope.toasters.push(toast);
                    if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) {
                        scope.toasters.shift();
                    }
                }
            }

            function setTimeout(toast, time) {
                toast.timeout = $timeout(function () {
                    scope.removeToast(toast.id);
                }, time);
            }

            scope.toasters = [];
            scope.$on('toaster-newToast', function (event, toast) {
                addToast(toast);
            });

            scope.$on('toaster-clearToasts', function () {
                scope.toasters.splice(0, scope.toasters.length);
            });
        },
        controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {

            $scope.stopTimer = function (toast) {
                if (toast.timeout) {
                    $timeout.cancel(toast.timeout);
                    toast.timeout = null;
                }
            };

            $scope.restartTimer = function (toast) {
                if (!toast.timeout)
                    $scope.configureTimer(toast);
            };

            $scope.removeToast = function (id) {
                var i = 0;
                for (i; i < $scope.toasters.length; i++) {
                    if ($scope.toasters[i].id === id)
                        break;
                }
                $scope.toasters.splice(i, 1);
            };

            $scope.remove = function (id) {
                if ($scope.config.tap === true) {
                    $scope.removeToast(id);
                }
            };
        }],
        template:
        '
' +
            '
' +
              '
{{toaster.title}}
' +
              '
' +
                '

' +
                '

' +
                '
{{toaster.body}}
' +
              '
' +
            '
' +
        '
'
    };
}]);
<commit_msg>Rename variable<commit_after>'use strict';

/*
 * AngularJS Toaster
 * Version: 0.4.5
 *
 * Copyright 2013 Jiri Kavulak.
 * All Rights Reserved.
 * Use, reproduction, distribution, and modification of this code is subject to the terms and
 * conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php
 *
 * Author: Jiri Kavulak
 * Related to project of John Papa and Hans Fjällemark
 */

angular.module('toaster', ['ngAnimate'])
.service('toaster', ['$rootScope', function ($rootScope) {
    this.pop = function (type, title, body, timeout, bodyOutputType, id) {
        var toast = {
            type: type,
            title: title,
            body: body,
            timeout: timeout,
            bodyOutputType: bodyOutputType,
            id: id
        };
        $rootScope.$broadcast('toaster-newToast', toast);
    };

    this.clear = function () {
        $rootScope.$broadcast('toaster-clearToasts');
    };
}])
.constant('toasterConfig', {
    'limit': 0,                   // limits max number of toasts
    'tap-to-dismiss': true,
    'newest-on-top': true,
    //'fade-in': 1000,            // done in css
    //'on-fade-in': undefined,    // not implemented
    //'fade-out': 1000,           // done in css
    // 'on-fade-out': undefined,  // not implemented
    //'extended-time-out': 1000,    // not implemented
    'time-out': 5000, // Set timeOut and extendedTimeout to 0 to make it sticky
    'icon-classes': {
        error: 'toast-error',
        info: 'toast-info',
        success: 'toast-success',
        warning: 'toast-warning'
    },
    'body-output-type': '', // Options: '', 'trustedHtml', 'template'
    'body-template': 'toasterBodyTmpl.html',
    'icon-class': 'toast-info',
    'position-class': 'toast-top-right',
    'title-class': 'toast-title',
    'message-class': 'toast-message',
    'default-id-prefix': '__toast-'
})
.directive('toasterContainer', ['$compile', '$timeout', '$sce', 'toasterConfig', 'toaster',
function ($compile, $timeout, $sce, toasterConfig, toaster) {
    return {
        replace: true,
        restrict: 'EA',
        scope: true, // creates an internal scope for this directive
        link: function (scope, elm, attrs) {

            var defaultToastIdCounter = 0,
                mergedConfig;
            scope.toasters = [];

            if (attrs.toasterOptions) {
                mergedConfig = angular.extend({}, toasterConfig, scope.$eval(attrs.toasterOptions));
            }

            scope.config = {
                position: mergedConfig['position-class'],
                title: mergedConfig['title-class'],
                message: mergedConfig['message-class'],
                tap: mergedConfig['tap-to-dismiss']
            };

            scope.configureTimer = function configureTimer(toast) {
                var timeout = typeof (toast.timeout) == "number" ? toast.timeout : mergedConfig['time-out'];
                if (timeout > 0)
                    setTimeout(toast, timeout);
            };

            function addToast(toast) {
                toast.type = mergedConfig['icon-classes'][toast.type];
                if (!toast.type)
                    toast.type = mergedConfig['icon-class'];

                if (toast.id == null) {
                    toast.id = mergedConfig['default-id-prefix'] + defaultToastIdCounter++;
                }

                // Set the toast.bodyOutputType to the default if it isn't set
                toast.bodyOutputType = toast.bodyOutputType || mergedConfig['body-output-type']
                switch (toast.bodyOutputType) {
                    case 'trustedHtml':
                        toast.html = $sce.trustAsHtml(toast.body);
                        break;
                    case 'template':
                        toast.bodyTemplate = toast.body || mergedConfig['body-template'];
                        break;
                }

                scope.configureTimer(toast);

                if (mergedConfig['newest-on-top'] === true) {
                    scope.toasters.unshift(toast);
                    if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) {
                        scope.toasters.pop();
                    }
                } else {
                    scope.toasters.push(toast);
                    if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) {
                        scope.toasters.shift();
                    }
                }
            }

            function setTimeout(toast, time) {
                toast.timeout = $timeout(function () {
                    scope.removeToast(toast.id);
                }, time);
            }

            scope.toasters = [];
            scope.$on('toaster-newToast', function (event, toast) {
                addToast(toast);
            });

            scope.$on('toaster-clearToasts', function () {
                scope.toasters.splice(0, scope.toasters.length);
            });
        },
        controller: ['$scope', '$element', '$attrs', function ($scope, $element, $attrs) {

            $scope.stopTimer = function (toast) {
                if (toast.timeout) {
                    $timeout.cancel(toast.timeout);
                    toast.timeout = null;
                }
            };

            $scope.restartTimer = function (toast) {
                if (!toast.timeout)
                    $scope.configureTimer(toast);
            };

            $scope.removeToast = function (id) {
                var i = 0;
                for (i; i < $scope.toasters.length; i++) {
                    if ($scope.toasters[i].id === id)
                        break;
                }
                $scope.toasters.splice(i, 1);
            };

            $scope.remove = function (id) {
                if ($scope.config.tap === true) {
                    $scope.removeToast(id);
                }
            };
        }],
        template:
        '
' +
            '
' +
              '
{{toaster.title}}
' +
              '
' +
                '

' +
                '

' +
                '
{{toaster.body}}
' +
              '
' +
            '
' +
        '
'
    };
}]);
<|endoftext|>


<commit_before>var $ = require('interlude');
var Tournament = require('tournament');
var helper = Tournament.helpers;

function Id(t, id) {
  $.extend(this, id); // Tournament style { s, r, m }
  this.t = t; // do after extend to override if `id.t` exists
}

Id.prototype.toString = function () {
  return "T" + this.t + " S" + this.s + " R" + this.r + " M" + this.m;
};

//------------------------------------------------------------------
// Setup and statics
//------------------------------------------------------------------

function Tourney(inst) {
  this._inst = inst;
  this.matches = inst.matches; // reference to above to match Tournament API
  this.oldMatches = []; // stash matches from completed instances here
  this.stage = 1;
  // for determining when we can expect Tourney API
  Object.defineProperty(this, 'hasStages', { value: true });
}

Tourney.inherit = function (Klass, Initial) {
  Initial = Initial || Tourney;
  Klass.prototype = Object.create(Initial.prototype);

  var methods = {
    _createNext: false,
    _mustPropagate: false
  };
  Object.keys(methods).forEach(function (fn) {
    // Implement a default if not already implemented (when Initial is Tourney)
    Klass.prototype[fn] = Initial.prototype[fn] || $.constant(methods[fn]);
  });

  Klass.configure = function (obj) {
    // Preserve Tournament API for invalid and defaults
    return Tournament.configure(Klass, obj, Initial);
  };

  // ignore inherited `sub`, `inherit`, and `from` for now for sanity
};

Tourney.sub = function (name, init, Initial) {
  // Preserve Tournament API. This ultimately calls (Initial || Tourney).inherit
  Tournament.sub(name, init, Initial || Tourney);
};

// TODO: Tourney.from should be almost identical to Tournament's
// but it cannot replaceMatches
// so that part either needs to be virtual
// or Klass.from is configured manually s.t.:
//  - Klass.from(inst, np, opts)
//  - -> var firstInst = FirstKlass.from(inst, np, subSetOfOpts);
//  - return new Klass(firstInst); // special ctor?

//------------------------------------------------------------------
// Helpers for piping modules together
//------------------------------------------------------------------

Tourney.prototype.stageDone = function () {
  return this._inst[this._inst.hasStages ? 'stageDone' : 'isDone']();
};

Tourney.prototype.isDone = function () {
  // self-referential isDone for Tourney's (checking if subTourneys are done)
  // but this eventually ends in a Tournament::isDone()
  return this._inst.isDone() && !this._mustPropagate();
};

var formatCurrent = function (stage, ms) {
  // prepare matches from a completed instance for oldMatches
  // NB: if `ms` come from a Tourney, the stage `t` key will be overridden
  // and will use the counter relative to this Tourney
  return ms.map(function (stage, m) {
    var o = { id: new Id(stage, m.id), p: m.p.slice() };
    if (m.m) {
      o.m = m.m.slice();
    }
    return o;
  });
};

Tourney.prototype.createNextStage = function () {
  if (!this.stageDone()) {
    throw new Error("cannot start next stage until current one is done");
  }

  // extend current matches' ids with `t` = this.stage (overwriting if necessary)
  var completedMatches = formatCurrent(this.stage, this.matches);
  Array.prototype.push.apply(this.oldMatches, completedMatches);

  if (this.isDone()) {
    this.matches = []; // ensure no double copies into oldMatches
    return false;
  }

  // _createNext cannot fail now - if it does implementation's fault
  this._inst = this._createNext(this.stage + 1);
  this.matches = this._inst.matches;
  this.stage += 1; // update after _createNext in case stage identifiers use counter
  return true;
};

//------------------------------------------------------------------
// Stuff dealing with current matches
//------------------------------------------------------------------
Tourney.prototype.unscorable = function (id, score, allowPast) {
  return this._inst.unscorable(id, score, allowPast);
};

Tourney.prototype.score = function (id, score) {
  return this._inst.score(id, score);
};

Tourney.prototype.upcoming = function (playerId) {
  // no upcoming in oldMatches so just look in active
  // TODO: this is end user stuff though.. maybe extend with Id?
  return helper.upcoming(this.matches, playerId);
};

//------------------------------------------------------------------
// Match finders - looks at union of active and inactive
//
// These are purely convenience methods for end user.
// Tourney & implementations end up using the ones on this._inst
//------------------------------------------------------------------

Tourney.prototype.findMatch = function (id) {
  return helper.findMatch(this.union(), id);
};
Tourney.prototype.findMatches = function (id) {
  return helper.findMatches(this.union(), id);
};

Tourney.prototype.rounds = function (stage) {
  return helper.partitionMatches(this.union(), 'r', 't', stage);
};

Tourney.prototype.section = function (stage) {
  return helper.partitionMatches(this.union(), 's', 't', stage);
};

Tourney.prototype.stages = function (section) {
  return helper.partitionMatches(this.union(), 't', 's', section);
};

Tourney.prototype.matchesFor = function (playerId) {
  return helper.matchesForPlayer(this.union(), playerId);
};
Tourney.prototype.players = function (id) {
  return helper.players(this.findMatches(id || {}));
};

//------------------------------------------------------------------
// Results - Not finialized
//------------------------------------------------------------------

var resultEntry = function (res, p) {
  return $.firstBy(function (r) {
    return r.seed === p;
  }, res);
};

Tourney.prototype.results = function () {
  // TODO: this.current no longer exposed to tourney, but need results..
  var currRes = this.current.results();
  // _oldRes maintained as results from previous stage(s)
  var knockedOutResults = this._oldRes.filter(function (r) {
    // players not in current stage exist in previous results below
    return !resultEntry(currRes, r.seed);
  });

  return currRes.concat(knockedOutResults);
};

module.exports = Tourney;
<commit_msg>since we use Tournament.sub we have to get numPlayers injected too<commit_after>var $ = require('interlude');
var Tournament = require('tournament');
var helper = Tournament.helpers;

function Id(t, id) {
  $.extend(this, id); // Tournament style { s, r, m }
  this.t = t; // do after extend to override if `id.t` exists
}

Id.prototype.toString = function () {
  return "T" + this.t + " S" + this.s + " R" + this.r + " M" + this.m;
};

//------------------------------------------------------------------
// Setup and statics
//------------------------------------------------------------------

function Tourney(np, inst) {
  this._inst = inst;
  this.matches = inst.matches; // reference to above to match Tournament API
  this.oldMatches = []; // stash matches from completed instances here
  this.stage = 1;
  // for determining when we can expect Tourney API
  Object.defineProperty(this, 'hasStages', { value: true });
}

Tourney.inherit = function (Klass, Initial) {
  Initial = Initial || Tourney;
  Klass.prototype = Object.create(Initial.prototype);

  var methods = {
    _createNext: false,
    _mustPropagate: false
  };
  Object.keys(methods).forEach(function (fn) {
    // Implement a default if not already implemented (when Initial is Tourney)
    Klass.prototype[fn] = Initial.prototype[fn] || $.constant(methods[fn]);
  });

  Klass.configure = function (obj) {
    // Preserve Tournament API for invalid and defaults
    return Tournament.configure(Klass, obj, Initial);
  };

  // ignore inherited `sub`, `inherit`, and `from` for now for sanity
};

Tourney.sub = function (name, init, Initial) {
  // Preserve Tournament API. This ultimately calls (Initial || Tourney).inherit
  Tournament.sub(name, init, Initial || Tourney);
};

// TODO: Tourney.from should be almost identical to Tournament's
// but it cannot replaceMatches
// so that part either needs to be virtual
// or Klass.from is configured manually s.t.:
//  - Klass.from(inst, np, opts)
//  - -> var firstInst = FirstKlass.from(inst, np, subSetOfOpts);
//  - return new Klass(firstInst); // special ctor?

//------------------------------------------------------------------
// Helpers for piping modules together
//------------------------------------------------------------------

Tourney.prototype.stageDone = function () {
  return this._inst[this._inst.hasStages ? 'stageDone' : 'isDone']();
};

Tourney.prototype.isDone = function () {
  // self-referential isDone for Tourney's (checking if subTourneys are done)
  // but this eventually ends in a Tournament::isDone()
  return this._inst.isDone() && !this._mustPropagate();
};

var formatCurrent = function (stage, ms) {
  // prepare matches from a completed instance for oldMatches
  // NB: if `ms` come from a Tourney, the stage `t` key will be overridden
  // and will use the counter relative to this Tourney
  return ms.map(function (stage, m) {
    var o = { id: new Id(stage, m.id), p: m.p.slice() };
    if (m.m) {
      o.m = m.m.slice();
    }
    return o;
  });
};

Tourney.prototype.createNextStage = function () {
  if (!this.stageDone()) {
    throw new Error("cannot start next stage until current one is done");
  }

  // extend current matches' ids with `t` = this.stage (overwriting if necessary)
  var completedMatches = formatCurrent(this.stage, this.matches);
  Array.prototype.push.apply(this.oldMatches, completedMatches);

  if (this.isDone()) {
    this.matches = []; // ensure no double copies into oldMatches
    return false;
  }

  // _createNext cannot fail now - if it does implementation's fault
  this._inst = this._createNext(this.stage + 1);
  this.matches = this._inst.matches;
  this.stage += 1; // update after _createNext in case stage identifiers use counter
  return true;
};

//------------------------------------------------------------------
// Stuff dealing with current matches
//------------------------------------------------------------------
Tourney.prototype.unscorable = function (id, score, allowPast) {
  return this._inst.unscorable(id, score, allowPast);
};

Tourney.prototype.score = function (id, score) {
  return this._inst.score(id, score);
};

Tourney.prototype.upcoming = function (playerId) {
  // no upcoming in oldMatches so just look in active
  // TODO: this is end user stuff though.. maybe extend with Id?
  return helper.upcoming(this.matches, playerId);
};

//------------------------------------------------------------------
// Match finders - looks at union of active and inactive
//
// These are purely convenience methods for end user.
// Tourney & implementations end up using the ones on this._inst
//------------------------------------------------------------------

Tourney.prototype.findMatch = function (id) {
  return helper.findMatch(this.union(), id);
};
Tourney.prototype.findMatches = function (id) {
  return helper.findMatches(this.union(), id);
};

Tourney.prototype.rounds = function (stage) {
  return helper.partitionMatches(this.union(), 'r', 't', stage);
};

Tourney.prototype.section = function (stage) {
  return helper.partitionMatches(this.union(), 's', 't', stage);
};

Tourney.prototype.stages = function (section) {
  return helper.partitionMatches(this.union(), 't', 's', section);
};

Tourney.prototype.matchesFor = function (playerId) {
  return helper.matchesForPlayer(this.union(), playerId);
};
Tourney.prototype.players = function (id) {
  return helper.players(this.findMatches(id || {}));
};

//------------------------------------------------------------------
// Results - Not finialized
//------------------------------------------------------------------

var resultEntry = function (res, p) {
  return $.firstBy(function (r) {
    return r.seed === p;
  }, res);
};

Tourney.prototype.results = function () {
  // TODO: this.current no longer exposed to tourney, but need results..
  var currRes = this.current.results();
  // _oldRes maintained as results from previous stage(s)
  var knockedOutResults = this._oldRes.filter(function (r) {
    // players not in current stage exist in previous results below
    return !resultEntry(currRes, r.seed);
  });

  return currRes.concat(knockedOutResults);
};

module.exports = Tourney;
<|endoftext|>


<commit_before>var TestRPC = require('ethereumjs-testrpc');

module.exports = {
  networks: {
    test: {
      provider: TestRPC.provider(), // in-memory TestRPC provider
      network_id: "*" // Match any network id
    },
    development: {
      host: "localhost",
      port: 8545,
      network_id: "*" // Match any network id
    },
    rinkeby: {
      host: '127.0.0.1',
      port: 8545,
      network_id: 4,
      gasPrice: "20000000000", // 20 gwei
    },
    live: {
      host: "127.0.0.1",
      port: 8545,
      network_id: "1", // Only mainnet
      gasPrice: "10000000000", // 10 gwei
      gas: "5000000", // 0.02 eth at 4 gwei price
    },
  }
};
<commit_msg>truffle.js: RIP<commit_after><|endoftext|>


<commit_before>var fs = require("fs");
var path = require("path");

var FILE_PATHS = {
    GPIO_ROOT: "/sys/class/gpio",
    ACCELEROMETER_ROOT: "/sys/class/misc/FreescaleAccelerometer",
    MAGNETOMETER_ROOT: "/sys/class/misc/FreescaleMagnetometer",
    GYROSCOPE_ROOT: "/sys/class/misc/FreescaleGyroscope",
    EXPORT_FILE: "export",
    UNEXPORT_FILE: "unexport"
};
var GPIOReference = {

    gpioNumbers: [
        106, 107, 180, 181, 172, 173, 182, 124,
        25, 22, 14, 15, 16, 17, 18, 19,
        20, 21, 203, 202, 177, 176, 175, 174,
        119, 124, 127, 116, 7, 6, 5, 4
    ],

    DIRECTION: {
        INPUT: "in",
        OUTPUT: "out"
    },
    VALUE: {
        HIGH: "1",
        LOW: "0"
    },

    fromPin: function (pinNumber) {
        if (16 > pinNumber || pinNumber > 47) throw new Error("Invalid pin number.");
        return GPIOReference.gpioNumbers[pinNumber - 16];
    },
    isValid: function (gpioNumber) {
        return GPIOReference.gpioNumbers.indexOf(gpioNumber) > -1;
    }

};

function GPIO(num) {
    if (num) {
        this.fromGpio(num);
    }
}

GPIO.prototype = {

    currentGpioNumber: null,
    currentGPIO: function () {
        if (!this.currentGpioNumber) throw new Error("Missing GPIO number.");
        return this.currentGpioNumber;
    },

    fromPin: function (num) {
        this.currentGpioNumber = GPIOReference.fromPin(num);
        return this;
    },
    fromGpio: function (gpioNumber) {
        if (!GPIOReference.isValid(gpioNumber)) throw new Error("GPIO number (" + gpioNumber + ") is out of range.");
        this.currentGpioNumber = gpioNumber;
        return this;
    },

    export: function (callback) {
        var currentNum = this.currentGPIO();
        var exportFilePath = FILE_PATHS.GPIO_ROOT + path.sep + FILE_PATHS.EXPORT_FILE;
        File.exists(FILE_PATHS.GPIO_ROOT + path.sep + "gpio" + currentNum,
            function () {
                // already exported
                if (callback) callback();
            },
            function () {
                File.write(currentNum.toString(), exportFilePath, function () {
                    if (callback) callback();
                });
            }
        );

    },
    unexport: function (callback) {
        var currentNum = this.currentGPIO();
        var exportFilePath = FILE_PATHS.GPIO_ROOT + path.sep + FILE_PATHS.UNEXPORT_FILE;
        File.exists(FILE_PATHS.GPIO_ROOT + path.sep + "gpio" + currentNum,
            function () {
                File.write(currentNum.toString(), exportFilePath, function () {
                    if (callback) callback();
                });
            },
            function () {
                // already unexported
                if (callback) callback();
            }
        );
    },

    setDirection: function (direction, callback) {
        if ([GPIOReference.DIRECTION.INPUT, GPIOReference.DIRECTION.OUTPUT].indexOf(direction) < 0) throw new Error("Invalid direction.");
        var currentGPIO = this.currentGPIO();
        this.export(function () {
            File.createDir(FILE_PATHS.GPIO_ROOT + path.sep + "gpio" + currentGPIO, function () {
                var directionPath = FILE_PATHS.GPIO_ROOT + path.sep + "gpio" + currentGPIO + path.sep + "direction";
                File.write(direction, directionPath, function () {
                    if (callback) callback();
                });
            });
        });
    },
    getDirection: function (callback) {
        var currentNum = this.currentGPIO();
        this.export(function () {
            var directionPath = FILE_PATHS.GPIO_ROOT + path.sep + "gpio" + currentNum + path.sep + "direction";
            File.read(directionPath, function (data) {
                callback(data);
            });
        });
    },
    setValue: function (value, callback) {
        if ([GPIOReference.VALUE.HIGH, GPIOReference.VALUE.LOW].indexOf(value) < 0) throw new Error("Invalid value.");
        var currentNum = this.currentGPIO();
        this.export(function () {
            File.createDir(FILE_PATHS.GPIO_ROOT + path.sep + "gpio" + currentNum, function () {
                var valuePath = FILE_PATHS.GPIO_ROOT + path.sep + "gpio" + currentNum + path.sep + "value";
                File.write(value.toString(), valuePath, function () {
                    if (callback) callback();
                });
            });
        });
    },
    getValue: function (callback) {
        var currentNum = this.currentGPIO();
        var valuePath = FILE_PATHS.GPIO_ROOT + path.sep + "gpio" + currentNum + path.sep + "value";
        this.export(function () {
            File.read(valuePath, function (data) {
                callback(data);
            });
        });
    },
    watchValue: function (callback) {
        var currentNum = this.currentGPIO();
        var valuePath = FILE_PATHS.GPIO_ROOT + path.sep + "gpio" + currentNum + path.sep + "value";
        var instance = this;
        File.exists(valuePath,
            function () {
                File.watch(valuePath, function () {
                    callback();
                });
            },
            function () {
                instance.export(function () {
                    File.watch(valuePath, function () {
                        callback();
                    });
                });
            }
        )

    }
};

function MotionSensor(path) {
    this.path = path;
}
MotionSensor.prototype = {
    enable: function (callback) {
        var filePath = this.path + path.sep + "enable";
        var value = 1;
        File.write(value.toString(), filePath, function () {
            if (callback) callback();
        });
    },
    disable: function (callback) {
        var filePath = this.path + path.sep + "disable";
        var value = 0;
        File.write(value.toString(), filePath, function () {
            if (callback) callback();
        });
    },
    getData: function (callback) {
        var filePath = this.path + path.sep + "data";
        File.read(filePath, function (data) {
            callback(data);
        });
    }
};

var File = {
    createDir: function (path, callback) {
        fs.mkdir(path, function () {
            callback();
        })
    },
    exists: function (path, success, failure) {
        fs.access(path, function (err) {
            if (!err) success(); else failure();
        });
    },
    read: function (filePath, callback) {
        fs.readFile(filePath, "utf-8", function (err, data) {
            if (err) throw err;
            callback(data);
        });
    },
    watch: function (filePath, callback) {
        fs.watch(filePath, function (event) {
            if ("change" === event) callback();
        });
    },
    write: function (data, filePath, callback) {
        // console.log("trying to write " + data + " in " + filePath);
        try {
            var fd = fs.openSync(filePath, "w", function (err) {
                if (err) {
                    console.log("Could not write " + data + " in " + filePath);
                    throw err;
                }
            });
            fs.writeSync(fd, data, "utf-8");
        } catch (err) {
            if ("EBUSY" === err.errno) {
                this.write(data, filePath, callback);
            }
        }
        callback();
    }
};

module.exports = {
    gpioNumbers: GPIOReference.gpioNumbers,
    DIRECTION: GPIOReference.DIRECTION,
    VALUE: GPIOReference.VALUE,
    GPIO: GPIO,
    Accelerometer: new MotionSensor(FILE_PATHS.ACCELEROMETER_ROOT),
    Magnetometer: new MotionSensor(FILE_PATHS.MAGNETOMETER_ROOT),
    Gyroscope: new MotionSensor(FILE_PATHS.GYROSCOPE_ROOT)
};<commit_msg>Adds watch method<commit_after>var fs = require("fs");
var path = require("path");

var FILE_PATHS = {
    GPIO_ROOT: "/sys/class/gpio",
    ACCELEROMETER_ROOT: "/sys/class/misc/FreescaleAccelerometer",
    MAGNETOMETER_ROOT: "/sys/class/misc/FreescaleMagnetometer",
    GYROSCOPE_ROOT: "/sys/class/misc/FreescaleGyroscope",
    EXPORT_FILE: "export",
    UNEXPORT_FILE: "unexport"
};
var GPIOReference = {

    gpioNumbers: [
        106, 107, 180, 181, 172, 173, 182, 124,
        25, 22, 14, 15, 16, 17, 18, 19,
        20, 21, 203, 202, 177, 176, 175, 174,
        119, 124, 127, 116, 7, 6, 5, 4
    ],

    DIRECTION: {
        INPUT: "in",
        OUTPUT: "out"
    },
    VALUE: {
        HIGH: "1",
        LOW: "0"
    },

    fromPin: function (pinNumber) {
        if (16 > pinNumber || pinNumber > 47) throw new Error("Invalid pin number.");
        return GPIOReference.gpioNumbers[pinNumber - 16];
    },
    isValid: function (gpioNumber) {
        return GPIOReference.gpioNumbers.indexOf(gpioNumber) > -1;
    }

};

function GPIO(num) {
    if (num) {
        this.fromGpio(num);
    }
}

GPIO.prototype = {

    currentGpioNumber: null,
    currentGPIO: function () {
        if (!this.currentGpioNumber) throw new Error("Missing GPIO number.");
        return this.currentGpioNumber;
    },

    fromPin: function (num) {
        this.currentGpioNumber = GPIOReference.fromPin(num);
        return this;
    },
    fromGpio: function (gpioNumber) {
        if (!GPIOReference.isValid(gpioNumber)) throw new Error("GPIO number (" + gpioNumber + ") is out of range.");
        this.currentGpioNumber = gpioNumber;
        return this;
    },

    export: function (callback) {
        var currentNum = this.currentGPIO();
        var exportFilePath = FILE_PATHS.GPIO_ROOT + path.sep + FILE_PATHS.EXPORT_FILE;
        File.exists(FILE_PATHS.GPIO_ROOT + path.sep + "gpio" + currentNum,
            function () {
                // already exported
                if (callback) callback();
            },
            function () {
                File.write(currentNum.toString(), exportFilePath, function () {
                    if (callback) callback();
                });
            }
        );

    },
    unexport: function (callback) {
        var currentNum = this.currentGPIO();
        var exportFilePath = FILE_PATHS.GPIO_ROOT + path.sep + FILE_PATHS.UNEXPORT_FILE;
        File.exists(FILE_PATHS.GPIO_ROOT + path.sep + "gpio" + currentNum,
            function () {
                File.write(currentNum.toString(), exportFilePath, function () {
                    if (callback) callback();
                });
            },
            function () {
                // already unexported
                if (callback) callback();
            }
        );
    },

    setDirection: function (direction, callback) {
        if ([GPIOReference.DIRECTION.INPUT, GPIOReference.DIRECTION.OUTPUT].indexOf(direction) < 0) throw new Error("Invalid direction.");
        var currentGPIO = this.currentGPIO();
        this.export(function () {
            File.createDir(FILE_PATHS.GPIO_ROOT + path.sep + "gpio" + currentGPIO, function () {
                var directionPath = FILE_PATHS.GPIO_ROOT + path.sep + "gpio" + currentGPIO + path.sep + "direction";
                File.write(direction, directionPath, function () {
                    if (callback) callback();
                });
            });
        });
    },
    getDirection: function (callback) {
        var currentNum = this.currentGPIO();
        this.export(function () {
            var directionPath = FILE_PATHS.GPIO_ROOT + path.sep + "gpio" + currentNum + path.sep + "direction";
            File.read(directionPath, function (data) {
                callback(data);
            });
        });
    },
    setValue: function (value, callback) {
        if ([GPIOReference.VALUE.HIGH, GPIOReference.VALUE.LOW].indexOf(value) < 0) throw new Error("Invalid value.");
        var currentNum = this.currentGPIO();
        this.export(function () {
            File.createDir(FILE_PATHS.GPIO_ROOT + path.sep + "gpio" + currentNum, function () {
                var valuePath = FILE_PATHS.GPIO_ROOT + path.sep + "gpio" + currentNum + path.sep + "value";
                File.write(value.toString(), valuePath, function () {
                    if (callback) callback();
                });
            });
        });
    },
    getValue: function (callback) {
        var currentNum = this.currentGPIO();
        var valuePath = FILE_PATHS.GPIO_ROOT + path.sep + "gpio" + currentNum + path.sep + "value";
        this.export(function () {
            File.read(valuePath, function (data) {
                callback(data);
            });
        });
    },
    watchValue: function (callback) {
        var currentNum = this.currentGPIO();
        var valuePath = FILE_PATHS.GPIO_ROOT + path.sep + "gpio" + currentNum + path.sep + "value";
        var instance = this;
        File.exists(valuePath,
            function () {
                File.watch(valuePath, function () {
                    callback();
                });
            },
            function () {
                instance.export(function () {
                    File.watch(valuePath, function () {
                        callback();
                    });
                });
            }
        )

    }
};

function MotionSensor(path) {
    this.path = path;
}
MotionSensor.prototype = {
    enable: function (callback) {
        var filePath = this.path + path.sep + "enable";
        var value = 1;
        File.write(value.toString(), filePath, function () {
            if (callback) callback();
        });
    },
    disable: function (callback) {
        var filePath = this.path + path.sep + "disable";
        var value = 0;
        File.write(value.toString(), filePath, function () {
            if (callback) callback();
        });
    },
    getData: function (callback) {
        var filePath = this.path + path.sep + "data";
        File.read(filePath, function (data) {
            callback(data);
        });
    },
    watchData: function (callback) {
        var filePath = this.path + path.sep + "data";
        File.watch(filePath, function () {
            File.read(filePath, function (data) {
                callback(data);
            });
        });
    }
};

var File = {
    createDir: function (path, callback) {
        fs.mkdir(path, function () {
            callback();
        })
    },
    exists: function (path, success, failure) {
        fs.access(path, function (err) {
            if (!err) success(); else failure();
        });
    },
    read: function (filePath, callback) {
        fs.readFile(filePath, "utf-8", function (err, data) {
            if (err) throw err;
            callback(data);
        });
    },
    watch: function (filePath, callback) {
        fs.watch(filePath, function (event) {
            if ("change" === event) callback();
        });
    },
    write: function (data, filePath, callback) {
        // console.log("trying to write " + data + " in " + filePath);
        try {
            var fd = fs.openSync(filePath, "w", function (err) {
                if (err) {
                    console.log("Could not write " + data + " in " + filePath);
                    throw err;
                }
            });
            fs.writeSync(fd, data, "utf-8");
        } catch (err) {
            if ("EBUSY" === err.errno) {
                this.write(data, filePath, callback);
            }
        }
        callback();
    }
};

module.exports = {
    gpioNumbers: GPIOReference.gpioNumbers,
    DIRECTION: GPIOReference.DIRECTION,
    VALUE: GPIOReference.VALUE,
    GPIO: GPIO,
    Accelerometer: new MotionSensor(FILE_PATHS.ACCELEROMETER_ROOT),
    Magnetometer: new MotionSensor(FILE_PATHS.MAGNETOMETER_ROOT),
    Gyroscope: new MotionSensor(FILE_PATHS.GYROSCOPE_ROOT)
};<|endoftext|>


<commit_before>process.env.BABEL_ENV = 'test';

module.exports = (wallaby) => {
  console.log(wallaby);
  return {
    files: ['src/**/*.js', 'test/helpers/*.js', 'package.json'],
    tests: ['test/**/*.test.js'],

    env: {
      type: 'node',
      runner: 'node',
    },

    compilers: {
      '**/*.js': wallaby.compilers.babel(require('./package.json').babel), // eslint-disable-line global-require
    },

    testFramework: 'jest',

    setup() {
      const jestConfig = require('./package.json').jest; // eslint-disable-line global-require
      wallaby.testFramework.configure(jestConfig);
    },
  };
};
<commit_msg>fix: remove console log<commit_after>process.env.BABEL_ENV = 'test';

module.exports = (wallaby) => {
  return {
    files: ['src/**/*.js', 'test/helpers/*.js', 'package.json'],
    tests: ['test/**/*.test.js'],

    env: {
      type: 'node',
      runner: 'node',
    },

    compilers: {
      '**/*.js': wallaby.compilers.babel(require('./package.json').babel), // eslint-disable-line global-require
    },

    testFramework: 'jest',

    setup() {
      const jestConfig = require('./package.json').jest; // eslint-disable-line global-require
      wallaby.testFramework.configure(jestConfig);
    },
  };
};
<|endoftext|>