<commit_before>'use strict'

var rk4 = require('../lib')
  , assert = require('chai').assert
  , richardson = require('richardson-extrapolation')

var ctors = {
  'float32': Float32Array,
  'float64': Float64Array,
  'array': function(){ return arguments[0] }
}

Object.keys(ctors).forEach(function(dtype) {
  var ctor = ctors[dtype]

  describe('rk4 integration (' + dtype + ')', function() {

    describe('integration of one variable', function() {
      var integrator, f, y0, t0, n

      beforeEach(function() {
        f = function(dydt, y) { dydt[0] = -y[0] }
        t0 = 1.5
        y0 = new ctor([1])
        n = 10

        integrator = rk4( y0, f, t0, 1/n )
      })

      it('creates work arrays of the same size as the input',function() {
        assert.equal( integrator._w.constructor,  y0.constructor )
        assert.equal( integrator._k1.constructor, y0.constructor )
        assert.equal( integrator._k2.constructor, y0.constructor )
        assert.equal( integrator._k3.constructor, y0.constructor )
        assert.equal( integrator._k4.constructor, y0.constructor )
      })

      it('creates work arrays of the same type as the input',function() {
        assert.equal( integrator._w.length,  y0.length )
        assert.equal( integrator._k1.length, y0.length )
        assert.equal( integrator._k2.length, y0.length )
        assert.equal( integrator._k3.length, y0.length )
        assert.equal( integrator._k4.length, y0.length )
      })

      it('takes multiple timesteps',function() {
        integrator.steps(n)
        assert.closeTo(integrator.y[0], Math.exp(-1), 1e-4 )
      })
    })

    describe('integration of two variables', function() {
      var integrator, f, y0, t0

      beforeEach(function() {
        f = function(dydt, y) {
          dydt[0] = -y[1]
          dydt[1] =  y[0]
        }

        t0 = 1.5
        y0 = new ctor([1,0])

        integrator = rk4( y0, f, t0, 1 )
      })

      it('creates work arrays of the same size as the input',function() {
        assert.equal( integrator._w.constructor,  y0.constructor )
        assert.equal( integrator._k1.constructor, y0.constructor )
        assert.equal( integrator._k2.constructor, y0.constructor )
        assert.equal( integrator._k3.constructor, y0.constructor )
        assert.equal( integrator._k4.constructor, y0.constructor )
      })

      it('creates work arrays of the same type as the input',function() {
        assert.equal( integrator._w.length,  y0.length )
        assert.equal( integrator._k1.length, y0.length )
        assert.equal( integrator._k2.length, y0.length )
        assert.equal( integrator._k3.length, y0.length )
        assert.equal( integrator._k4.length, y0.length )
      })

      it('takes a single timestep',function() {
        integrator.step()
        assert.closeTo( integrator.y[0], 0.5416666666666667, 1e-4 )
        assert.closeTo( integrator.y[1], 0.8333333333333333, 1e-4 )
      })

      it('increments the time',function() {
        integrator.step()
        assert.closeTo( integrator.t, t0 + integrator.dt, 1e-4 )
        integrator.step()
        assert.closeTo( integrator.t, t0 + 2*integrator.dt, 1e-4 )
      })

      it('takes multiple timesteps',function() {
        integrator.steps(2)
        assert.closeTo(integrator.y[0], -0.4010416666666664, 1e-4 )
        assert.closeTo(integrator.y[1], 0.9027777777777778, 1e-4)
      })
    })

    describe('convergence', function() {

      it('local truncation error is ~ O(h^5) in time', function() {
        // Integrate an exponential: dy/dt = -y  -->  y = exp(-t)
        var result = richardson(function(h) {
          var f = function(dydt, y) { dydt[0] = -y[0] }
          return rk4( new ctor([1]), f, 0, h ).step().y[0] - Math.exp(-h)
        }, [1,0.2], { f: 0 } )

        assert.closeTo( result.n, 5, 1e-1, 'n ~ 5' )
      })

      it('local truncation error of y is order O(h^5)', function() {
        var result = richardson(function(h) {

          // Integrate along a sector of a circle:
          var f = function(dydt, y) { dydt[0] = -y[1]; dydt[1] =  y[0] }
          var i = rk4( new ctor([1,0]), f, 0, h ).step()

          // Return the distance from the expected endpoint:
          return Math.sqrt( Math.pow(i.y[0]-Math.cos(h),2) + Math.pow(i.y[1]-Math.sin(h),2) )

        }, 2*Math.PI/20, { f: 0 } )

        assert.closeTo( result.n, 5, 1e-2, 'n ~ 5' )
      })

      it('total accumulated error of y is order O(h^4)', function() {

        var result = richardson(function(h) {

          // Integrate around a circle with this step size:
          var f = function(dydt, y) { dydt[0] = -y[1]; dydt[1] =  y[0] }
          var i = rk4( new ctor([1,0]), f, 0, h ).steps( Math.floor(2*Math.PI/h + 0.5) )

          // Return the distance from the expected endpoint:
          return Math.sqrt( Math.pow(i.y[0]-1,2) + Math.pow(i.y[1],2) )

        }, 2*Math.PI/20, { f: 0 } )

        assert.closeTo( result.n, 4, 1e-2, 'n ~ 4' )
      })

      it('total accumulated error is order O(h^4) in all variables', function() {

        var numSteps= 10

        var result = richardson(function(h) {
          // Integrate around a circle at an accelerating rate
          var f = function(dydt, y, t) {
            var s =  Math.sin(t * Math.PI) * Math.PI / 2
            dydt[0] = -y[1]* 2 * Math.PI * s
            dydt[1] =  y[0]* 2 * Math.PI * s
          }
          var i = rk4( new ctor([1,0,0]), f, 0, h ).steps( Math.floor(1/h+0.5))

          // Return the distance from the expected endpoint:
          return Math.sqrt( Math.pow(i.y[0]-1,2) + Math.pow(i.y[1],2) )

        }, 0.05, { f: 0 } )

        assert.closeTo( result.n, 4, 1e-2, 'n ~ 4' )
      })

    })

  })

})
<commit_msg>Typo fix<commit_after>'use strict'

var rk4 = require('../lib')
  , assert = require('chai').assert
  , richardson = require('richardson-extrapolation')

var ctors = {
  'float32': Float32Array,
  'float64': Float64Array,
  'array': function(){ return arguments[0] }
}

Object.keys(ctors).forEach(function(dtype) {
  var ctor = ctors[dtype]

  describe('rk4 integration (' + dtype + ')', function() {

    describe('integration of one variable', function() {
      var integrator, f, y0, t0, n

      beforeEach(function() {
        f = function(dydt, y) { dydt[0] = -y[0] }
        t0 = 1.5
        y0 = new ctor([1])
        n = 10

        integrator = rk4( y0, f, t0, 1/n )
      })

      it('creates work arrays of the same type as the input',function() {
        assert.equal( integrator._w.constructor,  y0.constructor )
        assert.equal( integrator._k1.constructor, y0.constructor )
        assert.equal( integrator._k2.constructor, y0.constructor )
        assert.equal( integrator._k3.constructor, y0.constructor )
        assert.equal( integrator._k4.constructor, y0.constructor )
      })

      it('creates work arrays of the same size as the input',function() {
        assert.equal( integrator._w.length,  y0.length )
        assert.equal( integrator._k1.length, y0.length )
        assert.equal( integrator._k2.length, y0.length )
        assert.equal( integrator._k3.length, y0.length )
        assert.equal( integrator._k4.length, y0.length )
      })

      it('takes multiple timesteps',function() {
        integrator.steps(n)
        assert.closeTo(integrator.y[0], Math.exp(-1), 1e-4 )
      })
    })

    describe('integration of two variables', function() {
      var integrator, f, y0, t0

      beforeEach(function() {
        f = function(dydt, y) {
          dydt[0] = -y[1]
          dydt[1] =  y[0]
        }

        t0 = 1.5
        y0 = new ctor([1,0])

        integrator = rk4( y0, f, t0, 1 )
      })

      it('creates work arrays of the same type as the input',function() {
        assert.equal( integrator._w.constructor,  y0.constructor )
        assert.equal( integrator._k1.constructor, y0.constructor )
        assert.equal( integrator._k2.constructor, y0.constructor )
        assert.equal( integrator._k3.constructor, y0.constructor )
        assert.equal( integrator._k4.constructor, y0.constructor )
      })

      it('creates work arrays of the same size as the input',function() {
        assert.equal( integrator._w.length,  y0.length )
        assert.equal( integrator._k1.length, y0.length )
        assert.equal( integrator._k2.length, y0.length )
        assert.equal( integrator._k3.length, y0.length )
        assert.equal( integrator._k4.length, y0.length )
      })

      it('takes a single timestep',function() {
        integrator.step()
        assert.closeTo( integrator.y[0], 0.5416666666666667, 1e-4 )
        assert.closeTo( integrator.y[1], 0.8333333333333333, 1e-4 )
      })

      it('increments the time',function() {
        integrator.step()
        assert.closeTo( integrator.t, t0 + integrator.dt, 1e-4 )
        integrator.step()
        assert.closeTo( integrator.t, t0 + 2*integrator.dt, 1e-4 )
      })

      it('takes multiple timesteps',function() {
        integrator.steps(2)
        assert.closeTo(integrator.y[0], -0.4010416666666664, 1e-4 )
        assert.closeTo(integrator.y[1], 0.9027777777777778, 1e-4)
      })
    })

    describe('convergence', function() {

      it('local truncation error is ~ O(h^5) in time', function() {
        // Integrate an exponential: dy/dt = -y  -->  y = exp(-t)
        var result = richardson(function(h) {
          var f = function(dydt, y) { dydt[0] = -y[0] }
          return rk4( new ctor([1]), f, 0, h ).step().y[0] - Math.exp(-h)
        }, [1,0.2], { f: 0 } )

        assert.closeTo( result.n, 5, 1e-1, 'n ~ 5' )
      })

      it('local truncation error of y is order O(h^5)', function() {
        var result = richardson(function(h) {

          // Integrate along a sector of a circle:
          var f = function(dydt, y) { dydt[0] = -y[1]; dydt[1] =  y[0] }
          var i = rk4( new ctor([1,0]), f, 0, h ).step()

          // Return the distance from the expected endpoint:
          return Math.sqrt( Math.pow(i.y[0]-Math.cos(h),2) + Math.pow(i.y[1]-Math.sin(h),2) )

        }, 2*Math.PI/20, { f: 0 } )

        assert.closeTo( result.n, 5, 1e-2, 'n ~ 5' )
      })

      it('total accumulated error of y is order O(h^4)', function() {

        var result = richardson(function(h) {

          // Integrate around a circle with this step size:
          var f = function(dydt, y) { dydt[0] = -y[1]; dydt[1] =  y[0] }
          var i = rk4( new ctor([1,0]), f, 0, h ).steps( Math.floor(2*Math.PI/h + 0.5) )

          // Return the distance from the expected endpoint:
          return Math.sqrt( Math.pow(i.y[0]-1,2) + Math.pow(i.y[1],2) )

        }, 2*Math.PI/20, { f: 0 } )

        assert.closeTo( result.n, 4, 1e-2, 'n ~ 4' )
      })

      it('total accumulated error is order O(h^4) in all variables', function() {

        var numSteps= 10

        var result = richardson(function(h) {
          // Integrate around a circle at an accelerating rate
          var f = function(dydt, y, t) {
            var s =  Math.sin(t * Math.PI) * Math.PI / 2
            dydt[0] = -y[1]* 2 * Math.PI * s
            dydt[1] =  y[0]* 2 * Math.PI * s
          }
          var i = rk4( new ctor([1,0,0]), f, 0, h ).steps( Math.floor(1/h+0.5))

          // Return the distance from the expected endpoint:
          return Math.sqrt( Math.pow(i.y[0]-1,2) + Math.pow(i.y[1],2) )

        }, 0.05, { f: 0 } )

        assert.closeTo( result.n, 4, 1e-2, 'n ~ 4' )
      })

    })

  })

})
<|endoftext|>


