<commit_before>var postcss = require('postcss');
var expect  = require('chai').expect;

var vars = require('../');

var test = function (input, output, opts) {
    expect(postcss(vars(opts)).process(input).css).to.eql(output);
};

describe('postcss-simple-vars', function () {

    it('replaces variables in values', function () {
        test('$size: 10px;\na{ width: $size; height: $size }',
             'a{ width: 10px; height: 10px }');
    });

    it('allows dashes and digits in variable name', function () {
        test('$a-b_10: 1;\na{ one: $a-b_10 a$(a-b_10) }', 'a{ one: 1 a1 }');
    });

    it('needs space before variable', function () {
        test('$size: 10px; a { width: one$size }', 'a { width: one$size }');
    });

    it('does not remove first symbol', function () {
        test('a{ a: 1 $a }', 'a{ a: 1 1 }', { variables: { a: 1 } });
    });

    it('allows to use in negative numbers', function () {
        test('a{ a: -$a }', 'a{ a: -1 }', { variables: { a: 1 } });
    });

    it('replaces multiple variables', function () {
        test('a{ a: $a $a }', 'a{ a: 1 1 }', { variables: { a: 1 } });
    });

    it('has second syntax for varibles', function () {
        test('$size: 10; a { width: $(size)px }', 'a { width: 10px }');
    });

    it('replaces variables in selector', function () {
        test('$name: a; $name $(name)b { }', 'a ab { }');
    });

    it('replaces variables in at-rule params', function () {
        test('$name: a; @at $name; @at $(name)b { }', '@at a; @at ab { }');
    });

    it('parses at-rule without params', function () {
        test('@atrule{}', '@atrule{}');
    });

    it('overrides variables', function () {
        test('$var: 1; a{ one: $var } b{ $var: 2; two: $var } c{ two: $var }',
             'a{ one: 1 } b{ two: 2 } c{ two: 2 }');
    });

    it('throws an error on unknown variable', function () {
        expect(function () {
            test('a{ width: -$size }');
        }).to.throw('<css input>:1:4: Undefined variable $size');
    });

    it('allows to silent errors', function () {
        test('a{ width: $size }', 'a{ width: $size }', { silent: true });
    });

    it('gets variables from options', function () {
        test('a{ width: $one }', 'a{ width: 1 }', { variables: { one: 1 } });
    });

    it('cans get variables only from option', function () {
        test('$one: 2; $two: 2; a{ one: $one $two }',
             '$one: 2; $two: 2; a{ one: 1 $two }',
             { only: { one: 1 } });
    });

    it('works with false value', function () {
        test('a{ zero: $zero }', 'a{ zero: 0 }', { variables: { zero: 0 } });
    });

    it('allows to use var in other vars', function () {
        test('$one: 1; $two: $one 2; a{ value: $two }', 'a{ value: 1 2 }');
    })

});
<commit_msg>Fix ESLint warning<commit_after>var postcss = require('postcss');
var expect  = require('chai').expect;

var vars = require('../');

var test = function (input, output, opts) {
    expect(postcss(vars(opts)).process(input).css).to.eql(output);
};

describe('postcss-simple-vars', function () {

    it('replaces variables in values', function () {
        test('$size: 10px;\na{ width: $size; height: $size }',
             'a{ width: 10px; height: 10px }');
    });

    it('allows dashes and digits in variable name', function () {
        test('$a-b_10: 1;\na{ one: $a-b_10 a$(a-b_10) }', 'a{ one: 1 a1 }');
    });

    it('needs space before variable', function () {
        test('$size: 10px; a { width: one$size }', 'a { width: one$size }');
    });

    it('does not remove first symbol', function () {
        test('a{ a: 1 $a }', 'a{ a: 1 1 }', { variables: { a: 1 } });
    });

    it('allows to use in negative numbers', function () {
        test('a{ a: -$a }', 'a{ a: -1 }', { variables: { a: 1 } });
    });

    it('replaces multiple variables', function () {
        test('a{ a: $a $a }', 'a{ a: 1 1 }', { variables: { a: 1 } });
    });

    it('has second syntax for varibles', function () {
        test('$size: 10; a { width: $(size)px }', 'a { width: 10px }');
    });

    it('replaces variables in selector', function () {
        test('$name: a; $name $(name)b { }', 'a ab { }');
    });

    it('replaces variables in at-rule params', function () {
        test('$name: a; @at $name; @at $(name)b { }', '@at a; @at ab { }');
    });

    it('parses at-rule without params', function () {
        test('@atrule{}', '@atrule{}');
    });

    it('overrides variables', function () {
        test('$var: 1; a{ one: $var } b{ $var: 2; two: $var } c{ two: $var }',
             'a{ one: 1 } b{ two: 2 } c{ two: 2 }');
    });

    it('throws an error on unknown variable', function () {
        expect(function () {
            test('a{ width: -$size }');
        }).to.throw('<css input>:1:4: Undefined variable $size');
    });

    it('allows to silent errors', function () {
        test('a{ width: $size }', 'a{ width: $size }', { silent: true });
    });

    it('gets variables from options', function () {
        test('a{ width: $one }', 'a{ width: 1 }', { variables: { one: 1 } });
    });

    it('cans get variables only from option', function () {
        test('$one: 2; $two: 2; a{ one: $one $two }',
             '$one: 2; $two: 2; a{ one: 1 $two }',
             { only: { one: 1 } });
    });

    it('works with false value', function () {
        test('a{ zero: $zero }', 'a{ zero: 0 }', { variables: { zero: 0 } });
    });

    it('allows to use var in other vars', function () {
        test('$one: 1; $two: $one 2; a{ value: $two }', 'a{ value: 1 2 }');
    });

});
<|endoftext|>


<commit_before>var debug = require('debug')('rose');
var mongoose = require('mongoose');

var mongoURI = process.env.MONGOLAB_URI || 'mongodb://localhost/mydb';
debug('Connecting to MongoDB at ' + mongoURI + '...');
mongoose.connect(mongoURI);

var featureSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  examples: {
    type: [{
      technology: { type: String, required: true },
      snippets: { type: [String], required: true }
    }],
    required: true
  }
});

featureSchema.statics.search = function (query) {
  return this.find({ $or: [
                     { name: new RegExp(query, 'i') },
                     { examples: { $elemMatch: {
                       $or: [
                         { technology: new RegExp(query, 'i') },
                         { snippets: new RegExp(query, 'i') }
                       ]
                     }}},
                  ]})
             .lean()
             .select('-__v -_id -examples._id')
             .exec();
};

module.exports = mongoose.model('Feature', featureSchema);
<commit_msg>Rename the DB from mydb to rose<commit_after>var debug = require('debug')('rose');
var mongoose = require('mongoose');

var mongoURI = process.env.MONGOLAB_URI || 'mongodb://localhost/rose';
debug('Connecting to MongoDB at ' + mongoURI + '...');
mongoose.connect(mongoURI);

var featureSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  examples: {
    type: [{
      technology: { type: String, required: true },
      snippets: { type: [String], required: true }
    }],
    required: true
  }
});

featureSchema.statics.search = function (query) {
  return this.find({ $or: [
                     { name: new RegExp(query, 'i') },
                     { examples: { $elemMatch: {
                       $or: [
                         { technology: new RegExp(query, 'i') },
                         { snippets: new RegExp(query, 'i') }
                       ]
                     }}},
                  ]})
             .lean()
             .select('-__v -_id -examples._id')
             .exec();
};

module.exports = mongoose.model('Feature', featureSchema);
<|endoftext|>


<commit_before>var average = require('./')
var test = require('tape')
var polygon = require('turf-polygon')
var point = require('turf-point')
var featurecollection =  require('turf-featurecollection')

test('average', function(t){
  var poly1 = polygon([[[0,0],[10,0],[10,10], [0,10]]])
  var poly2 = polygon([[[10,0],[20,10],[20,20], [20,0]]])
  var polyFC = featurecollection([poly1, poly2])
  var pt1 = point(1,1, {population: 500})
  var pt2 = point(1,3, {population: 400})
  var pt3 = point(14,2, {population: 600})
  var pt4 = point(13,1, {population: 500})
  var pt5 = point(19,7, {population: 200})
  var ptFC = featurecollection([pt1, pt2, pt3, pt4, pt5])

  var averaged = average(polyFC, ptFC, 'population', 'pop_avg')

  t.equal(averaged.features[0].geometry.type, 'Polygon')
  t.equal(averaged.features[0].properties.pop_avg, 450)
  t.equal(averaged.features[1].properties.pop_avg, 500)

  t.end()
})<commit_msg>fixed tape name<commit_after>var average = require('./')
var test = require('tape')
var polygon = require('turf-polygon')
var point = require('turf-point')
var featurecollection =  require('turf-featurecollection')

test('median', function(t){
  var poly1 = polygon([[[0,0],[10,0],[10,10], [0,10]]])
  var poly2 = polygon([[[10,0],[20,10],[20,20], [20,0]]])
  var polyFC = featurecollection([poly1, poly2])
  var pt1 = point(1,1, {population: 500})
  var pt2 = point(1,3, {population: 400})
  var pt3 = point(14,2, {population: 600})
  var pt4 = point(13,1, {population: 500})
  var pt5 = point(19,7, {population: 200})
  var ptFC = featurecollection([pt1, pt2, pt3, pt4, pt5])

  var averaged = average(polyFC, ptFC, 'population', 'pop_avg')

  t.equal(averaged.features[0].geometry.type, 'Polygon')
  t.equal(averaged.features[0].properties.pop_avg, 450)
  t.equal(averaged.features[1].properties.pop_avg, 500)

  t.end()
})<|endoftext|>


<commit_before>var assert = require('assert')
var convert = require('../chinese_convert')

describe('convert', function () {
  it('test cn2tw', function () {
    assert.equal(convert.cn2tw('简体转繁体功能测试'), '體轉繁體功能測試') // start travis ci
  })
  it('test tw2cn', function () {
    assert.equal(convert.tw2cn('繁體轉簡體功能測試'), '繁体转简体功能测试')
  })
})
<commit_msg>Update test.js<commit_after>var assert = require('assert')
var convert = require('../chinese_convert')

