<commit_before>/*jslint node: true */
'use strict';

const Stopwatch = require('../lib/Stopwatch');
const defaultPrecision = 15;
const assert = require('assert');
const should = require('should');

//TODO:
//replace with: statman.TestHelper.assertCloseEnough(testtime, delta, defaultPrecision);
function verifyDelta(expected, actual, acceptedconstiance) {
    const lowerThreshold = expected - acceptedconstiance;
    const upperThreshold = expected + acceptedconstiance;
    const message = 'Expected ' + expected + ' ± ' + acceptedconstiance + ', was ' + actual + '.';
    assert.ok((actual >= lowerThreshold) && (actual <= upperThreshold), message);
}

describe('stopwatch', function () {
    this.timeout(5000);

    describe('constructor', function () {
        it('w/no params', function () {
            const stopwatch = new Stopwatch();
            should.exist(stopwatch);
        });

        it('w/name as first param', function () {
            const stopwatch = new Stopwatch('metric-name');
            stopwatch.name().should.equal('metric-name');
        });

        it('w/autostart as first param', function () {
            const stopwatch = new Stopwatch(true);
            should.exist(stopwatch.name());
            stopwatch.name().should.not.equal(true);
        });

        it('w/both name and autostart', function () {
            const stopwatch = new Stopwatch('metric-name', true);
            stopwatch.name().should.equal('metric-name');
        });

        it('autocreated names are not constant', function () {
            const stopwatch1 = new Stopwatch(true);
            const stopwatch2 = new Stopwatch(true);
            stopwatch1.name().should.not.equal(stopwatch2.name());
        });
    });

    it('start and read (100ms)', function (done) {
        const testtime = 100;

        const stopwatch = new Stopwatch();
        stopwatch.start();
        setTimeout(function () {
            const delta = stopwatch.read();
            verifyDelta(testtime, delta, defaultPrecision);
            done();
        }, testtime);
    });

    it('start and read (10ms)', function (done) {
        const testtime = 10;

        const stopwatch = new Stopwatch();
        stopwatch.start();
        setTimeout(function () {
            const delta = stopwatch.read();
            verifyDelta(testtime, delta, defaultPrecision);
            done();
        }, testtime);
    });

    it('autostart set to true automatically starts stopwatch', function (done) {
        const testtime = 10;

        const stopwatch = new Stopwatch(true);
        setTimeout(function () {
            const delta = stopwatch.read();
            verifyDelta(testtime, delta, defaultPrecision);
            done();
        }, testtime);
    });

    it('autostart set to false does NOT automatically start stopwatch', function (done) {
        const testtime = 10;

        const stopwatch = new Stopwatch(false);
        setTimeout(function () {
            stopwatch.read().should.be.NaN();
            done();
        }, testtime);
    });

    it('with two stopwatches, do independent reads of each', function (done) {
        const stopwatch1 = new Stopwatch();
        const stopwatch2 = new Stopwatch();

        stopwatch1.start();

        //start first stopwatch, then do a read .3s later
        const testtimeA = 300;
        setTimeout(function () {
            const delta1 = stopwatch1.read();
            verifyDelta(testtimeA, delta1, defaultPrecision);
        }, testtimeA);

        //start second stopwatch .1s second after the first, then do a read .5s later
        const testtimeB = 500;
        setTimeout(function () {
            stopwatch2.start();
            setTimeout(function () {
                const delta2 = stopwatch2.read();
                verifyDelta(testtimeB, delta2, defaultPrecision);
                done();
            }, testtimeB);
        }, 100);
    });

    it('start, stop, and read should return the time at stop', function (done) {
        const testtime = 100;

        const stopwatch = new Stopwatch();
        stopwatch.start();
        setTimeout(function () {
            stopwatch.stop();

            setTimeout(function () {
                const delta = stopwatch.read();
                verifyDelta(testtime, delta, defaultPrecision);
                done();
            }, 500);
        }, testtime);
    });

    it('can restart a stopwatch', function () {
        const testtime = 100;

        const stopwatch = new Stopwatch();
        stopwatch.start();
        stopwatch.stop();
        stopwatch.start();
    });

    it('performing read without start() or stop() returns NaN', function (done) {
        const stopwatch = new Stopwatch();
        assert.ok(isNaN(stopwatch.read()));
        done();
    });

    it('performing read without start() returns NaN', function (done) {
        const stopwatch = new Stopwatch();
        stopwatch.stop();
        assert.ok(isNaN(stopwatch.read()));
        done();
    });

    it('executing stop twice should return time at second stop', function (done) {
        //start(), wait .1s, stop(), wait .2s, stop(), wait .5s, read(), ensure delta = .3s
        const stopwatch = new Stopwatch();
        stopwatch.start();
        setTimeout(function () {
            stopwatch.stop();

            setTimeout(function () {
                verifyDelta(100 + 200, stopwatch.stop(), defaultPrecision);

                setTimeout(function () {
                    const delta = stopwatch.read();
                    verifyDelta(100 + 200, delta, defaultPrecision);
                    done();
                }, 500);
            }, 200);
        }, 100);
    });

    it('ensure that stop() returns time', function (done) {
        const testtime = 100;
        const stopwatch = new Stopwatch();
        stopwatch.start();
        setTimeout(function () {
            const delta = stopwatch.stop();
            verifyDelta(testtime, delta, defaultPrecision);
            done();
        }, testtime);
    });

    describe('start time delta', function() {
        it('start at specific time delta and read (100ms)', function (done) {
            const initialStartTimeDelta = 500;
            const testtime = 100;

            const stopwatch = new Stopwatch();
            stopwatch.setStartTimeDelta(initialStartTimeDelta);
            stopwatch.start();
            setTimeout(function () {
                const delta = stopwatch.read();
                verifyDelta(testtime + initialStartTimeDelta, delta, defaultPrecision);
                done();
            }, testtime);
        });

        it('autostart set to true automatically starts stopwatch', function (done) {
            const stopwatchName = 'x';
            const initialStartTimeDelta = 500;
            const testtime = 10;

            const stopwatch = new Stopwatch(stopwatchName, true, initialStartTimeDelta);
            setTimeout(function () {
                const delta = stopwatch.read();
                verifyDelta(testtime + initialStartTimeDelta, delta, defaultPrecision);
                done();
            }, testtime);
        });

        it('autostart set to false does NOT automatically start stopwatch', function (done) {
            const initialStartTimeDelta = 500;
            const testtime = 10;

            const stopwatch = new Stopwatch(false);
            stopwatch.setStartTimeDelta(initialStartTimeDelta);
            setTimeout(function () {
                stopwatch.read().should.be.NaN();
                done();
            }, testtime);
        });
    });

    describe('toString()', function () {
        it('idle', function () {
            const stopwatch = new Stopwatch('sw');
            //[sw => state:init; value:NaN]
            stopwatch.toString().should.containEql('state:init');
            stopwatch.toString().should.containEql('value:');
        });
        it('started', function () {
            const stopwatch = new Stopwatch('sw', true);
            //[sw => state:running; value:0.01]
            stopwatch.toString().should.containEql('state:running');
            stopwatch.toString().should.containEql('value:0');
        });
        it('stopped', function () {
            const stopwatch = new Stopwatch('sw', true);
            stopwatch.stop();
            //[sw => state:stopped; value:0.01]
            stopwatch.toString().should.containEql('state:stopped');
            stopwatch.toString().should.containEql('value:0');
        });
    });

    // https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/StopWatch.html
    describe('java stopwatch compliance', function () {
        it('time should equal read on a running stopwatch', function () {
            //TODO: list time as alias of read
            const stopwatch = new Stopwatch('sw');
            stopwatch.start();

            const readTime = stopwatch.read();
            const time = stopwatch.time();

            verifyDelta(readTime, time, 10);
        });
        it('time should equal read on a stopped stopwatch', function (done) {
            //TODO: list time as alias of read
            const stopwatch = new Stopwatch('sw');
            stopwatch.start();
            setTimeout(function () {
                stopwatch.stop();
                stopwatch.read().should.be.equal(stopwatch.time());
                done();
            }, 10);

        });
        describe('reset', function () {
            it('resetting a not-started stopwatch should have no effect', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.reset();
                stopwatch.state().should.be.equal('init');
            });
            it('resetting a started stopwatch should bring it back to init', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.reset();
                should.not.exist(stopwatch.startTime);
                should.not.exist(stopwatch.stopTime);
                stopwatch.state().should.be.equal('init');
            });
            it('resetting a stopped stopwatch should bring it back to init', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.stop();
                stopwatch.reset();
                should.not.exist(stopwatch.startTime);
                should.not.exist(stopwatch.stopTime);
                stopwatch.state().should.be.equal('init');
            });
            it('resetting a split stopwatch should bring it back to init', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.split();
                stopwatch.reset();
                should.not.exist(stopwatch.startTime);
                should.not.exist(stopwatch.stopTime);
                stopwatch.state().should.be.equal('init');
            });
        });
        describe('split', function () {
            it('splitTime() will return the split time', function (done) {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();

                setTimeout(function () {
                    stopwatch.split();
                    setTimeout(function () {
                        verifyDelta(100, stopwatch.splitTime(), 10);
                        done();
                    }, 200);
                }, 100);
            });
            it('on split, time/read will return the split time', function (done) {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();

                setTimeout(function () {
                    stopwatch.split();
                    setTimeout(function () {
                        verifyDelta(100, stopwatch.time(), 10);
                        verifyDelta(100, stopwatch.read(), 10);
                        done();
                    }, 200);
                }, 100);
            });
            it('cannot call get splitTime on a init stopwatch', function () {
                const stopwatch = new Stopwatch('sw');
                assert.throws(
                    function () {
                        stopwatch.splitTime();
                    },
                    Error);
            });
            it('cannot call get splitTime() on a running stopwatch', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                assert.throws(
                    function () {
                        stopwatch.splitTime();
                    },
                    Error);
            });
            it('cannot call get splitTime() on a stopped stopwatch', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.stop();
                assert.throws(
                    function () {
                        stopwatch.splitTime();
                    },
                    Error);
            });
            it('cannot call get splitTime() folllowing unsplit', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.split();
                stopwatch.unsplit();
                assert.throws(
                    function () {
                        stopwatch.splitTime();
                    },
                    Error);
            });
            it('cannot split a init stopwatch', function () {
                const stopwatch = new Stopwatch('sw');
                assert.throws(
                    function () {
                        stopwatch.split();
                    },
                    Error);
            });
            it('cannot split a split stopwatch (for now, this may change)', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.split();
                assert.throws(
                    function () {
                        stopwatch.split();
                    },
                    Error);
            });
            it('cannot split a stopped stopwatch', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.stop();
                assert.throws(
                    function () {
                        stopwatch.split();
                    },
                    Error);
            });
            it('unsplit, time returns time from start', function (done) {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                setTimeout(function () {
                    stopwatch.split();
                    setTimeout(function () {
                        stopwatch.unsplit();
                        verifyDelta(50 + 75, stopwatch.time(), 20);
                        done();
                    }, 75);
                }, 50);
            });
            it('cannot unsplit a init stopwatch', function () {
                const stopwatch = new Stopwatch('sw');
                assert.throws(
                    function () {
                        stopwatch.unsplit();
                    },
                    Error);
            });
            it('cannot unsplit a running stopwatch', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                assert.throws(
                    function () {
                        stopwatch.unsplit();
                    },
                    Error);
            });
            it('cannot unsplit a stopped stopwatch', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.stop();
                assert.throws(
                    function () {
                        stopwatch.unsplit();
                    },
                    Error);
            });
        });
        it.skip('suspend/resume', function () {
            // This method suspends the watch until it is resumed. The watch will not include time between the suspend and resume calls in the total time.
            // IllegalStateException - if the StopWatch is not currently running.
            // IllegalStateException - if the StopWatch has not been suspended.
        });
        it('cannot start a running stopwatch', function () {
            const stopwatch = new Stopwatch('sw');
            stopwatch.start();
            assert.throws(
                function () {
                    stopwatch.start();
                },
                Error);
        });
        it('cannot start a split stopwatch', function () {
            const stopwatch = new Stopwatch('sw');
            stopwatch.start();
            stopwatch.split();
            assert.throws(
                function () {
                    stopwatch.start();
                },
                Error);
        });
        it('cannot stop a init stopwatch', function () {
            const stopwatch = new Stopwatch('sw');
            stopwatch.start();
            stopwatch.split();
            assert.throws(
                function () {
                    stopwatch.start();
                },
                Error);
        });
        it('cannot stop a stopped stopwatch', function () {
            const stopwatch = new Stopwatch('sw');
            stopwatch.start();
            stopwatch.split();
            assert.throws(
                function () {
                    stopwatch.start();
                },
                Error);
        });
    });
});