<commit_before>var inherit = require('../index.js').inherit;

exports.testIsFunction = function(test) {

    test.equal(typeof inherit, 'function');
    test.done();

};

exports.testInstanceProperties = function(test) {

    var A = inherit({
        __constructor : function(val) {
            this.prop = val;
        }
    });

    test.equal(new A('test').prop, 'test');
    test.equal(new A('other').prop, 'other');
    test.done();

};

exports.testInstanceOf = function(test) {

    var A = inherit({}),
        B = inherit(A, {});

    test.ok(new A() instanceof A);
    test.ok(!(new A() instanceof B));
    test.ok(new B() instanceof A);
    test.ok(new B() instanceof B);
    test.done();

};

exports.testSelf = function(test) {

    var A = inherit({}),
        B = inherit(A, {});

    test.strictEqual(new A().__self, A);
    test.strictEqual(new B().__self, B);
    test.done();

};

exports.testInherit = function(test) {

    var A = inherit({
        method1 : function() {
            return 'A';
        }
    }),
    B = inherit(A, {
        method2 : function() {
            return 'B';
        }
    });

    test.equal(typeof new A().method2, 'undefined');
    test.equal(new B().method1(), 'A');
    test.done();

};

exports.testStaticInherit = function(test) {

    var A = inherit({}, {
        method1 : function() {
            return 'A';
        }
    }),
    B = inherit(A, {}, {
        method2 : function() {
            return 'B';
        }
    });

    test.equal(typeof A.method2, 'undefined');
    test.equal(B.method1(), 'A');
    test.done();

};

exports.testOverride = function(test) {

    var A = inherit({
            method : function() {
                return 'A';
            }
        }),
        B = inherit(A, {
            method : function() {
                return 'B';
            }
        });

    test.equal(new A().method(), 'A');
    test.equal(new B().method(), 'B');
    test.done();

};

exports.testStaticOverride = function(test) {

    var A = inherit({}, {
            method : function() {
                return 'A';
            }
        }),
        B = inherit(A, {}, {
            method : function() {
                return 'B';
            }
        });

    test.equal(A.method(), 'A');
    test.equal(B.method(), 'B');
    test.done();

};

exports.testBase = function(test) {

    var A = inherit({
            method1 : function() {
                return 'A';
            }
        }),
        B = inherit(A, {
            method1 : function() {
                return this.__base() + 'B';
            },
            method2 : function() {
                return this.__base() + 'B2';
            }
        });

    test.equal(new B().method1(), 'AB');
    test.equal(new B().method2(), 'undefinedB2');
    test.done();

};

exports.testStaticBase = function(test) {

    var A = inherit({}, {
            staticMethod : function() {
                return 'A';
            }
        }),
        B = inherit(A, {}, {
            staticMethod : function() {
                return this.__base() + 'B';
            }
        });

    test.equal(B.staticMethod(), 'AB');
    test.done();

};<commit_msg>codestyle fixed<commit_after>var inherit = require('../index.js').inherit;

exports.testIsFunction = function(test) {

    test.equal(typeof inherit, 'function');
    test.done();

};

exports.testInstanceProperties = function(test) {

    var A = inherit({
        __constructor : function(val) {
            this.prop = val;
        }
    });

    test.equal(new A('test').prop, 'test');
    test.equal(new A('other').prop, 'other');
    test.done();

};

exports.testInstanceOf = function(test) {

    var A = inherit({}),
        B = inherit(A, {});

    test.ok(new A() instanceof A);
    test.ok(!(new A() instanceof B));
    test.ok(new B() instanceof A);
    test.ok(new B() instanceof B);
    test.done();

};

exports.testSelf = function(test) {

    var A = inherit({}),
        B = inherit(A, {});

    test.strictEqual(new A().__self, A);
    test.strictEqual(new B().__self, B);
    test.done();

};

exports.testInherit = function(test) {

    var A = inherit({
            method1 : function() {
                return 'A';
            }
        }),
        B = inherit(A, {
            method2 : function() {
                return 'B';
            }
        });

    test.equal(typeof new A().method2, 'undefined');
    test.equal(new B().method1(), 'A');
    test.done();

};

exports.testStaticInherit = function(test) {

    var A = inherit({}, {
            method1 : function() {
                return 'A';
            }
        }),
        B = inherit(A, {}, {
            method2 : function() {
                return 'B';
            }
        });

    test.equal(typeof A.method2, 'undefined');
    test.equal(B.method1(), 'A');
    test.done();

};

exports.testOverride = function(test) {

    var A = inherit({
            method : function() {
                return 'A';
            }
        }),
        B = inherit(A, {
            method : function() {
                return 'B';
            }
        });

    test.equal(new A().method(), 'A');
    test.equal(new B().method(), 'B');
    test.done();

};

exports.testStaticOverride = function(test) {

    var A = inherit({}, {
            method : function() {
                return 'A';
            }
        }),
        B = inherit(A, {}, {
            method : function() {
                return 'B';
            }
        });

    test.equal(A.method(), 'A');
    test.equal(B.method(), 'B');
    test.done();

};

exports.testBase = function(test) {

    var A = inherit({
            method1 : function() {
                return 'A';
            }
        }),
        B = inherit(A, {
            method1 : function() {
                return this.__base() + 'B';
            },
            method2 : function() {
                return this.__base() + 'B2';
            }
        });

    test.equal(new B().method1(), 'AB');
    test.equal(new B().method2(), 'undefinedB2');
    test.done();

};

exports.testStaticBase = function(test) {

    var A = inherit({}, {
            staticMethod : function() {
                return 'A';
            }
        }),
        B = inherit(A, {}, {
            staticMethod : function() {
                return this.__base() + 'B';
            }
        });

    test.equal(B.staticMethod(), 'AB');
    test.done();

};<|endoftext|>


<commit_before>var assert       = require('assert');
var _            = require('underscore');
var fixTitlecase = require('../lib/fix-titlecase');

var titleFixtures = {
  "PHP: tiff2pdf": "PHP: tiff2pdf",
  "follow step-by-step instructions": "Follow Step-by-Step Instructions",
  "this sub-phrase is nice": "This Sub-Phrase Is Nice",
  "catchy title: a subtitle": "Catchy Title: A Subtitle",
  "catchy title: \"a quoted subtitle\"": "Catchy Title: \"A Quoted Subtitle\"",
  "catchy title: \“‘a twice quoted subtitle’\”": "Catchy Title: \“‘A Twice Quoted Subtitle’\”",
  "\"a title inside double quotes\"": "\"A Title Inside Double Quotes\"",
  "all words capitalized": "All Words Capitalized",
  "small words are for by and of lowercase": "Small Words Are for by and of Lowercase",
  "a small word starts": "A Small Word Starts",
  "a small word it ends on": "A Small Word It Ends On",
  "do questions work?": "Do Questions Work?",
  "multiple sentences. more than one.": "Multiple Sentences. More Than One.",
  "Ends with small word of": "Ends With Small Word Of",
  "double quoted \"inner\" word": "Double Quoted \"Inner\" Word",
  "single quoted 'inner' word": "Single Quoted 'Inner' Word",
  "fancy double quoted “inner” word": "Fancy Double Quoted “Inner” Word",
  "fancy single quoted ‘inner’ word": "Fancy Single Quoted ‘Inner’ Word",
  "this vs. that": "This vs. That",
  "this vs that": "This vs That",
  "this v. that": "This v. That",
  "this v that": "This v That",
  "address email@example.com titles": "Address email@example.com Titles",
  "pass camelCase through": "Pass camelCase Through",
  "don't break": "Don't Break",
  "catchy title: substance subtitle": "Catchy Title: Substance Subtitle",
  "we keep NASA capitalized": "We Keep NASA Capitalized",
  "leave Q&A unscathed": "Leave Q&A Unscathed",
  "Scott Moritz and TheStreet.com’s million iPhone la-la land": "Scott Moritz and TheStreet.com’s Million iPhone La-La Land",
  "you have a http://example.com/foo/ title": "You Have a http://example.com/foo/ Title",
  "your hair[cut] looks (nice)": "Your Hair[cut] Looks (Nice)",
  "keep that colo(u)r": "Keep That Colo(u)r",
  "have you read “The Lottery”?": "Have You Read “The Lottery”?",
  "Read markdown_rules.txt to find out how _underscores around words_ will be interpreted": "Read markdown_rules.txt to Find Out How _Underscores Around Words_ Will Be Interpreted",
  "Read markdown_rules.txt to find out how *asterisks around words* will be interpreted": "Read markdown_rules.txt to Find Out How *Asterisks Around Words* Will Be Interpreted",
  "Notes and observations regarding Apple’s announcements from ‘The Beat Goes On’ special event": "Notes and Observations Regarding Apple’s Announcements From ‘The Beat Goes On’ Special Event",
  "Drink this piña colada while you listen to ænima": "Drink This Piña Colada While You Listen to Ænima",
  "capitalize hyphenated words on-demand": "Capitalize Hyphenated Words On-Demand"
};

var postFixtures = {
  '---\ntitle: "Deploy to a dynamic serverlist with Capistrano"': '---\ntitle: "Deploy to a Dynamic Serverlist With Capistrano"',
  '---\ntitle: "Access MySQL Without Password "': '---\ntitle: "Access MySQL Without Password"',
  '---\ntitle: "Better performance with mod_deflate"': '---\ntitle: "Better Performance With mod_deflate"',
  '---\ntitle: "New `frame` parameter for the /image/resize robot"': '---\ntitle: "New `frame` Parameter for the /image/resize Robot"',
  '---\ntitle: "A word on the focus of php.js"': '---\ntitle: "A Word on the Focus of php.js"',
  '---\ntitle: "Welcome to node.js"': null
};

describe('fixTitlecase', function(){
  describe('newPost', function(){
    it('should give an error for no frontmatter', function(done){
      fixTitlecase.newPost('title: Hey', function (err, actualPost, oldTitle, newTitle) {
        assert.strictEqual('No frontmatter in post', err);
        done();
      });
    });
    _.each(postFixtures, function(expectedPost, brokenPost) {
      it('should become ' + (expectedPost+'').replace('---\n', ''), function(done){
        fixTitlecase.newPost(brokenPost, function (err, actualPost, oldTitle, newTitle) {
          assert.strictEqual(null, err);
          assert.strictEqual(actualPost, expectedPost);
          done();
        });
      });
    });
  });
  describe('toTitleCase', function(){
    _.each(titleFixtures, function(expectedTitle, brokenTitle) {
      it('should become ' + (expectedTitle), function(){
        var actualTitle = fixTitlecase.toTitleCase(brokenTitle);
        assert.strictEqual(actualTitle, expectedTitle);
      });
    });
  });
});
<commit_msg>Add testcase for preserving MD5<commit_after>var assert       = require('assert');
var _            = require('underscore');
var fixTitlecase = require('../lib/fix-titlecase');