describe('convert', function () {
  it('test cn2tw', function () {
    assert.equal(convert.cn2tw('简体转繁体功能测试'), '簡體轉繁體功能測試') // start travis ci
  })
  it('test tw2cn', function () {
    assert.equal(convert.tw2cn('繁體轉簡體功能測試'), '繁体转简体功能测试')
  })
})
<|endoftext|>


<commit_before>require('proof')(43, async (okay) => {
    const rescue = require('rescue')
    const Destructible = require('..')
    const Future = require('perhaps')
    {
        const destructible = new Destructible('main')
        destructible.destroy()
        await destructible.promise
        await destructible.done
        const test = []
        try {
            destructible.cause
        } catch (error) {
            test.push(true)
        }
        okay(test, [ true ], 'cause throws an error')
    }
    {
        const destructible = new Destructible('main')
        destructible.durable('destructs', new Promise(resolve => {
            destructible.destruct(resolve)
        }))
        destructible.destroy()
        await destructible.promise
        okay(destructible.destroyed, 'set destructor')
    }
    {
        const test = []
        const destructible = new Destructible('main')
        const destructors = []
        destructors.push(destructible.destruct(() => { throw new Error }))
        destructible.destruct(() => test.push('destructed'))
        destructors.push(destructible.destruct(() => { throw new Error }))
        destructible.clear(destructors)
        destructible.destroy()
        await destructible.promise
        okay(test, [ 'destructed' ], 'create a destructor group')
    }
    {
        const destructible = new Destructible('main')
        const future = {}
        const one = new Promise(resolve => future.one = resolve)
        const two = new Promise(resolve => future.two = resolve)
        async function get (object) {
            for (const name in object) {
                object[name] = await object[name]
            }
            return object
        }
        const results = get({
            one: destructible.durable('one', one),
            two: destructible.durable('two', two),
        })
        await new Promise(resolve => setTimeout(resolve, 50))
        destructible.destroy()
        future.two.call(null, 2)
        future.one.call(null, 1)
        await destructible.promise
        okay(await results, { one: 1, two: 2 }, 'gather retrurn values')
    }
    {
        const destructible = new Destructible('main')
        const sub = destructible.ephemeral('child')
        const future = {}
        sub.durable('future', new Promise(resolve => future.resolve = resolve))
        sub.destruct(() => future.resolve.call(null, 1))
        destructible.destroy()
        okay(!await destructible.promise, 'create sub-destructible')
    }
    {
        const destructible = new Destructible('main')
        const sub = destructible.ephemeral('child')
        const subsub = sub.ephemeral('child')
        subsub.destroy()
        await subsub.promise
        okay(!destructible.destroyed, 'not destroyed')
        destructible.destroy()
        okay(!await destructible.promise, 'wait for sub-destructible to complete')
    }
    {
        const fs = require('fs').promises
        const test = []
        const destructible = new Destructible($ => $(), 'main')
        destructible.durable($ => $(), 'error', async function () {
            await new Promise(resolve => setTimeout(resolve, 0))
            throw new Error('thrown')
        })
        try {
            await destructible.promise
        } catch (error) {
            console.log(error.stack)
            test.push(error.errors[0].errors[0].message)
        } finally {
            destructible.destroy()
        }
        okay(test, [ 'thrown' ], 'catch error from monitored promise')
    }
    {
        const test = []
        const destructible = new Destructible($ => $(), 10000, 'main')
        const sub = destructible.durable($ => $(), 'parent')
        sub.ephemeral($ => $(), 'child', Promise.reject(new Error('thrown')))
        try {
            await destructible.promise
        } catch (error) {
            console.log(error.stack)
            test.push(error.errors[0].errors[0].errors[0].message)
        }
        okay(test, [ 'thrown' ], 'destroy a destructible when an ephemeral sub-destructible errors')
    }
    {
        const test = []
        const destructible = new Destructible(10000, 'main')
        destructible.destruct(() => { throw new Error('thrown') })
        destructible.destroy()
        try {
            await destructible.promise
        } catch (error) {
            console.log(error.stack)
            test.push(error.errors[0].errors[0].message)
        }
        okay(test, [ 'thrown' ], 'catch destructor error')
    }
    {
        const test = []
        const destructible = new Destructible(50, 'main')
        const latch = {}
        destructible.durable('unresolved', new Promise(resolve => latch.resolve = resolve))
        destructible.destroy()
        try {
            await destructible.promise
        } catch (error) {
            console.log(error.stack)
            test.push(error.code)
        }
        okay(test, [ 'SCRAMMED' ], 'scram')
        latch.resolve.call()
    }
    {
        const test = []
        const destructible = new Destructible(50, 'parent')
        let _resolve = null
        const sub = destructible.durable('child')
        sub.durable('unresolved', new Promise(resolve => _resolve = resolve))
        destructible.destroy()
        try {
            console.log('here')
            await destructible.promise
            console.log('there')
        } catch (error) {
            console.log(error.stack)
            test.push(error.errors[0].code)
        }
        okay(test, [ 'SCRAMMED' ], 'scram sub-destructible')
        _resolve()
    }
    {
        const test = []
        const destructible = new Destructible('main')
        destructible.increment()
        destructible.increment()
        destructible.decrement()
        destructible.decrement()
        destructible.decrement()
        await destructible.promise
        okay(test, [], 'countdown to destruction')
    }
    {
        const test = []
        const destructible = new Destructible('function')
        const result = await destructible.ephemeral('f', async () => 1)
        okay(result, 1, 'function')
        await destructible.destroy().promise
    }
    {
        const destructible = new Destructible('attempt')
        const promise = destructible.rescue('setup', async function () {
            return 1
        })
        destructible.destroy()
        try {
            await destructible.promise
        } catch (error) {
            console.log(error.stack)
        }
        okay(await promise, 1, 'instance rescue')
    }
    {
        const destructible = new Destructible('attempt')
        await destructible.rescue(async function () {
            destructible.destroy()
            destructible.durable('failure', async () => {})
        })
        destructible.destroy()
        try {
            await destructible.promise
        } catch (error) {
            console.log(error.stack)
        }
    }
    {
        const destructible = new Destructible('attempt')
        const test = []
        try {
            await destructible.rescue('setup', async function () {
                throw new Error('hello')
            })
        } catch (error) {
            test.push(true)
            okay(destructible.destroyed, 'auto destroyed')
            okay(error.message, 'hello', 'rescue rethrew non-destructible error')
            await destructible.promise
        }
        okay(test, [ true ], 'exception was thrown')
    }
    {
        const destructible = new Destructible(250, 'progress')
        const child = destructible.ephemeral('child')
        child.progress()
        child.durable('progress', async function () {
            let count = 7
            while (--count != 0) {
                await new Promise(resolve => setTimeout(resolve, 100))
                if (count % 2 == 0) {
                    destructible.progress()
                } else {
                    child.progress()
                }
            }
            destructible.destroy()
        })
        await destructible.promise
        okay('cleanup')
    }
    {
        const test = []
        const destructible = new Destructible('destroyed')
        destructible.destroy()
        try {
            destructible.ephemeral('destroyed')
        } catch (error) {
            test.push(error instanceof Destructible.Error)
        }
        okay(test, [ true ], 'destroyed')
    }
    {
        const destructible = new Destructible('remove scram')
        const one = {}
        one.promise = new Promise(resolve => one.resolve = resolve)
        const terminal = destructible.durable('one', one.promise)
        const ephemeral = destructible.ephemeral('two')
        ephemeral.destroy()
        await new Promise(resolve => setImmediate(resolve))
        destructible.destroy()
        one.resolve()
        await destructible.promise
    }
    {
        const destructible = new Destructible('main')
        const child = destructible.durable({ countdown: 0 }, 'child')
        child.increment()
        destructible.destroy()
        okay(destructible.destroyed, 'parent destroyed')
        okay(!child.destroyed, 'child not yet destroyed')
        child.decrement()
        okay(child.destroyed, 'child destroyed')
        await destructible.promise
    }
    {
        const test = []
        const destructible = new Destructible(50, 'main')
        const child = destructible.ephemeral({ countdown: 2 }, 'child')
        destructible.destroy()
        try {
            await destructible.promise
        } catch (error) {
            rescue(error, [{ code: 'SCRAMMED' }])
            test.push(true)
        }
        okay(test, [ true ], 'delayed child scrammed')
    }
    {
        const destructible = new Destructible(25, 'main')
        const child = destructible.ephemeral('child')
        let stop = false
        child.durable('future', async () => {
            while (! stop) {
                child.progress()
                await new Promise(resolve => setTimeout(resolve, 10))
            }
        })
        child.destroy()
        await new Promise(resolve => setTimeout(resolve, 50))
        destructible.destroy()
        await new Promise(resolve => setTimeout(resolve, 50))
        stop = true
        await destructible.promise
        okay('ephemeral timer takeover')
    }
    {
        const destructible = new Destructible('main')
        destructible.destruct(() => {
            destructible.ephemeral('shutdown', () => {})
        })
        destructible.destroy()
        await destructible.destroyed
        okay('async destroyed')
    }
    {
        const destructible = new Destructible('main')
        okay(destructible.drain(), null, 'nothing to drain')
        const latch = { resolve: null }
        destructible.durable('first', new Promise(resolve => latch.resolve = resolve))
        destructible.ephemeral('second', new Promise(resolve => setTimeout(resolve, 150)))
        destructible.ephemeral('third', new Promise(resolve => setTimeout(resolve, 150)))
        const promises = []
        promises.push(destructible.drain())
        promises.push(destructible.drain())
        for (const promise of promises) {
            await promise
        }
        destructible.destroy()
        latch.resolve()
        await destructible.promise
        okay('drain')
    }
    {
        const destructible = new Destructible('redurable')
        destructible.durable('early exit', async () => {})
        const test = []
        try {
            await destructible.promise
        } catch (error) {
            test.push(error.errors[0].code)
        }
        okay(test, [ 'DURABLE' ], 'exited too early')
    }
    {
        const destructible = new Destructible('redurable')
        const latch = { resolve: null }
        destructible.durable('resolve', new Promise(resolve => latch.resolve = resolve))
        destructible.destroy()
        latch.resolve.call()
        await destructible.promise
    }
    {
        const destructible = new Destructible('redurable')
        const latch = { resolve: null }
        destructible.durable('resolve', async () => { throw new Error('thrown') })
        const test = []
        try {
            await destructible.promise
        } catch (error) {
            test.push(error.errors[0].errors[0].message)
        }
        okay(test, [ 'thrown' ], 'durable reports an early exit due to exception with the exception')
    }
    {
        const destructible = new Destructible('destructive')
        okay(await destructible.destructive('sync', async () => 1), 1, 'destructive async')
        okay(await destructible.destructive($ => $(), 'async', Promise.resolve(1)), 1, 'destructive promise')
        okay(destructible.destructive($ => $(), 'sync', () => 1), 1, 'destructive sync')
        await destructible.destroy().promise
    }
    {
        const destructible = new Destructible('destructive')
        try {
            destructible.destructive($ => $(), 'sync', () => { throw new Error })
        } catch (error) {
            okay(error instanceof Destructible.Error, 'sync destructive throw')
        }
        try {
            await destructible.promise
        } catch (error) {
            okay(error.errors.length, 1, 'sync destructive throw funneled')
        }
    }
    {
        const destructible = new Destructible('destructive')
        okay(destructible.destructive($ => $(), 'sync', null, () => { throw new Error }), null, 'sync destructive returned')
        try {
            await destructible.promise
        } catch (error) {
            okay(error.errors.length, 1, 'sync destructive returned funneled')
        }
    }
    {
        const destructible = new Destructible('destructive')
        okay(await destructible.destructive($ => $(), 'async', null, async () => { throw new Error }), null, 'async destructive returned')
        try {
            await destructible.promise
        } catch (error) {
            okay(error.errors.length, 1, 'async destructive returned funneled')
        }
    }
    {
        const destructible = new Destructible('destructive')
        okay(destructible.copacetic('copacetic', () => 1), 1, 'copacetic not errored')
        await destructible.ephemeral('errored', async () => { throw new Error })
        okay(destructible.copacetic('copacetic', null, () => 1), null, 'copacetic errored error return')
        let ran = false
        destructible.copacetic('copacetic', () => ran = true)
        okay(! ran, 'copacetic errored no op')
        try {
            await destructible.promise
        } catch (error) {
            okay(error.errors.length, 1, 'async destructive returned funneled')
        }
    }
})
<commit_msg>Test rescue of a promise.<commit_after>require('proof')(44, async (okay) => {
    const rescue = require('rescue')
    const Destructible = require('..')
    const Future = require('perhaps')
    {
        const destructible = new Destructible('main')
        destructible.destroy()
        await destructible.promise
        await destructible.done
        const test = []
        try {
            destructible.cause
        } catch (error) {
            test.push(true)
        }
        okay(test, [ true ], 'cause throws an error')
    }
    {
        const destructible = new Destructible('main')
        destructible.durable('destructs', new Promise(resolve => {
            destructible.destruct(resolve)
        }))
        destructible.destroy()
        await destructible.promise
        okay(destructible.destroyed, 'set destructor')
    }
    {
        const test = []
        const destructible = new Destructible('main')
        const destructors = []
        destructors.push(destructible.destruct(() => { throw new Error }))
        destructible.destruct(() => test.push('destructed'))
        destructors.push(destructible.destruct(() => { throw new Error }))
        destructible.clear(destructors)
        destructible.destroy()
        await destructible.promise
        okay(test, [ 'destructed' ], 'create a destructor group')
    }
    {
        const destructible = new Destructible('main')
        const future = {}
        const one = new Promise(resolve => future.one = resolve)
        const two = new Promise(resolve => future.two = resolve)
        async function get (object) {
            for (const name in object) {
                object[name] = await object[name]
            }
            return object
        }
        const results = get({
            one: destructible.durable('one', one),
            two: destructible.durable('two', two),
        })
        await new Promise(resolve => setTimeout(resolve, 50))
        destructible.destroy()
        future.two.call(null, 2)
        future.one.call(null, 1)
        await destructible.promise
        okay(await results, { one: 1, two: 2 }, 'gather retrurn values')
    }
    {
        const destructible = new Destructible('main')
        const sub = destructible.ephemeral('child')
        const future = {}
        sub.durable('future', new Promise(resolve => future.resolve = resolve))
        sub.destruct(() => future.resolve.call(null, 1))
        destructible.destroy()
        okay(!await destructible.promise, 'create sub-destructible')
    }
    {
        const destructible = new Destructible('main')
        const sub = destructible.ephemeral('child')
        const subsub = sub.ephemeral('child')
        subsub.destroy()
        await subsub.promise
        okay(!destructible.destroyed, 'not destroyed')
        destructible.destroy()
        okay(!await destructible.promise, 'wait for sub-destructible to complete')
    }
    {
        const fs = require('fs').promises
        const test = []
        const destructible = new Destructible($ => $(), 'main')
        destructible.durable($ => $(), 'error', async function () {
            await new Promise(resolve => setTimeout(resolve, 0))
            throw new Error('thrown')
        })
        try {
            await destructible.promise
        } catch (error) {
            console.log(error.stack)
            test.push(error.errors[0].errors[0].message)
        } finally {
            destructible.destroy()
        }
        okay(test, [ 'thrown' ], 'catch error from monitored promise')
    }
    {
        const test = []
        const destructible = new Destructible($ => $(), 10000, 'main')
        const sub = destructible.durable($ => $(), 'parent')
        sub.ephemeral($ => $(), 'child', Promise.reject(new Error('thrown')))
        try {
            await destructible.promise
        } catch (error) {
            console.log(error.stack)
            test.push(error.errors[0].errors[0].errors[0].message)
        }
        okay(test, [ 'thrown' ], 'destroy a destructible when an ephemeral sub-destructible errors')
    }
    {
        const test = []
        const destructible = new Destructible(10000, 'main')
        destructible.destruct(() => { throw new Error('thrown') })
        destructible.destroy()
        try {
            await destructible.promise
        } catch (error) {
            console.log(error.stack)
            test.push(error.errors[0].errors[0].message)
        }
        okay(test, [ 'thrown' ], 'catch destructor error')
    }
    {
        const test = []
        const destructible = new Destructible(50, 'main')
        const latch = {}
        destructible.durable('unresolved', new Promise(resolve => latch.resolve = resolve))
        destructible.destroy()
        try {
            await destructible.promise
        } catch (error) {
            console.log(error.stack)
            test.push(error.code)
        }
        okay(test, [ 'SCRAMMED' ], 'scram')
        latch.resolve.call()
    }
    {
        const test = []
        const destructible = new Destructible(50, 'parent')
        let _resolve = null
        const sub = destructible.durable('child')
        sub.durable('unresolved', new Promise(resolve => _resolve = resolve))
        destructible.destroy()
        try {
            console.log('here')
            await destructible.promise
            console.log('there')
        } catch (error) {
            console.log(error.stack)
            test.push(error.errors[0].code)
        }
        okay(test, [ 'SCRAMMED' ], 'scram sub-destructible')
        _resolve()
    }
    {
        const test = []
        const destructible = new Destructible('main')
        destructible.increment()
        destructible.increment()
        destructible.decrement()
        destructible.decrement()
        destructible.decrement()
        await destructible.promise
        okay(test, [], 'countdown to destruction')
    }
    {
        const test = []
        const destructible = new Destructible('function')
        const result = await destructible.ephemeral('f', async () => 1)
        okay(result, 1, 'function')
        await destructible.destroy().promise
    }
    {
        const destructible = new Destructible('attempt')
        const promise = destructible.rescue('setup', async function () {
            return 1
        })
        destructible.destroy()
        await destructible.promise
        okay(await promise, 1, 'rescue function')
    }
    {
        const destructible = new Destructible('attempt')
        const promise = destructible.rescue('setup', Promise.resolve(1))
        destructible.destroy()
        await destructible.promise
        okay(await promise, 1, 'rescue promise')
    }
    {
        const destructible = new Destructible('attempt')
        await destructible.rescue(async function () {
            destructible.destroy()
            destructible.durable('failure', async () => {})
        })
        destructible.destroy()
        try {
            await destructible.promise
        } catch (error) {
            console.log(error.stack)
        }
    }
    {
        const destructible = new Destructible('attempt')
        const test = []
        try {
            await destructible.rescue('setup', async function () {
                throw new Error('hello')
            })
        } catch (error) {
            test.push(true)
            okay(destructible.destroyed, 'auto destroyed')
            okay(error.message, 'hello', 'rescue rethrew non-destructible error')
            await destructible.promise
        }
        okay(test, [ true ], 'exception was thrown')
    }
    {
        const destructible = new Destructible(250, 'progress')
        const child = destructible.ephemeral('child')
        child.progress()
        child.durable('progress', async function () {
            let count = 7
            while (--count != 0) {
                await new Promise(resolve => setTimeout(resolve, 100))
                if (count % 2 == 0) {
                    destructible.progress()
                } else {
                    child.progress()
                }
            }
            destructible.destroy()
        })
        await destructible.promise
        okay('cleanup')
    }
    {
        const test = []
        const destructible = new Destructible('destroyed')
        destructible.destroy()
        try {
            destructible.ephemeral('destroyed')
        } catch (error) {
            test.push(error instanceof Destructible.Error)
        }
        okay(test, [ true ], 'destroyed')
    }
    {
        const destructible = new Destructible('remove scram')
        const one = {}
        one.promise = new Promise(resolve => one.resolve = resolve)
        const terminal = destructible.durable('one', one.promise)
        const ephemeral = destructible.ephemeral('two')
        ephemeral.destroy()
        await new Promise(resolve => setImmediate(resolve))
        destructible.destroy()
        one.resolve()
        await destructible.promise
    }
    {
        const destructible = new Destructible('main')
        const child = destructible.durable({ countdown: 0 }, 'child')
        child.increment()
        destructible.destroy()
        okay(destructible.destroyed, 'parent destroyed')
        okay(!child.destroyed, 'child not yet destroyed')
        child.decrement()
        okay(child.destroyed, 'child destroyed')
        await destructible.promise
    }
    {
        const test = []
        const destructible = new Destructible(50, 'main')
        const child = destructible.ephemeral({ countdown: 2 }, 'child')
        destructible.destroy()
        try {
            await destructible.promise
        } catch (error) {
            rescue(error, [{ code: 'SCRAMMED' }])
            test.push(true)
        }
        okay(test, [ true ], 'delayed child scrammed')
    }
    {
        const destructible = new Destructible(25, 'main')
        const child = destructible.ephemeral('child')
        let stop = false
        child.durable('future', async () => {
            while (! stop) {
                child.progress()
                await new Promise(resolve => setTimeout(resolve, 10))
            }
        })
        child.destroy()
        await new Promise(resolve => setTimeout(resolve, 50))
        destructible.destroy()
        await new Promise(resolve => setTimeout(resolve, 50))
        stop = true
        await destructible.promise
        okay('ephemeral timer takeover')
    }
    {
        const destructible = new Destructible('main')
        destructible.destruct(() => {
            destructible.ephemeral('shutdown', () => {})
        })
        destructible.destroy()
        await destructible.destroyed
        okay('async destroyed')
    }
    {
        const destructible = new Destructible('main')
        okay(destructible.drain(), null, 'nothing to drain')
        const latch = { resolve: null }
        destructible.durable('first', new Promise(resolve => latch.resolve = resolve))
        destructible.ephemeral('second', new Promise(resolve => setTimeout(resolve, 150)))
        destructible.ephemeral('third', new Promise(resolve => setTimeout(resolve, 150)))
        const promises = []
        promises.push(destructible.drain())
        promises.push(destructible.drain())
        for (const promise of promises) {
            await promise
        }
        destructible.destroy()
        latch.resolve()
        await destructible.promise
        okay('drain')
    }
    {
        const destructible = new Destructible('redurable')
        destructible.durable('early exit', async () => {})
        const test = []
        try {
            await destructible.promise
        } catch (error) {
            test.push(error.errors[0].code)
        }
        okay(test, [ 'DURABLE' ], 'exited too early')
    }
    {
        const destructible = new Destructible('redurable')
        const latch = { resolve: null }
        destructible.durable('resolve', new Promise(resolve => latch.resolve = resolve))
        destructible.destroy()
        latch.resolve.call()
        await destructible.promise
    }
    {
        const destructible = new Destructible('redurable')
        const latch = { resolve: null }
        destructible.durable('resolve', async () => { throw new Error('thrown') })
        const test = []
        try {
            await destructible.promise
        } catch (error) {
            test.push(error.errors[0].errors[0].message)
        }
        okay(test, [ 'thrown' ], 'durable reports an early exit due to exception with the exception')
    }
    {
        const destructible = new Destructible('destructive')
        okay(await destructible.destructive('sync', async () => 1), 1, 'destructive async')
        okay(await destructible.destructive($ => $(), 'async', Promise.resolve(1)), 1, 'destructive promise')
        okay(destructible.destructive($ => $(), 'sync', () => 1), 1, 'destructive sync')
        await destructible.destroy().promise
    }
    {
        const destructible = new Destructible('destructive')
        try {
            destructible.destructive($ => $(), 'sync', () => { throw new Error })
        } catch (error) {
            okay(error instanceof Destructible.Error, 'sync destructive throw')
        }
        try {
            await destructible.promise
        } catch (error) {
            okay(error.errors.length, 1, 'sync destructive throw funneled')
        }
    }
    {
        const destructible = new Destructible('destructive')
        okay(destructible.destructive($ => $(), 'sync', null, () => { throw new Error }), null, 'sync destructive returned')
        try {
            await destructible.promise
        } catch (error) {
            okay(error.errors.length, 1, 'sync destructive returned funneled')
        }
    }
    {
        const destructible = new Destructible('destructive')
        okay(await destructible.destructive($ => $(), 'async', null, async () => { throw new Error }), null, 'async destructive returned')
        try {
            await destructible.promise
        } catch (error) {
            okay(error.errors.length, 1, 'async destructive returned funneled')
        }
    }
    {
        const destructible = new Destructible('destructive')
        okay(destructible.copacetic('copacetic', () => 1), 1, 'copacetic not errored')
        await destructible.ephemeral('errored', async () => { throw new Error })
        okay(destructible.copacetic('copacetic', null, () => 1), null, 'copacetic errored error return')
        let ran = false
        destructible.copacetic('copacetic', () => ran = true)
        okay(! ran, 'copacetic errored no op')
        try {
            await destructible.promise
        } catch (error) {
            okay(error.errors.length, 1, 'async destructive returned funneled')
        }
    }
})
<|endoftext|>