<commit_msg>test that cannot set delta on running stop watch<commit_after>/*jslint node: true */
'use strict';

const Stopwatch = require('../lib/Stopwatch');
const defaultPrecision = 15;
const assert = require('assert');
const should = require('should');

//TODO:
//replace with: statman.TestHelper.assertCloseEnough(testtime, delta, defaultPrecision);
function verifyDelta(expected, actual, acceptedconstiance) {
    const lowerThreshold = expected - acceptedconstiance;
    const upperThreshold = expected + acceptedconstiance;
    const message = 'Expected ' + expected + ' ± ' + acceptedconstiance + ', was ' + actual + '.';
    assert.ok((actual >= lowerThreshold) && (actual <= upperThreshold), message);
}

describe('stopwatch', function () {
    this.timeout(5000);

    describe('constructor', function () {
        it('w/no params', function () {
            const stopwatch = new Stopwatch();
            should.exist(stopwatch);
        });

        it('w/name as first param', function () {
            const stopwatch = new Stopwatch('metric-name');
            stopwatch.name().should.equal('metric-name');
        });

        it('w/autostart as first param', function () {
            const stopwatch = new Stopwatch(true);
            should.exist(stopwatch.name());
            stopwatch.name().should.not.equal(true);
        });

        it('w/both name and autostart', function () {
            const stopwatch = new Stopwatch('metric-name', true);
            stopwatch.name().should.equal('metric-name');
        });

        it('autocreated names are not constant', function () {
            const stopwatch1 = new Stopwatch(true);
            const stopwatch2 = new Stopwatch(true);
            stopwatch1.name().should.not.equal(stopwatch2.name());
        });
    });

    it('start and read (100ms)', function (done) {
        const testtime = 100;

        const stopwatch = new Stopwatch();
        stopwatch.start();
        setTimeout(function () {
            const delta = stopwatch.read();
            verifyDelta(testtime, delta, defaultPrecision);
            done();
        }, testtime);
    });

    it('start and read (10ms)', function (done) {
        const testtime = 10;

        const stopwatch = new Stopwatch();
        stopwatch.start();
        setTimeout(function () {
            const delta = stopwatch.read();
            verifyDelta(testtime, delta, defaultPrecision);
            done();
        }, testtime);
    });

    it('autostart set to true automatically starts stopwatch', function (done) {
        const testtime = 10;

        const stopwatch = new Stopwatch(true);
        setTimeout(function () {
            const delta = stopwatch.read();
            verifyDelta(testtime, delta, defaultPrecision);
            done();
        }, testtime);
    });

    it('autostart set to false does NOT automatically start stopwatch', function (done) {
        const testtime = 10;

        const stopwatch = new Stopwatch(false);
        setTimeout(function () {
            stopwatch.read().should.be.NaN();
            done();
        }, testtime);
    });

    it('with two stopwatches, do independent reads of each', function (done) {
        const stopwatch1 = new Stopwatch();
        const stopwatch2 = new Stopwatch();

        stopwatch1.start();

        //start first stopwatch, then do a read .3s later
        const testtimeA = 300;
        setTimeout(function () {
            const delta1 = stopwatch1.read();
            verifyDelta(testtimeA, delta1, defaultPrecision);
        }, testtimeA);

        //start second stopwatch .1s second after the first, then do a read .5s later
        const testtimeB = 500;
        setTimeout(function () {
            stopwatch2.start();
            setTimeout(function () {
                const delta2 = stopwatch2.read();
                verifyDelta(testtimeB, delta2, defaultPrecision);
                done();
            }, testtimeB);
        }, 100);
    });

    it('start, stop, and read should return the time at stop', function (done) {
        const testtime = 100;

        const stopwatch = new Stopwatch();
        stopwatch.start();
        setTimeout(function () {
            stopwatch.stop();

            setTimeout(function () {
                const delta = stopwatch.read();
                verifyDelta(testtime, delta, defaultPrecision);
                done();
            }, 500);
        }, testtime);
    });

    it('can restart a stopwatch', function () {
        const testtime = 100;

        const stopwatch = new Stopwatch();
        stopwatch.start();
        stopwatch.stop();
        stopwatch.start();
    });

    it('performing read without start() or stop() returns NaN', function (done) {
        const stopwatch = new Stopwatch();
        assert.ok(isNaN(stopwatch.read()));
        done();
    });

    it('performing read without start() returns NaN', function (done) {
        const stopwatch = new Stopwatch();
        stopwatch.stop();
        assert.ok(isNaN(stopwatch.read()));
        done();
    });

    it('executing stop twice should return time at second stop', function (done) {
        //start(), wait .1s, stop(), wait .2s, stop(), wait .5s, read(), ensure delta = .3s
        const stopwatch = new Stopwatch();
        stopwatch.start();
        setTimeout(function () {
            stopwatch.stop();

            setTimeout(function () {
                verifyDelta(100 + 200, stopwatch.stop(), defaultPrecision);

                setTimeout(function () {
                    const delta = stopwatch.read();
                    verifyDelta(100 + 200, delta, defaultPrecision);
                    done();
                }, 500);
            }, 200);
        }, 100);
    });

    it('ensure that stop() returns time', function (done) {
        const testtime = 100;
        const stopwatch = new Stopwatch();
        stopwatch.start();
        setTimeout(function () {
            const delta = stopwatch.stop();
            verifyDelta(testtime, delta, defaultPrecision);
            done();
        }, testtime);
    });

    describe('start time delta', function() {
        it('start at specific time delta and read (100ms)', function (done) {
            const initialStartTimeDelta = 500;
            const testtime = 100;

            const stopwatch = new Stopwatch();
            stopwatch.setStartTimeDelta(initialStartTimeDelta);
            stopwatch.start();
            setTimeout(function () {
                const delta = stopwatch.read();
                verifyDelta(testtime + initialStartTimeDelta, delta, defaultPrecision);
                done();
            }, testtime);
        });

        it('cannot change autostart on running stopwatch', function (done) {
            const initialStartTimeDelta = 500;
            const testtime = 100;

            const stopwatch = new Stopwatch();
            stopwatch.start();

            setTimeout(function () {
                assert.throws(
                    function () {
                        stopwatch.setStartTimeDelta(initialStartTimeDelta);
                        done();
                    },
                    Error);
                done();
            }, testtime);
        });

        it('autostart set to true automatically starts stopwatch', function (done) {
            const stopwatchName = 'x';
            const initialStartTimeDelta = 500;
            const testtime = 10;

            const stopwatch = new Stopwatch(stopwatchName, true, initialStartTimeDelta);
            setTimeout(function () {
                const delta = stopwatch.read();
                verifyDelta(testtime + initialStartTimeDelta, delta, defaultPrecision);
                done();
            }, testtime);
        });

        it('autostart set to false does NOT automatically start stopwatch', function (done) {
            const initialStartTimeDelta = 500;
            const testtime = 10;

            const stopwatch = new Stopwatch(false);
            stopwatch.setStartTimeDelta(initialStartTimeDelta);
            setTimeout(function () {
                stopwatch.read().should.be.NaN();
                done();
            }, testtime);
        });
    });

    describe('toString()', function () {
        it('idle', function () {
            const stopwatch = new Stopwatch('sw');
            //[sw => state:init; value:NaN]
            stopwatch.toString().should.containEql('state:init');
            stopwatch.toString().should.containEql('value:');
        });
        it('started', function () {
            const stopwatch = new Stopwatch('sw', true);
            //[sw => state:running; value:0.01]
            stopwatch.toString().should.containEql('state:running');
            stopwatch.toString().should.containEql('value:0');
        });
        it('stopped', function () {
            const stopwatch = new Stopwatch('sw', true);
            stopwatch.stop();
            //[sw => state:stopped; value:0.01]
            stopwatch.toString().should.containEql('state:stopped');
            stopwatch.toString().should.containEql('value:0');
        });
    });

    // https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/StopWatch.html
    describe('java stopwatch compliance', function () {
        it('time should equal read on a running stopwatch', function () {
            //TODO: list time as alias of read
            const stopwatch = new Stopwatch('sw');
            stopwatch.start();

            const readTime = stopwatch.read();
            const time = stopwatch.time();

            verifyDelta(readTime, time, 10);
        });
        it('time should equal read on a stopped stopwatch', function (done) {
            //TODO: list time as alias of read
            const stopwatch = new Stopwatch('sw');
            stopwatch.start();
            setTimeout(function () {
                stopwatch.stop();
                stopwatch.read().should.be.equal(stopwatch.time());
                done();
            }, 10);

        });
        describe('reset', function () {
            it('resetting a not-started stopwatch should have no effect', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.reset();
                stopwatch.state().should.be.equal('init');
            });
            it('resetting a started stopwatch should bring it back to init', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.reset();
                should.not.exist(stopwatch.startTime);
                should.not.exist(stopwatch.stopTime);
                stopwatch.state().should.be.equal('init');
            });
            it('resetting a stopped stopwatch should bring it back to init', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.stop();
                stopwatch.reset();
                should.not.exist(stopwatch.startTime);
                should.not.exist(stopwatch.stopTime);
                stopwatch.state().should.be.equal('init');
            });
            it('resetting a split stopwatch should bring it back to init', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.split();
                stopwatch.reset();
                should.not.exist(stopwatch.startTime);
                should.not.exist(stopwatch.stopTime);
                stopwatch.state().should.be.equal('init');
            });
        });
        describe('split', function () {
            it('splitTime() will return the split time', function (done) {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();

                setTimeout(function () {
                    stopwatch.split();
                    setTimeout(function () {
                        verifyDelta(100, stopwatch.splitTime(), 10);
                        done();
                    }, 200);
                }, 100);
            });
            it('on split, time/read will return the split time', function (done) {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();

                setTimeout(function () {
                    stopwatch.split();
                    setTimeout(function () {
                        verifyDelta(100, stopwatch.time(), 10);
                        verifyDelta(100, stopwatch.read(), 10);
                        done();
                    }, 200);
                }, 100);
            });
            it('cannot call get splitTime on a init stopwatch', function () {
                const stopwatch = new Stopwatch('sw');
                assert.throws(
                    function () {
                        stopwatch.splitTime();
                    },
                    Error);
            });
            it('cannot call get splitTime() on a running stopwatch', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                assert.throws(
                    function () {
                        stopwatch.splitTime();
                    },
                    Error);
            });
            it('cannot call get splitTime() on a stopped stopwatch', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.stop();
                assert.throws(
                    function () {
                        stopwatch.splitTime();
                    },
                    Error);
            });
            it('cannot call get splitTime() folllowing unsplit', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.split();
                stopwatch.unsplit();
                assert.throws(
                    function () {
                        stopwatch.splitTime();
                    },
                    Error);
            });
            it('cannot split a init stopwatch', function () {
                const stopwatch = new Stopwatch('sw');
                assert.throws(
                    function () {
                        stopwatch.split();
                    },
                    Error);
            });
            it('cannot split a split stopwatch (for now, this may change)', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.split();
                assert.throws(
                    function () {
                        stopwatch.split();
                    },
                    Error);
            });
            it('cannot split a stopped stopwatch', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.stop();
                assert.throws(
                    function () {
                        stopwatch.split();
                    },
                    Error);
            });
            it('unsplit, time returns time from start', function (done) {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                setTimeout(function () {
                    stopwatch.split();
                    setTimeout(function () {
                        stopwatch.unsplit();
                        verifyDelta(50 + 75, stopwatch.time(), 20);
                        done();
                    }, 75);
                }, 50);
            });
            it('cannot unsplit a init stopwatch', function () {
                const stopwatch = new Stopwatch('sw');
                assert.throws(
                    function () {
                        stopwatch.unsplit();
                    },
                    Error);
            });
            it('cannot unsplit a running stopwatch', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                assert.throws(
                    function () {
                        stopwatch.unsplit();
                    },
                    Error);
            });
            it('cannot unsplit a stopped stopwatch', function () {
                const stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.stop();
                assert.throws(
                    function () {
                        stopwatch.unsplit();
                    },
                    Error);
            });
        });
        it.skip('suspend/resume', function () {
            // This method suspends the watch until it is resumed. The watch will not include time between the suspend and resume calls in the total time.
            // IllegalStateException - if the StopWatch is not currently running.
            // IllegalStateException - if the StopWatch has not been suspended.
        });
        it('cannot start a running stopwatch', function () {
            const stopwatch = new Stopwatch('sw');
            stopwatch.start();
            assert.throws(
                function () {
                    stopwatch.start();
                },
                Error);
        });
        it('cannot start a split stopwatch', function () {
            const stopwatch = new Stopwatch('sw');
            stopwatch.start();
            stopwatch.split();
            assert.throws(
                function () {
                    stopwatch.start();
                },
                Error);
        });
        it('cannot stop a init stopwatch', function () {
            const stopwatch = new Stopwatch('sw');
            stopwatch.start();
            stopwatch.split();
            assert.throws(
                function () {
                    stopwatch.start();
                },
                Error);
        });
        it('cannot stop a stopped stopwatch', function () {
            const stopwatch = new Stopwatch('sw');
            stopwatch.start();
            stopwatch.split();
            assert.throws(
                function () {
                    stopwatch.start();
                },
                Error);
        });
    });
});