var titleFixtures = {
  "PHP: tiff2pdf": "PHP: tiff2pdf",
  "follow step-by-step instructions": "Follow Step-by-Step Instructions",
  "this sub-phrase is nice": "This Sub-Phrase Is Nice",
  "catchy title: a subtitle": "Catchy Title: A Subtitle",
  "catchy title: \"a quoted subtitle\"": "Catchy Title: \"A Quoted Subtitle\"",
  "catchy title: “‘a twice quoted subtitle’”": "Catchy Title: “‘A Twice Quoted Subtitle’”",
  "\"a title inside double quotes\"": "\"A Title Inside Double Quotes\"",
  "all words capitalized": "All Words Capitalized",
  "small words are for by and of lowercase": "Small Words Are for by and of Lowercase",
  "a small word starts": "A Small Word Starts",
  "a small word it ends on": "A Small Word It Ends On",
  "do questions work?": "Do Questions Work?",
  "multiple sentences. more than one.": "Multiple Sentences. More Than One.",
  "Ends with small word of": "Ends With Small Word Of",
  "double quoted \"inner\" word": "Double Quoted \"Inner\" Word",
  "single quoted 'inner' word": "Single Quoted 'Inner' Word",
  "fancy double quoted “inner” word": "Fancy Double Quoted “Inner” Word",
  "fancy single quoted ‘inner’ word": "Fancy Single Quoted ‘Inner’ Word",
  "We Added Support for MD5 File Hashes": "We Added Support for MD5 File Hashes",
  "this vs. that": "This vs. That",
  "this vs that": "This vs That",
  "this v. that": "This v. That",
  "this v that": "This v That",
  "address email@example.com titles": "Address email@example.com Titles",
  "pass camelCase through": "Pass camelCase Through",
  "don't break": "Don't Break",
  "catchy title: substance subtitle": "Catchy Title: Substance Subtitle",
  "we keep NASA capitalized": "We Keep NASA Capitalized",
  "leave Q&A unscathed": "Leave Q&A Unscathed",
  "Scott Moritz and TheStreet.com’s million iPhone la-la land": "Scott Moritz and TheStreet.com’s Million iPhone La-La Land",
  "you have a http://example.com/foo/ title": "You Have a http://example.com/foo/ Title",
  "your hair[cut] looks (nice)": "Your Hair[cut] Looks (Nice)",
  "keep that colo(u)r": "Keep That Colo(u)r",
  "have you read “The Lottery”?": "Have You Read “The Lottery”?",
  "Read markdown_rules.txt to find out how _underscores around words_ will be interpreted": "Read markdown_rules.txt to Find Out How _Underscores Around Words_ Will Be Interpreted",
  "Read markdown_rules.txt to find out how *asterisks around words* will be interpreted": "Read markdown_rules.txt to Find Out How *Asterisks Around Words* Will Be Interpreted",
  "Notes and observations regarding Apple’s announcements from ‘The Beat Goes On’ special event": "Notes and Observations Regarding Apple’s Announcements From ‘The Beat Goes On’ Special Event",
  "Drink this piña colada while you listen to ænima": "Drink This Piña Colada While You Listen to Ænima",
  "capitalize hyphenated words on-demand": "Capitalize Hyphenated Words On-Demand"
};

var postFixtures = {
  '---\ntitle: "Deploy to a dynamic serverlist with Capistrano"': '---\ntitle: "Deploy to a Dynamic Serverlist With Capistrano"',
  '---\ntitle: "Access MySQL Without Password "': '---\ntitle: "Access MySQL Without Password"',
  '---\ntitle: "Better performance with mod_deflate"': '---\ntitle: "Better Performance With mod_deflate"',
  '---\ntitle: "New `frame` parameter for the /image/resize robot"': '---\ntitle: "New `frame` Parameter for the /image/resize Robot"',
  '---\ntitle: "A word on the focus of php.js"': '---\ntitle: "A Word on the Focus of php.js"',
  '---\ntitle: "Welcome to node.js"': null
};

describe('fixTitlecase', function(){
  describe('newPost', function(){
    it('should give an error for no frontmatter', function(done){
      fixTitlecase.newPost('title: Hey', function (err, actualPost, oldTitle, newTitle) {
        assert.strictEqual('No frontmatter in post', err);
        done();
      });
    });
    _.each(postFixtures, function(expectedPost, brokenPost) {
      it('should become ' + (expectedPost+'').replace('---\n', ''), function(done){
        fixTitlecase.newPost(brokenPost, function (err, actualPost, oldTitle, newTitle) {
          assert.strictEqual(null, err);
          assert.strictEqual(actualPost, expectedPost);
          done();
        });
      });
    });
  });
  describe('toTitleCase', function(){
    _.each(titleFixtures, function(expectedTitle, brokenTitle) {
      it('should become ' + (expectedTitle), function(){
        var actualTitle = fixTitlecase.toTitleCase(brokenTitle);
        assert.strictEqual(actualTitle, expectedTitle);
      });
    });
  });
});
<|endoftext|>


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