<commit_before>var spawn = require('child_process').spawn,
		fs = require('fs'),
		path = require('path');

module.exports = function(appLibRoot) {
	var probeRoot = typeof appLibRoot !== undefined ? appLibRoot : "";

	function findBlocks(raw) {
		var stream_start = raw.indexOf('[STREAM]') + 8,
				stream_end = raw.lastIndexOf('[/STREAM]'),
				format_start = raw.indexOf('[FORMAT]') + 8,
				format_end = raw.lastIndexOf('[/FORMAT]');

		var blocks = { streams: null, format: null };

		if(stream_start !== 7 && stream_end !== -1) {
			blocks.streams = raw.slice(stream_start, stream_end).trim();
		}

		if(format_start !== 7 && format_end !== -1) {
			blocks.format = raw.slice(format_start, format_end).trim();
		}

		return blocks;
	};

	function parseField(str) {
		str = ("" + str).trim();
		return str.match(/^\d+\.?\d*$/) ? parseFloat(str) : str;
	};

	function parseBlock(block) {
		var block_object = {}, lines = block.split('\n');

		lines.forEach(function(line) {
			var data = line.split('=');
			if(data && data.length === 2) {
				block_object[data[0]] = parseField(data[1]);
			}
		});

		return block_object;
	};

	function parseStreams(text, callback) {
		if(!text) return { streams: null };

		var streams = [];
		var blocks = text.replace('[STREAM]\n', '').split('[/STREAM]');

		blocks.forEach(function(stream, idx) {
			var codec_data = parseBlock(stream);
			var sindex = codec_data.index;
			delete codec_data.index;

			if(sindex) streams[sindex] = codec_data;
			else streams.push(codec_data);
		});

		return { streams: streams };
	};

	function parseFormat(text, callback) {
		if(!text) return { format: null }

		var block = text.replace('[FORMAT]\n', '').replace('[/FORMAT]', '');

		var raw_format = parseBlock(block),
				format = { },
				metadata = { };

		//REMOVE metadata
		delete raw_format.filename;
		for(var attr in raw_format) {
			if(raw_format.hasOwnProperty(attr)) {
				if(attr.indexOf('TAG') === -1) format[attr] = raw_format[attr];
				else metadata[attr.slice(4)] = raw_format[attr];
			}
		}

		return { format: format, metadata: metadata };
	};

	function doProbe(file, callback) {
		var proc = spawn(probeRoot + 'ffprobe', ['-show_streams', '-show_format', '-loglevel', 'warning', file]),
				probeData = [],
				errData = [],
				exitCode = null,
				start = Date.now();

		proc.stdout.setEncoding('utf8');
		proc.stderr.setEncoding('utf8');

		proc.stdout.on('data', function(data) { probeData.push(data) });
		proc.stderr.on('data', function(data) { errData.push(data) });

		proc.on('exit', function(code) {
			exitCode = code;
		});
		proc.on('close', function() {
			var blocks = findBlocks(probeData.join(''));

			var s = parseStreams(blocks.streams),
					f = parseFormat(blocks.format);

			if (exitCode) {
				var err_output = errData.join('');
				return callback(err_output);
			}

			callback(null, {
				filename: path.basename(file),
				filepath: path.dirname(file),
				fileext: path.extname(file),
				file: file,
				probe_time: Date.now() - start,
				streams: s.streams,
				format: f.format,
				metadata: f.metadata
			});
		});
	};

	return doProbe;
}
<commit_msg>clean up ffprobe path restoring back compatibility<commit_after>var spawn = require('child_process').spawn,
		fs = require('fs'),
		path = require('path');