<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');

describe('beta', function() {
  describe('npm dryrun', function() {
    before(function() {
      this.timeout(60000);
      return helpers.run(path.join(__dirname, '../generators/beta'))
        .withPrompts({
          sourceDeliveryType: 'npm',
          sourceDeliveryPackageName: 'nop',
          sourceUsages: ['commonjs'],
          sourcePlatforms: ['node'],
          usePresetValues: false,
          useExistingRepository: false,
          username: 'unional',
          repositoryOrganization: 'typed-typings',
          repositoryName: 'npm-nop',
          repositoryNamePrefix: 'typed-',
          testFramework: 'blue-tape',
          browserTestHarness: 'tap-run+browserify',
          license: 'MIT',
          licenseSignature: 'unional'
        })
        .withOptions({
          skipGit: true
        })
        .toPromise();
    });

    it('creates files', function() {
    });
  });
  describe.skip('http dryrun', function() {
    before(function(done) {
      this.timeout(60000);
      helpers.run(path.join(__dirname, '../generators/beta'))
        .withPrompts({
          sourceDeliveryType: 'http',
          sourceDeliveryPackageName: '6px',
          sourceDeliveryUrl: 'https://cdnjs.cloudflare.com/ajax/libs/6px/1.0.3/6px.min.js',
          sourceUsages: ['script'],
          sourceVersion: '1.0.3',
          sourcePlatforms: ['browser'],
          useExistingRepository: false,
          username: 'unional',
          fullname: 'Homa Wong',
          email: 'homawong@gmail.com',
          repositoryOrganization: 'typed-typings',
          repositoryNamePrefix: 'typed-',
          testFrameworkInNode: 'blue-tape',
          testFrameworkInBrowser: 'blue-tape',
          license: 'MIT'
        })
        .withOptions({
          skipInstall: true
        })
        .on('end', done);
    });

    it('creates files', function() {
    });
  });
  describe.skip('bower dryrun', function() {
    before(function(done) {
      this.timeout(60000);
      helpers.run(path.join(__dirname, '../generators/beta'))
        .withPrompts({
          sourceDeliveryType: 'bower',
          sourceDeliveryPackageName: 'domready',
          sourceUsages: ['commonjs'],
          sourcePlatforms: ['node'],
          useExistingRepository: false,
          username: 'unional',
          repositoryOrganization: 'typed-typings',
          repositoryNamePrefix: 'typed-',
          testFrameworkInNode: 'blue-tape',
          testFrameworkInBrowser: 'blue-tape',
          license: 'MIT'
        })
        .on('end', done);
    });

    it('creates files', function() {
    });
  });
});
<commit_msg>misc update test<commit_after>'use strict';
var path = require('path');
var assert = require('yeoman-assert');
var helpers = require('yeoman-test');