describe("headers", function() {
  it("h1", function() {
    expect(downshow("
H1
")).to.equal('# H1');
  });

  it("h2", function() {
    expect(downshow("
H2
")).to.equal('## H2');
  });

  it("h3", function() {
    expect(downshow("
H3
")).to.equal('### H3');
  });

  it("h4", function() {
    expect(downshow("
H4
")).to.equal('#### H4');
  });

  it("h5", function() {
    expect(downshow("
H5
")).to.equal('##### H5');
  });

  it("h6", function() {
    expect(downshow("
H6
")).to.equal('###### H6');
  });

  it("h1+h2", function() {
    expect(downshow("
H1

H2
")).to.equal("# H1\n\n## H2");
  });
});

describe("inline span elements", function() {
  it("bold", function() {
    expect(downshow("bold")).to.equal("**bold**");
    expect(downshow("bold")).to.equal("**bold**");
  });

  it("italic", function() {
    expect(downshow("italic")).to.equal("_italic_");
    expect(downshow("italic")).to.equal("_italic_");
  });

  it("nested bold and italic.", function() {
    expect(downshow("bold and italic.")).to.equal("**bold and _italic_.**");
    expect(downshow("bold and italic.")).to.equal("_bold and **italic**._");
  });

  it("image", function() {
    var html = "";
    var md = "![example image](http://example.com/img/62838.jpg \"example title\")";
    expect(downshow(html)).to.equal(md);

    html = "";
    md = "![example image](http://example.com/img/62838.jpg)";
    expect(downshow(html)).to.equal(md);

    html = "";
    md = "![](http://example.com/img/62838.jpg)";
    expect(downshow(html)).to.equal(md);
  });

  it("link", function() {
    var html = "example link";
    var md = "[example link](http://www.example.com/ \"example title\")";
    expect(downshow(html)).to.equal(md);

    html = "example title";
    md = "[example title](http://www.example.com/)";
    expect(downshow(html)).to.equal(md);
  });
});

describe("separator elements", function() {
  it("br", function() {
    expect(downshow("a
b")).to.equal("a\n\nb");
  });

  it("hr", function() {
    expect(downshow("
")).to.equal("***");
    expect(downshow("a
b")).to.equal("a\n***\nb");
  });
});

describe("lists", function() {
  it("unordered list", function() {
    var html = "

item a

item b

";
    var md = "- item a\n- item b";
    expect(downshow(html)).to.equal(md);
  });

  it("ordered list", function() {
    var html = "

item a

item b

";
    var md = "1. item a\n1. item b";
    expect(downshow(html)).to.equal(md);
  });

  it("2-level lists", function() {
    var html = "

item a

item aa

item ab

item b

";
    var md = "- item a\n    - item aa\n    - item ab\n- item b";
    expect(downshow(html)).to.equal(md);
  });

  it("3-level lists", function() {
    var html = "

item a

item aa

item ab

item aba

item abb

item b

";
    var md = "- item a\n    - item aa\n    - item ab\n        - item aba\n        - item abb\n- item b";
    expect(downshow(html)).to.equal(md);
  });
});

describe("blockquotes", function() {
  it("single blockquote", function() {
    var html = "
This is blockquoted
";
    var md = "> This is blockquoted";
    expect(downshow(html)).to.equal(md);
  });

  it("separated blockquote", function() {
    var html = "
This is blockquoted

and this too
";
    var md = "> This is blockquoted\n\n> and this too";
    expect(downshow(html)).to.equal(md);
  });

  it("paragrphs in blocquotes", function() {
    var html = "
\n
Lorem ipsum
\n
Lorem ipsum
\n
";
    var md = "> Lorem ipsum\n\n> Lorem ipsum";
    expect(downshow(html)).to.equal(md);

    html = "
\n
Lorem ipsum
\n
\n
\n
Lorem ipsum
\n
";
    expect(downshow(html)).to.equal(md);
  });

  it("nested blockquote", function() {
    var html = "
blockquoted
nested blockquoted

";
    var md = "> blockquoted\n\n> > nested blockquoted";
    expect(downshow(html)).to.equal(md);
  });
});

describe("code formatting", function() {
  it("inline code", function () {
    expect(downshow("hello world")).to.equal("`hello world`");
  });

  it("block code", function() {
    var html = "";
    html += "
";
    html += "  void main(String[] args) {\n";
    html += "    System.out.println(\"Hello Markdown\");\n";
    html += "  }";
    html += "
";

    var md = "";
    md += "    " + "  void main(String[] args) {\n";
    md += "    " + "    System.out.println(\"Hello Markdown\");\n";
    md += "    " + "  }";

    expect(downshow(html)).to.equal(md);
  });
});

describe("empty elements", function() {
  it("img", function() {
    expect(downshow("")).to.equal("");
  });

  it("link", function() {
    expect(downshow("Empty Link Text")).to.equal("");
  });

  it("lists", function() {
    expect(downshow("

item 1

")).to.equal("1. item 1");
    expect(downshow("

item 1

")).to.equal("- item 1");
  });

  it("other elements", function() {
    expect(downshow("

")).to.equal('');
    expect(downshow("

")).to.equal('');
    expect(downshow("

")).to.equal('');
    expect(downshow("

")).to.equal('');
    expect(downshow("

")).to.equal('');
    expect(downshow("

")).to.equal('');
    expect(downshow("

")).to.equal('');
    expect(downshow("

")).to.equal('');
    expect(downshow("  ")).to.equal('');
    expect(downshow("  ")).to.equal('');
  });
});

describe("word spacing", function () {
  it("bold", function() {
    expect(downshow(" hello  world!  ")).to.equal("**hello world!**");
    expect(downshow("  ")).to.equal('');
  });

  it("italic", function() {
    expect(downshow(" hello  world! ")).to.equal("_hello world!_");
    expect(downshow("  ")).to.equal('');
  });

  it("paragraph", function () {
    var html = "this is text before paragraph
This is a paragraph
this is text after paragraph";
    var md = "this is text before paragraph\n\nThis is a paragraph\n\nthis is text after paragraph";
    expect(downshow(html)).to.equal(md);
  });

  it("headers", function() {
    expect(downshow("
 lorem   ipsum  dolor   sit   amet
")).to.equal('# lorem ipsum dolor sit amet');
    expect(downshow("
 lorem   ipsum  dolor   sit   amet
")).to.equal('## lorem ipsum dolor sit amet');
    expect(downshow("
 lorem   ipsum  dolor   sit   amet
")).to.equal('### lorem ipsum dolor sit amet');
    expect(downshow("
 lorem   ipsum  dolor   sit   amet
")).to.equal('#### lorem ipsum dolor sit amet');
    expect(downshow("
 lorem   ipsum  dolor   sit   amet
")).to.equal('##### lorem ipsum dolor sit amet');
    expect(downshow("
 lorem   ipsum  dolor   sit   amet
")).to.equal('###### lorem ipsum dolor sit amet');
  });

  it("span element", function() {
    expect(downshow("this is span element")).to.equal("this is span element");
    expect(downshow("beforethis is span elementafter")).to.equal("beforethis is span elementafter");
    expect(downshow("before this is span element after")).to.equal("before this is span element after");
    expect(downshow("before  this is span element  after")).to.equal("before this is span element after");
  });
});
<commit_msg>Fixed bold text in two following paragraphs issue (issue 3<commit_after>var downshow = require('..');
var expect = require('chai').expect;

describe("headers", function() {
  it("h1", function() {
    expect(downshow("
H1
")).to.equal('# H1');
  });

  it("h2", function() {
    expect(downshow("
H2
")).to.equal('## H2');
  });

  it("h3", function() {
    expect(downshow("
H3
")).to.equal('### H3');
  });

  it("h4", function() {
    expect(downshow("
H4
")).to.equal('#### H4');
  });

  it("h5", function() {
    expect(downshow("
H5
")).to.equal('##### H5');
  });

  it("h6", function() {
    expect(downshow("
H6
")).to.equal('###### H6');
  });

  it("h1+h2", function() {
    expect(downshow("
H1

H2
")).to.equal("# H1\n\n## H2");
  });
});

describe("inline span elements", function() {
  it("bold", function() {
    expect(downshow("bold")).to.equal("**bold**");
    expect(downshow("bold")).to.equal("**bold**");
  });

  it("italic", function() {
    expect(downshow("italic")).to.equal("_italic_");
    expect(downshow("italic")).to.equal("_italic_");
  });

  it("nested bold and italic.", function() {
    expect(downshow("bold and italic.")).to.equal("**bold and _italic_.**");
    expect(downshow("bold and italic.")).to.equal("_bold and **italic**._");
  });

  it("image", function() {
    var html = "";
    var md = "![example image](http://example.com/img/62838.jpg \"example title\")";
    expect(downshow(html)).to.equal(md);

    html = "";
    md = "![example image](http://example.com/img/62838.jpg)";
    expect(downshow(html)).to.equal(md);

    html = "";
    md = "![](http://example.com/img/62838.jpg)";
    expect(downshow(html)).to.equal(md);
  });

  it("link", function() {
    var html = "example link";
    var md = "[example link](http://www.example.com/ \"example title\")";
    expect(downshow(html)).to.equal(md);

    html = "example title";
    md = "[example title](http://www.example.com/)";
    expect(downshow(html)).to.equal(md);
  });
});

describe("separator elements", function() {
  it("br", function() {
    expect(downshow("a
b")).to.equal("a\n\nb");
  });

  it("hr", function() {
    expect(downshow("
")).to.equal("***");
    expect(downshow("a
b")).to.equal("a\n***\nb");
  });
});

describe("lists", function() {
  it("unordered list", function() {
    var html = "

item a

item b

";
    var md = "- item a\n- item b";
    expect(downshow(html)).to.equal(md);
  });

  it("ordered list", function() {
    var html = "

item a

item b

";
    var md = "1. item a\n1. item b";
    expect(downshow(html)).to.equal(md);
  });

  it("2-level lists", function() {
    var html = "

item a

item aa

item ab

item b

";
    var md = "- item a\n    - item aa\n    - item ab\n- item b";
    expect(downshow(html)).to.equal(md);
  });

  it("3-level lists", function() {
    var html = "

item a

item aa

item ab

item aba

item abb

item b

";
    var md = "- item a\n    - item aa\n    - item ab\n        - item aba\n        - item abb\n- item b";
    expect(downshow(html)).to.equal(md);
  });
});

describe("blockquotes", function() {
  it("single blockquote", function() {
    var html = "
This is blockquoted
";
    var md = "> This is blockquoted";
    expect(downshow(html)).to.equal(md);
  });

  it("separated blockquote", function() {
    var html = "
This is blockquoted

and this too
";
    var md = "> This is blockquoted\n\n> and this too";
    expect(downshow(html)).to.equal(md);
  });

  it("paragrphs in blocquotes", function() {
    var html = "
\n
Lorem ipsum
\n
Lorem ipsum
\n
";
    var md = "> Lorem ipsum\n\n> Lorem ipsum";
    expect(downshow(html)).to.equal(md);

    html = "
\n
Lorem ipsum
\n
\n
\n
Lorem ipsum
\n
";
    expect(downshow(html)).to.equal(md);
  });

  it("nested blockquote", function() {
    var html = "
blockquoted
nested blockquoted

";
    var md = "> blockquoted\n\n> > nested blockquoted";
    expect(downshow(html)).to.equal(md);
  });
});

describe("code formatting", function() {
  it("inline code", function () {
    expect(downshow("hello world")).to.equal("`hello world`");
  });

  it("block code", function() {
    var html = "";
    html += "
";
    html += "  void main(String[] args) {\n";
    html += "    System.out.println(\"Hello Markdown\");\n";
    html += "  }";
    html += "
";

    var md = "";
    md += "    " + "  void main(String[] args) {\n";
    md += "    " + "    System.out.println(\"Hello Markdown\");\n";
    md += "    " + "  }";

    expect(downshow(html)).to.equal(md);
  });
});

describe("empty elements", function() {
  it("img", function() {
    expect(downshow("")).to.equal("");
  });

  it("link", function() {
    expect(downshow("Empty Link Text")).to.equal("");
  });

  it("lists", function() {
    expect(downshow("

item 1

")).to.equal("1. item 1");
    expect(downshow("

item 1

")).to.equal("- item 1");
  });

  it("other elements", function() {
    expect(downshow("

")).to.equal('');
    expect(downshow("

")).to.equal('');
    expect(downshow("

")).to.equal('');
    expect(downshow("

")).to.equal('');
    expect(downshow("

")).to.equal('');
    expect(downshow("

")).to.equal('');
    expect(downshow("

")).to.equal('');
    expect(downshow("

")).to.equal('');
    expect(downshow("  ")).to.equal('');
    expect(downshow("  ")).to.equal('');
  });
});

describe("word spacing", function () {
  it("bold", function() {
    expect(downshow(" hello  world!  ")).to.equal("**hello world!**");
    expect(downshow("  ")).to.equal('');
  });

  it("italic", function() {
    expect(downshow(" hello  world! ")).to.equal("_hello world!_");
    expect(downshow("  ")).to.equal('');
  });

  it("paragraph", function () {
    var html = "this is text before paragraph
This is a paragraph
this is text after paragraph";
    var md = "this is text before paragraph\n\nThis is a paragraph\n\nthis is text after paragraph";
    expect(downshow(html)).to.equal(md);
  });

  it("headers", function() {
    expect(downshow("
 lorem   ipsum  dolor   sit   amet
")).to.equal('# lorem ipsum dolor sit amet');
    expect(downshow("
 lorem   ipsum  dolor   sit   amet
")).to.equal('## lorem ipsum dolor sit amet');
    expect(downshow("
 lorem   ipsum  dolor   sit   amet
")).to.equal('### lorem ipsum dolor sit amet');
    expect(downshow("
 lorem   ipsum  dolor   sit   amet
")).to.equal('#### lorem ipsum dolor sit amet');
    expect(downshow("
 lorem   ipsum  dolor   sit   amet
")).to.equal('##### lorem ipsum dolor sit amet');
    expect(downshow("
 lorem   ipsum  dolor   sit   amet
")).to.equal('###### lorem ipsum dolor sit amet');
  });

  it("span element", function() {
    expect(downshow("this is span element")).to.equal("this is span element");
    expect(downshow("beforethis is span elementafter")).to.equal("beforethis is span elementafter");
    expect(downshow("before this is span element after")).to.equal("before this is span element after");
    expect(downshow("before  this is span element  after")).to.equal("before this is span element after");
  });
});

describe("paragraphs", function () {
  it("should separate paragraphs with inline markup", function () {
    expect(downshow("
1

2
")).to.equal("**1**\n\n**2**");
  });
});
<|endoftext|>


<commit_before>'use strict';

const config = require('config');
const expect = require('chai').expect;
const nock = require('nock');
const supertest = require('supertest-as-promised');
const range = require('lodash/range');
const buildApp = require('./util/buildApp');
const assertBadge = require('./util/assertBadge');
const badgeVault = require('../lib/util/badgeVault');

const request = supertest.agent(buildApp().listen());

afterEach(() => nock.cleanAll());

describe('behavior', () => {
    it('should round score and display appropriate badge', () => {
        nock('http://127.0.0.1:9200')
        .get('/npms-current/module/gulp')
        .query({ _source: 'score.final' })
        .reply(200, {
            _source: { score: { final: 0.888 } },
        });

        return request
        .get('/gulp.svg')
        .expect(200)
        .then((res) => {
            expect(res.headers['content-type']).to.contain('svg');
            assertBadge(res.body, 89, { format: 'svg' });
            expect(nock.isDone()).to.equal(true);
        });
    });

    it('should render unknown badge if module does not exist', () => {
        nock('http://127.0.0.1:9200')
        .get('/npms-current/module/gulp')
        .query({ _source: 'score.final' })
        .reply(404, {});

        return request
        .get('/gulp.svg')
        .expect(200)
        .then((res) => {
            expect(res.headers['content-type']).to.contain('svg');
            assertBadge(res.body, null, { format: 'svg' });
            expect(nock.isDone()).to.equal(true);
        });
    });

    it('should render unknown badge if score is not yet calculated', () => {
        nock('http://127.0.0.1:9200')
        .get('/npms-current/module/gulp')
        .query({ _source: 'score.final' })
        .reply(200, {});

        return request
        .get('/gulp.svg')
        .expect(200)
        .then((res) => {
            expect(res.headers['content-type']).to.contain('svg');
            assertBadge(res.body, null, { format: 'svg' });
            expect(nock.isDone()).to.equal(true);
        });
    });
});

describe('errors & validation', () => {
    it('should fail on invalid endpoint', () => {
        return request
        .get('/gulp')
        .expect(404, { code: 'NOT_FOUND', message: 'The specified endpoint does not exist' })
        .then((res) => {
            expect(res.body).to.eql({ code: 'NOT_FOUND', message: 'The specified endpoint does not exist' });
        });
    });

    it('should fail on invalid module name', () => {
        return request
        .get('/_foo.svg')
        .expect(400, { code: 'INVALID_PARAMETER', message: 'name cannot start with an underscore ("_foo")' });
    });

    it('should fail on invalid format', () => {
        return request
        .get('/foo.foo')
        .expect(400, { code: 'INVALID_PARAMETER', message: 'child "format" fails because ["format" must be one of \
[svg, png, json]]' });
    });

    it('should fail on invalid style', () => {
        return request
        .get('/foo.svg?style=foo')
        .expect(400, { code: 'INVALID_PARAMETER', message: 'child "style" fails because ["style" must be one of \
[flat, flat-square, plastic]]' });
    });

    it('should fail if style is specified with json format', () => {
        return request
        .get('/foo.json?style=foo')
        .expect(400, { code: 'INVALID_PARAMETER', message: 'child "style" fails because ["style" is not allowed]' });
    });
});

describe('cache', () => {
    it('should set cache-control headers to cache badges', () => {
        nock('http://127.0.0.1:9200')
        .get('/npms-current/module/gulp')
        .query({ _source: 'score.final' })
        .reply(200, {
            _source: { score: { final: 0.8 } },
        });

        return request
        .get('/gulp.svg')
        .expect(200)
        .then((res) => {
            expect(res.headers['cache-control']).to.equal(`public,max-age=${config.get('app.maxAge')}`);
            expect(nock.isDone()).to.equal(true);
        });
    });

    it('should set cache-control headers to not cache unknown badges', () => {
        nock('http://127.0.0.1:9200')
        .get('/npms-current/module/gulp')
        .query({ _source: 'score.final' })
        .reply(404);

        return request
        .get('/gulp.svg')
        .expect(200)
        .then((res) => {
            expect(res.headers['cache-control']).to.equal('public,no-cache');
            expect(nock.isDone()).to.equal(true);
        });
    });

    it('should respect ETag', () => {
        nock('http://127.0.0.1:9200')
        .get('/npms-current/module/gulp')
        .query({ _source: 'score.final' })
        .reply(200, {
            _source: { score: { final: 0.8 } },
        });

        const badgeInfo = badgeVault.info(0.8, { format: 'svg', revision: config.get('app.revision') });

        return request
        .get('/gulp.svg')
        .set('If-None-Match', `W/"${badgeInfo.id}"`)
        .expect(304)
        .then((res) => {
            expect(res.body).to.be.empty;
        });
    });
});

describe('scores, formats and styles', () => {
    const formats = ['svg', 'png'];
    const styles = ['flat', 'flat-square', 'plastic'];
    const scores = range(0, 101).map((score) => score / 100);

    // Images
    formats.forEach((format) => {
        styles.forEach((style) => {
            scores.forEach((score) => {
                it(`should output a ${style} ${format} image for score ${score}`, () => {
                    nock('http://127.0.0.1:9200')
                    .get('/npms-current/module/gulp')
                    .query({ _source: 'score.final' })
                    .reply(200, {
                        _source: { score: { final: score } },
                    });

                    return request
                    .get(`/gulp.${format}?style=${style}`)
                    .expect(200)
                    .then((res) => {
                        expect(res.headers['content-type']).to.contain(format);
                        assertBadge(res.body, score * 100, { style, format });
                        expect(nock.isDone()).to.equal(true);
                    });
                });
            });
        });
    });

    // JSON
    it('should output JSON', () => {
        nock('http://127.0.0.1:9200')
        .get('/npms-current/module/gulp')
        .query({ _source: 'score.final' })
        .reply(200, {
            _source: { score: { final: 0.888 } },
        });

        return request
        .get('/gulp.json')
        .expect(200)
        .then((res) => {
            expect(res.headers['content-type']).to.contain('json');
            expect(res.body).to.eql({ name: 'npms score', value: '89%' });
            expect(nock.isDone()).to.equal(true);
        });
    });
});
<commit_msg>Fix tests.<commit_after>'use strict';

const config = require('config');
const expect = require('chai').expect;
const nock = require('nock');
const supertest = require('supertest-as-promised');
const range = require('lodash/range');
const buildApp = require('./util/buildApp');
const assertBadge = require('./util/assertBadge');
const badgeVault = require('../lib/util/badgeVault');

const request = supertest.agent(buildApp().listen());

afterEach(() => nock.cleanAll());

describe('behavior', () => {
    it('should round score and display appropriate badge', () => {
        nock('http://127.0.0.1:9200')
        .get('/npms-current/score/gulp')
        .query({ _source: 'score.final' })
        .reply(200, {
            _source: { score: { final: 0.888 } },
        });

        return request
        .get('/gulp.svg')
        .expect(200)
        .then((res) => {
            expect(res.headers['content-type']).to.contain('svg');
            assertBadge(res.body, 89, { format: 'svg' });
            expect(nock.isDone()).to.equal(true);
        });
    });

    it('should render unknown badge if score does not exist', () => {
        nock('http://127.0.0.1:9200')
        .get('/npms-current/score/gulp')
        .query({ _source: 'score.final' })
        .reply(404, {});

        return request
        .get('/gulp.svg')
        .expect(200)
        .then((res) => {
            expect(res.headers['content-type']).to.contain('svg');
            assertBadge(res.body, null, { format: 'svg' });
            expect(nock.isDone()).to.equal(true);
        });
    });

    it('should render unknown badge if score is not yet calculated', () => {
        nock('http://127.0.0.1:9200')
        .get('/npms-current/score/gulp')
        .query({ _source: 'score.final' })
        .reply(200, {});

        return request
        .get('/gulp.svg')
        .expect(200)
        .then((res) => {
            expect(res.headers['content-type']).to.contain('svg');
            assertBadge(res.body, null, { format: 'svg' });
            expect(nock.isDone()).to.equal(true);
        });
    });
});

describe('errors & validation', () => {
    it('should fail on invalid endpoint', () => {
        return request
        .get('/gulp')
        .expect(404, { code: 'NOT_FOUND', message: 'The specified endpoint does not exist' })
        .then((res) => {
            expect(res.body).to.eql({ code: 'NOT_FOUND', message: 'The specified endpoint does not exist' });
        });
    });

    it('should fail on invalid score name', () => {
        return request
        .get('/_foo.svg')
        .expect(400, { code: 'INVALID_PARAMETER', message: 'name cannot start with an underscore ("_foo")' });
    });

    it('should fail on invalid format', () => {
        return request
        .get('/foo.foo')
        .expect(400, { code: 'INVALID_PARAMETER', message: 'child "format" fails because ["format" must be one of \
[svg, png, json]]' });
    });

    it('should fail on invalid style', () => {
        return request
        .get('/foo.svg?style=foo')
        .expect(400, { code: 'INVALID_PARAMETER', message: 'child "style" fails because ["style" must be one of \
[flat, flat-square, plastic]]' });
    });

    it('should fail if style is specified with json format', () => {
        return request
        .get('/foo.json?style=foo')
        .expect(400, { code: 'INVALID_PARAMETER', message: 'child "style" fails because ["style" is not allowed]' });
    });
});

describe('cache', () => {
    it('should set cache-control headers to cache badges', () => {
        nock('http://127.0.0.1:9200')
        .get('/npms-current/score/gulp')
        .query({ _source: 'score.final' })
        .reply(200, {
            _source: { score: { final: 0.8 } },
        });

        return request
        .get('/gulp.svg')
        .expect(200)
        .then((res) => {
            expect(res.headers['cache-control']).to.equal(`public,max-age=${config.get('app.maxAge')}`);
            expect(nock.isDone()).to.equal(true);
        });
    });

    it('should set cache-control headers to not cache unknown badges', () => {
        nock('http://127.0.0.1:9200')
        .get('/npms-current/score/gulp')
        .query({ _source: 'score.final' })
        .reply(404);

        return request
        .get('/gulp.svg')
        .expect(200)
        .then((res) => {
            expect(res.headers['cache-control']).to.equal('public,no-cache');
            expect(nock.isDone()).to.equal(true);
        });
    });

    it('should respect ETag', () => {
        nock('http://127.0.0.1:9200')
        .get('/npms-current/score/gulp')
        .query({ _source: 'score.final' })
        .reply(200, {
            _source: { score: { final: 0.8 } },
        });

        const badgeInfo = badgeVault.info(0.8, { format: 'svg', revision: config.get('app.revision') });

        return request
        .get('/gulp.svg')
        .set('If-None-Match', `W/"${badgeInfo.id}"`)
        .expect(304)
        .then((res) => {
            expect(res.body).to.be.empty;
        });
    });
});

describe('scores, formats and styles', () => {
    const formats = ['svg', 'png'];
    const styles = ['flat', 'flat-square', 'plastic'];
    const scores = range(0, 101).map((score) => score / 100);

    // Images
    formats.forEach((format) => {
        styles.forEach((style) => {
            scores.forEach((score) => {
                it(`should output a ${style} ${format} image for score ${score}`, () => {
                    nock('http://127.0.0.1:9200')
                    .get('/npms-current/score/gulp')
                    .query({ _source: 'score.final' })
                    .reply(200, {
                        _source: { score: { final: score } },
                    });

                    return request
                    .get(`/gulp.${format}?style=${style}`)
                    .expect(200)
                    .then((res) => {
                        expect(res.headers['content-type']).to.contain(format);
                        assertBadge(res.body, score * 100, { style, format });
                        expect(nock.isDone()).to.equal(true);
                    });
                });
            });
        });
    });

    // JSON
    it('should output JSON', () => {
        nock('http://127.0.0.1:9200')
        .get('/npms-current/score/gulp')
        .query({ _source: 'score.final' })
        .reply(200, {
            _source: { score: { final: 0.888 } },
        });

        return request
        .get('/gulp.json')
        .expect(200)
        .then((res) => {
            expect(res.headers['content-type']).to.contain('json');
            expect(res.body).to.eql({ name: 'npms score', value: '89%' });
            expect(nock.isDone()).to.equal(true);
        });
    });
});
<|endoftext|>


<commit_before>
/**
 * This file of tests only gets executed by Travis CI
 */

describe('Impersonate user JWT, navigate to profile, edit last_name to & back.', function () {

    context('Wrangler User Profile', function () {

        before(function(){
            cy.visit('/');
        });

        /** Cypress clears browser state between tests so need to use beforeEach rather than before. This may change according to Cypress - https://github.com/cypress-io/cypress/issues/747 */
        /*
        beforeEach(function(){
            cy.login4DN({ 'email' : 'wrangler@wrangler.com' });
        });
        */

        it('Ensure logged in, visit profile page, edit last name 2x.', function(){

            cy.login4DN({ 'email' : 'wrangler@wrangler.com', 'useEnvToken' : false }).end().get('ul.navbar-acct li.user-account-item').should('have.class', 'is-logged-in').then((accountListItem)=>{
                expect(accountListItem.children('#user_actions_dropdown').text()).to.contain('Wrangler');
            }).end()
            .get("#user_actions_dropdown").click().wait(100).end()
            .get('ul.dropdown-menu[aria-labelledby="user_actions_dropdown"] a#profile').click().end()
            .get('.page-container .user-title-row-container h1.user-title').invoke('text').should('include', "Wrangler").end() // Test only for first name as we're editing last name & it may change re: delayed indexing, etc.
            // Edit wrangler last name
            .get('.page-container .user-title-row-container h1.user-title .last_name .value.saved a.edit-button').click().end()
            .get('.page-container .user-title-row-container h1.user-title .last_name .value.editing input').clear().type('SuperWrangler').then((inputfield)=>{
                //inputfield.type('SuperWrangler');
                return cy.wait(100).get('.page-container .user-title-row-container h1.user-title .last_name .value.editing .save-button').click()
                .should('have.length', 0).wait(100).end()
                .get('.page-container .user-title-row-container h1.user-title').should('have.text', "Wrangler SuperWrangler").end()
                .url().then((currUrl)=>{ // After reloading on datastore=database, last name stays edited. Then change back.
                    return cy.visit(currUrl + '?datastore=database').end()
                    .get('.page-container .user-title-row-container h1.user-title').should('have.text', "Wrangler SuperWrangler").end()
                    // Cleanup & test again
                    .get('.page-container .user-title-row-container h1.user-title .last_name .value.saved a.edit-button').click().end()
                    .get('.page-container .user-title-row-container h1.user-title .last_name .value.editing input').should('have.value', 'SuperWrangler').clear().type('Wrangler').then((inputfield)=>{
                        return cy.wait(100)
                        .get('.page-container .user-title-row-container h1.user-title .last_name .value.editing .save-button').click()
                        .should('have.length', 0).wait(100).end()
                        .get('.page-container .user-title-row-container h1.user-title').should('have.text', "Wrangler Wrangler").end();
                        //.reload()
                        //.get('.page-container .user-title-row-container h1.user-title').should('have.text', "Wrangler Wrangler").end();
                    });

                });

            });

        });

    });

});
<commit_msg>User Profile Access Key Test<commit_after>
/**
 * This file of tests only gets executed by Travis CI
 */

describe('Impersonate user JWT, navigate to profile, edit last_name to & back.', function () {

    context('Wrangler User Profile', function () {

        beforeEach(function(){
            cy.visit('/');
        });

        /** Cypress clears browser state between tests so need to use beforeEach rather than before. This may change according to Cypress - https://github.com/cypress-io/cypress/issues/747 */
        /*
        beforeEach(function(){
            cy.login4DN({ 'email' : 'wrangler@wrangler.com' });
        });
        */

        it('Ensure logged in, visit profile page, add & remove access key', function(){

            cy.login4DN({ 'email' : 'wrangler@wrangler.com', 'useEnvToken' : false }).end().get('ul.navbar-acct li.user-account-item').should('have.class', 'is-logged-in').then((accountListItem)=>{
                expect(accountListItem.children('#user_actions_dropdown').text()).to.contain('Wrangler');
            }).end()
            .get("#user_actions_dropdown").click().wait(100).end()
            .get('ul.dropdown-menu[aria-labelledby="user_actions_dropdown"] a#profile').click().end()
            .get('.page-container .user-title-row-container h1.user-title').should('contain', "Wrangler").end() // Test only for first name as we're editing last name & it may change re: delayed indexing, etc.
            .get('.page-container .access-keys-container h3').should('contain', "Access Keys").end()
            .get('.page-container .access-keys-container #add-access-key').click().wait(100).end()
            .get('.modal-body').should('contain', 'Access Key ID').should('contain', 'Secret Access Key').end()
            .get('.modal-body .key-value div:first-child dd').invoke('text').then((accessKeyID)=>{
                return cy.get('.fade.in.modal').click().wait(500).end()
                .get('.page-container .access-keys-container').should('contain', accessKeyID).end()
                .get('.page-container .access-keys-container .access-keys-table tr:last-child .access-key-buttons .btn-danger').click().end()
                .get('.page-container .access-keys-container').should('not.contain', accessKeyID);
            });

        });

        it('Ensure logged in, visit profile page, edit last name 2x.', function(){

            cy.login4DN({ 'email' : 'wrangler@wrangler.com', 'useEnvToken' : false }).end().get('ul.navbar-acct li.user-account-item').should('have.class', 'is-logged-in').then((accountListItem)=>{
                expect(accountListItem.children('#user_actions_dropdown').text()).to.contain('Wrangler');
            }).end()
            .get("#user_actions_dropdown").click().wait(100).end()
            .get('ul.dropdown-menu[aria-labelledby="user_actions_dropdown"] a#profile').click().end()
            .get('.page-container .user-title-row-container h1.user-title').invoke('text').should('include', "Wrangler").end() // Test only for first name as we're editing last name & it may change re: delayed indexing, etc.
            // Edit wrangler last name
            .get('.page-container .user-title-row-container h1.user-title .last_name .value.saved a.edit-button').click().end()
            .get('.page-container .user-title-row-container h1.user-title .last_name .value.editing input').clear().type('SuperWrangler').then((inputfield)=>{
                //inputfield.type('SuperWrangler');
                return cy.wait(100).get('.page-container .user-title-row-container h1.user-title .last_name .value.editing .save-button').click()
                .should('have.length', 0).wait(100).end()
                .get('.page-container .user-title-row-container h1.user-title').should('have.text', "Wrangler SuperWrangler").end()
                .url().then((currUrl)=>{ // After reloading on datastore=database, last name stays edited. Then change back.
                    return cy.visit(currUrl + '?datastore=database').end()
                    .get('.page-container .user-title-row-container h1.user-title').should('have.text', "Wrangler SuperWrangler").end()
                    // Cleanup & test again
                    .get('.page-container .user-title-row-container h1.user-title .last_name .value.saved a.edit-button').click().end()
                    .get('.page-container .user-title-row-container h1.user-title .last_name .value.editing input').should('have.value', 'SuperWrangler').clear().type('Wrangler').then((inputfield)=>{
                        return cy.wait(100)
                        .get('.page-container .user-title-row-container h1.user-title .last_name .value.editing .save-button').click()
                        .should('have.length', 0).wait(100).end()
                        .get('.page-container .user-title-row-container h1.user-title').should('have.text', "Wrangler Wrangler").end();
                        //.reload()
                        //.get('.page-container .user-title-row-container h1.user-title').should('have.text', "Wrangler Wrangler").end();
                    });

                });

            });

        });

    });

});
<|endoftext|>


<commit_before>'use strict';
/* global describe, it */

var assert = require('assert'),
    fs = require('fs'),
    _ = require('lodash'),
    n_ = require('../lib/n_'),
    line = n_.rli._events.line,
    osHomedir = require('os-homedir'),
    path = require('path'),
    result = null,
    useRedirect = parseInt(process.version.split('.')[0].split('v')[1]) < 6; // node < 6.x

n_.writer = _.wrap(n_.writer, function (writer, obj) {
    result = obj;
    if (_.isObject(result)) {
        return JSON.stringify(result);
    } else {
        return String(result);
    }
});

function reset() {
    // delete n_ require cache
    delete require.cache[require.resolve('../lib/n_.js')];

    // now require and setup n_ (it should now use the custom special var)
    n_ = require('../lib/n_');
    line = n_.rli._events.line;
    result = null;
    n_.writer = _.wrap(n_.writer, function (writer, obj) {
        result = obj;
        if (_.isObject(result)) {
            return JSON.stringify(result);
        } else {
            return String(result);
        }
    });
}

describe('n_', function () {

    describe('default special var', function () {
        it('should evaluate multiline input', function (done) {
            line('var users = [');
            line('    { "user": "fred",   "age": 48 },');
            line('    { "user": "barney", "age": 36 },');
            line('    { "user": "fred",   "age": 42 },');
            line('    { "user": "barney", "age": 34 }');
            line('];');
            assert.equal(result, undefined);
            line('_.sortBy(users, function(o) { return o.user; });');
            assert.deepEqual(result, [
                { user: 'barney', age: 36 },
                { user: 'barney', age: 34 },
                { user: 'fred', age: 48 },
                { user: 'fred', age: 42 }
            ]);
            done();
        });
        it('should evaluate simple input', function (done) {
            line('1+2');
            assert.equal(result, 3);
            done();
        });
        it('should evaluate multiple lodash method calls', function (done) {
            line('_.compact([1, 2, false, 4])');
            assert.deepEqual(result, [1, 2, 4]);
            result = null;
            line('_.compact([1, false, 3, 4])');
            assert.deepEqual(result, [1, 3, 4]);
            done();
        });
        it('should evaluate with built in libs', function (done) {
            line('util.isArray(_.drop([1, 2, 3]))');
            assert.equal(result, true);
            line('_.name');
            assert.equal(result, 'lodash');
            done();
        });
        it('should not contain method pluck', function (done) {
            line('typeof _.pluck');
            assert.equal(result, 'undefined');
            done();
        });

        if (useRedirect) { // if node < 6.x
            it('should redirect to $', function (done) {
                line('"abc"');
                assert.equal(result, 'abc');
                result = null;
                line('$');
                assert.equal(result, 'abc');
                done();
            });
            it('should overwrite _', function (done) {
                line('_="foobar"');
                assert.equal(result, 'foobar');
                result = null;
                line('_');
                assert.equal(result, 'foobar');
                done();
            });
        } else {
            it('should not redirect to $', function (done) {
                line('"abc"');
                assert.equal(result, 'abc');
                result = null;
                line('$');
                assert.equal(result, undefined);
                done();
            });
            it('should not overwrite _', function (done) {
                line('_="foobar"');
                assert.equal(result, 'foobar');
                result = null;
                line('_.name');
                assert.equal(result, 'lodash');
                done();
            });
        }
    });

    describe('custom special var', function () {
        if (useRedirect) { // if node < 6.x
            it('should redirect to special var', function (done) {
                // set a custom special var
                process.env.SPECIAL_VAR = 'qux';

                // now require and setup n_ (it should now use the custom special var)
                reset();

                line('"abc"');
                assert.equal(result, 'abc');
                result = null;
                line('qux');
                assert.equal(result, 'abc');
                line('_.compact([1, false, 3, null])');
                assert.deepEqual(result, [1, 3]);
                done();
            });
        } else {
             it('should not redirect to special var', function (done) {
                // set a custom special var
                process.env.SPECIAL_VAR = 'qux';

                // now require and setup n_ (it should not use the custom special var)
                reset();

                line('"abc"');
                assert.equal(result, 'abc');
                result = null;
                line('qux');
                assert.equal(result, undefined);
                line('_.compact([1, false, 3, null])');
                assert.deepEqual(result, [1, 3]);
                done();
            });
        }
    });

    describe('enabling fp mode', function () {
        it('should use lodash/fp', function (done) {
            // enable fp mode
            var previousArgv = process.argv;
            process.argv = _.concat(previousArgv, ['--fp']);

            // now require and setup n_ (it should now use lodash/fp)
            reset();
            // reset argv to previous value
            process.argv = previousArgv;

            line('_.map(function(v) { return v * 2; }, [1, 2, 3]);');
            assert.deepEqual(result, [2, 4, 6]);
            done();
        });
    });

    if (process.version.indexOf('v0.') !== 0) {
        describe('strict mode in node >= 4.x', function (done) {
            it('should not throw in magic mode', function (done) {
                line('var fixed = {}; Object.preventExtensions(fixed); fixed.newProp = 1;');
                assert.equal(result, 1);
                done();
            });
            it('should throw in strict mode set via environment variable', function (done) {
                // enable strict mode
                var previousReplMode = process.env.NODE_REPL_MODE;
                process.env.NODE_REPL_MODE = 'strict';

                // now require and setup n_ (it should now run in strict mode)
                reset();
                // reset NODE_REPL_MODE to previous value
                process.env.NODE_REPL_MODE = previousReplMode;

                line('var fixed = {}; Object.preventExtensions(fixed); fixed.newProp = 1;');
                assert.equal(result, null);
                done();
            });
            it('should throw in strict mode set via command line option', function (done) {
                // enable strict mode
                var previousArgv = process.argv;
                process.argv = _.concat(previousArgv, ['--use_strict']);

                // now require and setup n_ (it should now run with strict mode enabled)
                reset();
                // reset argv to previous value
                process.argv = previousArgv;

                line('var fixed = {}; Object.preventExtensions(fixed); fixed.newProp = 1;');
                assert.equal(result, null);
                done();
            });
        });
    }

    describe('repl history', function () {
        it('should save and load repl history across multiple sessions', function (done) {
            var historyPath = path.join(osHomedir(), '.n_repl_history');

            // delete any previously created history file
            fs.unlinkSync(historyPath);

            reset(); // new session
            line('1+2');
            reset(); // new session
            line('null');
            reset(); // new session
            line('"foobar"');
            reset(); // new session

            // check history (as thoroughly as possible)
            var historyFileContent = fs.readFileSync(historyPath, 'utf-8');
            assert.equal(historyFileContent, ['1+2', 'null', '"foobar"', ''].join('\n'));
            line('.load ' + historyPath);
            assert.equal(result, 'foobar');
            done();
        });
    });
});

describe('n_3', function () {

    describe('lodash@3.x specific evaluation', function () {
        it('should contain method pluck', function (done) {
            process.env.N_LODASH_REQUIRE_PATH = 'lodash@^3.10.1';
            reset();
            line('typeof _.pluck');
            assert.equal(result, 'function');
            done();
        });
        it('should evaluate simple input', function (done) {
            line('var objects = [{ a: 1 }, { a: 2 }];');
            line('_.pluck(objects, "a");');
            assert.deepEqual(result, [1, 2]);
            done();
        });
    });
});
<commit_msg>fix: using tar.gz package to “manually” unpack lodash@3 instead of npm-install-version - fixed test<commit_after>'use strict';
/* global describe, it */

var assert = require('assert'),
    fs = require('fs'),
    _ = require('lodash'),
    n_ = require('../lib/n_'),
    line = n_.rli._events.line,
    osHomedir = require('os-homedir'),
    path = require('path'),
    result = null,
    useRedirect = parseInt(process.version.split('.')[0].split('v')[1]) < 6; // node < 6.x

n_.writer = _.wrap(n_.writer, function (writer, obj) {
    result = obj;
    if (_.isObject(result)) {
        return JSON.stringify(result);
    } else {
        return String(result);
    }
});

function reset() {
    // delete n_ require cache
    delete require.cache[require.resolve('../lib/n_.js')];

    // now require and setup n_ (it should now use the custom special var)
    n_ = require('../lib/n_');
    line = n_.rli._events.line;
    result = null;
    n_.writer = _.wrap(n_.writer, function (writer, obj) {
        result = obj;
        if (_.isObject(result)) {
            return JSON.stringify(result);
        } else {
            return String(result);
        }
    });
}

describe('n_', function () {

    describe('default special var', function () {
        it('should evaluate multiline input', function (done) {
            line('var users = [');
            line('    { "user": "fred",   "age": 48 },');
            line('    { "user": "barney", "age": 36 },');
            line('    { "user": "fred",   "age": 42 },');
            line('    { "user": "barney", "age": 34 }');
            line('];');
            assert.equal(result, undefined);
            line('_.sortBy(users, function(o) { return o.user; });');
            assert.deepEqual(result, [
                { user: 'barney', age: 36 },
                { user: 'barney', age: 34 },
                { user: 'fred', age: 48 },
                { user: 'fred', age: 42 }
            ]);
            done();
        });
        it('should evaluate simple input', function (done) {
            line('1+2');
            assert.equal(result, 3);
            done();
        });
        it('should evaluate multiple lodash method calls', function (done) {
            line('_.compact([1, 2, false, 4])');
            assert.deepEqual(result, [1, 2, 4]);
            result = null;
            line('_.compact([1, false, 3, 4])');
            assert.deepEqual(result, [1, 3, 4]);
            done();
        });
        it('should evaluate with built in libs', function (done) {
            line('util.isArray(_.drop([1, 2, 3]))');
            assert.equal(result, true);
            line('_.name');
            assert.equal(result, 'lodash');
            done();
        });
        it('should not contain method pluck', function (done) {
            line('typeof _.pluck');
            assert.equal(result, 'undefined');
            done();
        });

        if (useRedirect) { // if node < 6.x
            it('should redirect to $', function (done) {
                line('"abc"');
                assert.equal(result, 'abc');
                result = null;
                line('$');
                assert.equal(result, 'abc');
                done();
            });
            it('should overwrite _', function (done) {
                line('_="foobar"');
                assert.equal(result, 'foobar');
                result = null;
                line('_');
                assert.equal(result, 'foobar');
                done();
            });
        } else {
            it('should not redirect to $', function (done) {
                line('"abc"');
                assert.equal(result, 'abc');
                result = null;
                line('$');
                assert.equal(result, undefined);
                done();
            });
            it('should not overwrite _', function (done) {
                line('_="foobar"');
                assert.equal(result, 'foobar');
                result = null;
                line('_.name');
                assert.equal(result, 'lodash');
                done();
            });
        }
    });

    describe('custom special var', function () {
        if (useRedirect) { // if node < 6.x
            it('should redirect to special var', function (done) {
                // set a custom special var
                process.env.SPECIAL_VAR = 'qux';

                // now require and setup n_ (it should now use the custom special var)
                reset();

                line('"abc"');
                assert.equal(result, 'abc');
                result = null;
                line('qux');
                assert.equal(result, 'abc');
                line('_.compact([1, false, 3, null])');
                assert.deepEqual(result, [1, 3]);
                done();
            });
        } else {
             it('should not redirect to special var', function (done) {
                // set a custom special var
                process.env.SPECIAL_VAR = 'qux';

                // now require and setup n_ (it should not use the custom special var)
                reset();

                line('"abc"');
                assert.equal(result, 'abc');
                result = null;
                line('qux');
                assert.equal(result, undefined);
                line('_.compact([1, false, 3, null])');
                assert.deepEqual(result, [1, 3]);
                done();
            });
        }
    });

    describe('enabling fp mode', function () {
        it('should use lodash/fp', function (done) {
            // enable fp mode
            var previousArgv = process.argv;
            process.argv = _.concat(previousArgv, ['--fp']);

            // now require and setup n_ (it should now use lodash/fp)
            reset();
            // reset argv to previous value
            process.argv = previousArgv;

            line('_.map(function(v) { return v * 2; }, [1, 2, 3]);');
            assert.deepEqual(result, [2, 4, 6]);
            done();
        });
    });

    if (process.version.indexOf('v0.') !== 0) {
        describe('strict mode in node >= 4.x', function (done) {
            it('should not throw in magic mode', function (done) {
                line('var fixed = {}; Object.preventExtensions(fixed); fixed.newProp = 1;');
                assert.equal(result, 1);
                done();
            });
            it('should throw in strict mode set via environment variable', function (done) {
                // enable strict mode
                var previousReplMode = process.env.NODE_REPL_MODE;
                process.env.NODE_REPL_MODE = 'strict';

                // now require and setup n_ (it should now run in strict mode)
                reset();
                // reset NODE_REPL_MODE to previous value
                process.env.NODE_REPL_MODE = previousReplMode;

                line('var fixed = {}; Object.preventExtensions(fixed); fixed.newProp = 1;');
                assert.equal(result, null);
                done();
            });
            it('should throw in strict mode set via command line option', function (done) {
                // enable strict mode
                var previousArgv = process.argv;
                process.argv = _.concat(previousArgv, ['--use_strict']);

                // now require and setup n_ (it should now run with strict mode enabled)
                reset();
                // reset argv to previous value
                process.argv = previousArgv;

                line('var fixed = {}; Object.preventExtensions(fixed); fixed.newProp = 1;');
                assert.equal(result, null);
                done();
            });
        });
    }

    describe('repl history', function () {
        it('should save and load repl history across multiple sessions', function (done) {
            var historyPath = path.join(osHomedir(), '.n_repl_history');

            // delete any previously created history file
            fs.unlinkSync(historyPath);

            reset(); // new session
            line('1+2');
            reset(); // new session
            line('null');
            reset(); // new session
            line('"foobar"');
            reset(); // new session

            // check history (as thoroughly as possible)
            var historyFileContent = fs.readFileSync(historyPath, 'utf-8');
            assert.equal(historyFileContent, ['1+2', 'null', '"foobar"', ''].join('\n'));
            line('.load ' + historyPath);
            assert.equal(result, 'foobar');
            done();
        });
    });
});

describe('n_3', function () {

    describe('lodash@3.x specific evaluation', function () {
        it('should contain method pluck', function (done) {
            process.env.N_LODASH_REQUIRE_PATH = 'lodash3/package/';
            reset();
            line('typeof _.pluck');
            assert.equal(result, 'function');
            done();
        });
        it('should evaluate simple input', function (done) {
            line('var objects = [{ a: 1 }, { a: 2 }];');
            line('_.pluck(objects, "a");');
            assert.deepEqual(result, [1, 2]);
            done();
        });
    });
});
<|endoftext|>


<commit_before>require("chai").should();
global._ = require('underscore');
global.Backbone = require('backbone');
require('../backbone.attributes');

describe('Backbone.Attributes', function() {
  it('should work with plain objects', function() {
    var obj = _.extend({}, Backbone.Attributes);

    obj.on('change:name', function(ctx, name) {
      ctx.should.equal(obj);
      this.should.equal(obj);
      name.should.equal('foo');
    });
    obj.setAttribute('name', 'foo');
  });

  it('should work with defaults', function() {
    var obj = {
      defaults: {
        name: 'Moe'
      }
    };
    obj = _.extend(obj, Backbone.Attributes);

    obj.getAttribute('name').should.equal('Moe');
    obj.on('change:name', function(ctx, name) {
      name.should.equal('Larry');
      this.getAttribute('name').should.equal(name);
    });
    obj.setAttribute('name', 'Larry');
  });

  it('should not collide with Backbone.Collection methods', function() {
    var col = _.extend(new Backbone.Collection, Backbone.Attributes);

    col.on('change:name', function(ctx, name) {
      ctx.should.equal(col);
      this.should.equal(col);
      name.should.equal('foo');
      this.getAttribute('name').should.equal(name);
    });
    col.setAttribute('name', 'foo');
  });
});<commit_msg>check that col.get is Collection::get<commit_after>require("chai").should();
global._ = require('underscore');
global.Backbone = require('backbone');
require('../backbone.attributes');

describe('Backbone.Attributes', function() {
  it('should work with plain objects', function() {
    var obj = _.extend({}, Backbone.Attributes);

    obj.on('change:name', function(ctx, name) {
      ctx.should.equal(obj);
      this.should.equal(obj);
      name.should.equal('foo');
    });
    obj.setAttribute('name', 'foo');
  });

  it('should work with defaults', function() {
    var obj = {
      defaults: {
        name: 'Moe'
      }
    };
    obj = _.extend(obj, Backbone.Attributes);

    obj.getAttribute('name').should.equal('Moe');
    obj.on('change:name', function(ctx, name) {
      name.should.equal('Larry');
      this.getAttribute('name').should.equal(name);
    });
    obj.setAttribute('name', 'Larry');
  });

  it('should not collide with Backbone.Collection methods', function() {
    var col = _.extend(new Backbone.Collection, Backbone.Attributes);

    col.get.should.equal(Backbone.Collection.prototype.get);
    col.on('change:name', function(ctx, name) {
      ctx.should.equal(col);
      this.should.equal(col);
      name.should.equal('foo');
      this.getAttribute('name').should.equal(name);
    });
    col.setAttribute('name', 'foo');
  });
});<|endoftext|>


<commit_before>'use strict';
var should    = require('should');
var mkdirp    = require('mkdirp');
var cp        = require('child_process');
var path      = require('path');
var rimraf    = require('rimraf');
var ps        = require('ps-node');
var outpath   = path.join(__dirname, '/project');
var jlboxPath = path.join(__dirname, '../bin/jlbox.js');
var fs        = require('fs');
require('mocha');

describe('jlbox', function() {
  before(function(done) {
    mkdirp(outpath, done);
  });

  describe('jlbox commands', function() {
    it('should bootstrap project via init command', function(done) {
      this.timeout(60000);
      cp.exec(jlboxPath + ' init', {cwd: outpath}, function(err) {
        if (err) return done(err);
        console.log(outpath);
        should.exist(path.join(outpath, 'test'));
        should.exist(path.join(outpath, 'src'));
        should.exist(path.join(outpath, 'gulpfile.js'));
        should.exist(path.join(outpath, 'gulp.jl'));
        should.exist(path.join(outpath, 'package.json'));
        should.exist(path.join(outpath, 'node_modules'));
        should.exist(path.join(outpath, 'test/helper.jl'));
        return done();
      });
    });

    it('should bootstrap module files via module command', function(done) {
      cp.exec(jlboxPath + ' module Sample', {cwd: outpath}, function(err) {
        if(err) return done(err);
        should(fs.existsSync(path.join(outpath, 'src/Sample.jl'))).be.true;
        should.exist(path.join(outpath, 'src/Sample.jl'));
        should.exist(path.join(outpath, 'test/Sample_test.jl'));
        return done();
      });
    });
  });
  var child;
  describe('jlbox watch', function() {
    before(function(done) {
      this.timeout(15000);
      child = cp.spawn('gulp', {cwd: outpath});
      var count = 0;
      child.stdout.setEncoding('utf8');
      child.stdout.on('data', function(data) {
        data = data.trim();
        if (data) {
          console.log(data);
          if (data.match(/.*Waiting for changes...*/) && count === 0) {
            count += 1;
            done();
          }
        }
      });
    });

    var hook;
    beforeEach(function(){
      hook = captureStream(process.stdout);
    });

    afterEach(function(){
      hook.unhook();
    });

    it('should re-run test when module is changed', function(done) {
      fs.writeFile(path.join(outpath, '/src/Sample.jl'), "module Sample\n\nend\n", function(err) {
        if (err) return done(err);
        return setTimeout(function() {
          should.exist(hook.captured().match(/0 facts verified/));
          return done();
        }, 1000);
      });
    });

    it('should re-run test when test is changed', function(done) {
      var content = 'module SampleTest\n' +
            'include("$(pwd())/test/helper.jl")\n' +
            'reload("$(pwd())/src/Sample.jl")\n' +
            'using Sample\n' +
            'facts("Sample") do\n' +
            '@fact 1 => 1\n' +
            'end\n' +
            'end # module SampleTest\n';
      fs.writeFile(path.join(outpath, '/test/Sample_test.jl'), content, function(err) {
        if (err) return done(err);
        return setTimeout(function() {
          should.exist(hook.captured().match(/1 fact verified/));
          return done();
        }, 1000);
      });
    });

    it('should restart julia when there is a syntax error', function(done) {
      this.timeout(10000);
      var content = 'module SampleTest\n' +
            'include("$(pwd())/test/helper.jl")\n' +
            'reload("$(pwd())/src/Sample.jl")\n' +
            'using Sample\n' +
            'facts("Sample") do\n' +
            '@fact 1 => 1:\n' +
            'end\n' +
            'end # module SampleTest\n';
      fs.writeFile(path.join(outpath, '/test/Sample_test.jl'), content, function(err) {
        if (err) return done(err);

        return setTimeout(function() {
          should.exist(hook.captured().match(/ZMQ bound/));
          return done();
        }, 8000);
      });
    });

    // http://stackoverflow.com/questions/18543047/mocha-monitor-application-output
    function captureStream(stream){
      var oldWrite = stream.write;
      var buf = '';
      stream.write = function(chunk, encoding, callback){
        buf += chunk.toString(); // chunk is a String or Buffer
        oldWrite.apply(stream, arguments);
      };

      return {
        unhook: function unhook(){
          stream.write = oldWrite;
        },
        captured: function(){
          return buf;
        }
      };
    }
  });

  after(function(done) {
    child.kill('SIGINT');
    // kill julia process
    ps.lookup({command: 'julia', arguments: [ '--color', 'gulp.jl' ]}, function(err,res) {
      if (err) return done(err);
      // if julia process remains... kill it
      if (res && res[0]) {
        process.kill(res[0].pid, 'SIGINT');
      }
      // clean-up project dir
      return rimraf(outpath, done);
    });
  });
});
<commit_msg>tests use EventEmitter and clean-up child process<commit_after>'use strict';
var should       = require('should');
var mkdirp       = require('mkdirp');
var cp           = require('child_process');
var path         = require('path');
var rimraf       = require('rimraf');
var outpath      = path.join(__dirname, '/project');
var jlboxPath    = path.join(__dirname, '../bin/jlbox.js');
var fs           = require('fs');
var events       = require('events');
var jlboxEmitter = new events.EventEmitter();
var child;
require('mocha');

describe('jlbox', function() {
  before(function(done) {
    mkdirp(outpath, done);
  });

  describe('jlbox commands', function() {
    it('should bootstrap project via init command', function(done) {
      this.timeout(60000);
      cp.exec(jlboxPath + ' init', {cwd: outpath}, function(err) {
        if (err) return done(err);
        fs.existsSync(path.join(outpath, 'test')).should.be.true;
        fs.existsSync(path.join(outpath, 'src')).should.be.true;
        fs.existsSync(path.join(outpath, 'gulpfile.js')).should.be.true;
        fs.existsSync(path.join(outpath, 'gulp.jl')).should.be.true;
        fs.existsSync(path.join(outpath, 'package.json')).should.be.true;
        fs.existsSync(path.join(outpath, 'node_modules')).should.be.true;
        fs.existsSync(path.join(outpath, 'test/helper.jl')).should.be.true;
        return done();
      });
    });

    it('should bootstrap module files via module command', function(done) {
      cp.exec(jlboxPath + ' module Sample', {cwd: outpath}, function(err) {
        if(err) return done(err);
        fs.existsSync(path.join(outpath, 'src/Sample.jl')).should.be.true;
        fs.existsSync(path.join(outpath, 'src/Sample.jl')).should.be.true;
        fs.existsSync(path.join(outpath, 'test/Sample_test.jl')).should.be.true;
        return done();
      });
    });
  });

  describe('jlbox watch', function() {
    before(function(done) {
      this.timeout(15000);
      child = cp.spawn('gulp', {cwd: outpath});
      var count = 0;
      child.stdout.setEncoding('utf8');
      child.stdout.on('data', function(data) {
        data = data.trim();
        if (data) {
          console.log(data);
          if (data.match(/Waiting for changes/)) {
            // if it's the first time, then call done
            if (count === 0) {
              count += 1;
              done();
            }
            // otherwise emit an event that the test should list for
            else {
              jlboxEmitter.emit('jlbox:done', true);
            }
          }
        }
      });

      child.stderr.setEncoding('utf8');
      child.stderr.on('data', function(data) {
        console.log('err');
        console.log(data);
      });
    });

    var hook;
    beforeEach(function(){
      hook = captureStream(process.stdout);
    });

    afterEach(function(){
      hook.unhook();
    });

    // clean up child process and folder at the end
    after(function(done) {
      child.kill('SIGINT');
      return rimraf(outpath, done);
    });

    // NOTE: use different file names for each test, otherwise gulp/gaze will think they are the same event, given they happen so quickly, and ignore one.
    // alternatively, you can use setTimeout on each test of about 1000ms if you want to modify the same file twice
    it('should re-run test when module is changed', function(done) {
      fs.writeFile(path.join(outpath, '/src/Sample.jl'), "module Sample\n\nend\n", function(err) {
        if (err) return done(err);
        return jlboxEmitter.once('jlbox:done', function() {
          should.exist(hook.captured().match(/0 facts verified/));
          return done();
        });
      });
    });

    it('should re-run test when test is changed', function(done) {
      var content = 'module SampleTest\n' +
            'include("$(pwd())/test/helper.jl")\n' +
            'reload("$(pwd())/src/Sample.jl")\n' +
            'using Sample\n' +
            'facts("Sample") do\n' +
            '@fact 1 => 1\n' +
            'end\n' +
            'end # module SampleTest\n';
      fs.writeFile(path.join(outpath, '/test/Sample_test.jl'), content, function(err) {
        if (err) return done(err);
        return jlboxEmitter.once('jlbox:done', function() {
          should.exist(hook.captured().match(/1 fact verified/));
          return done();
        });
      });
    });

    it('should restart julia when there is a syntax error', function(done) {
      this.timeout(8000);
      var content = 'module SampleTest2\n' +
            'include("$(pwd())/test/helper.jl")\n' +
            'facts("Sample2") do\n' +
            '@fact 1 => 1:\n' +
            'end\n' +
            'end # module Sample2Test\n';
      fs.writeFile(path.join(outpath, '/test/Sample_test2.jl'), content, function(err) {
        if (err) return done(err);
        return jlboxEmitter.once('jlbox:done', function() {
          should.exist(hook.captured().match(/ZMQ bound/));
          return done();
        });
      });
    });

    // http://stackoverflow.com/questions/18543047/mocha-monitor-application-output
    function captureStream(stream){
      var oldWrite = stream.write;
      var buf = '';
      stream.write = function(chunk, encoding, callback){
        buf += chunk.toString(); // chunk is a String or Buffer
        oldWrite.apply(stream, arguments);
      };

      return {
        unhook: function unhook(){
          stream.write = oldWrite;
        },
        captured: function(){
          return buf;
        }
      };
    }
  });
});
<|endoftext|>


<commit_before>var rollup       = require('rollup');
var hypothetical = require('..');

function resolve(promise, expected) {
  return promise.then(function(bundle) {
    var code = bundle.generate().code;
    var object = {};
    (new Function('object', code))(object);
    for(var key in expected) {
      if(!(key in object)) {
        throw Error("Expected object to have key \""+key+"\"!");
      }
      var ok = JSON.stringify(object[key]), ek = JSON.stringify(expected[key]);
      if(ok !== ek)  {
        throw Error("Expected object."+key+" to be "+ek+", not "+ok+"!");
      }
    }
    for(var key in object) {
      if(!(key in expected)) {
        throw Error("Didn't expect object to have key \""+key+"\"!");
      }
    }
  });
}

function reject(promise, message) {
  return promise.then(function() {
    throw Error("Promise was resolved when it should have been rejected!");
  }, function(reason) {
    if(message && reason.message.indexOf(message) === -1) {
      throw Error("Rejection message \""+reason.message+"\" does not contain \""+message+"\"!");
    }
  });
}

it("should let nothing through if no options are passed", function() {
  return reject(rollup.rollup({
    entry: './test/fixtures/a.js',
    plugins: [hypothetical()]
  }), "does not exist in the hypothetical file system");
});
<commit_msg>Added some more tests<commit_after>var rollup       = require('rollup');
var hypothetical = require('..');

function resolve(promise, expected) {
  return promise.then(function(bundle) {
    var code = bundle.generate().code;
    var object = {};
    (new Function('object', code))(object);
    for(var key in expected) {
      if(!(key in object)) {
        throw Error("Expected object to have key \""+key+"\"!");
      }
      var ok = JSON.stringify(object[key]), ek = JSON.stringify(expected[key]);
      if(ok !== ek)  {
        throw Error("Expected object."+key+" to be "+ek+", not "+ok+"!");
      }
    }
    for(var key in object) {
      if(!(key in expected)) {
        throw Error("Didn't expect object to have key \""+key+"\"!");
      }
    }
  });
}

function reject(promise, message) {
  return promise.then(function() {
    throw Error("Promise was resolved when it should have been rejected!");
  }, function(reason) {
    if(message && reason.message.indexOf(message) === -1) {
      throw Error("Rejection message \""+reason.message+"\" does not contain \""+message+"\"!");
    }
  });
}

it("should let nothing through if no options are passed", function() {
  return reject(rollup.rollup({
    entry: './test/fixtures/a.js',
    plugins: [hypothetical()]
  }), "does not exist in the hypothetical file system");
});

it("should be able to simulate an entry file", function() {
  return resolve(rollup.rollup({
    entry: './x.js',
    plugins: [hypothetical({ files: { './x.js': 'object.key = false;' } })]
  }), { key: false });
});

it("should be able to simulate an entry file where one already exists", function() {
  return resolve(rollup.rollup({
    entry: './test/fixtures/a.js',
    plugins: [hypothetical({ files: { './test/fixtures/a.js': 'object.key = false;' } })]
  }), { key: false });
});

it("should handle an entry point that appears to be external", function() {
  return resolve(rollup.rollup({
    entry: 'x.js',
    plugins: [hypothetical({ files: { './x.js': 'object.key = false;' } })]
  }), { key: false });
});

it("should handle absolute paths", function() {
  return resolve(rollup.rollup({
    entry: '/x.js',
    plugins: [hypothetical({ files: { '/x.js': 'object.key = false;' } })]
  }), { key: false });
});
<|endoftext|>