module.exports = (function() {
	function findBlocks(raw) {
		var stream_start = raw.indexOf('[STREAM]') + 8,
				stream_end = raw.lastIndexOf('[/STREAM]'),
				format_start = raw.indexOf('[FORMAT]') + 8,
				format_end = raw.lastIndexOf('[/FORMAT]');

		var blocks = { streams: null, format: null };

		if(stream_start !== 7 && stream_end !== -1) {
			blocks.streams = raw.slice(stream_start, stream_end).trim();
		}

		if(format_start !== 7 && format_end !== -1) {
			blocks.format = raw.slice(format_start, format_end).trim();
		}

		return blocks;
	};

	function parseField(str) {
		str = ("" + str).trim();
		return str.match(/^\d+\.?\d*$/) ? parseFloat(str) : str;
	};

	function parseBlock(block) {
		var block_object = {}, lines = block.split('\n');

		lines.forEach(function(line) {
			var data = line.split('=');
			if(data && data.length === 2) {
				block_object[data[0]] = parseField(data[1]);
			}
		});

		return block_object;
	};

	function parseStreams(text, callback) {
		if(!text) return { streams: null };

		var streams = [];
		var blocks = text.replace('[STREAM]\n', '').split('[/STREAM]');

		blocks.forEach(function(stream, idx) {
			var codec_data = parseBlock(stream);
			var sindex = codec_data.index;
			delete codec_data.index;

			if(sindex) streams[sindex] = codec_data;
			else streams.push(codec_data);
		});

		return { streams: streams };
	};

	function parseFormat(text, callback) {
		if(!text) return { format: null }

		var block = text.replace('[FORMAT]\n', '').replace('[/FORMAT]', '');

		var raw_format = parseBlock(block),
				format = { },
				metadata = { };

		//REMOVE metadata
		delete raw_format.filename;
		for(var attr in raw_format) {
			if(raw_format.hasOwnProperty(attr)) {
				if(attr.indexOf('TAG') === -1) format[attr] = raw_format[attr];
				else metadata[attr.slice(4)] = raw_format[attr];
			}
		}

		return { format: format, metadata: metadata };
	};

	function doProbe(file, callback) {
		var proc = spawn(module.exports.FFPROBE_PATH || 'ffprobe', ['-show_streams', '-show_format', '-loglevel', 'warning', file]),
				probeData = [],
				errData = [],
				exitCode = null,
				start = Date.now();

		proc.stdout.setEncoding('utf8');
		proc.stderr.setEncoding('utf8');

		proc.stdout.on('data', function(data) { probeData.push(data) });
		proc.stderr.on('data', function(data) { errData.push(data) });

		proc.on('exit', function(code) {
			exitCode = code;
		});
		proc.on('close', function() {
			var blocks = findBlocks(probeData.join(''));

			var s = parseStreams(blocks.streams),
					f = parseFormat(blocks.format);

			if (exitCode) {
				var err_output = errData.join('');
				return callback(err_output);
			}

			callback(null, {
				filename: path.basename(file),
				filepath: path.dirname(file),
				fileext: path.extname(file),
				file: file,
				probe_time: Date.now() - start,
				streams: s.streams,
				format: f.format,
				metadata: f.metadata
			});
		});
	};

	return doProbe;
})()
<|endoftext|>