describe('beta', function() {
  describe('npm dryrun', function() {
    before(function() {
      this.timeout(60000);
      return helpers.run(path.join(__dirname, '../generators/beta'))
        .withPrompts({
          sourceDeliveryType: 'npm',
          sourceDeliveryPackageName: 'nop',
          sourceUsages: ['commonjs'],
          sourcePlatforms: ['node'],
          usePresetValues: false,
          useExistingRepository: false,
          username: 'unional',
          repositoryOrganization: 'typed-typings',
          repositoryName: 'npm-nop',
          repositoryNamePrefix: 'typed-',
          testFramework: 'blue-tape',
          browserTestHarness: 'tape-run+jspm',
          license: 'MIT',
          licenseSignature: 'unional'
        })
        .withOptions({
          skipGit: true
        })
        .toPromise();
    });

    it('creates files', function() {
    });
  });
  describe.skip('http dryrun', function() {
    before(function(done) {
      this.timeout(60000);
      helpers.run(path.join(__dirname, '../generators/beta'))
        .withPrompts({
          sourceDeliveryType: 'http',
          sourceDeliveryPackageName: '6px',
          sourceDeliveryUrl: 'https://cdnjs.cloudflare.com/ajax/libs/6px/1.0.3/6px.min.js',
          sourceUsages: ['script'],
          sourceVersion: '1.0.3',
          sourcePlatforms: ['browser'],
          useExistingRepository: false,
          username: 'unional',
          fullname: 'Homa Wong',
          email: 'homawong@gmail.com',
          repositoryOrganization: 'typed-typings',
          repositoryNamePrefix: 'typed-',
          testFrameworkInNode: 'blue-tape',
          testFrameworkInBrowser: 'blue-tape',
          license: 'MIT'
        })
        .withOptions({
          skipInstall: true
        })
        .on('end', done);
    });

    it('creates files', function() {
    });
  });
  describe.skip('bower dryrun', function() {
    before(function(done) {
      this.timeout(60000);
      helpers.run(path.join(__dirname, '../generators/beta'))
        .withPrompts({
          sourceDeliveryType: 'bower',
          sourceDeliveryPackageName: 'domready',
          sourceUsages: ['commonjs'],
          sourcePlatforms: ['node'],
          useExistingRepository: false,
          username: 'unional',
          repositoryOrganization: 'typed-typings',
          repositoryNamePrefix: 'typed-',
          testFrameworkInNode: 'blue-tape',
          testFrameworkInBrowser: 'blue-tape',
          license: 'MIT'
        })
        .on('end', done);
    });

    it('creates files', function() {
    });
  });
});
<|endoftext|>


<commit_before>// self.js
//
// © 2011 David J. Goehrig
// All Rights Reserved

Object.prototype.can = function(x) { return typeof(this[x]) == 'function' };

Object.prototype.has = function(x) { return this.hasOwnPrototype(x) };

Object.prototype.static = function(x,y) {
	this[x.replace(/\*$/,"")] = function() { return y };
	return this;
}

Object.prototype.slot = function(x,y) {
	this['.' + x] = y;
	this[x.replace(/\*$/,"")] = function() { return this['.' + x] };
	this[x.replace(/\*$/,"")+":"] = function(y) { this['.' + x] = y; return this }
	return this;
}

Object.prototype.after = function(i) {
	var retval = [];
	for (++i;i < this.length;++i) retval.push(this[i]);
	return retval;
}

Object.prototype.list = function() {
	var retval = [];
	for (var i = 0; i < this.length; ++i) retval.push(this[i]);
	return retval;
}

String.prototype.compile = function() {
	var parts = this.split("|");
	return Function.constructor.apply(Function,parts[0].split(/\s/).concat(parts[1]).filter(function(x) { return x != "" }))
}

Function.prototype.eval = function(selector) {
	return this[selector].apply(this,arguments.after(0));
}

Function.prototype.does = function(selector,definition) {
	this[selector] = definition.compile();
	return this;
}

_ = function() {
	var _ = function() { return arguments.callee.eval.apply(arguments.callee,arguments) };
	if (arguments[0]) window[arguments[0]] = _;
	return _;
}

<commit_msg>fixed bug in compiler forgot about binary or for a moment<commit_after>// self.js
//
// © 2011 David J. Goehrig
// All Rights Reserved

Object.prototype.can = function(x) { return typeof(this[x]) == 'function' };

Object.prototype.has = function(x) { return this.hasOwnPrototype(x) };

Object.prototype.static = function(x,y) {
	this[x.replace(/\*$/,"")] = function() { return y };
	return this;
}

Object.prototype.slot = function(x,y) {
	this['.' + x] = y;
	this[x.replace(/\*$/,"")] = function() { return this['.' + x] };
	this[x.replace(/\*$/,"")+":"] = function(y) { this['.' + x] = y; return this }
	return this;
}

Object.prototype.after = function(i) {
	var retval = [];
	for (++i;i < this.length;++i) retval.push(this[i]);
	return retval;
}

Object.prototype.list = function() {
	var retval = [];
	for (var i = 0; i < this.length; ++i) retval.push(this[i]);
	return retval;
}

String.prototype.compile = function() {
	var parts = this.split("|");
	return Function.constructor.apply(Function,parts.shift().split(/\s/).concat(parts.join("|")).filter(function(x) { return x != "" }))
}

Function.prototype.eval = function(selector) {
	return this[selector].apply(this,arguments.after(0));
}

Function.prototype.does = function(selector,definition) {
	this[selector] = definition.compile();
	return this;
}

_ = function() {
	var _ = function() { return arguments.callee.eval.apply(arguments.callee,arguments) };
	if (arguments[0]) window[arguments[0]] = _;
	return _;
}

<|endoftext|>


<commit_before>/*jslint node: true */
"use strict";

var Stopwatch = require('../lib/Stopwatch');
var defaultPrecision = 15;
var assert = require('assert');
var should = require('should');

