<commit_before>var Lab = require('lab');
var Template = require('../../lib/template');
var assert  = require('chai').assert;
var assertHtml = require('../helper').assertHtml;

var lab = exports.lab = Lab.script();

lab.experiment('Code structure', function() {
  var template;
  lab.before(function(done) {
    template = new Template(require('../../lib/vm_node'));
    done();
  });

  lab.test('render with conditional', function(done) {
    assertHtml(template, [
      'div',
      '  - if this.showFirst()',
      '      p The first paragraph',
      '  - else',
      '      p The second paragraph'
      ],
      '

The second paragraph

',
      {}, done);
  });

  lab.test('render with conditional else if', function(done) {
    assertHtml(template, [
      'div',
      '  - if this.showFirst()',
      '      p The first paragraph',
      '  - else if this.showFirst(true)',
      '      p The second paragraph',
      '  - else',
      '      p The third paragraph'
      ],
      '

The second paragraph

',
      {}, done);
  });

  lab.test('render with consecutive conditionals', function(done) {
    assertHtml(template, [
      'div',
      '  - if this.showFirst(true)',
      '      p The first paragraph',
      '  - if this.showFirst(true)',
      '      p The second paragraph'
      ],
      '

The first paragraph

The second paragraph

',
      {}, done);
  });

  lab.test('render with when string in condition', function(done) {
    assertHtml(template, [
      '- if true',
      '  | Hello',

      '- if "when" !== null',
      '  |  world'
      ],
      'Hello world',
      {}, done);
  });

  lab.test('render with conditional and following nonconditonal', function(done) {
    assertHtml(template, [
      'div',
      '  - if true',
      '      p The first paragraph',
      '  - var x = 42',
      '  = x'
      ],
      '

The first paragraph
42
',
      {}, done);
  });

  lab.test('render with case', function(done) {
    assertHtml(template, [
      '- var url = require("url")',
      'p',
      '  - switch(42)',
      '    - case 41:',
      '      | 41',
      '      - break',
      '    - case 42:',
      '      | 42',
      '      - break',
      '  |  is the answer',
      'p',
      '  - switch(41)',
      '    - case 41:',
      '      | 41',
      '      - break',
      '    - case 42:',
      '      | 42',
      '      - break',
      '  |  is the answer',
      'p',
      '  - switch(42)',
      '    - case 41:',
      '      | 41',
      '      - break',
      '    - case 42:',
      '      | 42',
      '      - break',
      '  |  is the answer',
      'p',
      '  - switch(41)',
      '    - case 41:',
      '      | 41',
      '      - break',
      '    - case 42:',
      '      | 42',
      '      - break',
      '  |  is the answer'
      ],
      '
42 is the answer

41 is the answer

42 is the answer

41 is the answer
',
      {}, done);
  });

  lab.test('render with slm comments', function(done) {
    assertHtml(template, [
      'p Hello',
      '/ This is a comment',
      '  Another comment',
      'p World'
      ],
      '
Hello

World
',
      {}, done);
  });

  lab.test('render with slm comments and empty line', function(done) {
    assertHtml(template, [
      'p Hello',
      '/ This is a comment',
      '',
      '  Another comment',
      'p World'
      ],
      '
Hello

World
',
      {}, done);
  });

  lab.test('render with try catch', function(done) {
    assertHtml(template, [
      '- try',
      '  p Try',
      '- catch error',
      '  p Catch',
      'p After'
      ],
      '
Try

After
',
      {}, done);
  });

  lab.test('render with try catch exception', function(done) {
    assertHtml(template, [
      '- try',
      '  p Try',
      '  - throw "Boom"',
      '  p After Boom',
      '- catch ex',
      '  p = ex',
      'p After'
      ],
      '
Try

Boom

After
',
      {}, done);
  });

  lab.test('render with try catch finally', function(done) {
    assertHtml(template, [
      '- try',
      '  p Try',
      '  - throw "Boom"',
      '  p After Boom',
      '- catch ex',
      '  p = ex',
      '- finally',
      '  p Finally',
      'p After'
      ],
      '
Try

Boom

Finally

After
',
      {}, done);
  });

  lab.test('injects callback arg', function(done) {
    assertHtml(template, [
      '= this.block()',
      '  p Block',
      'p After'
      ],
      '
Block

After
',
      {}, done);
  });

  lab.test('detects missing brace', function(done) {
    var src = [
      '= this.block)',
      '  p Block',
      'p After'
      ].join('\n');
    assert.throw(function() {
      template.render(src, {}, {});
    }, 'Missing open brace \"(\" in `this.block)`');

    done();
  });

  lab.test('content', function(done) {
    assertHtml(template, [
      '= content()',
      'p After 1',
      '= content("head")',
      'p After 2',
      '= content(false)',
        'title title1',
      'p After 3',
      '= content("head")',
        'title title2',
      'p After 4',
      '= content("head")',
      '= content(false)',
      '  p Not captured'
      ],
      '
After 1

After 2
<title>title1</title>
After 3
<title>title2</title>
After 4

Not captured
',
      {}, done);
  });

  lab.test('render with forEach', function(done) {
    assertHtml(template, [
      'div',
      '  - this.items.forEach(function(i))',
      '    p = i',
      ],
      '

1

2

3

',
      {}, done);
  });

  lab.test('render with for', function(done) {
    assertHtml(template, [
      'ul',
      '  - for item in this.items',
      '    li = item'
    ],
    '

0

1

2

',
    {}, done);
  });

  lab.test('render with multiline attributes', function(done) {
    assertHtml(template, [
      'div class="test\\',
      '    nice"'
      ],
      '

',
      {});

    assertHtml(template, [
      'div class=[1,',
      '  2].join("")'
      ],
      '

',
      {}, done);
  });

  lab.test('render with multiline attributes', function(done) {
    assertHtml(template, [
      'div class=(1 + \\',
      '  2)'
      ],
      '

',
      {});

    assertHtml(template, [
      'div class=[1,',
      '  2].join("")'
      ],
      '

',
      {}, done);
  });
});
<commit_msg>Fix memory leak in tests<commit_after>var Lab = require('lab');
var Template = require('../../lib/template');
var assert  = require('chai').assert;
var assertHtml = require('../helper').assertHtml;

var lab = exports.lab = Lab.script();