<commit_before>var test = require('tape');

var pack = require('./lib/util/pack.js');
var unpack = require('./lib/util/unpack.js');
var Spec = require('./lib/amf/spec.js');
var Stream = require('./lib/io/stream.js');
var InputStream = require('./lib/io/input.js');
var OutputStream = require('./lib/io/output.js');
var AMF = require('./lib/amf/amf.js');

// var os = new OutputStream("ABC");
// var s = new InputStream(os.getRaw());
// console.log(s.readBytes(3));

test('undefined', function(t) {
  t.plan(1);

  t.equal(Spec.AMF3_UNDEFINED, AMF.deserialize(AMF.serialize()));
});

// console.log(s.readDouble() == Number.MAX_VALUE);

  return;

test('int roundtrip', function (t) {
  var pointer = 0;
  var startVal = Math.floor(Math.random() * Spec.MAX_INT);
  console.log(startVal);

  var stream = '';
  var writeByte = function (byte) {
    stream += pack('c', byte);
  };

  var readByte = function () {
    var value = stream.substr(pointer, 1);
    pointer += value.length;
    return value.charCodeAt(0);
  };

// type marker
  writeByte(0x04);

  if (startVal < Spec.MIN_INT || startVal > Spec.MAX_INT) {
    throw new Error('Integer out of range: ' + startVal);
  }

  if (startVal < 0 || startVal >= Spec.MIN_4_BYTE_INT) {
    writeByte((startVal >> 22) | 0x80);
    writeByte((startVal >> 15) | 0x80);
    writeByte((startVal >> 8) | 0x80);
    writeByte(startVal);
  } else if (startVal >= Spec.MIN_3_BYTE_INT) {
    writeByte((startVal >> 14) | 0x80);
    writeByte((startVal >> 7) | 0x80);
    writeByte(startVal & 0x7f);
  } else if (startVal >= Spec.MIN_2_BYTE_INT) {
    writeByte((startVal >> 7) | 0x80);
    writeByte(startVal & 0x7f);
  } else {
    writeByte(startVal);
  }

  var marker = readByte();
  var count = 1;
  var endVal = 0;
  var byte = readByte();

  while (((byte & 0x80) != 0) && count < 4) {
    endVal <<= 7;
    endVal |= (byte & 0x7F);
    byte = readByte();
    count++;
  }

  if (count < 4) {
    endVal <<= 7;
    endVal |= byte;
  } else {
    // Use all 8 bits from the 4th byte
    endVal <<= 8;
    endVal |= byte;
  }

  if ((endVal & 0x18000000) == 0x18000000) {
    endVal ^= 0x1fffffff;
    endVal *= -1;
    endVal -= 1;
  } else {
    if ((endVal & 0x10000000) == 0x10000000) {
      // remove the signed flag
      endVal &= 0x0fffffff;
    }
  }

  t.plan(1);

  t.equal(startVal, endVal);
});

// test('is dense array', function(t) {
//   t.plan(6);

//   t.equal(true, Spec.isDenseArray());
//   t.equal(true, Spec.isDenseArray([1,2,3]));
//   t.equal(true, Spec.isDenseArray(["a", "x", "p"]));
//   t.equal(true, Spec.isDenseArray({0: 'hi', 1: 'xxx'}));
//   t.notEqual(true, Spec.isDenseArray({0: 'hi', 2: 'xxx'}));
//   t.notEqual(true, Spec.isDenseArray({'hi': 'xxx'}));
// })<commit_msg>Fixed test<commit_after>var test = require('tape');

var pack = require('./lib/util/pack.js');
var unpack = require('./lib/util/unpack.js');
var Spec = require('./lib/amf/spec.js');
var Stream = require('./lib/io/stream.js');
var InputStream = require('./lib/io/input.js');
var OutputStream = require('./lib/io/output.js');
var AMF = require('./lib/amf/amf.js');

// var os = new OutputStream("ABC");
// var s = new InputStream(os.getRaw());
// console.log(s.readBytes(3));

test('undefined', function(t) {
  t.plan(1);

  var serialized = AMF.serialize();
  t.equal(undefined, AMF.deserialize(serialized));
});

// console.log(s.readDouble() == Number.MAX_VALUE);

  return;

test('int roundtrip', function (t) {
  var pointer = 0;
  var startVal = Math.floor(Math.random() * Spec.MAX_INT);
  console.log(startVal);

  var stream = '';
  var writeByte = function (byte) {
    stream += pack('c', byte);
  };

  var readByte = function () {
    var value = stream.substr(pointer, 1);
    pointer += value.length;
    return value.charCodeAt(0);
  };

// type marker
  writeByte(0x04);

  if (startVal < Spec.MIN_INT || startVal > Spec.MAX_INT) {
    throw new Error('Integer out of range: ' + startVal);
  }

  if (startVal < 0 || startVal >= Spec.MIN_4_BYTE_INT) {
    writeByte((startVal >> 22) | 0x80);
    writeByte((startVal >> 15) | 0x80);
    writeByte((startVal >> 8) | 0x80);
    writeByte(startVal);
  } else if (startVal >= Spec.MIN_3_BYTE_INT) {
    writeByte((startVal >> 14) | 0x80);
    writeByte((startVal >> 7) | 0x80);
    writeByte(startVal & 0x7f);
  } else if (startVal >= Spec.MIN_2_BYTE_INT) {
    writeByte((startVal >> 7) | 0x80);
    writeByte(startVal & 0x7f);
  } else {
    writeByte(startVal);
  }

  var marker = readByte();
  var count = 1;
  var endVal = 0;
  var byte = readByte();

  while (((byte & 0x80) != 0) && count < 4) {
    endVal <<= 7;
    endVal |= (byte & 0x7F);
    byte = readByte();
    count++;
  }

  if (count < 4) {
    endVal <<= 7;
    endVal |= byte;
  } else {
    // Use all 8 bits from the 4th byte
    endVal <<= 8;
    endVal |= byte;
  }

  if ((endVal & 0x18000000) == 0x18000000) {
    endVal ^= 0x1fffffff;
    endVal *= -1;
    endVal -= 1;
  } else {
    if ((endVal & 0x10000000) == 0x10000000) {
      // remove the signed flag
      endVal &= 0x0fffffff;
    }
  }

  t.plan(1);

  t.equal(startVal, endVal);
});

// test('is dense array', function(t) {
//   t.plan(6);

//   t.equal(true, Spec.isDenseArray());
//   t.equal(true, Spec.isDenseArray([1,2,3]));
//   t.equal(true, Spec.isDenseArray(["a", "x", "p"]));
//   t.equal(true, Spec.isDenseArray({0: 'hi', 1: 'xxx'}));
//   t.notEqual(true, Spec.isDenseArray({0: 'hi', 2: 'xxx'}));
//   t.notEqual(true, Spec.isDenseArray({'hi': 'xxx'}));
// })<|endoftext|>