describe('stopwatch', function () {
    this.timeout(5000);

    describe('constructor', function () {
        it('w/no params', function () {
            var stopwatch = new Stopwatch();
            should.exist(stopwatch);
        });

        it('w/name as first param', function () {
            var stopwatch = new Stopwatch('metric-name');
            stopwatch.name().should.equal('metric-name');
        });

        it('w/autostart as first param', function () {
            var stopwatch = new Stopwatch(true);
            should.exist(stopwatch.name());
            stopwatch.name().should.not.equal(true);
        });

        it('w/both name and autostart', function () {
            var stopwatch = new Stopwatch('metric-name', true);
            stopwatch.name().should.equal('metric-name');
        });

        it('autocreated names are not constant', function () {
            var stopwatch1 = new Stopwatch(true);
            var stopwatch2 = new Stopwatch(true);
            stopwatch1.name().should.not.equal(stopwatch2.name());
        });
    });

    it('start and read (100ms)', function (done) {
        var testtime = 100;

        var stopwatch = new Stopwatch();
        stopwatch.start();
        setTimeout(function () {
            var delta = stopwatch.read();
            verifyDelta(testtime, delta, defaultPrecision);
            done();
        }, testtime);
    });

    it('start and read (10ms)', function (done) {
        var testtime = 10;

        var stopwatch = new Stopwatch();
        stopwatch.start();
        setTimeout(function () {
            var delta = stopwatch.read();
            verifyDelta(testtime, delta, defaultPrecision);
            done();
        }, testtime);
    });

    it('autostart set to true automatically starts stopwatch', function (done) {
        var testtime = 10;

        var stopwatch = new Stopwatch(true);
        setTimeout(function () {
            var delta = stopwatch.read();
            verifyDelta(testtime, delta, defaultPrecision);
            done();
        }, testtime);
    });

    it('autostart set to false does NOT automatically start stopwatch', function (done) {
        var testtime = 10;

        var stopwatch = new Stopwatch(false);
        setTimeout(function () {
            stopwatch.read().should.be.NaN();
            done();
        }, testtime);
    });

    it('with two stopwatches, do independent reads of each', function (done) {
        var stopwatch1 = new Stopwatch();
        var stopwatch2 = new Stopwatch();

        stopwatch1.start();

        //start first stopwatch, then do a read .3s later
        var testtimeA = 300;
        setTimeout(function () {
            var delta1 = stopwatch1.read();
            verifyDelta(testtimeA, delta1, defaultPrecision);
        }, testtimeA);

        //start second stopwatch .1s second after the first, then do a read .5s later
        var testtimeB = 500;
        setTimeout(function () {
            stopwatch2.start();
            setTimeout(function () {
                var delta2 = stopwatch2.read();
                verifyDelta(testtimeB, delta2, defaultPrecision);
                done();
            }, testtimeB);
        }, 100);
    });

    it('start, stop, and read should return the time at stop', function (done) {
        var testtime = 100;

        var stopwatch = new Stopwatch();
        stopwatch.start();
        setTimeout(function () {
            stopwatch.stop();

            setTimeout(function () {
                var delta = stopwatch.read();
                verifyDelta(testtime, delta, defaultPrecision);
                done();
            }, 500);
        }, testtime);
    });

    it('performing read without start() or stop() returns NaN', function (done) {
        var stopwatch = new Stopwatch();
        assert.ok(isNaN(stopwatch.read()));
        done();
    });

    it('performing read without start() returns NaN', function (done) {
        var stopwatch = new Stopwatch();
        stopwatch.stop();
        assert.ok(isNaN(stopwatch.read()));
        done();
    });

    it('executing stop twice should return time at second stop', function (done) {
        //start(), wait .1s, stop(), wait .2s, stop(), wait .5s, read(), ensure delta = .3s
        var stopwatch = new Stopwatch();
        stopwatch.start();
        setTimeout(function () {
            stopwatch.stop();

            setTimeout(function () {
                verifyDelta(100 + 200, stopwatch.stop(), defaultPrecision);

                setTimeout(function () {
                    var delta = stopwatch.read();
                    verifyDelta(100 + 200, delta, defaultPrecision);
                    done();
                }, 500);
            }, 200);
        }, 100);
    });

    it('ensure that stop() returns time', function (done) {
        var testtime = 100;
        var stopwatch = new Stopwatch();
        stopwatch.start();
        setTimeout(function () {
            var delta = stopwatch.stop();
            verifyDelta(testtime, delta, defaultPrecision);
            done();
        }, testtime);
    });

    describe('toString()', function () {
        it('idle', function () {
            var stopwatch = new Stopwatch('sw');
            //[sw => state:init; value:NaN]
            stopwatch.toString().should.containEql('state:init');
            stopwatch.toString().should.containEql('value:');
        });
        it('started', function () {
            var stopwatch = new Stopwatch('sw', true);
            //[sw => state:running; value:0.01]
            stopwatch.toString().should.containEql('state:running');
            stopwatch.toString().should.containEql('value:0');
        });
        it('stopped', function () {
            var stopwatch = new Stopwatch('sw', true);
            stopwatch.stop();
            //[sw => state:stopped; value:0.01]
            stopwatch.toString().should.containEql('state:stopped');
            stopwatch.toString().should.containEql('value:0');
        });
    });

    // https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/StopWatch.html
    describe('java stopwatch compliance', function () {
        it('time should equal read on a running stopwatch', function () {
            //TODO: list time as alias of read
            var stopwatch = new Stopwatch('sw');
            stopwatch.start();

            var readTime = stopwatch.read();
            var time = stopwatch.time();

            verifyDelta(readTime, time, 10);
        });
        it('time should equal read on a stopped stopwatch', function (done) {
            //TODO: list time as alias of read
            var stopwatch = new Stopwatch('sw');
            stopwatch.start();
            setTimeout(function () {
                stopwatch.stop();
                stopwatch.read().should.be.equal(stopwatch.time());
                done();
            }, 10);

        });
        describe('reset', function () {
            it('reseting a not-started stopwatch should have no effect', function () {
                var stopwatch = new Stopwatch('sw');
                stopwatch.reset();
                stopwatch.state().should.be.equal("init");
            });
            it('reseting a started stopwatch should bring it back to init', function () {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.reset();
                should.not.exist(stopwatch.startTime);
                should.not.exist(stopwatch.stopTime);
                stopwatch.state().should.be.equal("init");
            });
            it('reseting a stopped stopwatch should bring it back to init', function () {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.stop();
                stopwatch.reset();
                should.not.exist(stopwatch.startTime);
                should.not.exist(stopwatch.stopTime);
                stopwatch.state().should.be.equal("init");
            });
            it.skip('reseting a split stopwatch should bring it back to init', function () {
            });
        });
        describe('split', function () {
            it('splitTime() will return the split time', function (done) {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();

                setTimeout(function () {
                    stopwatch.split();
                    setTimeout(function () {
                        verifyDelta(100, stopwatch.splitTime(), 10);
                        done();
                    }, 200);
                }, 100);
            });
            it('on split, time/read will return the split time', function (done) {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();

                setTimeout(function () {
                    stopwatch.split();
                    setTimeout(function () {
                        verifyDelta(100, stopwatch.time(), 10);
                        verifyDelta(100, stopwatch.read(), 10);
                        done();
                    }, 200);
                }, 100);
            });
            it('cannot call get splitTime on a init stopwatch', function () {
                var stopwatch = new Stopwatch('sw');
                assert.throws(
                    function () {
                        stopwatch.splitTime();
                    },
                    Error);
            });
            it('cannot call get splitTime() on a running stopwatch', function () {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();
                assert.throws(
                    function () {
                        stopwatch.splitTime();
                    },
                    Error);
            });
            it('cannot call get splitTime() on a stopped stopwatch', function () {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.stop();
                assert.throws(
                    function () {
                        stopwatch.splitTime();
                    },
                    Error);
            });
            it('cannot call get splitTime() folllowing unsplit', function () {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.split();
                stopwatch.unsplit();
                assert.throws(
                    function () {
                        stopwatch.splitTime();
                    },
                    Error);
            });
            it('cannot split a init stopwatch', function () {
                var stopwatch = new Stopwatch('sw');
                assert.throws(
                    function () {
                        stopwatch.split();
                    },
                    Error);
            });
            it('cannot split a split stopwatch (for now, this may change)', function () {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.split();
                assert.throws(
                    function () {
                        stopwatch.split();
                    },
                    Error);
            });
            it('cannot split a stopped stopwatch', function () {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.stop();
                assert.throws(
                    function () {
                        stopwatch.split();
                    },
                    Error);
            });
            it('unsplit, time returns time from start', function (done) {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();
                setTimeout(function () {
                    stopwatch.split();
                    setTimeout(function () {
                        stopwatch.unsplit();
                        verifyDelta(50 + 75, stopwatch.time(), 20);
                        done();
                    }, 75);
                }, 50);
            });
            it('cannot unsplit a init stopwatch', function () {
                var stopwatch = new Stopwatch('sw');
                assert.throws(
                    function () {
                        stopwatch.unsplit();
                    },
                    Error);
            });
            it('cannot unsplit a running stopwatch', function () {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();
                assert.throws(
                    function () {
                        stopwatch.unsplit();
                    },
                    Error);
            });
            it('cannot unsplit a stopped stopwatch', function () {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.stop();
                assert.throws(
                    function () {
                        stopwatch.unsplit();
                    },
                    Error);
            });
        });
        it.skip('suspend/resume', function () {
            // This method suspends the watch until it is resumed. The watch will not include time between the suspend and resume calls in the total time.
            // IllegalStateException - if the StopWatch is not currently running.
            // IllegalStateException - if the StopWatch has not been suspended.
        });
        it.skip('start while already running', function () {
            // IllegalStateException - if the StopWatch is already running.
        });
        it.skip('stop while not running', function () {
            // IllegalStateException - if the StopWatch is not running.
        });
    });
});

//TODO:
//replace with: statman.TestHelper.assertCloseEnough(testtime, delta, defaultPrecision);
function verifyDelta(expected, actual, acceptedVariance) {
    var lowerThreshold = expected - acceptedVariance;
    var upperThreshold = expected + acceptedVariance;
    var message = "Expected " + expected + " ± " + acceptedVariance + ", was " + actual + ".";
    assert.ok((actual >= lowerThreshold) && (actual <= upperThreshold), message);
}<commit_msg>placeholder tests<commit_after>/*jslint node: true */
"use strict";

var Stopwatch = require('../lib/Stopwatch');
var defaultPrecision = 15;
var assert = require('assert');
var should = require('should');