lab.experiment('Code structure', function() {
  var template;
  lab.before(function(done) {
    template = new Template(require('../../lib/vm_node'));
    done();
  });

  lab.test('render with conditional', function(done) {
    assertHtml(template, [
      'div',
      '  - if this.showFirst()',
      '      p The first paragraph',
      '  - else',
      '      p The second paragraph'
      ],
      '

The second paragraph

',
      {}, done);
  });

  lab.test('render with conditional else if', function(done) {
    assertHtml(template, [
      'div',
      '  - if this.showFirst()',
      '      p The first paragraph',
      '  - else if this.showFirst(true)',
      '      p The second paragraph',
      '  - else',
      '      p The third paragraph'
      ],
      '

The second paragraph

',
      {}, done);
  });

  lab.test('render with consecutive conditionals', function(done) {
    assertHtml(template, [
      'div',
      '  - if this.showFirst(true)',
      '      p The first paragraph',
      '  - if this.showFirst(true)',
      '      p The second paragraph'
      ],
      '

The first paragraph

The second paragraph

',
      {}, done);
  });

  lab.test('render with when string in condition', function(done) {
    assertHtml(template, [
      '- if true',
      '  | Hello',

      '- if "when" !== null',
      '  |  world'
      ],
      'Hello world',
      {}, done);
  });

  lab.test('render with conditional and following nonconditonal', function(done) {
    assertHtml(template, [
      'div',
      '  - if true',
      '      p The first paragraph',
      '  - var x = 42',
      '  = x'
      ],
      '

The first paragraph
42
',
      {}, done);
  });

  lab.test('render with case', function(done) {
    assertHtml(template, [
      '- var url = require("url")',
      'p',
      '  - switch(42)',
      '    - case 41:',
      '      | 41',
      '      - break',
      '    - case 42:',
      '      | 42',
      '      - break',
      '  |  is the answer',
      'p',
      '  - switch(41)',
      '    - case 41:',
      '      | 41',
      '      - break',
      '    - case 42:',
      '      | 42',
      '      - break',
      '  |  is the answer',
      'p',
      '  - switch(42)',
      '    - case 41:',
      '      | 41',
      '      - break',
      '    - case 42:',
      '      | 42',
      '      - break',
      '  |  is the answer',
      'p',
      '  - switch(41)',
      '    - case 41:',
      '      | 41',
      '      - break',
      '    - case 42:',
      '      | 42',
      '      - break',
      '  |  is the answer'
      ],
      '
42 is the answer

41 is the answer

42 is the answer

41 is the answer
',
      {}, done);
  });

  lab.test('render with slm comments', function(done) {
    assertHtml(template, [
      'p Hello',
      '/ This is a comment',
      '  Another comment',
      'p World'
      ],
      '
Hello

World
',
      {}, done);
  });

  lab.test('render with slm comments and empty line', function(done) {
    assertHtml(template, [
      'p Hello',
      '/ This is a comment',
      '',
      '  Another comment',
      'p World'
      ],
      '
Hello

World
',
      {}, done);
  });

  lab.test('render with try catch', function(done) {
    assertHtml(template, [
      '- try',
      '  p Try',
      '- catch error',
      '  p Catch',
      'p After'
      ],
      '
Try

After
',
      {}, done);
  });

  lab.test('render with try catch exception', function(done) {
    assertHtml(template, [
      '- try',
      '  p Try',
      '  - throw "Boom"',
      '  p After Boom',
      '- catch ex',
      '  p = ex',
      'p After'
      ],
      '
Try

Boom

After
',
      {}, done);
  });

  lab.test('render with try catch finally', function(done) {
    assertHtml(template, [
      '- try',
      '  p Try',
      '  - throw "Boom"',
      '  p After Boom',
      '- catch ex',
      '  p = ex',
      '- finally',
      '  p Finally',
      'p After'
      ],
      '
Try

Boom

Finally

After
',
      {}, done);
  });

  lab.test('injects callback arg', function(done) {
    assertHtml(template, [
      '= this.block()',
      '  p Block',
      'p After'
      ],
      '
Block

After
',
      {}, done);
  });

  lab.test('detects missing brace', function(done) {
    var src = [
      '= this.block)',
      '  p Block',
      'p After'
      ].join('\n');
    assert.throw(function() {
      template.render(src, {}, {});
    }, 'Missing open brace \"(\" in `this.block)`');

    done();
  });

  lab.test('content', function(done) {
    assertHtml(template, [
      '= content()',
      'p After 1',
      '= content("head")',
      'p After 2',
      '= content(false)',
        'title title1',
      'p After 3',
      '= content("head")',
        'title title2',
      'p After 4',
      '= content("head")',
      '= content(false)',
      '  p Not captured'
      ],
      '
After 1

After 2
<title>title1</title>
After 3
<title>title2</title>
After 4

Not captured
',
      {}, done);
  });

  lab.test('render with forEach', function(done) {
    assertHtml(template, [
      'div',
      '  - this.items.forEach(function(i))',
      '    p = i',
      ],
      '

1

2

3

',
      {}, done);
  });

  lab.test('render with for', function(done) {
    assertHtml(template, [
      'ul',
      '  - for var item in this.items',
      '    li = item'
    ],
    '

0

1

2

',
    {}, done);
  });

  lab.test('render with multiline attributes', function(done) {
    assertHtml(template, [
      'div class="test\\',
      '    nice"'
      ],
      '

',
      {});

    assertHtml(template, [
      'div class=[1,',
      '  2].join("")'
      ],
      '

',
      {}, done);
  });

  lab.test('render with multiline attributes', function(done) {
    assertHtml(template, [
      'div class=(1 + \\',
      '  2)'
      ],
      '

',
      {});

    assertHtml(template, [
      'div class=[1,',
      '  2].join("")'
      ],
      '

',
      {}, done);
  });
});
<|endoftext|>


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

var cares = require('../lib/cares.js');
var net = require('net');

var SERVERS = ['127.0.0.1'];
var PORT = 49160;
var dnsentries = require('./setup/dnsentries.js');