<commit_before>/*
  Copyright 2016 - 2018 by Jan Dockx

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

'use strict'

const os = require('os')
const assert = require('assert')

function skipsForEach () {
  try {
    const array = [1]
    array.forEach(() => {
      throw new Error('Dummy error to check occurrence of forEach in stack trace')
    })
  } catch (err) {
    return err.stack.indexOf('forEach') < 0
  }
}

const stack = {
  /**
   * The (depth + 1)nd line from a stack trace created here, after the `toString()` (the `toString()` might prepended
   * to the stack).
   *
   * When this result is used as a line on its own, it is clickable to navigate to the referred source code
   * in most consoles.
   *
   * Note that in Safari, the result cannot be trusted. Safari skips (optimized?) stack frames. In Safari, this
   * will return 'a' stack line, but not necessarily a semantic meaningful one.
   */
  location: function (depth) {
    assert(!depth || Number.isInteger(depth), 'optional depth is an integer')
    assert(!depth || depth >= 0, 'optional depth is positive')

    const stackSource = new Error()
    // most environments add the stackSource.toString() at the beginning of the stack; Firefox does not
    const stackSourceStr = stackSource.toString()
    const stack = stackSource.stack.replace(stackSourceStr + os.EOL, '')
    const stackLines = stack.split(os.EOL)
    /* Return the line at 1 + (depth || 0)
       Since Safari skips stack frames, this might not work in Safari.
       There will however be at least 1 element in stack frames.
       The Math.min protects this call for safari for array out of bounds problems.
       This returns a technical result (a string), without real semantic meaning. */
    return stackLines[Math.min(1 + (depth || 0), stackLines.length - 1)]
  },

  /**
   * The stack lines from the (depth + 1)nd down, from a stack trace created here, after the `toString()`
   * (the `toString()` might prepended to the stack). This is a multi-line string, with at least 1 line.
   *
   * Note that in Safari, the result cannot be trusted. Safari skips (optimized?) stack frames. In Safari, this
   * will return 'a' stack, but not necessarily a semantic meaningful one.
   */
  raw: function (depth) {
    assert(!depth || Number.isInteger(depth), 'optional depth is an integer')
    assert(!depth || depth >= 0, 'optional depth is positive')

    const stackSource = new Error()
    // most environments add the stackSource.toString() at the beginning of the stack; Firefox does not
    const stackSourceStr = stackSource.toString()
    const stack = stackSource.stack.replace(stackSourceStr + os.EOL, '')
    const stackLines = stack.split(os.EOL).filter(sl => !!sl) // Firefox has empty lines (at the end)
    /* Return the lines after 1 + (depth || 0)
       Since Safari skips stack frames, this might not work in Safari.
       There will however be at least 1 element in stack frames.
       The Math.min protects this call for safari for array out of bounds problems.
       This returns a technical result (a string), without real semantic meaning.
       We cannot use splice, because that requires deleteCount to be > 0.
       https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice */
    const relevant = stackLines.slice(Math.min(1 + (depth || 0), stackLines.length - 1))
    return relevant.join(os.EOL)
  },

  /**
   * Boolean that says whether or not this platform skips forEach stack frames in an Error stack.
   * Firefox does. Node, Chrome, Safari do not.
   */
  skipsForEach: skipsForEach()
}

module.exports = stack
<commit_msg>Override Chrome stack limit<commit_after>/*
  Copyright 2016 - 2018 by Jan Dockx

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

'use strict'

const os = require('os')
const assert = require('assert')

/* Chrome limits the number of frames in a stack trace to 10 by default.
   https://github.com/v8/v8/wiki/Stack-Trace-API
   This changes overrides that limit. Other browsers do not limit. */
Error.stackTraceLimit = Number.POSITIVE_INFINITY

function skipsForEach () {
  try {
    const array = [1]
    array.forEach(() => {
      throw new Error('Dummy error to check occurrence of forEach in stack trace')
    })
  } catch (err) {
    return err.stack.indexOf('forEach') < 0
  }
}

const stack = {
  /**
   * The (depth + 1)nd line from a stack trace created here, after the `toString()` (the `toString()` might prepended
   * to the stack).
   *
   * When this result is used as a line on its own, it is clickable to navigate to the referred source code
   * in most consoles.
   *
   * Note that in Safari, the result cannot be trusted. Safari skips (optimized?) stack frames. In Safari, this
   * will return 'a' stack line, but not necessarily a semantic meaningful one.
   */
  location: function (depth) {
    assert(!depth || Number.isInteger(depth), 'optional depth is an integer')
    assert(!depth || depth >= 0, 'optional depth is positive')

    const stackSource = new Error()
    // most environments add the stackSource.toString() at the beginning of the stack; Firefox does not
    const stackSourceStr = stackSource.toString()
    const stack = stackSource.stack.replace(stackSourceStr + os.EOL, '')
    const stackLines = stack.split(os.EOL)
    /* Return the line at 1 + (depth || 0)
       Since Safari skips stack frames, this might not work in Safari.
       There will however be at least 1 element in stack frames.
       The Math.min protects this call for safari for array out of bounds problems.
       This returns a technical result (a string), without real semantic meaning. */
    return stackLines[Math.min(1 + (depth || 0), stackLines.length - 1)]
  },

  /**
   * The stack lines from the (depth + 1)nd down, from a stack trace created here, after the `toString()`
   * (the `toString()` might prepended to the stack). This is a multi-line string, with at least 1 line.
   *
   * Note that in Safari, the result cannot be trusted. Safari skips (optimized?) stack frames. In Safari, this
   * will return 'a' stack, but not necessarily a semantic meaningful one.
   */
  raw: function (depth) {
    assert(!depth || Number.isInteger(depth), 'optional depth is an integer')
    assert(!depth || depth >= 0, 'optional depth is positive')

    const stackSource = new Error()
    // most environments add the stackSource.toString() at the beginning of the stack; Firefox does not
    const stackSourceStr = stackSource.toString()
    const stack = stackSource.stack.replace(stackSourceStr + os.EOL, '')
    const stackLines = stack.split(os.EOL).filter(sl => !!sl) // Firefox has empty lines (at the end)
    /* Return the lines after 1 + (depth || 0)
       Since Safari skips stack frames, this might not work in Safari.
       There will however be at least 1 element in stack frames.
       The Math.min protects this call for safari for array out of bounds problems.
       This returns a technical result (a string), without real semantic meaning.
       We cannot use splice, because that requires deleteCount to be > 0.
       https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice */
    const relevant = stackLines.slice(Math.min(1 + (depth || 0), stackLines.length - 1))
    return relevant.join(os.EOL)
  },

  /**
   * Boolean that says whether or not this platform skips forEach stack frames in an Error stack.
   * Firefox does. Node, Chrome, Safari do not.
   */
  skipsForEach: skipsForEach()
}

module.exports = stack
<|endoftext|>


<commit_before>var request = require('supertest');
var app = require('../app.js');

describe('GET /', function() {
  it('respond with hello world', function(done) {
    request(app).get('/').expect('hello world', done);
  });
});

<commit_msg>Fixed the test<commit_after>var request = require('supertest');
var app = require('../app.js');

describe('GET /', function() {
  it('respond with hello world', function(done) {
    request(app).get('/').expect('hello jenkins', done);
  });
});

<|endoftext|>


<commit_before>// @flow

import { chTest, randomString } from './helper';

const ch = chTest();

// FIXME: creating new events takes a few seconds, so we rely on a known
// customerId already having some associated events
const cid = '689ef20e-e37a-4b8e-8d3f-2494ec901bc5';

describe('ContactHub', () => {

  describe('addEvent', () => {
    it('creates a new event', async () => {
      const res = await ch.addEvent({
        customerId: cid,
        context: 'WEB',
        type: 'viewedPage',
        properties: {}
      });

      expect(res).toBe(true);
    });

    it('creates an anonymous event', async () => {
      const res = await ch.addEvent({
        sessionId: randomString(),
        context: 'WEB',
        type: 'viewedPage',
        properties: {}
      });

      expect(res).toBe(true);
    });
  });

  describe('getEvent', () => {
    it('retrieves an Event by id', async () => {
      const events = await ch.getEvents(cid);

      const event = await ch.getEvent(events[0].id);
      expect(event.id).toBe(events[0].id);
    });
  });

  describe('getEvents', () => {
    it('retrieves all Events for a Customer', async () => {
      const events = await ch.getEvents(cid);
      expect(events.length).toBe(10);
      expect(events[0].customerId).toBe(cid);
    });
  });

  describe('getEvents', () => {
    it('retrieves all Events for a Customer using filters', async () => {
      const dateFrom = new Date('2017-02-10');
      const dateTo = new Date('2017-02-20');
      const filters = {
        mode: 'ACTIVE',
        context: 'WEB',
        dateFrom,
        dateTo
      };

      const events = await ch.getEvents(cid, filters);
      expect(events.length > 0).toBe(true);

      const areWebEvents = events.every((v) => v.context === 'WEB');
      expect(areWebEvents).toBe(true);

      const haveRightDate = events.every((v) => {
        const eventDate = new Date(v.date);
        return dateTo >= eventDate && eventDate >= dateFrom;
      });
      expect(haveRightDate).toBe(true);
    });
  });

});
<commit_msg>Added test for events filtering by context.<commit_after>// @flow

import { chTest, randomString } from './helper';

const ch = chTest();

// FIXME: creating new events takes a few seconds, so we rely on a known
// customerId already having some associated events
const cid = '689ef20e-e37a-4b8e-8d3f-2494ec901bc5';

describe('ContactHub', () => {

  describe('addEvent', () => {
    it('creates a new event', async () => {
      const res = await ch.addEvent({
        customerId: cid,
        context: 'WEB',
        type: 'viewedPage',
        properties: {}
      });

      expect(res).toBe(true);
    });

    it('creates an anonymous event', async () => {
      const res = await ch.addEvent({
        sessionId: randomString(),
        context: 'WEB',
        type: 'viewedPage',
        properties: {}
      });

      expect(res).toBe(true);
    });
  });

  describe('getEvent', () => {
    it('retrieves an Event by id', async () => {
      const events = await ch.getEvents(cid);

      const event = await ch.getEvent(events[0].id);
      expect(event.id).toBe(events[0].id);
    });
  });

  describe('getEvents', () => {
    it('retrieves all Events for a Customer', async () => {
      const events = await ch.getEvents(cid);
      expect(events.length).toBe(10);
      expect(events[0].customerId).toBe(cid);
    });
  });

  describe('getEvents', () => {
    it('retrieves all Events for a Customer using date range filter', async () => {
      const dateFrom = new Date('2017-02-10');
      const dateTo = new Date('2017-02-20');
      const filters = { dateFrom, dateTo };

      const events = await ch.getEvents(cid, filters);
      expect(events.length > 0).toBe(true);

      const haveRightDate = events.every((v) => {
        const eventDate = new Date(v.date);
        return dateTo >= eventDate && eventDate >= dateFrom;
      });
      expect(haveRightDate).toBe(true);
    });

    it('retrieves all Events for a customer with "MOBILE" context', async () => {
      const eventData = {
        customerId: cid,
        context: 'MOBILE',
        type: 'viewedPage',
        properties: {}
      };

      await ch.addEvent(eventData);

      const events = await ch.getEvents(cid, { context: 'MOBILE' });
      expect(events.length > 0).toBe(true);

      const areMobileEvents = events.every(({ context }) => context === 'MOBILE');
      expect(areMobileEvents).toBe(true);
    });
  });

});
<|endoftext|>


<commit_before>//http://www.runoob.com/cssref/css3-pr-filter.html