describe('stopwatch', function () {
    this.timeout(5000);

    describe('constructor', function () {
        it('w/no params', function () {
            var stopwatch = new Stopwatch();
            should.exist(stopwatch);
        });

        it('w/name as first param', function () {
            var stopwatch = new Stopwatch('metric-name');
            stopwatch.name().should.equal('metric-name');
        });

        it('w/autostart as first param', function () {
            var stopwatch = new Stopwatch(true);
            should.exist(stopwatch.name());
            stopwatch.name().should.not.equal(true);
        });

        it('w/both name and autostart', function () {
            var stopwatch = new Stopwatch('metric-name', true);
            stopwatch.name().should.equal('metric-name');
        });

        it('autocreated names are not constant', function () {
            var stopwatch1 = new Stopwatch(true);
            var stopwatch2 = new Stopwatch(true);
            stopwatch1.name().should.not.equal(stopwatch2.name());
        });
    });

    it('start and read (100ms)', function (done) {
        var testtime = 100;

        var stopwatch = new Stopwatch();
        stopwatch.start();
        setTimeout(function () {
            var delta = stopwatch.read();
            verifyDelta(testtime, delta, defaultPrecision);
            done();
        }, testtime);
    });

    it('start and read (10ms)', function (done) {
        var testtime = 10;

        var stopwatch = new Stopwatch();
        stopwatch.start();
        setTimeout(function () {
            var delta = stopwatch.read();
            verifyDelta(testtime, delta, defaultPrecision);
            done();
        }, testtime);
    });

    it('autostart set to true automatically starts stopwatch', function (done) {
        var testtime = 10;

        var stopwatch = new Stopwatch(true);
        setTimeout(function () {
            var delta = stopwatch.read();
            verifyDelta(testtime, delta, defaultPrecision);
            done();
        }, testtime);
    });

    it('autostart set to false does NOT automatically start stopwatch', function (done) {
        var testtime = 10;

        var stopwatch = new Stopwatch(false);
        setTimeout(function () {
            stopwatch.read().should.be.NaN();
            done();
        }, testtime);
    });

    it('with two stopwatches, do independent reads of each', function (done) {
        var stopwatch1 = new Stopwatch();
        var stopwatch2 = new Stopwatch();

        stopwatch1.start();

        //start first stopwatch, then do a read .3s later
        var testtimeA = 300;
        setTimeout(function () {
            var delta1 = stopwatch1.read();
            verifyDelta(testtimeA, delta1, defaultPrecision);
        }, testtimeA);

        //start second stopwatch .1s second after the first, then do a read .5s later
        var testtimeB = 500;
        setTimeout(function () {
            stopwatch2.start();
            setTimeout(function () {
                var delta2 = stopwatch2.read();
                verifyDelta(testtimeB, delta2, defaultPrecision);
                done();
            }, testtimeB);
        }, 100);
    });

    it('start, stop, and read should return the time at stop', function (done) {
        var testtime = 100;

        var stopwatch = new Stopwatch();
        stopwatch.start();
        setTimeout(function () {
            stopwatch.stop();

            setTimeout(function () {
                var delta = stopwatch.read();
                verifyDelta(testtime, delta, defaultPrecision);
                done();
            }, 500);
        }, testtime);
    });

    it('performing read without start() or stop() returns NaN', function (done) {
        var stopwatch = new Stopwatch();
        assert.ok(isNaN(stopwatch.read()));
        done();
    });

    it('performing read without start() returns NaN', function (done) {
        var stopwatch = new Stopwatch();
        stopwatch.stop();
        assert.ok(isNaN(stopwatch.read()));
        done();
    });

    it('executing stop twice should return time at second stop', function (done) {
        //start(), wait .1s, stop(), wait .2s, stop(), wait .5s, read(), ensure delta = .3s
        var stopwatch = new Stopwatch();
        stopwatch.start();
        setTimeout(function () {
            stopwatch.stop();

            setTimeout(function () {
                verifyDelta(100 + 200, stopwatch.stop(), defaultPrecision);

                setTimeout(function () {
                    var delta = stopwatch.read();
                    verifyDelta(100 + 200, delta, defaultPrecision);
                    done();
                }, 500);
            }, 200);
        }, 100);
    });

    it('ensure that stop() returns time', function (done) {
        var testtime = 100;
        var stopwatch = new Stopwatch();
        stopwatch.start();
        setTimeout(function () {
            var delta = stopwatch.stop();
            verifyDelta(testtime, delta, defaultPrecision);
            done();
        }, testtime);
    });

    describe('toString()', function () {
        it('idle', function () {
            var stopwatch = new Stopwatch('sw');
            //[sw => state:init; value:NaN]
            stopwatch.toString().should.containEql('state:init');
            stopwatch.toString().should.containEql('value:');
        });
        it('started', function () {
            var stopwatch = new Stopwatch('sw', true);
            //[sw => state:running; value:0.01]
            stopwatch.toString().should.containEql('state:running');
            stopwatch.toString().should.containEql('value:0');
        });
        it('stopped', function () {
            var stopwatch = new Stopwatch('sw', true);
            stopwatch.stop();
            //[sw => state:stopped; value:0.01]
            stopwatch.toString().should.containEql('state:stopped');
            stopwatch.toString().should.containEql('value:0');
        });
    });

    // https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/StopWatch.html
    describe('java stopwatch compliance', function () {
        it('time should equal read on a running stopwatch', function () {
            //TODO: list time as alias of read
            var stopwatch = new Stopwatch('sw');
            stopwatch.start();

            var readTime = stopwatch.read();
            var time = stopwatch.time();

            verifyDelta(readTime, time, 10);
        });
        it('time should equal read on a stopped stopwatch', function (done) {
            //TODO: list time as alias of read
            var stopwatch = new Stopwatch('sw');
            stopwatch.start();
            setTimeout(function () {
                stopwatch.stop();
                stopwatch.read().should.be.equal(stopwatch.time());
                done();
            }, 10);

        });
        describe('reset', function () {
            it('reseting a not-started stopwatch should have no effect', function () {
                var stopwatch = new Stopwatch('sw');
                stopwatch.reset();
                stopwatch.state().should.be.equal("init");
            });
            it('reseting a started stopwatch should bring it back to init', function () {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.reset();
                should.not.exist(stopwatch.startTime);
                should.not.exist(stopwatch.stopTime);
                stopwatch.state().should.be.equal("init");
            });
            it('reseting a stopped stopwatch should bring it back to init', function () {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.stop();
                stopwatch.reset();
                should.not.exist(stopwatch.startTime);
                should.not.exist(stopwatch.stopTime);
                stopwatch.state().should.be.equal("init");
            });
            it.skip('reseting a split stopwatch should bring it back to init', function () {
            });
        });
        describe('split', function () {
            it('splitTime() will return the split time', function (done) {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();

                setTimeout(function () {
                    stopwatch.split();
                    setTimeout(function () {
                        verifyDelta(100, stopwatch.splitTime(), 10);
                        done();
                    }, 200);
                }, 100);
            });
            it('on split, time/read will return the split time', function (done) {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();

                setTimeout(function () {
                    stopwatch.split();
                    setTimeout(function () {
                        verifyDelta(100, stopwatch.time(), 10);
                        verifyDelta(100, stopwatch.read(), 10);
                        done();
                    }, 200);
                }, 100);
            });
            it('cannot call get splitTime on a init stopwatch', function () {
                var stopwatch = new Stopwatch('sw');
                assert.throws(
                    function () {
                        stopwatch.splitTime();
                    },
                    Error);
            });
            it('cannot call get splitTime() on a running stopwatch', function () {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();
                assert.throws(
                    function () {
                        stopwatch.splitTime();
                    },
                    Error);
            });
            it('cannot call get splitTime() on a stopped stopwatch', function () {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.stop();
                assert.throws(
                    function () {
                        stopwatch.splitTime();
                    },
                    Error);
            });
            it('cannot call get splitTime() folllowing unsplit', function () {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.split();
                stopwatch.unsplit();
                assert.throws(
                    function () {
                        stopwatch.splitTime();
                    },
                    Error);
            });
            it('cannot split a init stopwatch', function () {
                var stopwatch = new Stopwatch('sw');
                assert.throws(
                    function () {
                        stopwatch.split();
                    },
                    Error);
            });
            it('cannot split a split stopwatch (for now, this may change)', function () {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.split();
                assert.throws(
                    function () {
                        stopwatch.split();
                    },
                    Error);
            });
            it('cannot split a stopped stopwatch', function () {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.stop();
                assert.throws(
                    function () {
                        stopwatch.split();
                    },
                    Error);
            });
            it('unsplit, time returns time from start', function (done) {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();
                setTimeout(function () {
                    stopwatch.split();
                    setTimeout(function () {
                        stopwatch.unsplit();
                        verifyDelta(50 + 75, stopwatch.time(), 20);
                        done();
                    }, 75);
                }, 50);
            });
            it('cannot unsplit a init stopwatch', function () {
                var stopwatch = new Stopwatch('sw');
                assert.throws(
                    function () {
                        stopwatch.unsplit();
                    },
                    Error);
            });
            it('cannot unsplit a running stopwatch', function () {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();
                assert.throws(
                    function () {
                        stopwatch.unsplit();
                    },
                    Error);
            });
            it('cannot unsplit a stopped stopwatch', function () {
                var stopwatch = new Stopwatch('sw');
                stopwatch.start();
                stopwatch.stop();
                assert.throws(
                    function () {
                        stopwatch.unsplit();
                    },
                    Error);
            });
        });
        it.skip('suspend/resume', function () {
            // This method suspends the watch until it is resumed. The watch will not include time between the suspend and resume calls in the total time.
            // IllegalStateException - if the StopWatch is not currently running.
            // IllegalStateException - if the StopWatch has not been suspended.
        });
        it.skip('cannot start a running stopwatch', function () {
            var stopwatch = new Stopwatch('sw');
            stopwatch.start();
            assert.throws(
                function () {
                    stopwatch.start();
                },
                Error);
        });
        it.skip('cannot start a split stopwatch', function () {
            var stopwatch = new Stopwatch('sw');
            stopwatch.start();
            stopwatch.split();
            assert.throws(
                function () {
                    stopwatch.start();
                },
                Error);
        });
        it.skip('cannot stop a init stopwatch', function () {
            var stopwatch = new Stopwatch('sw');
            stopwatch.start();
            stopwatch.split();
            assert.throws(
                function () {
                    stopwatch.start();
                },
                Error);
        });
        it.skip('cannot stop a stopped stopwatch', function () {
            var stopwatch = new Stopwatch('sw');
            stopwatch.start();
            stopwatch.split();
            assert.throws(
                function () {
                    stopwatch.start();
                },
                Error);
        });
    });
});

//TODO:
//replace with: statman.TestHelper.assertCloseEnough(testtime, delta, defaultPrecision);
function verifyDelta(expected, actual, acceptedVariance) {
    var lowerThreshold = expected - acceptedVariance;
    var upperThreshold = expected + acceptedVariance;
    var message = "Expected " + expected + " ± " + acceptedVariance + ", was " + actual + ".";
    assert.ok((actual >= lowerThreshold) && (actual <= upperThreshold), message);
}<|endoftext|>


<commit_before>import React from 'react';

import Firebase from 'firebase';

// Material Design stuff
import RaisedButton from 'material-ui/RaisedButton';
import Header from './Header';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';

/*
  MyAccount
  Let's us make <MyAccount/> elements
*/