module.exports = {

    setUp: function (callback) {
        this.resolver = new cares.Resolver({
            servers: SERVERS,
            udp_port: PORT,
        });
        callback();
    },
    tearDown: function (callback) {
        callback();
    },

    resolve: function (test) {
        this.resolver.resolve('www.something.com', function (err, response) {
            test.ifError(err);
            test.notStrictEqual(response, null, err);
            test.ok(response instanceof Array, "Invalid response returned.");
            test.ok(response.length > 0, "Invalid response returned.");
            response.forEach(function (ip) {
                test.ok(net.isIP(ip), "Invalid IP address.");
                test.ok(net.isIPv4(ip), "Invalid IP address.");
            });

            var expected = (
                dnsentries[cares.NS_C_IN]
                [cares.NS_T_A]
                ['www.something.com']
                ['answer']
            )
            .filter( function (answer) {
                return answer['type'] === cares.NS_T_A;
            })
            .map( function (answer) {
                return answer['address'];
            });

            test.strictEqual(
                expected.length,
                response.length,
                "Number of records expected and recived are not same."
            );

            response.forEach(function (answer, index) {
                test.strictEqual(
                    answer,
                    expected[index],
                    "Expected and recieved record is not same."
                );
            });

            test.done();
        });
    },

    resolve_explicit_A: function (test) {
        this.resolver.resolve('www.something.com', 'A', function (err, response) {
            test.ifError(err);
            test.notStrictEqual(response, null, err);
            test.ok(response instanceof Array, "Invalid response returned.");
            test.ok(response.length > 0, "Invalid response returned.");
            response.forEach(function (ip) {
                test.ok(net.isIP(ip), "Invalid IP address.");
                test.ok(net.isIPv4(ip), "Invalid IP address.");
            });

            var expected = (
                dnsentries[cares.NS_C_IN]
                [cares.NS_T_A]
                ['www.something.com']
                ['answer']
            )
            .filter( function (answer) {
                return answer['type'] === cares.NS_T_A;
            })
            .map( function (answer) {
                return answer['address'];
            });

            test.strictEqual(
                expected.length,
                response.length,
                "Number of records expected and recived are not same."
            );

            response.forEach(function (answer, index) {
                test.strictEqual(
                    answer,
                    expected[index],
                    "Expected and recieved record is not same."
                );
            });

            test.done();
        });
    },

    resolve_explicit_AAAA: function (test) {
        this.resolver.resolve('www.something.com', 'AAAA', function (err, response) {
            test.ifError(err);
            test.notStrictEqual(response, null, err);
            test.ok(response instanceof Array, "Invalid response returned.");
            test.ok(response.length > 0, "Invalid response returned.");
            response.forEach(function (ip) {
                test.ok(net.isIP(ip), "Invalid IP address.");
                test.ok(net.isIPv6(ip), "Invalid IP address.");
            });

            var expected = (
                dnsentries[cares.NS_C_IN]
                [cares.NS_T_AAAA]
                ['www.something.com']
                ['answer']
            )
            .filter( function (answer) {
                return answer['type'] === cares.NS_T_AAAA;
            })
            .map( function (answer) {
                return answer['address'];
            });

            test.strictEqual(
                expected.length,
                response.length,
                "Number of records expected and recived are not same."
            );

            response.forEach(function (answer, index) {
                test.strictEqual(
                    answer,
                    expected[index],
                    "Expected and recieved record is not same."
                );
            });

            test.done();
        });
    },

    resolve4: function (test) {
        this.resolver.resolve4('www.something.com', function (err, response) {
            test.ifError(err);
            test.notStrictEqual(response, null, err);
            test.ok(response instanceof Array, "Invalid response returned.");
            test.ok(response.length > 0, "Invalid response returned.");
            response.forEach(function (ip) {
                test.ok(net.isIP(ip), "Invalid IP address.");
                test.ok(net.isIPv4(ip), "Invalid IP address.");
            });

            var expected = (
                dnsentries[cares.NS_C_IN]
                [cares.NS_T_A]
                ['www.something.com']
                ['answer']
            )
            .filter( function (answer) {
                return answer['type'] === cares.NS_T_A;
            })
            .map( function (answer) {
                return answer['address'];
            });

            test.strictEqual(
                expected.length,
                response.length,
                "Number of records expected and recived are not same."
            );

            response.forEach(function (answer, index) {
                test.strictEqual(
                    answer,
                    expected[index],
                    "Expected and recieved record is not same."
                );
            });

            test.done();
        });
    },

    resolve6: function (test) {
        this.resolver.resolve6('www.something.com', function (err, response) {
            test.ifError(err);
            test.notStrictEqual(response, null, err);
            test.ok(response instanceof Array, "Invalid response returned.");
            test.ok(response.length > 0, "Invalid response returned.");
            response.forEach(function (ip) {
                test.ok(net.isIP(ip), "Invalid IP address.");
                test.ok(net.isIPv6(ip), "Invalid IP address.");
            });

            var expected = (
                dnsentries[cares.NS_C_IN]
                [cares.NS_T_AAAA]
                ['www.something.com']
                ['answer']
            )
            .filter( function (answer) {
                return answer['type'] === cares.NS_T_AAAA;
            })
            .map( function (answer) {
                return answer['address'];
            });

            test.strictEqual(
                expected.length,
                response.length,
                "Number of records expected and recived are not same."
            );

            response.forEach(function (answer, index) {
                test.strictEqual(
                    answer,
                    expected[index],
                    "Expected and recieved record is not same."
                );
            });

            test.done();
        });
    },

    resolveCname: function (test) {
        this.resolver.resolveCname('www.something.com', function (err, response) {
            test.ifError(err);
            test.notStrictEqual(response, null, err);
            test.ok(response instanceof Array, "Invalid response returned.");
            test.ok(response.length > 0, "Invalid response returned.");
            response.forEach(function (data) {
                test.notStrictEqual(data, null, "Invalid CNAME");
            });

            var expected = (
                dnsentries[cares.NS_C_IN]
                [cares.NS_T_CNAME]
                ['www.something.com']
                ['answer']
            )
            .filter( function (answer) {
                return answer['type'] === cares.NS_T_CNAME;
            })
            .map( function (answer) {
                return answer['data'];
            });

            test.strictEqual(
                expected.length,
                response.length,
                "Number of records expected and recived are not same."
            );

            response.forEach(function (answer, index) {
                test.strictEqual(
                    answer,
                    expected[index],
                    "Expected and recieved record is not same."
                );
            });

            test.done();
        });
    },

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

var cares = require('../lib/cares.js');
var net = require('net');

var SERVERS = ['127.0.0.1'];
var PORT = 49160;
var dnsentries = require('./setup/dnsentries.js');

module.exports = {

    setUp: function(callback) {
        this.resolver = new cares.Resolver({
            servers: SERVERS,
            udp_port: PORT,
        });
        callback();
    },
    tearDown: function(callback) {
        callback();
    },

    resolve: function(test) {
        this.resolver.resolve('www.something.com', function(err, response) {
            test.ifError(err);
            test.notStrictEqual(response, null, err);
            test.ok(response instanceof Array, "Invalid response returned.");
            test.ok(response.length > 0, "Invalid response returned.");
            response.forEach(function(ip) {
                test.ok(net.isIP(ip), "Invalid IP address.");
                test.ok(net.isIPv4(ip), "Invalid IP address.");
            });

            var expected = (
                dnsentries[cares.NS_C_IN][cares.NS_T_A]['www.something.com']
                .answer
            )
            .filter(function(answer) {
                return answer.type === cares.NS_T_A;
            })
            .map(function(answer) {
                return answer.address;
            });

            test.strictEqual(
                expected.length,
                response.length,
                "Number of records expected and recived are not same."
            );

            response.forEach(function(answer, index) {
                test.strictEqual(
                    answer,
                    expected[index],
                    "Expected and recieved record is not same."
                );
            });

            test.done();
        });
    },

    resolve_explicit_A: function(test) {
        this.resolver.resolve('www.something.com', 'A', function(err,
            response) {
            test.ifError(err);
            test.notStrictEqual(response, null, err);
            test.ok(response instanceof Array, "Invalid response returned.");
            test.ok(response.length > 0, "Invalid response returned.");
            response.forEach(function(ip) {
                test.ok(net.isIP(ip), "Invalid IP address.");
                test.ok(net.isIPv4(ip), "Invalid IP address.");
            });

            var expected = (
                dnsentries[cares.NS_C_IN][cares.NS_T_A]['www.something.com']
                .answer
            )
            .filter(function(answer) {
                return answer.type === cares.NS_T_A;
            })
            .map(function(answer) {
                return answer.address;
            });

            test.strictEqual(
                expected.length,
                response.length,
                "Number of records expected and recived are not same."
            );

            response.forEach(function(answer, index) {
                test.strictEqual(
                    answer,
                    expected[index],
                    "Expected and recieved record is not same."
                );
            });

            test.done();
        });
    },

    resolve_explicit_AAAA: function(test) {
        this.resolver.resolve('www.something.com', 'AAAA', function(err,
            response) {
            test.ifError(err);
            test.notStrictEqual(response, null, err);
            test.ok(response instanceof Array, "Invalid response returned.");
            test.ok(response.length > 0, "Invalid response returned.");
            response.forEach(function(ip) {
                test.ok(net.isIP(ip), "Invalid IP address.");
                test.ok(net.isIPv6(ip), "Invalid IP address.");
            });

            var expected = (
                dnsentries[cares.NS_C_IN][cares.NS_T_AAAA]['www.something.com']
                .answer
            )
            .filter(function(answer) {
                return answer.type === cares.NS_T_AAAA;
            })
            .map(function(answer) {
                return answer.address;
            });

            test.strictEqual(
                expected.length,
                response.length,
                "Number of records expected and recived are not same."
            );

            response.forEach(function(answer, index) {
                test.strictEqual(
                    answer,
                    expected[index],
                    "Expected and recieved record is not same."
                );
            });

            test.done();
        });
    },

    resolve4: function(test) {
        this.resolver.resolve4('www.something.com', function(err, response) {
            test.ifError(err);
            test.notStrictEqual(response, null, err);
            test.ok(response instanceof Array, "Invalid response returned.");
            test.ok(response.length > 0, "Invalid response returned.");
            response.forEach(function(ip) {
                test.ok(net.isIP(ip), "Invalid IP address.");
                test.ok(net.isIPv4(ip), "Invalid IP address.");
            });

            var expected = (
                dnsentries[cares.NS_C_IN][cares.NS_T_A]['www.something.com']
                .answer
            )
            .filter(function(answer) {
                return answer.type === cares.NS_T_A;
            })
            .map(function(answer) {
                return answer.address;
            });

            test.strictEqual(
                expected.length,
                response.length,
                "Number of records expected and recived are not same."
            );

            response.forEach(function(answer, index) {
                test.strictEqual(
                    answer,
                    expected[index],
                    "Expected and recieved record is not same."
                );
            });

            test.done();
        });
    },

    resolve6: function(test) {
        this.resolver.resolve6('www.something.com', function(err, response) {
            test.ifError(err);
            test.notStrictEqual(response, null, err);
            test.ok(response instanceof Array, "Invalid response returned.");
            test.ok(response.length > 0, "Invalid response returned.");
            response.forEach(function(ip) {
                test.ok(net.isIP(ip), "Invalid IP address.");
                test.ok(net.isIPv6(ip), "Invalid IP address.");
            });

            var expected = (
                dnsentries[cares.NS_C_IN][cares.NS_T_AAAA]['www.something.com']
                .answer
            )
            .filter(function(answer) {
                return answer.type === cares.NS_T_AAAA;
            })
            .map(function(answer) {
                return answer.address;
            });

            test.strictEqual(
                expected.length,
                response.length,
                "Number of records expected and recived are not same."
            );

            response.forEach(function(answer, index) {
                test.strictEqual(
                    answer,
                    expected[index],
                    "Expected and recieved record is not same."
                );
            });

            test.done();
        });
    },

    resolveCname: function(test) {
        this.resolver.resolveCname('www.something.com', function(err,
            response) {
            test.ifError(err);
            test.notStrictEqual(response, null, err);
            test.ok(response instanceof Array, "Invalid response returned.");
            test.ok(response.length > 0, "Invalid response returned.");
            response.forEach(function(data) {
                test.notStrictEqual(data, null, "Invalid CNAME");
            });

            var expected = (
                dnsentries[cares.NS_C_IN][cares.NS_T_CNAME]['www.something.com']
                .answer
            )
            .filter(function(answer) {
                return answer.type === cares.NS_T_CNAME;
            })
            .map(function(answer) {
                return answer.data;
            });

            test.strictEqual(
                expected.length,
                response.length,
                "Number of records expected and recived are not same."
            );

            response.forEach(function(answer, index) {
                test.strictEqual(
                    answer,
                    expected[index],
                    "Expected and recieved record is not same."
                );
            });

            test.done();
        });
    },

};
<|endoftext|>


<commit_before>/* eslint-env mocha */
'use strict'

const expect = require('chai').expect
// const DAGLink = require('../src').DAGLink
const DAGNode = require('../src').DAGNode
const resolver = require('../src').resolver

const Block = require('ipfs-block')

describe('IPLD format resolver (local)', () => {
  let emptyNodeBlock
  let linksNodeBlock
  let dataLinksNodeBlock

  const links = [{
    Name: '',
    Hash: 'QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCVVEcRTWJBmLgR39U',
    Size: 10
  }, {
    Name: 'named link',
    Hash: 'QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCVVEcRTWJBmLgR39V',
    Size: 8
  }]

  before(() => {
    // create a bunch of nodes serialized into Blocks
    //    const d1 = new DAGNode(new Buffer('some data'), l1)
    const emptyNode = new DAGNode(new Buffer(0))

    const linksNode = new DAGNode(new Buffer(0), links)
    const dataLinksNode = new DAGNode(new Buffer('aaah the data'), links)

    // TODO we need to hint block with its CID,
    // so it knows how to hash it
    emptyNodeBlock = new Block(emptyNode.serialize())
    linksNodeBlock = new Block(linksNode.serialize())
    dataLinksNodeBlock = new Block(dataLinksNode.serialize())
  })

  it('multicodec is dag-pb', () => {
    expect(resolver.multicodec).to.equal('dag-pb')
  })

  describe('empty node', () => {
    describe('resolver.resolve', () => {
      it('links path', () => {
        const links = resolver.resolve(emptyNodeBlock, 'links')
        expect(links).to.eql([])
      })

      it('data path', () => {
        const data = resolver.resolve(emptyNodeBlock, 'data')
        expect(data).to.eql(new Buffer(0))
      })

      it('non existent path', () => {
        expect(() => {
          resolver.resolve(emptyNodeBlock, 'pathThatDoesNotExist')
        }).to.throw
      })
    })

    it('resolver.tree', () => {
      const paths = resolver.tree(emptyNodeBlock)
      expect(paths).to.eql([])
    })

    it.skip('resolver.patch', (done) => {})
  })

  describe('links node', () => {
    describe('resolver.resolve', () => {
      it('links path', () => {
        const links = resolver.resolve(linksNodeBlock, 'links')
        expect(links).to.eql(links)
      })

      it('links position path', () => {
        const link = resolver.resolve(linksNodeBlock, 'links/1')
        expect(link).to.eql(links[1])
      })
    })

    it('resolver.tree', () => {
      const paths = resolver.tree(linksNodeBlock)
      expect(paths).to.eql([{
        'path': '',
        'value': 'QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCVVEcRTWJBmLgR39U'
      }, {
        'path': 'named link',
        'value': 'QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCVVEcRTWJBmLgR39V'
      }])
    })

    it.skip('resolver.patch', () => {})
  })

  describe('links and data node', () => {
    describe('resolver.resolve', () => {
      it('links path', () => {
        const links = resolver.resolve(dataLinksNodeBlock, 'links')
        expect(links).to.eql(links)
      })

      it('data path', () => {
        const data = resolver.resolve(dataLinksNodeBlock, 'data')
        expect(data).to.eql(new Buffer('aaah the data'))
      })

      it('non existent path', () => {
        expect(() => {
          resolver.resolve(dataLinksNodeBlock, 'pathThatDoesNotExist')
        }).to.throw
      })
    })

    it('resolver.tree', () => {
      const paths = resolver.tree(dataLinksNodeBlock)
      expect(paths).to.eql([{
        'path': '',
        'value': 'QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCVVEcRTWJBmLgR39U'
      }, {
        'path': 'named link',
        'value': 'QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCVVEcRTWJBmLgR39V'
      }, {
        'path': 'data',
        'value': new Buffer('aaah the data')
      }])
    })

    it.skip('resolver.patch', () => {})
  })
})
<commit_msg>style: solve lint issues<commit_after>/* eslint-env mocha */
/* eslint max-nested-callbacks: ["error", 8] */

'use strict'

const expect = require('chai').expect
// const DAGLink = require('../src').DAGLink
const DAGNode = require('../src').DAGNode
const resolver = require('../src').resolver

const Block = require('ipfs-block')

describe('IPLD format resolver (local)', () => {
  let emptyNodeBlock
  let linksNodeBlock
  let dataLinksNodeBlock

  const links = [{
    Name: '',
    Hash: 'QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCVVEcRTWJBmLgR39U',
    Size: 10
  }, {
    Name: 'named link',
    Hash: 'QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCVVEcRTWJBmLgR39V',
    Size: 8
  }]

  before(() => {
    // create a bunch of nodes serialized into Blocks
    //    const d1 = new DAGNode(new Buffer('some data'), l1)
    const emptyNode = new DAGNode(new Buffer(0))

    const linksNode = new DAGNode(new Buffer(0), links)
    const dataLinksNode = new DAGNode(new Buffer('aaah the data'), links)

    // TODO we need to hint block with its CID,
    // so it knows how to hash it
    emptyNodeBlock = new Block(emptyNode.serialize())
    linksNodeBlock = new Block(linksNode.serialize())
    dataLinksNodeBlock = new Block(dataLinksNode.serialize())
  })

  it('multicodec is dag-pb', () => {
    expect(resolver.multicodec).to.equal('dag-pb')
  })

  describe('empty node', () => {
    describe('resolver.resolve', () => {
      it('links path', () => {
        const links = resolver.resolve(emptyNodeBlock, 'links')
        expect(links).to.eql([])
      })

      it('data path', () => {
        const data = resolver.resolve(emptyNodeBlock, 'data')
        expect(data).to.eql(new Buffer(0))
      })

      it('non existent path', () => {
        expect(() => {
          resolver.resolve(emptyNodeBlock, 'pathThatDoesNotExist')
        }).to.throw
      })
    })

    it('resolver.tree', () => {
      const paths = resolver.tree(emptyNodeBlock)
      expect(paths).to.eql([])
    })

    it.skip('resolver.patch', (done) => {})
  })

  describe('links node', () => {
    describe('resolver.resolve', () => {
      it('links path', () => {
        const links = resolver.resolve(linksNodeBlock, 'links')
        expect(links).to.eql(links)
      })

      it('links position path', () => {
        const link = resolver.resolve(linksNodeBlock, 'links/1')
        expect(link).to.eql(links[1])
      })
    })

    it('resolver.tree', () => {
      const paths = resolver.tree(linksNodeBlock)
      expect(paths).to.eql([{
        path: '',
        value: 'QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCVVEcRTWJBmLgR39U'
      }, {
        path: 'named link',
        value: 'QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCVVEcRTWJBmLgR39V'
      }])
    })

    it.skip('resolver.patch', () => {})
  })

  describe('links and data node', () => {
    describe('resolver.resolve', () => {
      it('links path', () => {
        const links = resolver.resolve(dataLinksNodeBlock, 'links')
        expect(links).to.eql(links)
      })

      it('data path', () => {
        const data = resolver.resolve(dataLinksNodeBlock, 'data')
        expect(data).to.eql(new Buffer('aaah the data'))
      })

      it('non existent path', () => {
        expect(() => {
          resolver.resolve(dataLinksNodeBlock, 'pathThatDoesNotExist')
        }).to.throw
      })
    })

    it('resolver.tree', () => {
      const paths = resolver.tree(dataLinksNodeBlock)
      expect(paths).to.eql([{
        path: '',
        value: 'QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCVVEcRTWJBmLgR39U'
      }, {
        path: 'named link',
        value: 'QmXg9Pp2ytZ14xgmQjYEiHjVjMFXzCVVEcRTWJBmLgR39V'
      }, {
        path: 'data',
        value: new Buffer('aaah the data')
      }])
    })

    it.skip('resolver.patch', () => {})
  })
})
<|endoftext|>


<commit_before>
// TODO
// validate all routes
// documentation
// try code cleanup

// imports

const window        = require("global/window");
const pathToRegexp  = require("path-to-regexp");
const noop          = require("lodash/noop");
const isPlainObject = require("lodash/isPlainObject");
const isArray       = require("lodash/isArray");
const isBoolean     = require("lodash/isBoolean");
const log           = require("../../services/logger")("pyramid:effects:router");

const symbols = require("./symbols");

// export effect

module.exports = make;

// define effect

function make ({ routes, useHash = true }) {

  // validate arguments

  const options = arguments[0];
  let valid = true;

  if (!isPlainObject(options)) {
    log.error("options must be a plain object", { options });
    valid = false;
  }

  //TODO validate all routes specified individually as well
  if (!isArray(routes)) {
    log.error("options.routes must be an array", { routes });
    valid = false;
  }

  if (!isBoolean(useHash)) {
    log.error("options.useHash must be a boolean", { useHash });
    valid = false;
  }

  // if validation fails, exit early and provide empty effect
  if (!valid) {
    log.error("effect creation's validation failed, returning no-op effect");
    return noop;
  }

  // cache regular expressions on routes
  routes.forEach(route => {
    route.keys = [];
    route.regexp = pathToRegexp(route.pattern, route.keys);
  });

  // return effect handler

  return function (state, update) {

    // initialize the router state if necessary
    // and abort
    const initialized = state.get(symbols.STATE_INITIALIZED);
    if (!initialized) {
      // handle popstate events
      window.onpopstate = function (event) {
        update(symbols.ACTION_START_NAVIGATION, {
          path: event.state.path, // path stored when state is "pushed"
          isPopState: true
        });
      };
      // run state initialization
      return update(symbols.ACTION_INITIALIZE, { update, routes });
    }

    // handle navigation, if required
    const transitionLock = state.get(symbols.STATE_TRANSITION_LOCK);
    const currentRoute = state.get(symbols.STATE_CURRENT_ROUTE);
    const incomingRoute = state.get(symbols.STATE_INCOMING_ROUTE);
    if (transitionLock && currentRoute && incomingRoute) {
      const currentRouteStatus = currentRoute.get("status");
      const incomingRouteStatus = incomingRoute.get("status");
      if (currentRouteStatus === symbols.STATUS_EXITING && incomingRouteStatus === symbols.STATUS_ENTERING)
        update(symbols.ACTION_HANDLE_NAVIGATION);

      // otherwise, finish navigation, if required
      else if (currentRouteStatus === symbols.STATUS_INACTIVE && incomingRouteStatus === symbols.STATUS_ACTIVE)
        update(symbols.ACTION_FINISH_NAVIGATION, { update });
    }

    // propagate state to the current route's effects
    const effects = currentRoute.get("component").get("effects");
    if (effects && effects.forEach)
      effects.forEach(effect => effect(state, update));

  };

};
<commit_msg>add use strict to router, update todo<commit_after>"use strict";
// TODO
// validate all routes
// documentation

// imports

const window        = require("global/window");
const pathToRegexp  = require("path-to-regexp");
const noop          = require("lodash/noop");
const isPlainObject = require("lodash/isPlainObject");
const isArray       = require("lodash/isArray");
const isBoolean     = require("lodash/isBoolean");
const log           = require("../../services/logger")("pyramid:effects:router");

const symbols = require("./symbols");

// export effect

module.exports = make;

// define effect

function make ({ routes, useHash = true }) {

  // validate arguments

  const options = arguments[0];
  let valid = true;

  if (!isPlainObject(options)) {
    log.error("options must be a plain object", { options });
    valid = false;
  }

  //TODO validate all routes specified individually as well
  if (!isArray(routes)) {
    log.error("options.routes must be an array", { routes });
    valid = false;
  }

  if (!isBoolean(useHash)) {
    log.error("options.useHash must be a boolean", { useHash });
    valid = false;
  }

  // if validation fails, exit early and provide empty effect
  if (!valid) {
    log.error("effect creation's validation failed, returning no-op effect");
    return noop;
  }

  // cache regular expressions on routes
  routes.forEach(route => {
    route.keys = [];
    route.regexp = pathToRegexp(route.pattern, route.keys);
  });

  // return effect handler

  return function (state, update) {

    // initialize the router state if necessary
    // and abort
    const initialized = state.get(symbols.STATE_INITIALIZED);
    if (!initialized) {
      // handle popstate events
      window.onpopstate = function (event) {
        update(symbols.ACTION_START_NAVIGATION, {
          path: event.state.path, // path stored when state is "pushed"
          isPopState: true
        });
      };
      // run state initialization
      return update(symbols.ACTION_INITIALIZE, { update, routes });
    }

    // handle navigation, if required
    const transitionLock = state.get(symbols.STATE_TRANSITION_LOCK);
    const currentRoute = state.get(symbols.STATE_CURRENT_ROUTE);
    const incomingRoute = state.get(symbols.STATE_INCOMING_ROUTE);
    if (transitionLock && currentRoute && incomingRoute) {
      const currentRouteStatus = currentRoute.get("status");
      const incomingRouteStatus = incomingRoute.get("status");
      if (currentRouteStatus === symbols.STATUS_EXITING && incomingRouteStatus === symbols.STATUS_ENTERING)
        update(symbols.ACTION_HANDLE_NAVIGATION);

      // otherwise, finish navigation, if required
      else if (currentRouteStatus === symbols.STATUS_INACTIVE && incomingRouteStatus === symbols.STATUS_ACTIVE)
        update(symbols.ACTION_FINISH_NAVIGATION, { update });
    }

    // propagate state to the current route's effects
    const effects = currentRoute.get("component").get("effects");
    if (effects && effects.forEach)
      effects.forEach(effect => effect(state, update));

  };

};
<|endoftext|>


<commit_before>'use strict';

var expect = require('chai').expect;
var Room = require('../../server/db/models/room');
var Score = require('../../server/db/models/score');
var User = require('../../server/db/models/user');

/**
 *
 * Start here!
 *
 * These tests describe the model that you'll be writing in models/article.js
 *
 */

<commit_msg>database specs complete<commit_after>'use strict';

const expect = require('chai').expect;
const { User, Room, Score, db } = require('../../server/db/index');

//Test specs for User model
//*****************************************************************************
describe('The `User` model', function () {
  before(function () {
    return db.sync({force: true});
  });
  let user;
  beforeEach(function(){
    user = User.build({
      email: 'a@gmail.com',
      admin: true,
      username: 'nemo1',
      guest:false,
      nickname: 'nemo2'
    });
  });

  afterEach(function () {
    return Promise.all([
      User.truncate({ cascade: true })
    ]);
  });

  describe('attributes definition', function(){

    it('includes `email` and `username` fields', function () {

      return user.save()
      .then(function (savedUser) {
        expect(savedUser.email).to.equal('a@gmail.com');
        expect(savedUser.admin).to.equal(true);
        expect(savedUser.username).to.equal('nemo1');
        expect(savedUser.nickname).to.equal('nemo2');
        expect(savedUser.guest).to.equal(false);

      });

    });

    it('requires `nickname`', function () {

      user.nickname = null;

      return user.validate()
      .then(function(result) {
        expect(result).to.be.an.instanceOf(Error);
        expect(result.message).to.contain('notNull Violation: nickname cannot be null');
      });

    });

  });

});

//Test specs for Score model
//*****************************************************************************

describe('The `Score` model', function () {
  before(function () {
    return db.sync({force: true});
  });
  let score;
  let time = new Date
  beforeEach(function(){
    score = Score.build({
      value: 100,
      time: time,
    });
  });

  afterEach(function () {
    return Promise.all([
      Score.truncate({ cascade: true })
    ]);
  });

  describe('attributes definition', function(){

    it('includes `value` and `time` fields', function () {

      return score.save()
      .then(function (savedScore) {
        expect(savedScore.value).to.equal(100);
        expect((savedScore.time).toString()).to.equal(time.toString());
      });

    });

    it('requires `value` and `date` and value should be non-negative integer', function () {

    	let validTime =Date.now();
    	let timeArray = [null, validTime];
    	let valueArray = [-20,null,30];
    	score.time = timeArray[Math.round(Math.random())];
	    	 (score.time===null) ? score.value = valueArray[2]: score.value = valueArray[Math.round(Math.random())]

	      	// console.log("test",score.time,score.value);
      return score.validate()
      .then(function(result) {
        expect(result).to.be.an.instanceOf(Error);

      });

    });
  });

});

//Test specs for Room model
//*****************************************************************************

describe('The `Room` model', function () {
  before(function () {
    return db.sync({force: true});
  });
  let room;
  beforeEach(function(){
    room = Room.build({
      name: 'room2'
    });
  });

  afterEach(function () {
    return Promise.all([
      Room.truncate({ cascade: true })
    ]);
  });

  describe('attributes definition', function(){
    it('includes `name` fields', function () {

      return room.save()
      .then(function (savedRoom) {
        expect(savedRoom.name).to.equal('room2');
      });

    });

    // it('requires `value` and `date` and value should be non-negative integer', function () {

    //   let violationErr1 = 'notNull Violation: nickname cannot be null';
    //   let violationErr2 ='Validation error: Validation min failed';

    //   return score.validate()
    //   .then(function(result) {
    //     expect(result).to.be.an.instanceOf(Error);
    //     expect(result.message).to.contain(vviolationErr1);
    //   });

    // });

  });

});

<|endoftext|>


<commit_before>/* global jasmine, describe, beforeEach, it, expect */

'use strict';

var git 	= require('../lib/git');
var fs      = require('fs');
var path    = require('path');
var rimraf  = require('rimraf');
var when 	= require('when');

jasmine.getEnv().defaultTimeoutInterval = 10000;

function copyFile (src, dest) {
	var defer = when.defer();
	var called = false;

	function done (err) {
		if (!called) {
			defer.reject(err);
		}
	}

	var read = fs.createReadStream(src);
	read.on('error', function (err) {
		done(err);
	});

	var write = fs.createWriteStream(dest);
	write.on('error', function (err) {
		done(err);
	});

	write.on('close', function() {
		defer.resolve();
	});

	read.pipe(write);

	return defer.promise;
}

function copyFileHelper (repo, src, dest) {
	var defer = when.defer();
	copyFile(src, dest)
	.then(function () {
		defer.resolve(repo);
	}, function (err) {
		defer.reject(err);
	});
	return defer.promise;
}

describe('git operations on a repo', function () {
	var promise;
	var tmpDir = path.join(require('os').tmpdir(), 'tmpRepo');
	var remoteUrl = 'git://github.com/rowoot/rowoot.github.io.git';

	beforeEach(function () {
		rimraf.sync(tmpDir);
		promise = git.prepareRepo(remoteUrl);
	});

	it('should determine the remoteUrl of a git repository', function (cb) {
		promise
		.then(function (repo) {
			return git.getRemoteUrl(repo._repo, 'origin');
		})
		.then(function (rUrl) {
			expect(rUrl).toBe(remoteUrl);
			cb();
		});
	});

  	it('should create a branch', function (cb) {
	  	var branchName = 'new-branch';

	    promise
	    .then(function (repo) {
	    	return repo.createBranch(branchName);
	    })
	    .then(function (repo) {
	    	expect(repo._localBranches).toContain(branchName);
	    	cb();
	    }, function (err) {
	    	console.log(err);
	    });
  	});

  	it('should throw an error when checking out a non existent branch', function (cb) {
	  	var branchName = 'non-existent-branch';

	    promise
	    .then(function (repo) {
	    	return repo.checkoutBranch(branchName);
	    })
	    .then(function (repo) {
	    	// none
	    }, function (err) {
	    	expect(err.message).toBe('Command failed: error: pathspec \''+branchName+'\' did not match any file(s) known to git.\n');
	    	cb();
	    });
  	});

  	it('should checkout a existing remote branch', function (cb) {
	  	var branchName = 'gh-branch';

	    promise
	    .then(function (repo) {
	    	return repo.checkoutBranch(branchName);
	    })
	    .then(function (repo) {
	    	expect(repo._currentBranch).toBe(branchName);
	    	cb();
	    });
  	});

  	it('should create and checkout a branch', function (cb) {
	  	var branchName = 'new-and-checkout-branch';

	    promise
	    .then(function (repo) {
	    	return repo.createAndCheckoutBranch(branchName);
	    })
	    .then(function (repo) {
	    	expect(repo._currentBranch).toBe(branchName);
	    	expect(repo._localBranches).toContain(branchName);
	    	cb();
	    });
  	});

  	it('should add a file successfully and stage it', function (cb) {
	  	var file = 'test.txt';
	  	var src = path.join(__dirname, 'fixtures', file);
	  	var dest = path.join(tmpDir, file);

	    promise
	    .then(function (repo) {
	    	return copyFileHelper(repo, src, dest);
	    })
	    .then(function (repo) {
	    	return repo.addFiles(path.join(tmpDir , file));
	    })
	    .then(function (repo) {
	    	expect(Object.keys(repo._staged).length).toBe(1);
	    	expect(Object.keys(repo._staged)).toContain(file);
	    	cb();
	    });
  	});

  	// it('should commit a file successfully', function (cb) {
	  // 	var file = 'test.txt';
	  // 	var message = 'commit message';
	  // 	var src = path.join(__dirname, 'fixtures', file);
	  // 	var dest = path.join(tmpDir, file);

	  //   promise
	  //   .then(function (repo) {
	  //   	return copyFileHelper(repo, src, dest);
	  //   })
	  //   .then(function (repo) {
	  //   	return repo.addFiles(path.join(tmpDir , file));
	  //   })
	  //   .then(function (repo) {
	  //   	return repo.commit(message);
	  //   })
	  //   .then(function (repo) {
	  //   	expect(Object.keys(repo._staged).length).toBe(0);
	  //   	expect(repo._commits[0].message).toBe(message);
	  //   	cb();
	  //   });
  	// });
});

describe('git operations on special repositories', function () {
	var tmpDir = path.join(require('os').tmpdir(), 'tmpRepo');

	beforeEach(function () {
		rimraf.sync(tmpDir);
	});

	it('should be initialized on the default branch', function (cb) {
		var promise = git.prepareRepo('git://github.com/LeaVerou/csss.git');
		promise.then(function (repo) {
			expect(repo._currentBranch).toBe('gh-pages');
			cb();
		});
	});
});
<commit_msg>Update repo with url from branch new-test-repo<commit_after>/* global jasmine, describe, beforeEach, it, expect */

'use strict';

var git 	= require('../lib/git');
var fs      = require('fs');
var path    = require('path');
var rimraf  = require('rimraf');
var when 	= require('when');

jasmine.getEnv().defaultTimeoutInterval = 10000;

function copyFile (src, dest) {
	var defer = when.defer();
	var called = false;

	function done (err) {
		if (!called) {
			defer.reject(err);
		}
	}

	var read = fs.createReadStream(src);
	read.on('error', function (err) {
		done(err);
	});

	var write = fs.createWriteStream(dest);
	write.on('error', function (err) {
		done(err);
	});

	write.on('close', function() {
		defer.resolve();
	});

	read.pipe(write);

	return defer.promise;
}

function copyFileHelper (repo, src, dest) {
	var defer = when.defer();
	copyFile(src, dest)
	.then(function () {
		defer.resolve(repo);
	}, function (err) {
		defer.reject(err);
	});
	return defer.promise;
}

describe('git operations on a repo', function () {
	var promise;
	var tmpDir = path.join(require('os').tmpdir(), 'tmpRepo');
	var remoteUrl = 'git://github.com/rowoot/test-gh-pages.git';

	beforeEach(function () {
		rimraf.sync(tmpDir);
		promise = git.prepareRepo(remoteUrl);
	});

	it('should determine the remoteUrl of a git repository', function (cb) {
		promise
		.then(function (repo) {
			return git.getRemoteUrl(repo._repo, 'origin');
		})
		.then(function (rUrl) {
			expect(rUrl).toBe(remoteUrl);
			cb();
		});
	});

  	it('should create a branch', function (cb) {
	  	var branchName = 'new-branch';

	    promise
	    .then(function (repo) {
	    	return repo.createBranch(branchName);
	    })
	    .then(function (repo) {
	    	expect(repo._localBranches).toContain(branchName);
	    	cb();
	    }, function (err) {
	    	console.log(err);
	    });
  	});

  	it('should throw an error when checking out a non existent branch', function (cb) {
	  	var branchName = 'non-existent-branch';

	    promise
	    .then(function (repo) {
	    	return repo.checkoutBranch(branchName);
	    })
	    .then(function (repo) {
	    	// none
	    }, function (err) {
	    	expect(err.message).toBe('Command failed: error: pathspec \''+branchName+'\' did not match any file(s) known to git.\n');
	    	cb();
	    });
  	});

  	it('should checkout a existing remote branch', function (cb) {
	  	var branchName = 'gh-pages';

	    promise
	    .then(function (repo) {
	    	return repo.checkoutBranch(branchName);
	    })
	    .then(function (repo) {
	    	expect(repo._currentBranch).toBe(branchName);
	    	cb();
	    });
  	});

  	it('should create and checkout a branch', function (cb) {
	  	var branchName = 'new-and-checkout-branch';

	    promise
	    .then(function (repo) {
	    	return repo.createAndCheckoutBranch(branchName);
	    })
	    .then(function (repo) {
	    	expect(repo._currentBranch).toBe(branchName);
	    	expect(repo._localBranches).toContain(branchName);
	    	cb();
	    });
  	});

  	it('should add a file successfully and stage it', function (cb) {
	  	var file = 'test.txt';
	  	var src = path.join(__dirname, 'fixtures', file);
	  	var dest = path.join(tmpDir, file);

	    promise
	    .then(function (repo) {
	    	return copyFileHelper(repo, src, dest);
	    })
	    .then(function (repo) {
	    	return repo.addFiles(path.join(tmpDir , file));
	    })
	    .then(function (repo) {
	    	expect(Object.keys(repo._staged).length).toBe(1);
	    	expect(Object.keys(repo._staged)).toContain(file);
	    	cb();
	    });
  	});

  	// it('should commit a file successfully', function (cb) {
	  // 	var file = 'test.txt';
	  // 	var message = 'commit message';
	  // 	var src = path.join(__dirname, 'fixtures', file);
	  // 	var dest = path.join(tmpDir, file);

	  //   promise
	  //   .then(function (repo) {
	  //   	return copyFileHelper(repo, src, dest);
	  //   })
	  //   .then(function (repo) {
	  //   	return repo.addFiles(path.join(tmpDir , file));
	  //   })
	  //   .then(function (repo) {
	  //   	return repo.commit(message);
	  //   })
	  //   .then(function (repo) {
	  //   	expect(Object.keys(repo._staged).length).toBe(0);
	  //   	expect(repo._commits[0].message).toBe(message);
	  //   	cb();
	  //   });
  	// });
});

describe('git operations on special repositories', function () {
	var tmpDir = path.join(require('os').tmpdir(), 'tmpRepo');

	beforeEach(function () {
		rimraf.sync(tmpDir);
	});

	it('should be initialized on the default branch', function (cb) {
		var promise = git.prepareRepo('git://github.com/LeaVerou/csss.git');
		promise.then(function (repo) {
			expect(repo._currentBranch).toBe('gh-pages');
			cb();
		});
	});
});
<|endoftext|>


<commit_before>//
// Integration test helper that makes it easy to write fast integration tests.
// One of the ways it does this is by providing the methods `startServer` and
// `closeServer` that will spawn a child process of this project. This means
// a version of this project server will run on localhost:5000 using a fake
// API server exposed below a `api`.
//

var spawn = require('child_process').spawn
  , express = require('express')
  , child;

// Fake API server currently stubbing responses from GitHub's API.
// You will want to edit this to stub your own API's behavior.
var api = module.exports.api = express()

api.get('/repos/:owner/:repo/commits', function(req, res) {
  res.send([
    { commit: { message: 'Adding a README.md' } }
  ]);
});

// Spawns a child process with ENV variables that will launch it in "test"
// mode. This includes an API_URL that points to the fake API server mounted
// under /__api.
startServer = module.exports.startServer = function(callback) {
  var envVars  = {
    NODE_ENV: 'test',
    API_URL: 'http://localhost:5000/__api',
    PORT: 5000
  };
  for(var k in process.env) {
    if(!envVars[k]) envVars[k] = process.env[k];
  };
  child = spawn('make', ['s'], {
    customFds: [0, 1, 2],
    stdio: ['ipc'],
    env: envVars
  });
  child.on('message', callback);
  child.stdout.on('data', function(data) {
    console.log(data.toString());
  });
}

// Closes the server child process, used in an `after` hook and on
// `process.exit` in case the test suite is interupted.
closeServer = module.exports.closeServer = function() {
  if(child) child.kill();
  child = null;
}
process.on('exit', closeServer);

// You can debug your integration app and run this app server by running
// this module directly and opening up localhost:5000.
// e.g. `node test/helpers/integration.js`
if(module != require.main) return;
startServer(function() {
  child.stdout.on('data', function(data) {
    console.log(data.toString());
  });
});<commit_msg>remove js helper<commit_after><|endoftext|>


<commit_before>describe('html_to_tokens', function(){
  var cut, res, diff, create_token, tokenize;

  beforeEach(function(){
    diff = require('../js/htmldiff')
    cut = diff.html_to_tokens;

    create_token = diff.find_matching_blocks.create_token;
    tokenize = function(tokens) {
      return tokens.map(function(token) {
        return create_token(token);
      });
    };
  });

  it('should be a function', function(){
    expect(cut).is.a('function');
  });

  describe('when called with text', function(){
    beforeEach(function(){
      res = cut('this is a test');
    });

    it('should return 4', function(){
      expect(res.length).to.equal(7);
    });
  }); // describe('when called with text')

  describe('when called with html', function(){
    beforeEach(function(){
      res = cut('
this is a test
');
    });

    it('should return 11', function(){
      expect(res.length).to.equal(11);
    });

    it('should remove any html comments', function() {
      res = cut('
 this is
');
      console.log(res);
      expect(res.length).to.equal(8);
    });
  }); // describe('when called with html')

  it('should identify contiguous whitespace as a single token', function(){
    expect(cut('a   b')).to.eql(tokenize(['a', '   ', 'b']));
  });

  it('should identify a single space as a single token', function(){
    expect(cut(' a b ')).to.eql(tokenize([' ', 'a', ' ', 'b', ' ']));
  });

  it('should identify self closing tags as tokens', function(){
    expect(cut('
hello
goodbye
'))
    .eql(tokenize(['
', 'hello', '
', 'goodbye', '
']));
  });

  describe('when encountering atomic tags', function(){
    it('should identify an image tag as a single token', function(){
      expect(cut('

'))
      .eql(tokenize(['
', '', '', '
']));
    });

    it('should identify an iframe tag as a single token', function(){
      expect(cut('

'))
      .eql(tokenize(['
', '', '
']));
    });

    it('should identify an object tag as a single token', function(){
      expect(cut('
<object><param name="1" /><param name="2" /></object>
'))
      .eql(tokenize(['
', '<object><param name="1" /><param name="2" /></object>', '
']));
    });

    it('should identify a math tag as a single token', function(){
      expect(cut('
<math xmlns="http://www.w3.org/1998/Math/MathML">' +
        '<mi>π</mi>' +
        '<mo></mo>' +
        '<msup><mi>r</mi><mn>2</mn></msup></math>
'))
      .eql(tokenize([
        '
',
        '<math xmlns="http://www.w3.org/1998/Math/MathML">' +
            '<mi>π</mi>' +
            '<mo></mo>' +
            '<msup><mi>r</mi><mn>2</mn></msup></math>',
        '
']));
    });

    it('should identify an svg tag as a single token', function(){
      expect(cut('
<svg width="100" height="100">' +
        '<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />' +
        '</svg>
'))
      .eql(tokenize([
        '
',
        '<svg width="100" height="100">' +
          '<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />' +
          '</svg>',
        '
']));
    });

    it('should identify a script tag as a single token', function(){
      expect(cut('

'))
      .eql(tokenize(['
', '', '
']));
    });
  }); // describe('when encountering atomic tags')
}); // describe('html_to_tokens')
<commit_msg>Remove console.log :-p<commit_after>describe('html_to_tokens', function(){
  var cut, res, diff, create_token, tokenize;

  beforeEach(function(){
    diff = require('../js/htmldiff')
    cut = diff.html_to_tokens;

    create_token = diff.find_matching_blocks.create_token;
    tokenize = function(tokens) {
      return tokens.map(function(token) {
        return create_token(token);
      });
    };
  });

  it('should be a function', function(){
    expect(cut).is.a('function');
  });

  describe('when called with text', function(){
    beforeEach(function(){
      res = cut('this is a test');
    });

    it('should return 4', function(){
      expect(res.length).to.equal(7);
    });
  }); // describe('when called with text')

  describe('when called with html', function(){
    beforeEach(function(){
      res = cut('
this is a test
');
    });

    it('should return 11', function(){
      expect(res.length).to.equal(11);
    });

    it('should remove any html comments', function() {
      res = cut('
 this is
');
      expect(res.length).to.equal(8);
    });
  }); // describe('when called with html')

  it('should identify contiguous whitespace as a single token', function(){
    expect(cut('a   b')).to.eql(tokenize(['a', '   ', 'b']));
  });

  it('should identify a single space as a single token', function(){
    expect(cut(' a b ')).to.eql(tokenize([' ', 'a', ' ', 'b', ' ']));
  });

  it('should identify self closing tags as tokens', function(){
    expect(cut('
hello
goodbye
'))
    .eql(tokenize(['
', 'hello', '
', 'goodbye', '
']));
  });

  describe('when encountering atomic tags', function(){
    it('should identify an image tag as a single token', function(){
      expect(cut('

'))
      .eql(tokenize(['
', '', '', '
']));
    });

    it('should identify an iframe tag as a single token', function(){
      expect(cut('

'))
      .eql(tokenize(['
', '', '
']));
    });

    it('should identify an object tag as a single token', function(){
      expect(cut('
<object><param name="1" /><param name="2" /></object>
'))
      .eql(tokenize(['
', '<object><param name="1" /><param name="2" /></object>', '
']));
    });

    it('should identify a math tag as a single token', function(){
      expect(cut('
<math xmlns="http://www.w3.org/1998/Math/MathML">' +
        '<mi>π</mi>' +
        '<mo></mo>' +
        '<msup><mi>r</mi><mn>2</mn></msup></math>
'))
      .eql(tokenize([
        '
',
        '<math xmlns="http://www.w3.org/1998/Math/MathML">' +
            '<mi>π</mi>' +
            '<mo></mo>' +
            '<msup><mi>r</mi><mn>2</mn></msup></math>',
        '
']));
    });

    it('should identify an svg tag as a single token', function(){
      expect(cut('
<svg width="100" height="100">' +
        '<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />' +
        '</svg>
'))
      .eql(tokenize([
        '
',
        '<svg width="100" height="100">' +
          '<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />' +
          '</svg>',
        '
']));
    });

    it('should identify a script tag as a single token', function(){
      expect(cut('

'))
      .eql(tokenize(['
', '', '
']));
    });
  }); // describe('when encountering atomic tags')
}); // describe('html_to_tokens')
<|endoftext|>


<commit_before>// Copyright 2015 Fabian Dietenberger

var should = require('chai').should(),
    hypemResolver = require('../hypem-resolver');

var grizHypemId = "2c87x",
    grizHypemUrl = "http://hypem.com/track/2c87x",
    grizSoundcloudUrl = "https://soundcloud.com/griz/summer-97-ft-muzzy-bearr";

describe('The song is hosted on soundcloud', function () {

    describe('if the hypem id is given', function () {

        it('should return a soundcloud url', function (done) {
            var soundcloudUrl = hypemResolver.getById(grizHypemId);
            soundcloudUrl.should.be.a('string');
            soundcloudUrl.should.equal(grizSoundcloudUrl);
            done();
        });

        it('should also return a soundcloud url async', function (done) {
            hypemResolver.getByIdAsync(grizHypemId, function (soundcloudUrl) {
                soundcloudUrl.should.be.a('string');
                soundcloudUrl.should.equal(grizSoundcloudUrl);
                done();
            });
        })
    });

    describe('if the hypem url is given', function () {
        it('should return a soundcloud url', function (done) {
            var soundcloudUrl = hypemResolver.getByUrl(grizHypemUrl);
            soundcloudUrl.should.be.a('string');
            soundcloudUrl.should.equal(grizSoundcloudUrl);
            done();
        });

        it('should ignore leading and ending whitspace', function (done) {
            var soundcloudUrl = hypemResolver.getByUrl("    " + grizHypemUrl + "   ");
            soundcloudUrl.should.be.a('string');
            soundcloudUrl.should.equal(grizSoundcloudUrl);
            done();
        });

        it('should throw an error if the url is incorrect', function (done) {
            (function () {
                hypemResolver.getByUrl("dfesfessfe");
            }).should.throw();
            done();
        });

        it('should also return a soundcloud url async', function (done) {
            hypemResolver.getByUrlAsync(grizHypemUrl, function (soundcloudUrl) {
                soundcloudUrl.should.be.a('string');
                soundcloudUrl.should.equal(grizSoundcloudUrl);
                done();
            });
        })
    })
});

<commit_msg>Refactor test description<commit_after>// Copyright 2015 Fabian Dietenberger

var should = require('chai').should(),
    hypemResolver = require('../hypem-resolver');

var grizHypemId = "2c87x",
    grizHypemUrl = "http://hypem.com/track/2c87x",
    grizSoundcloudUrl = "https://soundcloud.com/griz/summer-97-ft-muzzy-bearr";

describe('If the song is hosted on soundcloud', function () {

    describe('and the hypem id is given', function () {

        it('should return a soundcloud url', function (done) {
            var soundcloudUrl = hypemResolver.getById(grizHypemId);
            soundcloudUrl.should.be.a('string');
            soundcloudUrl.should.equal(grizSoundcloudUrl);
            done();
        });

        it('should also return a soundcloud url async', function (done) {
            hypemResolver.getByIdAsync(grizHypemId, function (soundcloudUrl) {
                soundcloudUrl.should.be.a('string');
                soundcloudUrl.should.equal(grizSoundcloudUrl);
                done();
            });
        })
    });

    describe('and the hypem url is given', function () {
        it('should return a soundcloud url', function (done) {
            var soundcloudUrl = hypemResolver.getByUrl(grizHypemUrl);
            soundcloudUrl.should.be.a('string');
            soundcloudUrl.should.equal(grizSoundcloudUrl);
            done();
        });

        it('should ignore leading and ending whitspace', function (done) {
            var soundcloudUrl = hypemResolver.getByUrl("    " + grizHypemUrl + "   ");
            soundcloudUrl.should.be.a('string');
            soundcloudUrl.should.equal(grizSoundcloudUrl);
            done();
        });

        it('should throw an error if the url is incorrect', function (done) {
            (function () {
                hypemResolver.getByUrl("dfesfessfe");
            }).should.throw();
            done();
        });

        it('should also return a soundcloud url async', function (done) {
            hypemResolver.getByUrlAsync(grizHypemUrl, function (soundcloudUrl) {
                soundcloudUrl.should.be.a('string');
                soundcloudUrl.should.equal(grizSoundcloudUrl);
                done();
            });
        })
    })
});

<|endoftext|>