export default {
  blur( px){
    return `blur(${px})`
  },
  brightness(percent){
    return `brightness(${percent})`
  },
  contrast(percent){
    return `contrast(${percent})`
  },
  /*
  dropShadow(context, offsetX, offsetY, shadowRadius, color)
   */
  grayscale(percent){
    return `grayscale(${percent})`
  },
  hueRotate(deg){
    return `hueRotate(${deg})`
  },
  invert(percent){
    return `invert(${percent})`
  },
  opacity(percent){
    return `opacity(${percent})`
  },
  saturate(percent){
    return `saturate(${percent})`
  },
  sepia(percent){
    return `sepia(${percent})`
  },
  url(path){

  },
  toStr(filter = {}){
    console.log(filter)
    return  Object.entries(filter).reduce((p, c, index, array) => {
      // console.log(c)
        return p.concat(this[c[0]](c[1]))
      }, []).join(' ')
  }
}
<commit_msg>delete console in filter.js<commit_after>//http://www.runoob.com/cssref/css3-pr-filter.html

export default {
  blur( px){
    return `blur(${px})`
  },
  brightness(percent){
    return `brightness(${percent})`
  },
  contrast(percent){
    return `contrast(${percent})`
  },
  /*
  dropShadow(context, offsetX, offsetY, shadowRadius, color)
   */
  grayscale(percent){
    return `grayscale(${percent})`
  },
  hueRotate(deg){
    return `hueRotate(${deg})`
  },
  invert(percent){
    return `invert(${percent})`
  },
  opacity(percent){
    return `opacity(${percent})`
  },
  saturate(percent){
    return `saturate(${percent})`
  },
  sepia(percent){
    return `sepia(${percent})`
  },
  url(path){

  },
  toStr(filter = {}){
    return  Object.entries(filter).reduce((p, c, index, array) => {
        return p.concat(this[c[0]](c[1]))
      }, []).join(' ')
  }
}
<|endoftext|>


<commit_before>'use strict';
import getSetProps from './get-set-props';
import test from 'ava';

test(t => {
	t.truthy(Object.keys(getSetProps).length > 0);
	t.truthy(getSetProps.hasOwnProperty('Array'));
	t.truthy(getSetProps.hasOwnProperty('Number'));
	t.truthy(getSetProps.Error.indexOf('stack') !== -1);
});
<commit_msg>chore(deps): support xo@0.14<commit_after>'use strict';
import test from 'ava';
import getSetProps from './get-set-props';

test(t => {
	t.true(Object.keys(getSetProps).length > 0);
	t.truthy(getSetProps.hasOwnProperty('Array'));
	t.truthy(getSetProps.hasOwnProperty('Number'));
	t.true(getSetProps.Error.indexOf('stack') !== -1);
});
<|endoftext|>


<commit_before>/*
□ webdriver + chromeのテストを書いていく
□ 最終的にはphantomjsで動作するようにしてコマンドラインでテスト実行できるようにする

1. 初期状態は４つのサイトがstay状態で登録済み
2. 新規追加して保存
3. 更新して保存
4. stay状態のものを削除
5. 新規追加しようとして削除
6. stay状態のものをeditにして削除
*/

describe('初期状態は4つのサイトが登録済み', function() {
	describe('(1/4) facebook https://www.facebook.com/](https://www.facebook.com/', function() {
		it('input表示');
		it('removeボタン表示');
	});
	describe('(2/4) gmail https://mail.google.com/mail](https://mail.google.com/mail', function() {
		it('input表示');
		it('removeボタン表示');
	});
	describe('(3/4) tweetdeck https://web.tweetdeck.com/](https://web.tweetdeck.com/', function() {
		it('input表示');
		it('removeボタン表示');
	});
	describe('(4/4) doit.im https://i.doit.im/home](https://i.doit.im/home', function() {
		it('input表示');
		it('removeボタン表示');
	});
	it('localStorageの登録');
});
describe('新規追加して保存');
describe('更新して保存');
describe('既に登録済みのものを削除');
describe('新規追加しようとして保存せずに削除');
describe('既に登録済みのものを編集中にして削除');<commit_msg>add test skelton<commit_after>/*
□ webdriver + chromeのテストを書いていく
□ 最終的にはphantomjsで動作するようにしてコマンドラインでテスト実行できるようにする

1. 初期状態は４つのサイトがstay状態で登録済み
2. 新規追加して保存
3. 更新して保存
4. stay状態のものを削除
5. 新規追加しようとして削除
6. stay状態のものをeditにして削除
*/
var port = process.env.TEST_PORT || 3333;
var base = 'http://localhost:' + port;

describe('初期状態は4つのサイトが登録済み', function() {
	describe('(1/4) facebook https://www.facebook.com/](https://www.facebook.com/', function() {
		it('input表示');
		it('removeボタン表示');
	});
	describe('(2/4) gmail https://mail.google.com/mail](https://mail.google.com/mail', function() {
		it('input表示');
		it('removeボタン表示');
	});
	describe('(3/4) tweetdeck https://web.tweetdeck.com/](https://web.tweetdeck.com/', function() {
		it('input表示');
		it('removeボタン表示');
	});
	describe('(4/4) doit.im https://i.doit.im/home](https://i.doit.im/home', function() {
		it('input表示');
		it('removeボタン表示');
	});
	it('localStorageの登録');
});
describe('新規追加して保存');
describe('更新して保存');
describe('既に登録済みのものを削除');
describe('新規追加しようとして保存せずに削除');
describe('既に登録済みのものを編集中にして削除');<|endoftext|>


<commit_before>function getPooled (...args) {
  const Klass = this

  if (Klass.instancePool.length) {
    const instance = Klass.instancePool.pop()
    Klass.apply(instance, args)
    return instance
  } else {
    return new Klass(...args)
  }
}

function releaseInstance (instance) {
  const Klass = this
  Klass.instancePool.push(instance)
}

module.exports = function actsAsPoolable (poolSize) {

  return function (Klass) {
    Klass.instancePool = []
    Klass.poolSize = poolSize
    Klass.getPooled = getPooled
    Klass.releaseInstance = releaseInstance

    return Klass
  }

}
<commit_msg>Actually use poolSize<commit_after>function getPooled (...args) {
  const Klass = this

  if (Klass.instancePool.length) {
    const instance = Klass.instancePool.pop()
    Klass.apply(instance, args)
    return instance
  } else {
    return new Klass(...args)
  }
}

function releaseInstance (instance) {
  const Klass = this

  if (Klass.instancePool.length < Klass.poolSize) {
    Klass.instancePool.push(instance)
  }
}

module.exports = function actsAsPoolable (poolSize) {

  return function (Klass) {
    Klass.instancePool = []
    Klass.poolSize = poolSize
    Klass.getPooled = getPooled
    Klass.releaseInstance = releaseInstance

    return Klass
  }

}
<|endoftext|>


<commit_before>/*!
 * make-callback <https://github.com/tunnckoCore/make-callback>
 *
 * Copyright (c) 2015 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk)
 * Released under the MIT license.
 */

/* jshint asi:true */

'use strict'

var fs = require('fs')
var test = require('assertit')
var makeCallback = require('./index')

test('make-callback:', function () {
  test('should throw TypeError "is-async-function expect a function"', function (done) {
    function fixture () {
      makeCallback(12345)
    }

    test.throws(fixture, TypeError)
    test.throws(fixture, /is-async-function expect a function/)
    done()
  })
  test('should throw TypeError "make-callback expect sync function', function (done) {
    function fixture () {
      makeCallback(fs.readFile)
    }

    test.throws(fixture, TypeError)
    test.throws(fixture, /make-callback expect sync function/)
    done()
  })
  test('should throw TypeError "async `fn` expect a callback"', function (done) {
    function fixture () {
      var JSONParseAsync = makeCallback(JSON.parse)
      JSONParseAsync('{"foo":"bar"}')
    }

    test.throws(fixture, TypeError)
    test.throws(fixture, /async `fn` expect a callback/)
    done()
  })
  test('should pass result to callback', function (done) {
    var JSONParseAsync = makeCallback(JSON.parse)

    JSONParseAsync('{"foo":"bar"}', function (err, json) {
      test.ifError(err)
      test.deepEqual(json, {foo: 'bar'})
      done()
    })
  })
  test('should pass error to callback', function (done) {
    var JSONParseAsync = makeCallback(JSON.parse)

    JSONParseAsync('foo bar baz', function (err, json) {
      test.ok(err)
      test.ifError(!err)
      test.equal(err.message, 'Unexpected token o')
      done()
    })
  })
})
<commit_msg>add more tests, close #2<commit_after>/*!
 * make-callback <https://github.com/tunnckoCore/make-callback>
 *
 * Copyright (c) 2015 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk)
 * Released under the MIT license.
 */

/* jshint asi:true */

'use strict'

var fs = require('fs')
var test = require('assertit')
var makeCallback = require('./index')

test('make-callback:', function () {
  test('should throw TypeError "is-async-function expect a function"', function (done) {
    function fixture () {
      makeCallback(12345)
    }

    test.throws(fixture, TypeError)
    test.throws(fixture, /is-async-function expect a function/)
    done()
  })
  test('should throw TypeError "make-callback expect sync function', function (done) {
    function fixture () {
      makeCallback(fs.readFile)
    }

    test.throws(fixture, TypeError)
    test.throws(fixture, /make-callback expect sync function/)
    done()
  })
  test('should throw TypeError "async `fn` expect a callback"', function (done) {
    function fixture () {
      var JSONParseAsync = makeCallback(JSON.parse)
      JSONParseAsync('{"foo":"bar"}')
    }

    test.throws(fixture, TypeError)
    test.throws(fixture, /async `fn` expect a callback/)
    done()
  })
  test('should pass result to callback', function (done) {
    var JSONParseAsync = makeCallback(JSON.parse)

    JSONParseAsync('{"foo":"bar"}', function (err, res) {
      test.ifError(err)
      test.deepEqual(res, {foo: 'bar'})
      done()
    })
  })
  test('should pass error to callback', function (done) {
    var JSONParseAsync = makeCallback(JSON.parse)

    JSONParseAsync('foo bar baz', function (err) {
      test.ok(err)
      test.ifError(!err)
      test.equal(err.message, 'Unexpected token o')
      done()
    })
  })
  test('should pass contents of file to callback (when readFileSync)', function (done) {
    var readFile = makeCallback(fs.readFileSync)

    readFile('./package.json', 'utf8', function (err, res) {
      test.ifError(err)
      test.ok(res.indexOf('tunnckoCore/make-callback') !== -1)
      done()
    })
  })
  test('should pass errors to callback (when readFileSync)', function (done) {
    var readFile = makeCallback(fs.readFileSync)

    readFile('./packdsgfdfgdfgage.json', 'utf8', function (err, res) {
      test.ifError(!err)
      test.equal(err.code, 'ENOENT')
      test.ok(err.message.indexOf('no such file') !== -1)
      done()
    })
  })
})
<|endoftext|>