var MyAccount = React.createClass({
  getInitialState: function() {
      return {
        'uid':null,
        'name':null
      }
  },

  componentWillMount: function() {
    var user = Firebase.auth().currentUser;
    if (user) {
      this.state.name = user.displayName;
      this.state.uid = user.uid;
      this.setState(this.state);
    }
  },

  triggerLogin : function() {
    var successfulLogin = this.successfulLogin;
    var provider = new Firebase.auth.GoogleAuthProvider();
    var auth = Firebase.auth().signInWithPopup(provider).then(function(result) {
      var user = result.user;
      successfulLogin(user);
    }).catch(function(error) {
      console.log("couldn't log in for some reason");
      console.log(error);
    });
  },

  triggerLogout : function() {
    var accountComponent = this;
    var auth = Firebase.auth().signOut().then(function() {
      accountComponent.state.name = null;
      accountComponent.state.uid = null;
      accountComponent.setState(accountComponent.state);
    }, function(error) {
      console.log("couldn't log out for some reason");
      console.log(error);
    });
  },

  successfulLogin : function(user) {
    this.state.name = user.displayName;
    this.state.uid = user.uid;
    this.setState(this.state);
  },

  render : function() {
    var styles = {
      container: {
        textAlign: 'center',
        paddingTop: 200,
      },
    };

    var headline = "You're not logged in. Want to log in?";
    if (this.state.uid) {
      var headline = "Hey, you're logged in as " + this.state.name;
    }

    return (

        <MuiThemeProvider>

{headline}

            <RaisedButton style={{'margin':'20px 20px 20px 20px'}}
              label="Log In"
              onClick={this.triggerLogin}
              primary={true}
            />
            <RaisedButton style={{'margin':'20px 20px 20px 20px'}}
              label="Log Out"
              onClick={this.triggerLogout}
              primary={true}
            />

        </MuiThemeProvider>

    )
  }

});

export default MyAccount;
<commit_msg>Add headshots<commit_after>import React from 'react';

import Firebase from 'firebase';

// Material Design stuff
import RaisedButton from 'material-ui/RaisedButton';
import Header from './Header';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Paper from 'material-ui/Paper';

/*
  MyAccount
  Let's us make <MyAccount/> elements
*/

var MyAccount = React.createClass({
  getInitialState: function() {
      return {
        'uid':null,
        'name':null
      }
  },

  componentWillMount: function() {
    var user = Firebase.auth().currentUser;
    if (user) {
      this.state.name = user.displayName;
      this.state.uid = user.uid;
      this.setState(this.state);
    }
  },

  triggerLogin : function() {
    var successfulLogin = this.successfulLogin;
    var provider = new Firebase.auth.GoogleAuthProvider();
    var auth = Firebase.auth().signInWithPopup(provider).then(function(result) {
      var user = result.user;
      successfulLogin(user);
    }).catch(function(error) {
      console.log("couldn't log in for some reason");
      console.log(error);
    });
  },

  triggerLogout : function() {
    var accountComponent = this;
    var auth = Firebase.auth().signOut().then(function() {
      accountComponent.state.name = null;
      accountComponent.state.uid = null;
      accountComponent.setState(accountComponent.state);
    }, function(error) {
      console.log("couldn't log out for some reason");
      console.log(error);
    });
  },

  successfulLogin : function(user) {
    this.state.name = user.displayName;
    this.state.uid = user.uid;
    this.setState(this.state);
  },

  render : function() {
    var styles = {
      container: {
        textAlign: 'center',
        paddingTop: 20,
      },
    };

    var headline = "You're not logged in. Want to log in?";
    if (this.state.uid) {
      var headline = "Hey, you're logged in as " + this.state.user.displayName;
    }

    var getHeadshot = function(user) {
      if (user) {
        var headshot = "";
        return headshot;
      } else {
        return "";
      }
    }

    return (

        <MuiThemeProvider>
          <Paper style={{'width':'60%','margin':'25px auto'}} zDepth={2}>

{headline}

               {getHeadshot(this.state.user)}

            <RaisedButton style={{'margin':'20px 20px 20px 20px'}}
              label="Log In"
              onClick={this.triggerLogin}
              primary={true}
            />
            <RaisedButton style={{'margin':'20px 20px 20px 20px'}}
              label="Log Out"
              onClick={this.triggerLogout}
              primary={true}
            />

          </Paper>
        </MuiThemeProvider>

    )
  }

});

export default MyAccount;
<|endoftext|>


<commit_before>const ava = require('ava');
const { join, basename } = require('path');
const { fs, tempFile, tempFileLoc, tempDir, tempDirLoc, tempSymlink } = require('./lib');
const nextra = require('../src');

ava('File to New File Location', async test => {
	const newFile = tempFileLoc();
	const file = tempFile();
	await nextra.copy(file, newFile);

	const stats = await fs.statAsync(newFile);
	test.true(stats.isFile());
});

ava('File to Existing File', async test => {
	const newFile = tempFile();
	const file = tempFile();
	await nextra.copy(file, newFile);

	const stats = await fs.statAsync(newFile);
	test.true(stats.isFile());
});

ava('File to Existing File w/ errorOnExist', async test => {
	const newFile = tempFile();
	const file = tempFile();
	await test.throwsAsync(nextra.copy(file, newFile, { overwrite: false, errorOnExist: true }));
});

ava('File to Existing File w/o errorOnExist', async test => {
	const newFile = tempFile();
	const file = tempFile();
	await test.notThrowsAsync(nextra.copy(file, newFile, { overwrite: false, errorOnExist: false }));
});

ava('File to Empty Directory', async test => {
	const emptyDir = tempDir();
	const file = tempFile();
	await nextra.copy(file, emptyDir);

	const stats = await fs.statAsync(join(emptyDir, basename(file)));
	test.true(stats.isFile());
});

ava('Directory to Empty Directory', async test => {
	const fullDir = tempDir();
	const emptyDir = tempDir();
	const file = tempFile(fullDir);
	await nextra.copy(fullDir, emptyDir);

	const stats = await fs.statAsync(join(emptyDir, basename(file)));
	test.true(stats.isFile());
});

ava('Directory to Child Directory', async test => {
	const parent = tempDir();
	const child = tempDir(parent);
	await test.throwsAsync(nextra.copy(parent, child));
});

ava('Directory to new Deep Directory', async test => {
	const fullDir = tempDir();
	const emptyDir = tempDirLoc(tempDirLoc());
	const file = tempFile(fullDir);
	await nextra.copy(fullDir, emptyDir);

	const stats = await fs.statAsync(join(emptyDir, basename(file)));
	test.true(stats.isFile());
});

ava('Symlink to Empty Directory', async test => {
	const emptyDir = tempDir();
	const symlink = tempSymlink();
	await nextra.copy(symlink, emptyDir);

	const stats = await fs.lstatAsync(join(emptyDir, basename(symlink)));
	test.true(stats.isSymbolicLink());
});

ava('Symlink to Existing Symlink', async test => {
	const newFile = tempSymlink();
	const symlink = tempSymlink();
	await nextra.copy(symlink, newFile);

	const stats = await fs.lstatAsync(newFile);
	test.true(stats.isSymbolicLink());
});

ava('Duplicated Directories (error on exist)', async test => {
	const dir = tempDir();
	tempFile(dir);
	await test.throwsAsync(nextra.copy(dir, dir, { errorOnExist: true }));
});

ava('Duplicated File (no error on exist)', async test => {
	const file = tempFile();
	await nextra.copy(file, file);

	const stats = await fs.statAsync(file);
	test.true(stats.isFile());
});

ava('filter shortcut', async test => {
	const emptyDir = tempDir();
	const file = tempFile();
	await nextra.copy(file, emptyDir, () => true);

	const stats = await fs.statAsync(join(emptyDir, basename(file)));
	test.true(stats.isFile());
});
<commit_msg>and another<commit_after>const ava = require('ava');
const { join, basename } = require('path');
const { fs, tempFile, tempFileLoc, tempDir, tempDirLoc, tempSymlink } = require('./lib');
const nextra = require('../src');

ava('File to New File Location', async test => {
	const newFile = tempFileLoc();
	const file = tempFile();
	await nextra.copy(file, newFile);

	const stats = await fs.statAsync(newFile);
	test.true(stats.isFile());
});

ava('File to Existing File', async test => {
	const newFile = tempFile();
	const file = tempFile();
	await nextra.copy(file, newFile);

	const stats = await fs.statAsync(newFile);
	test.true(stats.isFile());
});

ava('File to Existing File w/ errorOnExist', async test => {
	const newFile = tempFile();
	const file = tempFile();
	await test.throwsAsync(nextra.copy(file, newFile, { overwrite: false, errorOnExist: true }));
});

ava('File to Existing File w/o errorOnExist', async test => {
	const newFile = tempFile();
	const file = tempFile();
	await test.notThrowsAsync(nextra.copy(file, newFile, { overwrite: false, errorOnExist: false }));
});

ava('File to Empty Directory', async test => {
	const emptyDir = tempDir();
	const file = tempFile();
	await nextra.copy(file, emptyDir);

	const stats = await fs.statAsync(join(emptyDir, basename(file)));
	test.true(stats.isFile());
});

ava('Directory to Empty Directory', async test => {
	const fullDir = tempDir();
	const emptyDir = tempDir();
	const file = tempFile(fullDir);
	await nextra.copy(fullDir, emptyDir);

	const stats = await fs.statAsync(join(emptyDir, basename(file)));
	test.true(stats.isFile());
});

ava('Directory to Child Directory', async test => {
	const parent = tempDir();
	const child = tempDir(parent);
	await test.throwsAsync(nextra.copy(parent, child));
});

ava('Directory to new Deep Directory', async test => {
	const fullDir = tempDir();
	const emptyDir = tempDirLoc(tempDirLoc());
	const file = tempFile(fullDir);
	await nextra.copy(fullDir, emptyDir);

	const stats = await fs.statAsync(join(emptyDir, basename(file)));
	test.true(stats.isFile());
});

ava('Symlink to Empty Directory', async test => {
	const emptyDir = tempDir();
	const symlink = tempSymlink();
	await nextra.copy(symlink, emptyDir);

	const stats = await fs.lstatAsync(join(emptyDir, basename(symlink)));
	test.true(stats.isSymbolicLink());
});

ava('Symlink to Existing Symlink', async test => {
	const newFile = tempSymlink();
	const symlink = tempSymlink();
	await nextra.copy(symlink, newFile);

	const stats = await fs.lstatAsync(newFile);
	test.true(stats.isSymbolicLink());
});

ava('Duplicated Directories (error on exist)', async test => {
	const dir = tempDir();
	tempFile(dir);
	await test.throwsAsync(nextra.copy(dir, dir, { errorOnExist: true }));
});

ava('Duplicated File (no error on exist)', async test => {
	const file = tempFile();
	await nextra.copy(file, file);

	const stats = await fs.statAsync(file);
	test.true(stats.isFile());
});

ava('filter shortcut', async test => {
	const emptyDir = tempDir();
	const file = tempFile();
	await nextra.copy(file, emptyDir, () => true);

	const stats = await fs.statAsync(join(emptyDir, basename(file)));
	test.true(stats.isFile());
});

ava('filter everything', async test => {
	const emptyDir = tempDir();
	const file = tempFile();
	await nextra.copy(file, emptyDir, () => false);

	await test.throwsAsync(fs.statAsync(join(emptyDir, basename(file))));
});
<|endoftext|>


<commit_before>const express = require('express');
const router = express.Router();
const passport = require('passport');

const multer = require('multer');
const sharp = require('sharp');
const crypto = require('crypto');
const fs = require('fs');

const formatError = require('../../helpers/errors.js').formatError;
const path = require('path');

const mongoose = require('mongoose');
const Asset = mongoose.model('Asset');

const UPLOAD_PATH = 'uploads';

const storage = multer.diskStorage({
  destination: `${UPLOAD_PATH}/temp/`,
  // fileFilter: function (req, file, callback) {
  //   let ext = path.extname(file.originalname);
  //   if(ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') { // accept only images
  //       return callback(new Error('Only images are allowed'));
  //   }
  //   callback(null, true);
  // },
  filename: function (req, file, cb) {
    crypto.pseudoRandomBytes(16, (err, raw) =>{
      if (err) return cb(err);
      cb(null, file.fieldname + '-' + raw.toString('hex') + path.extname(file.originalname));
    });
  }
});

const upload = multer({ storage: storage });

router.post('/avatar', upload.single('avatar'), passport.authenticate('jwt', { session: false }), function (req, res, next) {
  // console.log('storing new asset:' + JSON.stringify(req.file));
  let ext = path.extname(req.file.originalname);
  if(ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') { // accept only images
    res.status(500).json({code: 500, status: 'error', errors: [formatError('Only images are allowed.')]});
  } else {
    sharp(`${UPLOAD_PATH}/temp/${req.file.filename}`).resize(768).toFile(`${UPLOAD_PATH}/${req.file.filename}`)
    .then(resized => {
      fs.unlink(`${UPLOAD_PATH}/temp/${req.file.filename}`, (err) => {
        if (err) throw err;
        // console.log(`successfully deleted: ${UPLOAD_PATH}/temp/${req.file.filename}`);
      });
      Asset.createAvatarAsset(req.body, {original: req.file, resized: resized}, req.user, (err, asset) => {
        if (err) res.status(500).json({code: 500, status: 'error', errors: [formatError(err)]});
        else res.status(201).json({code: 201, status: 'created', data: {asset: asset}});
      });
      // console.log(resized);
    })
    .catch(reason => {
      console.log(reason);
      res.status(500).json({code: 500, status: 'error', errors: [formatError(reason)]});
    });
  }
});

router.post('/image', upload.single('image'), passport.authenticate('jwt', { session: false }), function (req, res, next) {
  // console.log('storing new asset:' + JSON.stringify(req.file));
  let ext = path.extname(req.file.originalname);
  if(ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') { // accept only images
    res.status(500).json({code: 500, status: 'error', errors: [formatError('Only images are allowed.')]});
  } else {
    sharp(`${UPLOAD_PATH}/temp/${req.file.filename}`).resize(768).toFile(`${UPLOAD_PATH}/${req.file.filename}`)
    .then(resized => {
      fs.unlink(`${UPLOAD_PATH}/temp/${req.file.filename}`, (err) => {
        if (err) throw err;
        // console.log(`successfully deleted: ${UPLOAD_PATH}/temp/${req.file.filename}`);
      });
      Asset.createAvatarAsset(req.body, {original: req.file, resized: resized}, req.user, (err, asset) => {
        if (err) res.status(500).json({code: 500, status: 'error', errors: [formatError(err)]});
        else res.status(201).json({code: 201, status: 'created', data: {asset: asset}});
      });
      // console.log(resized);
    })
    .catch(reason => {
      console.log(reason);
      res.status(500).json({code: 500, status: 'error', errors: [formatError(reason)]});
    });
  }
});

module.exports = router;<commit_msg>easier configuration for image sizes (scaling)<commit_after>const express = require('express');
const router = express.Router();
const passport = require('passport');

const multer = require('multer');
const sharp = require('sharp');
const crypto = require('crypto');
const fs = require('fs');

const formatError = require('../../helpers/errors.js').formatError;
const path = require('path');

const mongoose = require('mongoose');
const Asset = mongoose.model('Asset');

// defaults
const UPLOAD_PATH = 'uploads';
const AVATAR_IMAGE_SIZE = 768; // scaling target for avatar images (single value is width, X * X is witdth * hight)
const OTHER_IMAGE_SIZE = 768; // scaling target for other images (single value is width, X * X is witdth * hight)

const storage = multer.diskStorage({
  destination: `${UPLOAD_PATH}/temp/`,
  // fileFilter: function (req, file, callback) {
  //   let ext = path.extname(file.originalname);
  //   if(ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') { // accept only images
  //       return callback(new Error('Only images are allowed'));
  //   }
  //   callback(null, true);
  // },
  filename: function (req, file, cb) {
    crypto.pseudoRandomBytes(16, (err, raw) =>{
      if (err) return cb(err);
      cb(null, file.fieldname + '-' + raw.toString('hex') + path.extname(file.originalname));
    });
  }
});

const upload = multer({ storage: storage });

router.post('/avatar', upload.single('avatar'), passport.authenticate('jwt', { session: false }), function (req, res, next) {
  // console.log('storing new asset:' + JSON.stringify(req.file));
  let ext = path.extname(req.file.originalname);
  if(ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') { // accept only images
    res.status(500).json({code: 500, status: 'error', errors: [formatError('Only images are allowed.')]});
  } else {
    sharp(`${UPLOAD_PATH}/temp/${req.file.filename}`).resize(AVATAR_IMAGE_SIZE).toFile(`${UPLOAD_PATH}/${req.file.filename}`)
    .then(resized => {
      fs.unlink(`${UPLOAD_PATH}/temp/${req.file.filename}`, (err) => {
        if (err) throw err;
        // console.log(`successfully deleted: ${UPLOAD_PATH}/temp/${req.file.filename}`);
      });
      Asset.createAvatarAsset(req.body, {original: req.file, resized: resized}, req.user, (err, asset) => {
        if (err) res.status(500).json({code: 500, status: 'error', errors: [formatError(err)]});
        else res.status(201).json({code: 201, status: 'created', data: {asset: asset}});
      });
      // console.log(resized);
    })
    .catch(reason => {
      console.log(reason);
      res.status(500).json({code: 500, status: 'error', errors: [formatError(reason)]});
    });
  }
});

router.post('/image', upload.single('image'), passport.authenticate('jwt', { session: false }), function (req, res, next) {
  // console.log('storing new asset:' + JSON.stringify(req.file));
  let ext = path.extname(req.file.originalname);
  if(ext !== '.png' && ext !== '.jpg' && ext !== '.gif' && ext !== '.jpeg') { // accept only images
    res.status(500).json({code: 500, status: 'error', errors: [formatError('Only images are allowed.')]});
  } else {
    sharp(`${UPLOAD_PATH}/temp/${req.file.filename}`).resize(OTHER_IMAGE_SIZE).toFile(`${UPLOAD_PATH}/${req.file.filename}`)
    .then(resized => {
      fs.unlink(`${UPLOAD_PATH}/temp/${req.file.filename}`, (err) => {
        if (err) throw err;
        // console.log(`successfully deleted: ${UPLOAD_PATH}/temp/${req.file.filename}`);
      });
      Asset.createAvatarAsset(req.body, {original: req.file, resized: resized}, req.user, (err, asset) => {
        if (err) res.status(500).json({code: 500, status: 'error', errors: [formatError(err)]});
        else res.status(201).json({code: 201, status: 'created', data: {asset: asset}});
      });
      // console.log(resized);
    })
    .catch(reason => {
      console.log(reason);
      res.status(500).json({code: 500, status: 'error', errors: [formatError(reason)]});
    });
  }
});

module.exports = router;<|endoftext|>