<commit_before>// For authoring Nightwatch tests, see
// http://nightwatchjs.org/guide#usage

function pretty (str) {
  return str.replace(/-/g, '−').replace(/\./g, ',').replace(/\//g, '÷').replace(/\*/g, '×')
}

function toCssClass (char) {
  if (char === 'C') {
    return 'CA'
  }
  if (char === 'B') {
    return 'Backspace'
  }
  if (char === 'R') {
    return 'Randon'
  }
  if (char === '/') {
    return 'Divide'
  }
  if (char === '*') {
    return 'Multiply'
  }
  if (char === '-') {
    return 'Minus'
  }
  if (char === '+') {
    return 'Plus'
  }
  if (char === '.') {
    return 'Period'
  }
  if (char === 'S') {
    return 'Sign'
  }
  if (char === '=') {
    return 'Equal'
  }
  return char
}

function expression (clicks, expressionDisplay, resultDisplay, browser, devServer) {
  expressionDisplay = pretty(expressionDisplay)
  resultDisplay = pretty(resultDisplay)
  browser
    .url(devServer)
    .waitForElementVisible('#app', 5000)
    .assert.elementPresent('.calculator')
  for (var i = 0, len = clicks.length; i < len; i++) {
    const selector = '.btn' + toCssClass(clicks[i])
    browser.waitForElementVisible(selector, 100)
    browser.click(selector);
  }
  browser
    .assert.containsText('.expression', expressionDisplay)
    .assert.containsText('.result', resultDisplay)

}

module.exports = {
  'default e2e tests': function (browser) {
    // automatically uses dev Server port from /config.index.js
    // default: http://localhost:8080
    // see nightwatch.conf.js
    const devServer = browser.globals.devServerURL

    expression('', '', '', browser, devServer)
    expression('2+3', '2 + 3', '5', browser, devServer)
    browser.end()
  }
}
<commit_msg>first tests<commit_after>// For authoring Nightwatch tests, see
// http://nightwatchjs.org/guide#usage

function pretty (str) {
  return str.replace(/-/g, '−').replace(/\./g, ',').replace(/\//g, '÷').replace(/\*/g, '×')
}

function toCssClass (char) {
  if (char === 'C') {
    return 'CA'
  }
  if (char === 'B') {
    return 'Backspace'
  }
  if (char === 'R') {
    return 'Randon'
  }
  if (char === '/') {
    return 'Divide'
  }
  if (char === '*') {
    return 'Multiply'
  }
  if (char === '-') {
    return 'Minus'
  }
  if (char === '+') {
    return 'Plus'
  }
  if (char === '.') {
    return 'Period'
  }
  if (char === 'S') {
    return 'Sign'
  }
  if (char === '=') {
    return 'Equal'
  }
  return char
}

function expression (clicks, expressionDisplay, resultDisplay, browser, devServer) {
  expressionDisplay = expressionDisplay === null ? null : pretty(expressionDisplay)
  resultDisplay = pretty(resultDisplay)
  browser
    .url(devServer)
    .waitForElementVisible('#app', 5000)
    .assert.elementPresent('.calculator')
  for (var i = 0, len = clicks.length; i < len; i++) {
    const selector = '.btn' + toCssClass(clicks[i])
    browser.waitForElementVisible(selector, 100)
    browser.click(selector);
  }
  if (expressionDisplay !== null) {
    browser.assert.containsText('.expression', expressionDisplay)
  }
  browser.assert.containsText('.result', resultDisplay)
  return browser
}

module.exports = {
  'empty state': function (browser) {
    // automatically uses dev Server port from /config.index.js
    // default: http://localhost:8080
    // see nightwatch.conf.js
    const devServer = browser.globals.devServerURL

    expression('', '', '', browser, devServer)

    browser.end()
  },
  'one button': function (browser) {
    const devServer = browser.globals.devServerURL

    expression('1', '1', '', browser, devServer)
    expression('2', '2', '', browser, devServer)
    expression('3', '3', '', browser, devServer)
    expression('4', '4', '', browser, devServer)
    expression('5', '5', '', browser, devServer)
    expression('6', '6', '', browser, devServer)
    expression('7', '7', '', browser, devServer)
    expression('8', '8', '', browser, devServer)
    expression('9', '9', '', browser, devServer)
    expression('0', '', '', browser, devServer)
    expression('01', '1', '', browser, devServer)

    expression('R', null, '', browser, devServer)
    //  .assert.containsText('.expression', expressionDisplay)

    expression('C', '', '', browser, devServer)
    expression('B', '', '', browser, devServer)
    expression('/', '', '', browser, devServer)
    expression('*', '', '', browser, devServer)
    expression('-', '', '', browser, devServer)
    expression('+', '', '', browser, devServer)
    expression('.', '0.', '', browser, devServer)
    expression('S', '', '', browser, devServer)
    expression('=', '', '', browser, devServer)

    browser.end()
  },
  'button + operation': function (browser) {
    const devServer = browser.globals.devServerURL

    //expression('1R', null, '', browser, devServer)
    expression('1+', '1 +', '', browser, devServer)
    expression('1-', '1 -', '', browser, devServer)
    expression('1*', '1 *', '', browser, devServer)
    expression('1/', '1 /', '', browser, devServer)
    expression('1S', '(-1)', '', browser, devServer)
    expression('1.', '1.', '', browser, devServer)
    expression('1C', '', '', browser, devServer)
    expression('1B', '', '', browser, devServer)
    expression('12C', '', '', browser, devServer)
    expression('12B', '1', '', browser, devServer)
    expression('1=', '1', '1', browser, devServer)

    browser.end()
  },
  'button + operation + operation': function (browser) {
    const devServer = browser.globals.devServerURL

    expression('1RR', null, '', browser, devServer)
    //TODO: castom assert for random
    //  .assert.containsText('.expression', expressionDisplay)

    //expression('1R', null, '', browser, devServer)
    expression('1+*', '1 +', '', browser, devServer)
    expression('1-/', '1 -', '', browser, devServer)
    expression('1*-', '1 *', '', browser, devServer)
    expression('1/+', '1 /', '', browser, devServer)
    expression('1SS', '1', '', browser, devServer)
    expression('0SS', '', '', browser, devServer)
    expression('1..', '1.', '', browser, devServer)
    expression('1CC', '', '', browser, devServer)
    expression('1BB', '', '', browser, devServer)
    expression('12CC', '', '', browser, devServer)
    expression('12BB', '', '', browser, devServer)
    expression('123BB', '1', '', browser, devServer)
    expression('1==', '1', '1', browser, devServer)

    browser.end()
  },
  'one full operation': function (browser) {
    const devServer = browser.globals.devServerURL

    expression('1+2', '1 + 2', '3', browser, devServer)
    expression('1-2', '1 - 2', '-1', browser, devServer)
    expression('1*2', '1 * 2', '2', browser, devServer)
    expression('1/2', '1 / 2', '0.5', browser, devServer)
    expression('1+2S', '1 + (-2)', '-1', browser, devServer)
    expression('1.2', '1.2', '', browser, devServer)
    expression('1+2C', '', '', browser, devServer)
    expression('1+2=', '3', '', browser, devServer)

    browser.end()
  },
  'two full operations': function (browser) {
    const devServer = browser.globals.devServerURL

    expression('1+2-3', '1 + 2 - 3', '0', browser, devServer)
    expression('1-2*3', '1 - 2 * 3', '-3', browser, devServer)
    expression('1*2+1', '1 * 2 + 1', '3', browser, devServer)
    expression('1/2*3', '1 / 2 * 3', '1.5', browser, devServer)
    expression('1+2S+5', '1 + (-2) + 5', '4', browser, devServer)
    expression('1.2 + 2', '1.2 + 2', '3.2', browser, devServer)
    expression('1+2/3C', '', '', browser, devServer)
    expression('1+2-3=', '', '', browser, devServer)
    expression('1+2-4=', '(-1)', '', browser, devServer)

    browser.end()
  },
  'first zero': function (browser) {
    const devServer = browser.globals.devServerURL

    expression('01', '1', '', browser, devServer)
    expression('0+', '', '', browser, devServer)
    expression('0-', '', '', browser, devServer)
    expression('0*', '', '', browser, devServer)
    expression('0/', '', '', browser, devServer)
    expression('0=', '', '', browser, devServer)
    expression('0C', '', '', browser, devServer)
    expression('0B', '', '', browser, devServer)
    expression('0S', '', '', browser, devServer)
    expression('0.', '0,', '', browser, devServer)

    browser.end()
  },
  'edge cases': function (browser) {
    const devServer = browser.globals.devServerURL

    expression('1,+', '1 +', '', browser, devServer)
    expression('1,+2,3', '1 + 2.3', '3.3', browser, devServer)
    expression('1,1+2,3', '1.1 + 2.3', '3.4', browser, devServer)

    expression('3+2*', '3 + 2 *', '', browser, devServer)
    expression('4+2B', '4 +', '', browser, devServer)
    expression('2+3=99', '599', '', browser, devServer)
    expression('/=', '', '', browser, devServer)

    browser.end()
  }
}
<|endoftext|>