<commit_before>'use strict'

var fs = require('../')
var rimraf = require('rimraf')
var mkdirp = require('mkdirp')
var test = require('tap').test
var p = require('path').resolve(__dirname, 'files')

process.chdir(__dirname)

// Make sure to reserve the stderr fd
process.stderr.write('')

var num = 4097
var paths = new Array(num)

test('write files', function (t) {
  rimraf.sync(p)
  mkdirp.sync(p)

  var done = 0
  for (var i = 0; i < num; ++i) {
    paths[i] = 'files/file-' + i
    var stream = fs.createWriteStream(paths[i])
    stream.on('end', function () {
      ++done
      if (done === num) {
        t.pass('success')
        t.end()
      }
    })
    stream.write('content')
    stream.end()
  }

  t.end()
})

test('read files', function (t) {
  // now read them
  var done = 0
  for (var i = 0; i < num; ++i) {
    var stream = fs.createReadStream(paths[i])
    stream.on('data', function (data) {})
    stream.on('end', function () {
      ++done
      if (done === num) {
        t.pass('success')
        t.end()
      }
    })
  }
})

test('cleanup', function (t) {
  rimraf.sync(p)
  t.end()
})
<commit_msg>Validate data in stream test<commit_after>'use strict'

var fs = require('../')
var rimraf = require('rimraf')
var mkdirp = require('mkdirp')
var test = require('tap').test
var p = require('path').resolve(__dirname, 'files')

process.chdir(__dirname)

// Make sure to reserve the stderr fd
process.stderr.write('')

var num = 4097
var paths = new Array(num)

test('write files', function (t) {
  rimraf.sync(p)
  mkdirp.sync(p)

  t.plan(num)
  for (var i = 0; i < num; ++i) {
    paths[i] = 'files/file-' + i
    var stream = fs.createWriteStream(paths[i])
    stream.on('finish', function () {
      t.pass('success')
    })
    stream.write('content')
    stream.end()
  }
})

test('read files', function (t) {
  // now read them
  t.plan(num)
  for (var i = 0; i < num; ++i) (function (i) {
    var stream = fs.createReadStream(paths[i])
    var data = ''
    stream.on('data', function (c) {
      data += c
    })
    stream.on('end', function () {
      t.equal(data, 'content')
    })
  })(i)
})

test('cleanup', function (t) {
  rimraf.sync(p)
  t.end()
})
<|endoftext|>


<commit_before>var fs = require("fs");
var buster = require("buster");
var assert = buster.assert;
var refute = buster.refute;
var busterResources = require("./../lib/buster-resources");
var resourceSet = require("./../lib/resource-set");

buster.testCase("resource-set", {
    setUp: function () {
        this.br = Object.create(busterResources);
    },

    "test creating with blank object": function () {
        var r = this.br.createResourceSet({resources: {}});
        assert(r.load instanceof Array);
        assert.equals(r.load.length, 0);

        assert.equals("", r.contextPath);
    },

    "test prepending entries to load post creation": function () {
        var r = this.br.createResourceSet({
            load: ["/foo"],
            resources: {
                "/foo":{"content":"foo"},
                "/bar": {"content":"bar"}
            }
        });

        r.prependToLoad(["/bar"]);
        assert.equals(r.load, ["/bar", "/foo"]);
    },

    "test prepending entry to load post creation that isn't in 'resources'": function (done) {
        var r = this.br.createResourceSet({resources: {}});

        try {
            r.prependToLoad(["/bar"]);
        } catch (e) {
            assert.match(e.message, "missing corresponding");
            done();
        }
    },

    "test prepending multiple entries in prependToLoad": function () {
        var r = this.br.createResourceSet({
            load: ["/foo"],
            resources: {
                "/foo": {content:"a"},
                "/bar": {content:"b"},
                "/baz": {content:"b"}
            }
        });

        r.prependToLoad(["/bar", "/baz"]);

        assert.equals(r.load, ["/bar", "/baz", "/foo"]);
    },

    "test prepending multiple entries in prependToLoad where one is not present": function () {
        var r = this.br.createResourceSet({
            load: ["/foo"],
            resources: {
                "/foo": {content:"a"},
                "/bar": {content:"b"}
            }
        });

        assert.exception(function () {
            r.prependToLoad(["/bar", "/baz"]);
        });
        assert.equals(r.load, ["/foo"]);
    },

    "test adding existing entry in prependToLoad": function (done) {
        var r = this.br.createResourceSet({
            load: ["/foo"],
            resources: {
                "/foo": {content:"a"},
                "/bar": {content:"b"}
            }
        });

        try {
            r.prependToLoad(["/bar", "/foo"]);
        } catch (e) {
            assert.match(e.message, "Can not prepend")
            assert.match(e.message, "/foo");
            assert.equals(r.load, ["/foo"]);
            done();
        }
    },

    "test appending entries to load post creation": function () {
        var r = this.br.createResourceSet({
            load: ["/foo"],
            resources: {
                "/foo":{"content":"foo"},
                "/bar": {"content":"bar"}
            }
        });

        r.appendToLoad(["/bar"]);
        assert.equals(r.load, ["/foo", "/bar"]);
    },

    "test appending entry to load post creation that isn't in 'resources'": function (done) {
        var r = this.br.createResourceSet({resources: {}});

        try {
            r.appendToLoad(["/bar"]);
        } catch (e) {
            assert.match(e.message, "missing corresponding");
            done();
        }
    },

    "test appending multiple entries in appendToLoad": function () {
        var r = this.br.createResourceSet({
            load: ["/foo"],
            resources: {
                "/foo": {content:"a"},
                "/bar": {content:"b"},
                "/baz": {content:"b"}
            }
        });

        r.appendToLoad(["/bar", "/baz"]);

        assert.equals(r.load, ["/foo", "/bar", "/baz"]);
    },

    "test appending multiple entries in appendToLoad where one is not present": function () {
        var r = this.br.createResourceSet({
            load: ["/foo"],
            resources: {
                "/foo": {content:"a"},
                "/bar": {content:"b"}
            }
        });

        assert.exception(function () {
            r.appendToLoad(["/bar", "/baz"]);
        });
        assert.equals(r.load, ["/foo"]);
    },

    "test adding existing entry in appendToLoad": function (done) {
        var r = this.br.createResourceSet({
            load: ["/foo"],
            resources: {
                "/foo": {content:"a"},
                "/bar": {content:"b"}
            }
        });

        try {
            r.appendToLoad(["/bar", "/foo"]);
        } catch (e) {
            assert.match(e.message, "Can not append")
            assert.match(e.message, "/foo");
            assert.equals(r.load, ["/foo"]);
            done();
        }
    },

    "test all entries in 'load' are script injected to root resource": function (done) {
        var r = this.br.createResourceSet({resources:{}});

        // NOTE: altering 'load' directly is not a supported API.
        r.load = ["/foo", "/bar", "/baz"];

        r.getResource("/", function (err, resource) {
            var body = resource.content;
            assert.match(body,'<script src="' + r.contextPath  + '/foo"');
            assert.match(body, '<script src="' + r.contextPath  + '/bar"');
            assert.match(body, '<script src="' + r.contextPath  + '/baz"');
            done();
        });
    },

    "test adding file by path": function (done) {
        var rs = resourceSet.create({});
        rs.addFile(__filename);

        rs.getResource(__filename, function (err, resource) {
            assert.equals(resource.content.toString("utf8"), fs.readFileSync(__filename).toString("utf8"));
            done();
        });
    },

    "test adding file by path with missing file": function (done) {
        var filename = "/tmp/i-sure-hope-this-file-does-not-exist" + new Date().getTime().toString();
        var rs = resourceSet.create({});
        rs.addFile(filename);

        rs.getResource(filename, function (err, resource) {
            assert.isUndefined(resource);
            assert.equals(err.code, "ENOENT");
            done();
        });
    },

    "test adding file by path with custom resource path": function (done) {
        var rs = resourceSet.create({});
        rs.addFile(__filename, {path: "/custom.txt"});

        rs.getResource("/custom.txt", function (err, resource) {
            assert.equals(resource.content.toString("utf8"), fs.readFileSync(__filename).toString("utf8"));
            done();
        });
    },

    "test adding file by path with options": function (done) {
        var rs = resourceSet.create({});
        rs.addFile(__filename, {headers: {"X-Foo": "Bar"}});

        rs.getResource(__filename, function (err, resource) {
            assert.match(resource.headers, {"X-Foo": "Bar"});
            done();
        });
    },

    "test getResource fails for none existing resource": function () {
        var rs = resourceSet.create({});
        assert.isFalse(rs.getResource("/foo.txt", function(){}));
    },

    "test deleting resource": function () {
        var rs = resourceSet.create({resources:{"/foo":{content:"foo"}}});
        rs.removeResource("/foo");
        refute("/foo" in rs.resources);
    },

    "test deleting resource removes it from load": function () {
        var rs = resourceSet.create({load:["/foo"],resources:{"/foo":{content:"foo"}}});
        rs.removeResource("/foo");
        assert.equals(rs.load, []);
    },

    "test deleting resource does not remove entries before itself in load": function () {
        var rs = resourceSet.create({load:["/bar", "/foo"],resources:{
            "/foo":{content:"foo"},
            "/bar":{content:"bar"}
        }});

        rs.removeResource("/foo");
        assert.equals(rs.load, ["/bar"]);
    },

    "test deleting resource does not remove entries after itself in load": function () {
        var rs = resourceSet.create({load:["/foo", "/bar"],resources:{
            "/foo":{content:"foo"},
            "/bar":{content:"bar"}
        }});

        rs.removeResource("/foo");
        assert.equals(rs.load, ["/bar"]);
    },

    "test deleting none existing resource": function () {
        var rs = resourceSet.create({resources:{"/foo":{content:"foo"}}});
        assert.exception(function () {
            rs.removeResource("/bar");
        });
    },

    "test getting none existent resource": function (done) {
        var rs = resourceSet.create({resources:{"/foo":{content:"foo"}}});
        rs.getResource("/bar", function (err, resource) {
            assert.isUndefined(resource);
            assert.equals(err, resourceSet.RESOURCE_NOT_FOUND);
            done();
        });
    },

    "validations": {
        "should fail if load entry misses corresponding resources entry": function (done) {
            try {
                var r = this.br.createResourceSet({load:["/foo"]})
            } catch (e) {
                assert.equals(e.message, "'load' entry '/foo' missing corresponding 'resources' entry.");
                done();
            }
        },

        "with content property present": {
            "should fail if not a buffer or string": function () {
                var self = this;

                refute.exception(function () {
                    self.br.createResourceSet({resources:{"/foo":{"content":"foo"}}});
                });

                refute.exception(function () {
                    self.br.createResourceSet({resources:{"/foo":{"content":new Buffer([0x00, 0x01])}}});
                });

                assert.exception(function () {
                    self.br.createResourceSet({resources:{"/foo":{"content":1234}}});
                });

                assert.exception(function () {
                    self.br.createResourceSet({resources:{"/foo":{"content":{}}}});
                });

                assert.exception(function () {
                    self.br.createResourceSet({resources:{"/foo":{"content":[]}}});
                });
            }
        },

        "should fail when not an object": function (done) {
            try {
                var r = this.br.createResourceSet()
            } catch (e) {
                assert.equals(e.message, "Resource object is null or undefined.");
                done();
            }
        },

        "should fail if neither etag, content, backend or combine is present": function () {
            var self = this;

            assert.exception(function () {
                self.br.createResourceSet({resources:{"/foo":{}}});
            }, "Error", "Received no resource etag, content, backend or combine");
        },

        "should fail if more than one of content, backend or combine is present": function () {
            var self = this;
            var msg = "Can only have one of content, combine and backend";

            assert.exception(function () {
                self.br.createResourceSet({resources:{"/foo":{content:"foo", combine: ["/xxx"]}}});
            }, "Error", msg);

            assert.exception(function () {
                self.br.createResourceSet({resources:{"/foo":{content:"foo", backend: "http://foo.com"}}});
            }, "Error", msg);

            assert.exception(function () {
                self.br.createResourceSet({resources:{"/foo":{combine:["/xxx"], backend: "http://foo.com"}}});
            }, "Error", msg);
        },

        "should fail if backend is not a valid URL": function () {
            var self = this;
            var msg = "Proxy resource backend is invalid";

            assert.exception(function () {
                self.br.createResourceSet({resources:{"/foo":{backend:"wtf"}}});
            }, "Error", msg);
        },

        "should fail with relative path": function () {
            var self = this;
            var msg = "Proxy resource backend is invalid";

            assert.exception(function () {
                self.br.createResourceSet({resources:{"../foo":{content:""}}});
            }, "Error", "Path can not be relative");
        }
    },

    "read only output": {
        "should handle basic resource": function (done) {
            var r = this.br.createResourceSet({
                load: ["/foo"],
                resources: {
                    "/foo":{"content":"foo"},
                    "/bar": {"content":"bar"}
                }
            });

            r.getReadOnly(function (err, ro) {
                assert.isUndefined(err);
                assert.match(ro, {
                    load: ["/foo"],
                    resources: {
                        "/foo":{"content":"foo"},
                        "/bar": {"content":"bar"}
                    }
                });

                assert("/" in ro.resources);
                assert(Object.keys(ro.resources).length, 3);

                done();
            });
        },

        "should handle resources with etag": function (done) {
            var r = resourceSet.create({
                resources: {
                    "/foo":{"etag":"1234"}
                }
            });

            r.getReadOnly(function (err, ro) {
                assert.isUndefined(err);
                assert.match(ro, {
                    resources: {
                        "/foo":{"etag":"1234"},
                    }
                });

                refute("content" in ro.resources["/foo"]);
                refute("backend" in ro.resources["/foo"]);
                refute("combine" in ro.resources["/foo"]);

                done();
            });
        },

        "should handle resources with backend": function (done) {
            var r = resourceSet.create({
                resources: {
                    "/foo":{"backend":"http://foo.com"}
                }
            });

            r.getReadOnly(function (err, ro) {
                assert.isUndefined(err);
                assert.match(ro, {
                    resources: {
                        "/foo":{"backend":"http://foo.com"},
                    }
                });

                refute("content" in ro.resources["/foo"]);
                refute("etag" in ro.resources["/foo"]);
                refute("combine" in ro.resources["/foo"]);

                done();
            });
        },

        "should handle resources with combine": function (done) {
            var r = resourceSet.create({
                resources: {
                    "/foo":{"combine":["/bar", "/baz"]},
                    "/bar":{"content":"1234"},
                    "/baz":{"content":"abcd"}
                }
            });

            r.getReadOnly(function (err, ro) {
                assert.isUndefined(err);
                assert.match(ro, {
                    resources: {
                        "/foo":{"combine":["/bar", "/baz"]},
                    }
                });

                refute("content" in ro.resources["/foo"]);
                refute("etag" in ro.resources["/foo"]);
                refute("backend" in ro.resources["/foo"]);

                done();
            });
        }
    }
});<commit_msg>Removing unneeded white space.<commit_after>var fs = require("fs");
var buster = require("buster");
var assert = buster.assert;
var refute = buster.refute;
var busterResources = require("./../lib/buster-resources");
var resourceSet = require("./../lib/resource-set");

buster.testCase("resource-set", {
    setUp: function () {
        this.br = Object.create(busterResources);
    },

    "test creating with blank object": function () {
        var r = this.br.createResourceSet({resources: {}});
        assert(r.load instanceof Array);
        assert.equals(r.load.length, 0);

        assert.equals("", r.contextPath);
    },

    "test prepending entries to load post creation": function () {
        var r = this.br.createResourceSet({
            load: ["/foo"],
            resources: {
                "/foo":{"content":"foo"},
                "/bar": {"content":"bar"}
            }
        });

        r.prependToLoad(["/bar"]);
        assert.equals(r.load, ["/bar", "/foo"]);
    },

    "test prepending entry to load post creation that isn't in 'resources'": function (done) {
        var r = this.br.createResourceSet({resources: {}});

        try {
            r.prependToLoad(["/bar"]);
        } catch (e) {
            assert.match(e.message, "missing corresponding");
            done();
        }
    },

    "test prepending multiple entries in prependToLoad": function () {
        var r = this.br.createResourceSet({
            load: ["/foo"],
            resources: {
                "/foo": {content:"a"},
                "/bar": {content:"b"},
                "/baz": {content:"b"}
            }
        });

        r.prependToLoad(["/bar", "/baz"]);

        assert.equals(r.load, ["/bar", "/baz", "/foo"]);
    },

    "test prepending multiple entries in prependToLoad where one is not present": function () {
        var r = this.br.createResourceSet({
            load: ["/foo"],
            resources: {
                "/foo": {content:"a"},
                "/bar": {content:"b"}
            }
        });

        assert.exception(function () {
            r.prependToLoad(["/bar", "/baz"]);
        });
        assert.equals(r.load, ["/foo"]);
    },

    "test adding existing entry in prependToLoad": function (done) {
        var r = this.br.createResourceSet({
            load: ["/foo"],
            resources: {
                "/foo": {content:"a"},
                "/bar": {content:"b"}
            }
        });

        try {
            r.prependToLoad(["/bar", "/foo"]);
        } catch (e) {
            assert.match(e.message, "Can not prepend")
            assert.match(e.message, "/foo");
            assert.equals(r.load, ["/foo"]);
            done();
        }
    },

    "test appending entries to load post creation": function () {
        var r = this.br.createResourceSet({
            load: ["/foo"],
            resources: {
                "/foo":{"content":"foo"},
                "/bar": {"content":"bar"}
            }
        });

        r.appendToLoad(["/bar"]);
        assert.equals(r.load, ["/foo", "/bar"]);
    },

    "test appending entry to load post creation that isn't in 'resources'": function (done) {
        var r = this.br.createResourceSet({resources: {}});

        try {
            r.appendToLoad(["/bar"]);
        } catch (e) {
            assert.match(e.message, "missing corresponding");
            done();
        }
    },

    "test appending multiple entries in appendToLoad": function () {
        var r = this.br.createResourceSet({
            load: ["/foo"],
            resources: {
                "/foo": {content:"a"},
                "/bar": {content:"b"},
                "/baz": {content:"b"}
            }
        });

        r.appendToLoad(["/bar", "/baz"]);

        assert.equals(r.load, ["/foo", "/bar", "/baz"]);
    },

    "test appending multiple entries in appendToLoad where one is not present": function () {
        var r = this.br.createResourceSet({
            load: ["/foo"],
            resources: {
                "/foo": {content:"a"},
                "/bar": {content:"b"}
            }
        });

        assert.exception(function () {
            r.appendToLoad(["/bar", "/baz"]);
        });
        assert.equals(r.load, ["/foo"]);
    },

    "test adding existing entry in appendToLoad": function (done) {
        var r = this.br.createResourceSet({
            load: ["/foo"],
            resources: {
                "/foo": {content:"a"},
                "/bar": {content:"b"}
            }
        });

        try {
            r.appendToLoad(["/bar", "/foo"]);
        } catch (e) {
            assert.match(e.message, "Can not append")
            assert.match(e.message, "/foo");
            assert.equals(r.load, ["/foo"]);
            done();
        }
    },

    "test all entries in 'load' are script injected to root resource": function (done) {
        var r = this.br.createResourceSet({resources:{}});

        // NOTE: altering 'load' directly is not a supported API.
        r.load = ["/foo", "/bar", "/baz"];

        r.getResource("/", function (err, resource) {
            var body = resource.content;
            assert.match(body,'<script src="' + r.contextPath  + '/foo"');
            assert.match(body, '<script src="' + r.contextPath  + '/bar"');
            assert.match(body, '<script src="' + r.contextPath  + '/baz"');
            done();
        });
    },

    "test adding file by path": function (done) {
        var rs = resourceSet.create({});
        rs.addFile(__filename);

        rs.getResource(__filename, function (err, resource) {
            assert.equals(resource.content.toString("utf8"), fs.readFileSync(__filename).toString("utf8"));
            done();
        });
    },

    "test adding file by path with missing file": function (done) {
        var filename = "/tmp/i-sure-hope-this-file-does-not-exist" + new Date().getTime().toString();
        var rs = resourceSet.create({});
        rs.addFile(filename);

        rs.getResource(filename, function (err, resource) {
            assert.isUndefined(resource);
            assert.equals(err.code, "ENOENT");
            done();
        });
    },

    "test adding file by path with custom resource path": function (done) {
        var rs = resourceSet.create({});
        rs.addFile(__filename, {path: "/custom.txt"});

        rs.getResource("/custom.txt", function (err, resource) {
            assert.equals(resource.content.toString("utf8"), fs.readFileSync(__filename).toString("utf8"));
            done();
        });
    },

    "test adding file by path with options": function (done) {
        var rs = resourceSet.create({});
        rs.addFile(__filename, {headers: {"X-Foo": "Bar"}});

        rs.getResource(__filename, function (err, resource) {
            assert.match(resource.headers, {"X-Foo": "Bar"});
            done();
        });
    },

    "test getResource fails for none existing resource": function () {
        var rs = resourceSet.create({});
        assert.isFalse(rs.getResource("/foo.txt", function(){}));
    },

    "test deleting resource": function () {
        var rs = resourceSet.create({resources:{"/foo":{content:"foo"}}});
        rs.removeResource("/foo");
        refute("/foo" in rs.resources);
    },

    "test deleting resource removes it from load": function () {
        var rs = resourceSet.create({load:["/foo"],resources:{"/foo":{content:"foo"}}});
        rs.removeResource("/foo");
        assert.equals(rs.load, []);
    },

    "test deleting resource does not remove entries before itself in load": function () {
        var rs = resourceSet.create({load:["/bar", "/foo"],resources:{
            "/foo":{content:"foo"},
            "/bar":{content:"bar"}
        }});

        rs.removeResource("/foo");
        assert.equals(rs.load, ["/bar"]);
    },

    "test deleting resource does not remove entries after itself in load": function () {
        var rs = resourceSet.create({load:["/foo", "/bar"],resources:{
            "/foo":{content:"foo"},
            "/bar":{content:"bar"}
        }});

        rs.removeResource("/foo");
        assert.equals(rs.load, ["/bar"]);
    },

    "test deleting none existing resource": function () {
        var rs = resourceSet.create({resources:{"/foo":{content:"foo"}}});
        assert.exception(function () {
            rs.removeResource("/bar");
        });
    },

    "test getting none existent resource": function (done) {
        var rs = resourceSet.create({resources:{"/foo":{content:"foo"}}});
        rs.getResource("/bar", function (err, resource) {
            assert.isUndefined(resource);
            assert.equals(err, resourceSet.RESOURCE_NOT_FOUND);
            done();
        });
    },

    "validations": {
        "should fail if load entry misses corresponding resources entry": function (done) {
            try {
                var r = this.br.createResourceSet({load:["/foo"]})
            } catch (e) {
                assert.equals(e.message, "'load' entry '/foo' missing corresponding 'resources' entry.");
                done();
            }
        },

        "with content property present": {
            "should fail if not a buffer or string": function () {
                var self = this;

                refute.exception(function () {
                    self.br.createResourceSet({resources:{"/foo":{"content":"foo"}}});
                });

                refute.exception(function () {
                    self.br.createResourceSet({resources:{"/foo":{"content":new Buffer([0x00, 0x01])}}});
                });

                assert.exception(function () {
                    self.br.createResourceSet({resources:{"/foo":{"content":1234}}});
                });

                assert.exception(function () {
                    self.br.createResourceSet({resources:{"/foo":{"content":{}}}});
                });

                assert.exception(function () {
                    self.br.createResourceSet({resources:{"/foo":{"content":[]}}});
                });
            }
        },

        "should fail when not an object": function (done) {
            try {
                var r = this.br.createResourceSet()
            } catch (e) {
                assert.equals(e.message, "Resource object is null or undefined.");
                done();
            }
        },

        "should fail if neither etag, content, backend or combine is present": function () {
            var self = this;

            assert.exception(function () {
                self.br.createResourceSet({resources:{"/foo":{}}});
            }, "Error", "Received no resource etag, content, backend or combine");
        },

        "should fail if more than one of content, backend or combine is present": function () {
            var self = this;
            var msg = "Can only have one of content, combine and backend";

            assert.exception(function () {
                self.br.createResourceSet({resources:{"/foo":{content:"foo", combine: ["/xxx"]}}});
            }, "Error", msg);

            assert.exception(function () {
                self.br.createResourceSet({resources:{"/foo":{content:"foo", backend: "http://foo.com"}}});
            }, "Error", msg);

            assert.exception(function () {
                self.br.createResourceSet({resources:{"/foo":{combine:["/xxx"], backend: "http://foo.com"}}});
            }, "Error", msg);
        },

        "should fail if backend is not a valid URL": function () {
            var self = this;
            var msg = "Proxy resource backend is invalid";

            assert.exception(function () {
                self.br.createResourceSet({resources:{"/foo":{backend:"wtf"}}});
            }, "Error", msg);
        },

        "should fail with relative path": function () {
            var self = this;
            var msg = "Proxy resource backend is invalid";

            assert.exception(function () {
                self.br.createResourceSet({resources:{"../foo":{content:""}}});
            }, "Error", "Path can not be relative");
        }
    },

    "read only output": {
        "should handle basic resource": function (done) {
            var r = this.br.createResourceSet({
                load: ["/foo"],
                resources: {
                    "/foo":{"content":"foo"},
                    "/bar": {"content":"bar"}
                }
            });

            r.getReadOnly(function (err, ro) {
                assert.isUndefined(err);
                assert.match(ro, {
                    load: ["/foo"],
                    resources: {
                        "/foo":{"content":"foo"},
                        "/bar": {"content":"bar"}
                    }
                });

                assert("/" in ro.resources);
                assert(Object.keys(ro.resources).length, 3);

                done();
            });
        },

        "should handle resources with etag": function (done) {
            var r = resourceSet.create({
                resources: {
                    "/foo":{"etag":"1234"}
                }
            });

            r.getReadOnly(function (err, ro) {
                assert.isUndefined(err);
                assert.match(ro, {
                    resources: {
                        "/foo":{"etag":"1234"},
                    }
                });

                refute("content" in ro.resources["/foo"]);
                refute("backend" in ro.resources["/foo"]);
                refute("combine" in ro.resources["/foo"]);

                done();
            });
        },

        "should handle resources with backend": function (done) {
            var r = resourceSet.create({
                resources: {
                    "/foo":{"backend":"http://foo.com"}
                }
            });

            r.getReadOnly(function (err, ro) {
                assert.isUndefined(err);
                assert.match(ro, {
                    resources: {
                        "/foo":{"backend":"http://foo.com"},
                    }
                });

                refute("content" in ro.resources["/foo"]);
                refute("etag" in ro.resources["/foo"]);
                refute("combine" in ro.resources["/foo"]);

                done();
            });
        },

        "should handle resources with combine": function (done) {
            var r = resourceSet.create({
                resources: {
                    "/foo":{"combine":["/bar", "/baz"]},
                    "/bar":{"content":"1234"},
                    "/baz":{"content":"abcd"}
                }
            });

            r.getReadOnly(function (err, ro) {
                assert.isUndefined(err);
                assert.match(ro, {
                    resources: {
                        "/foo":{"combine":["/bar", "/baz"]},
                    }
                });

                refute("content" in ro.resources["/foo"]);
                refute("etag" in ro.resources["/foo"]);
                refute("backend" in ro.resources["/foo"]);

                done();
            });
        }
    }
});<|endoftext|>


<commit_before>require('with-env')();

var expect = require('chai').expect;

var mongoose = require('mongoose');

var postModel = require('../../../src/models/post');

describe('post model', function () {

    var postId = null,
        messageId = null,
        profileID = mongoose.Types.ObjectId();

    before(function (done) {

        mongoose.connect('mongodb://localhost/test');

        postModel.find().remove(done);

    });

    after(function (done) {

        postModel.find().remove(function () {

            mongoose.connection.close(done);

        });

    });

    it('should create post', function (done) {

        postModel.createPost({
            title: 'Lorem ipsum dolor sit amet',
            contents: 'Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
        }, profileID).then(function (post) {

            expect(post).to.have.property('id');
            expect(post.id).to.be.a('string');

            postId = post.id;

            done();

        });

    });

    it('should be able to add message to post', function (done) {

        postModel.addMessageToPostById(postId, {
            contents: 'Sed egestas, ante et vulputate volutpat, eros pede semper est, vitae luctus metus libero eu augue. Morbi purus libero, faucibus adipiscing, commodo quis, gravida id, est. Sed lectus. Praesent elementum hendrerit tortor. Sed semper lorem at felis. Vestibulum volutpat, lacus a ultrices sagittis, mi neque euismod dui, eu pulvinar nunc sapien ornare nisl. Phasellus pede arcu, dapibus eu, fermentum et, dapibus sed, urna.'
        }, profileID).then(function (message) {

            expect(message).to.have.property('id');
            expect(message.id).to.be.a('string');

            messageId = message.id;

            done();

        });

    });

    it('should be able to show post', function (done) {

        postModel.showPostById(postId).then(function (post) {

            expect(post).to.have.property('_id');
            expect(post._id.equals(postId)).to.equal(true);

            done();

        });

    });

    it('should error on invalid postID', function (done) {

        postModel.showPostById('invalid').catch(function (err) {

            expect(err.status).to.equal(404);

            done();

        });

    });

    it('should be able to list posts', function (done) {

        postModel.listPosts().then(function (posts) {

            expect(posts).to.have.length(1);

            done();

        });

    });

    it('should be able to list messages by post ID', function (done) {

        postModel.listMessagesByPostId(postId).then(function (messages) {

            expect(messages).to.have.length(1);

            done();

        });

    });

    it('should error on invalid postID for message list', function (done) {

        postModel.listMessagesByPostId('invalid').catch(function (err) {

            expect(err.status).to.equal(404);

            done();

        });

    });

    it('should be able to search posts', function (done) {

        postModel.searchPosts('lorem').then(function (posts) {

            expect(posts).to.have.length(1);

            done();

        });

    });

    it('should be able to search posts (with no query)', function (done) {

        postModel.searchPosts('').then(function (posts) {

            expect(posts).to.have.length(0);

            done();

        });

    });

    it('should be able to search posts (with invalid query)', function (done) {

        postModel.searchPosts('&^%').then(function (posts) {

            expect(posts).to.have.length(0);

            done();

        });

    });

    it('should be able to search posts (with no results)', function (done) {

        postModel.searchPosts('sports').then(function (posts) {

            expect(posts).to.have.length(0);

            done();

        });

    });

    it('should be able to update post by ID', function (done) {

        postModel.updatePostById(postId, { title: 'Test', contents: 'test' }, profileID).then(function (post) {

            expect(post.title).to.be.equal('Test');
            expect(post.contents).to.be.equal('test');

            done();

        });

    });

    it('should be able to update messages in a post by ID', function (done) {

        postModel.updateMessageToPostById(postId, messageId, { contents: 'test' }, profileID).then(function (message) {

            expect(message.contents).to.be.equal('test');

            done();

        });

    });

    it('should be able to delete messages in a post by ID', function (done) {

        postModel.deleteMessageFromPostById(postId, messageId, { contents: 'test' }, profileID).then(function (messages) {

            expect(messages).to.have.length(0);

            done();

        });

    });

});
<commit_msg>Added tests.<commit_after>require('with-env')();

var expect = require('chai').expect;

var mongoose = require('mongoose');

var postModel = require('../../../src/models/post');

describe('post model', function () {

    var postId = null,
        messageId = null,
        profileID = mongoose.Types.ObjectId();

    before(function (done) {

        mongoose.connect('mongodb://localhost/test');

        postModel.find().remove(done);

    });

    after(function (done) {

        postModel.find().remove(function () {

            mongoose.connection.close(done);

        });

    });

    it('should create post', function (done) {

        postModel.createPost({
            title: 'Lorem ipsum dolor sit amet',
            contents: 'Consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.'
        }, profileID).then(function (post) {

            expect(post).to.have.property('id');
            expect(post.id).to.be.a('string');

            postId = post.id;

            done();

        });

    });

    it('should error while trying to create a post without a title', function (done) {

        postModel.createPost({
            title: ''
        }, profileID).catch(function (err) {

            expect(err.status).to.equal(500);

            done();

        });

    });

    it('should be able to add message to post', function (done) {

        postModel.addMessageToPostById(postId, {
            contents: 'Sed egestas, ante et vulputate volutpat, eros pede semper est, vitae luctus metus libero eu augue. Morbi purus libero, faucibus adipiscing, commodo quis, gravida id, est. Sed lectus. Praesent elementum hendrerit tortor. Sed semper lorem at felis. Vestibulum volutpat, lacus a ultrices sagittis, mi neque euismod dui, eu pulvinar nunc sapien ornare nisl. Phasellus pede arcu, dapibus eu, fermentum et, dapibus sed, urna.'
        }, profileID).then(function (message) {

            expect(message).to.have.property('id');
            expect(message.id).to.be.a('string');

            messageId = message.id;

            done();

        });

    });

    it('should be able to show post', function (done) {

        postModel.showPostById(postId).then(function (post) {

            expect(post).to.have.property('_id');
            expect(post._id.equals(postId)).to.equal(true);

            done();

        });

    });

    it('should error on invalid postID', function (done) {

        postModel.showPostById('invalid').catch(function (err) {

            expect(err.status).to.equal(404);

            done();

        });

    });

    it('should be able to list posts', function (done) {

        postModel.listPosts().then(function (posts) {

            expect(posts).to.have.length(1);

            done();

        });

    });

    it('should be able to list messages by post ID', function (done) {

        postModel.listMessagesByPostId(postId).then(function (messages) {

            expect(messages).to.have.length(1);

            done();

        });

    });

    it('should error on invalid postID for message list', function (done) {

        postModel.listMessagesByPostId('invalid').catch(function (err) {

            expect(err.status).to.equal(404);

            done();

        });

    });

    it('should be able to search posts', function (done) {

        postModel.searchPosts('lorem').then(function (posts) {

            expect(posts).to.have.length(1);

            done();

        });

    });

    it('should be able to search posts (with no query)', function (done) {

        postModel.searchPosts('').then(function (posts) {

            expect(posts).to.have.length(0);

            done();

        });

    });

    it('should be able to search posts (with invalid query)', function (done) {

        postModel.searchPosts('&^%').then(function (posts) {

            expect(posts).to.have.length(0);

            done();

        });

    });

    it('should be able to search posts (with no results)', function (done) {

        postModel.searchPosts('sports').then(function (posts) {

            expect(posts).to.have.length(0);

            done();

        });

    });

    it('should be able to update post by ID', function (done) {

        postModel.updatePostById(postId, { title: 'Test', contents: 'test' }, profileID).then(function (post) {

            expect(post.title).to.be.equal('Test');
            expect(post.contents).to.be.equal('test');

            done();

        });

    });

    it('should error when trying to update post by invalid ID', function (done) {

        postModel.updatePostById(mongoose.Types.ObjectId(), { title: 'Test', contents: 'test' }, profileID).catch(function (err) {

            expect(err.status).to.equal(500);

            done();

        });

    });

    it('should error when trying to update post by ID when not the original author', function (done) {

        postModel.updatePostById(postId, { title: 'Test', contents: 'test' }, mongoose.Types.ObjectId()).catch(function (err) {

            expect(err.status).to.equal(401);

            done();

        });

    });

    it('should be able to update messages in a post by ID', function (done) {

        postModel.updateMessageToPostById(postId, messageId, { contents: 'test' }, profileID).then(function (message) {

            expect(message.contents).to.be.equal('test');

            done();

        });

    });

    it('should error when trying to update post by ID when removing the title', function (done) {

        postModel.updatePostById(postId, { title: '' }, profileID).catch(function (err) {

            expect(err.status).to.equal(500);

            done();

        });

    });

    it('should be able to delete messages in a post by ID', function (done) {

        postModel.deleteMessageFromPostById(postId, messageId, { contents: 'test' }, profileID).then(function (messages) {

            expect(messages).to.have.length(0);

            done();

        });

    });

    it('should error when trying to delete messages in a post by invalid ID', function (done) {

        postModel.deleteMessageFromPostById(mongoose.Types.ObjectId(), messageId, { contents: 'test' }, profileID).catch(function (err) {

            expect(err.status).to.equal(500);

            done();

        });

    });

    it('should error when trying to delete messages in a post by invalid ID', function (done) {

        postModel.deleteMessageFromPostById(postId, mongoose.Types.ObjectId(), { contents: 'test' }, profileID).catch(function (err) {

            expect(err.status).to.equal(500);

            done();

        });

    });

});
<|endoftext|>


<commit_before>var chai = require('chai');
var expect = chai.expect;
var chaiHttp = require('chai-http');
var server = require('../../server/server.js');
var should = chai.should();
var db = require('../../server/db/schema');
var knex = require('knex');
var userController = require('../../server/controllers/userController');

chai.use(chaiHttp);

describe('Server', function(){
  it('should exists!', function(){
    expect(!!server).to.be.true;
  });
});

describe('userController', function(){
  it('should contain signin', function(){
    expect(!!userController.signin).to.be.true;
  });
  it('should contain signup', function(){
    expect(!!userController.signup).to.be.true;
  });
});

describe('Database', function(){
  it('should have a users table', function(){
    expect(true).to.be.true;
  });
  it('should have a highscores table', function(){
    expect(true).to.be.true;
  });
});

describe('Promts requests', function(){
  it('should send a prompt back',function(done){
    chai.request(server)
    .get('/api/getRandomPrompt')
    .end(function(err, res){
      res.should.have.status(200);
      done();
    });
  });
});

<commit_msg>[refactor] refactors and cleans up testing<commit_after>var chai = require('chai');
var expect = chai.expect;
var chaiHttp = require('chai-http');
var server = require('../../server/server.js');
var should = chai.should();
var db = require('../../server/db/schema');
var knex = require('knex');
var userController = require('../../server/controllers/userController');

chai.use(chaiHttp);

describe('Server', function(){
  it('should exists!', function(){
    expect(!!server).to.be.true;
  });
});

describe('userController', function(){
  it('should contain signin', function(){
    expect(!!userController.signin).to.be.true;
  });
  it('should contain signup', function(){
    expect(!!userController.signup).to.be.true;
  });
});

xdescribe('Database', function(){
  it('should have a users table', function(){
    expect(true).to.be.true;
  });
  it('should have a highscores table', function(){
    expect(true).to.be.true;
  });
});

describe('Promts requests', function(){
  it('should send a prompt back',function(done){
    chai.request(server)
    .get('/api/getRandomPrompt')
    .end(function(err, res){
      res.should.have.status(200);
      done();
    });
  });

});

<|endoftext|>


<commit_before>
describe('replace()', function () {
	it('.where(hash).eq( wrongtype ) - should fail', function(done) {
		DynamoDB
			.table($tableName)
			.replace({
				hash: 1,
				range: 1,
				key: 'value'
			}, function(err, data) {
				if (err)
					return done()

				throw {error: 'should fail'}
			})
	})

	it('should fail if we try to replace GSI index range key with the wrong type', function(done) {
		DynamoDB
			.table($tableName)
			.replace({
				hash: 'hash',
				range: 1,
				gsi_range: 1
			}, function(err, data) {
				if (err)
					done()
				else
					throw {error: 'should fail'}
			})
	})
	it('should fail if we try to replace an inexistent item', function(done) {
		DynamoDB
			.table($tableName)
			.where('hash').eq()
			.where('range').eq(1)
			.replace({
				hash: 'hash999',
				range: 1,
			}, function(err, data) {
				if (err)
					done()
				else
					throw {error: 'should fail'}
			})
	})

	it('.replace()', function(done) {
		// insert
		DynamoDB.table($tableName).insert({hash: 'hash1',range:1, old_number: 1, old_array: [1,2,3], string: 'aaa', 'ignore': 'me', 'delete': 'me'}, function(err) {
			if (err)
				throw err

			DynamoDB
				.table($tableName)
				.replace({
					hash: 'hash1',
					range: 1,
					gsi_range: 'b',
					string: 'newstring',
					boolean: false,
					null: null,
					old_array: [ 1, 'a', null, { k1: 'v1', k2: 'v2', k3: 'v3' }, [] ],
					object: { key1: 'value1', key2: 22 },
				}, function(err, data) {
					if (err)
						throw err
					else
						DynamoDB
							.table($tableName)
							.where('hash').eq('hash1')
							.where('range').eq(1)
							.consistentRead()
							.get(function( err, data ) {
								if (err)
									throw err

								assert.deepEqual(data, {
									hash: 'hash1',
									range: 1,
									old_array: [ 1, 'a', null, { k3: 'v3', k1: 'v1', k2: 'v2' }, [] ],
									string: 'newstring',
									boolean: false,

									null: null,
									gsi_range: 'b',
									object: { key2: 22, key1: 'value1' },
								})
								done()
							})
				})
		})
	})
	it('.return(DynamoDB.ALL_OLD).replace( existing_item )', function(done) {
		DynamoDB
			.table($tableName)
			.return(DynamoDB.ALL_OLD)
			.replace({
				hash: 'hash1',
				range: 1,
				string: 'aaa',
			}, function(err, data ) {
				if (err) throw err

				assert.deepEqual(data, { hash: 'hash1',
					null: null,
					range: 1,
					gsi_range: 'b',
					object: { key2: 22, key1: 'value1' },
					old_array: [ 1, 'a', null, { k3: 'v3', k1: 'v1', k2: 'v2' }, [] ],
					string: 'newstring',
					boolean: false,
				})
				done()
			})
	})
	it('.replace().then()', function(done) {
		DynamoDB
			.table($tableName)
			.return(DynamoDB.ALL_OLD)
			.replace({
				hash: 'hash1',
				range: 1,
				key: 'promise1'
			})
			.then(function(data) {
				done()
			})
	})
	it('.replace() - unhandled', function(done) {
		DynamoDB
			.table($tableName)
			.return(DynamoDB.ALL_OLD)
			.replace({
				hash: 'hash1',
				range: 1,
				key: 'promise2'
			})
		setTimeout(function() {
			done()
		},5000)
	})
	it('.replace().catch()', function(done) {
		DynamoDB
			.table($tableName)
			.replace({
				hash: 'promise',
				range: 1,
			})
			.catch(function(err) {
				done()
			})
	})
	it('.replace().then(,errorHandler)', function(done) {
		DynamoDB
			.table($tableName)
			.replace({
				hash: 'promise',
				range: 1,
			})
			.then( null, function(err) {
				done()
			})
	})
	it('cleanup...', function(done) {
		DynamoDB
			.table($tableName)
			.scan(function(err, data) {
				if (err)
					throw err
				else {
					async.each(data, function(item,cb) {
						DynamoDB.table($tableName).where('hash').eq(item.hash).where('range').eq(item.range).delete(function(err) { cb(err) })
					}, function(err) {
						if (err)
							throw err
						else
							done()
					})
				}
			})
	})
})
<commit_msg>update() - test empty string<commit_after>
describe('replace()', function () {
	it('.where(hash).eq( wrongtype ) - should fail', function(done) {
		DynamoDB
			.table($tableName)
			.replace({
				hash: 1,
				range: 1,
				key: 'value'
			}, function(err, data) {
				if (err)
					return done()

				throw {error: 'should fail'}
			})
	})

	it('should fail if we try to replace GSI index range key with the wrong type', function(done) {
		DynamoDB
			.table($tableName)
			.replace({
				hash: 'hash',
				range: 1,
				gsi_range: 1
			}, function(err, data) {
				if (err)
					done()
				else
					throw {error: 'should fail'}
			})
	})
	it('should fail if we try to replace an inexistent item', function(done) {
		DynamoDB
			.table($tableName)
			.where('hash').eq()
			.where('range').eq(1)
			.replace({
				hash: 'hash999',
				range: 1,
			}, function(err, data) {
				if (err)
					done()
				else
					throw {error: 'should fail'}
			})
	})

	it('.replace()', function(done) {
		// insert
		DynamoDB.table($tableName).insert({hash: 'hash1',range:1, old_number: 1, old_array: [1,2,3], string: 'aaa', 'ignore': 'me', 'delete': 'me'}, function(err) {
			if (err)
				throw err

			DynamoDB
				.table($tableName)
				.replace({
					hash: 'hash1',
					range: 1,
					gsi_range: 'b',
					string: 'newstring',
					boolean: false,
					null: null,
					old_array: [ 1, 'a', null, { k1: 'v1', k2: 'v2', k3: 'v3' }, [] ],
					object: { key1: 'value1', key2: 22 },
				}, function(err, data) {
					if (err)
						throw err
					else
						DynamoDB
							.table($tableName)
							.where('hash').eq('hash1')
							.where('range').eq(1)
							.consistentRead()
							.get(function( err, data ) {
								if (err)
									throw err

								assert.deepEqual(data, {
									hash: 'hash1',
									range: 1,
									old_array: [ 1, 'a', null, { k3: 'v3', k1: 'v1', k2: 'v2' }, [] ],
									string: 'newstring',
									boolean: false,

									null: null,
									gsi_range: 'b',
									object: { key2: 22, key1: 'value1' },
								})
								done()
							})
				})
		})
	})
	it('.return(DynamoDB.ALL_OLD).replace( existing_item )', function(done) {
		DynamoDB
			.table($tableName)
			.return(DynamoDB.ALL_OLD)
			.replace({
				hash: 'hash1',
				range: 1,
				string: 'aaa',
			}, function(err, data ) {
				if (err) throw err

				assert.deepEqual(data, { hash: 'hash1',
					null: null,
					range: 1,
					gsi_range: 'b',
					object: { key2: 22, key1: 'value1' },
					old_array: [ 1, 'a', null, { k3: 'v3', k1: 'v1', k2: 'v2' }, [] ],
					string: 'newstring',
					boolean: false,
				})
				done()
			})
	})

	it('replace() test empty string', function(done) {
		var $obj = {
			hash: 'hash1',
			range: 1,
			empty_string: '',
		}
		DynamoDB
			.table($tableName)
			.replace($obj, function(err, data) {
				if (err)
					throw err

				DynamoDB
					.table($tableName)
					.where('hash').eq('hash1')
					.where('range').eq(1)
					.get(function(err, item) {
						if (err)
							throw err

						assert.deepEqual(item.empty_string, '', {strict: true } )

						done()
					})
			})
	})

	it('.replace().then()', function(done) {
		DynamoDB
			.table($tableName)
			.return(DynamoDB.ALL_OLD)
			.replace({
				hash: 'hash1',
				range: 1,
				key: 'promise1'
			})
			.then(function(data) {
				done()
			})
	})
	it('.replace() - unhandled', function(done) {
		DynamoDB
			.table($tableName)
			.return(DynamoDB.ALL_OLD)
			.replace({
				hash: 'hash1',
				range: 1,
				key: 'promise2'
			})
		setTimeout(function() {
			done()
		},5000)
	})
	it('.replace().catch()', function(done) {
		DynamoDB
			.table($tableName)
			.replace({
				hash: 'promise',
				range: 1,
			})
			.catch(function(err) {
				done()
			})
	})
	it('.replace().then(,errorHandler)', function(done) {
		DynamoDB
			.table($tableName)
			.replace({
				hash: 'promise',
				range: 1,
			})
			.then( null, function(err) {
				done()
			})
	})
	it('cleanup...', function(done) {
		DynamoDB
			.table($tableName)
			.scan(function(err, data) {
				if (err)
					throw err
				else {
					async.each(data, function(item,cb) {
						DynamoDB.table($tableName).where('hash').eq(item.hash).where('range').eq(item.range).delete(function(err) { cb(err) })
					}, function(err) {
						if (err)
							throw err
						else
							done()
					})
				}
			})
	})
})
<|endoftext|>


<commit_before>var assert = require('chai').assert;
var fs = require("fs");
var config = require('nconf');
var path = require("path");
config.argv().env().file({ file: './polarvargen.json' });

describe('All entry points are compiled successfully', function() {
	describe('style entry points', function () {
		entryCss = config.get('entryCss');

		for(var pointCss in entryCss) {
			pathCss = path.join('.', config.get('distFolder'), config.get('cssPath'), pointCss+'.css');

			(function(path){
				it('should return true when '+path+' file exist', function () {
					fs.stat(path, function(err, data) {
	                   	if (err)
							throw err;
						return true;
		            });
				});
			})(pathCss);
		1}
	});

	describe('script entry points', function () {
		entryJs = config.get('entryJs');

		for(var pointJs in entryJs) {
		    pathJs = path.join('.', config.get('distFolder'), config.get('jsPath'), pointJs+'.js');

			(function(path){
		        it('should return true when '+path+' file exist', function (done) {
		            fs.stat(path, function(err, data) {
	                   	if (err)
							throw err;
						return true;
		            });
		         });
		    })(pathJs);
		}
	});
});<commit_msg>mistake in test case<commit_after>var assert = require('chai').assert;
var fs = require("fs");
var config = require('nconf');
var path = require("path");
config.argv().env().file({ file: './polarvargen.json' });

describe('All entry points are compiled successfully', function() {
	describe('style entry points', function () {
		entryCss = config.get('entryCss');

		for(var pointCss in entryCss) {
			pathCss = path.join('.', config.get('distFolder'), config.get('cssPath'), pointCss+'.css');

			(function(path){
				it('should return true when '+path+' file exist', function () {
					fs.stat(path, function(err, data) {
	                   	if (err)
							throw err;
						done();
		            });
				});
			})(pathCss);
		}
	});

	describe('script entry points', function () {
		entryJs = config.get('entryJs');

		for(var pointJs in entryJs) {
		    pathJs = path.join('.', config.get('distFolder'), config.get('jsPath'), pointJs+'.js');

			(function(path){
		        it('should return true when '+path+' file exist', function () {
		            fs.stat(path, function(err, data) {
	                   	if (err)
							throw err;
						done();
		            });
		         });
		    })(pathJs);
		}
	});
});<|endoftext|>


<commit_before>import expect from 'expect.js'
import typo from '../src/typographic-fixer'

describe('typographyFixer', () => {
  let [fixer] = []

  beforeEach(() => {
    fixer = typo()
  })

  it('returns a new fixer object', () => {
    expect(fixer.check).to.be.a(Function)
    expect(fixer.fix).to.be.a(Function)
    expect(fixer.rules).to.be.a(Function)
  })

  describe('.rules', () => {

    it('throws when called without a lang', () => {
      expect(() => { fixer.rules() }).to.throwError()
    })

    it('throws when called without a block', () => {
      expect(() => { fixer.rules('lang') }).to.throwError()
    })

    it('calls the passed-in function with a rules object', () => {
      let rulesObject
      fixer.rules('lang', (rules) => {
        rulesObject = rules
      })

      expect(rulesObject).not.to.be(undefined)
    })

    describe('defining a rule', () => {
      it('makes it available in check method', () => {
        fixer.rules('lang', ({define}) => {
          define('Foo', /foo/, 'bar')
        })

        expect(fixer.check('Da foo foo', {lang: 'lang'})).to.have.length(2)
        expect(fixer.check('Da bar', {lang: 'lang'})).to.be(undefined)
      })

      it('makes it available in fix method', () => {
        fixer.rules('lang', ({define}) => {
          define('Foo', /foo/, 'bar')
        })

        expect(fixer.fix('Da foo foo', {lang: 'lang'})).to.eql('Da bar bar')
      })

      it('makes it available only for the defined lang', () => {
        fixer.rules('lang', ({define}) => {
          define('Foo', /foo/, 'bar')
        })

        expect(fixer.check('Da foo foo', {lang: 'en'})).to.be(undefined)
        expect(fixer.fix('Da foo foo', {lang: 'en'})).to.eql('Da foo foo')
      })
    })
  })

  describe('.check', () => {
    it('returns a report of the broken rules with concerned ranges', () => {
      fixer.rules('lang', ({define}) => {
        define('Foo', /foo/, 'bar')
      })

      const reports = fixer.check('Da foo foo', {lang: 'lang'})

      expect(reports).to.eql([
        {rule: 'Foo', range: [3, 6]},
        {rule: 'Foo', range: [7, 10]}
      ])
    })
  })
})
<commit_msg>:green_heart: Fix linter issues<commit_after>import expect from 'expect.js'
import typo from '../src/typographic-fixer'

describe('typographyFixer', () => {
  let [fixer] = []

  beforeEach(() => {
    fixer = typo()
  })

  it('returns a new fixer object', () => {
    expect(fixer.check).to.be.a(Function)
    expect(fixer.fix).to.be.a(Function)
    expect(fixer.rules).to.be.a(Function)
  })

  describe('.rules', () => {
    it('throws when called without a lang', () => {
      expect(() => { fixer.rules() }).to.throwError()
    })

    it('throws when called without a block', () => {
      expect(() => { fixer.rules('lang') }).to.throwError()
    })

    it('calls the passed-in function with a rules object', () => {
      let rulesObject
      fixer.rules('lang', (rules) => {
        rulesObject = rules
      })

      expect(rulesObject).not.to.be(undefined)
    })

    describe('defining a rule', () => {
      it('makes it available in check method', () => {
        fixer.rules('lang', ({define}) => {
          define('Foo', /foo/, 'bar')
        })

        expect(fixer.check('Da foo foo', {lang: 'lang'})).to.have.length(2)
        expect(fixer.check('Da bar', {lang: 'lang'})).to.be(undefined)
      })

      it('makes it available in fix method', () => {
        fixer.rules('lang', ({define}) => {
          define('Foo', /foo/, 'bar')
        })

        expect(fixer.fix('Da foo foo', {lang: 'lang'})).to.eql('Da bar bar')
      })

      it('makes it available only for the defined lang', () => {
        fixer.rules('lang', ({define}) => {
          define('Foo', /foo/, 'bar')
        })

        expect(fixer.check('Da foo foo', {lang: 'en'})).to.be(undefined)
        expect(fixer.fix('Da foo foo', {lang: 'en'})).to.eql('Da foo foo')
      })
    })
  })

  describe('.check', () => {
    it('returns a report of the broken rules with concerned ranges', () => {
      fixer.rules('lang', ({define}) => {
        define('Foo', /foo/, 'bar')
      })

      const reports = fixer.check('Da foo foo', {lang: 'lang'})

      expect(reports).to.eql([
        {rule: 'Foo', range: [3, 6]},
        {rule: 'Foo', range: [7, 10]}
      ])
    })
  })
})
<|endoftext|>


<commit_before>/*
 * Copyright 2013 BlackBerry Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var root = __dirname + "/../../",
    fs = require("fs"),
    cp = require("child_process"),
    path = require("path"),
    project = require(root + "routes/project"),
    apiUtil = require(root + "lib/util"),
    mockResponse = {
        send: jasmine.createSpy()
    };

describe("project", function () {
    beforeEach(function () {
        spyOn(console, "log");
    });

    afterEach(function () {
        mockResponse.send.reset();
    });

    it("calls project command if it is a valid project", function () {
        var projectPath = "hellow1",
            cmd = "build";

        spyOn(apiUtil, "isValidProject").andReturn(true);
        spyOn(fs, "existsSync").andReturn(true);
        spyOn(cp, "exec").andCallFake(function (execStr, callback, callback2) {
            if (typeof callback === "function") {
                callback(undefined, "", "");
            } else if (typeof callback2 === "function") {
                callback2(undefined, "", "");
            }
        });

        project.get({
            query: {
                path: projectPath,
                cmd: cmd,
                args: ""
            }
        }, mockResponse);

        expect(apiUtil.isValidProject).toHaveBeenCalledWith(projectPath);
        expect(cp.exec).toHaveBeenCalled();
        expect(mockResponse.send).toHaveBeenCalledWith(200, {
            success: true,
            code: 0,
            path: projectPath,
            cmd: projectPath + "/platforms/blackberry10/cordova/" + cmd,
            args: "",
            stdout: "",
            stderr: ""
        });
    });

    it("sends 500 if project is not valid", function () {
        var projectPath = "hellow1",
            cmd = "build";

        spyOn(apiUtil, "isValidProject").andReturn(false);
        spyOn(cp, "exec");

        project.get({
            query: {
                path: projectPath,
                cmd: cmd,
                args: ""
            }
        }, mockResponse);

        expect(apiUtil.isValidProject).toHaveBeenCalledWith(projectPath);
        expect(cp.exec).not.toHaveBeenCalled();
        expect(mockResponse.send).toHaveBeenCalledWith(500, jasmine.any(Object));
    });

    it("sends 500 if prepare fails", function () {
        var projectPath = "hellow1",
            cmd = "build";

        spyOn(apiUtil, "isValidProject").andReturn(false);
        spyOn(cp, "exec").andCallFake(function (execString, args, callback) {
            callback("BAD TIMES");
        });

        project.get({
            query: {
                path: projectPath,
                cmd: cmd,
                args: ""
            }
        }, mockResponse);

        expect(mockResponse.send).toHaveBeenCalledWith(500, jasmine.any(Object));

    });
});
<commit_msg>Fix unit tests for project route<commit_after>/*
 * Copyright 2013 BlackBerry Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

var root = __dirname + "/../../",
    fs = require("fs"),
    cp = require("child_process"),
    path = require("path"),
    project = require(root + "routes/project"),
    apiUtil = require(root + "lib/util"),
    mockResponse = {
        send: jasmine.createSpy()
    };

describe("project", function () {
    beforeEach(function () {
        spyOn(console, "log");
    });

    afterEach(function () {
        mockResponse.send.reset();
    });

    it("calls project command if it is a valid project", function () {
        var projectPath = "hellow1",
            cmd = "build";

        spyOn(apiUtil, "isValidProject").andReturn(true);
        spyOn(fs, "existsSync").andReturn(true);
        spyOn(cp, "exec").andCallFake(function (execStr, callback, callback2) {
            if (typeof callback === "function") {
                callback(undefined, "", "");
            } else if (typeof callback2 === "function") {
                callback2(undefined, "", "");
            }
        });

        project.get({
            connection: {
                setTimeout: jasmine.createSpy()
            },
            query: {
                path: projectPath,
                cmd: cmd,
                args: ""
            }
        }, mockResponse);

        expect(apiUtil.isValidProject).toHaveBeenCalledWith(projectPath);
        expect(cp.exec).toHaveBeenCalled();
        expect(mockResponse.send).toHaveBeenCalledWith(200, {
            success: true,
            code: 0,
            path: projectPath,
            cmd: projectPath + "/platforms/blackberry10/cordova/" + cmd,
            args: "",
            stdout: "",
            stderr: ""
        });
    });

    it("sends 500 if project is not valid", function () {
        var projectPath = "hellow1",
            cmd = "build";

        spyOn(apiUtil, "isValidProject").andReturn(false);
        spyOn(cp, "exec");

        project.get({
            connection: {
                setTimeout: jasmine.createSpy()
            },
            query: {
                path: projectPath,
                cmd: cmd,
                args: ""
            }
        }, mockResponse);

        expect(apiUtil.isValidProject).toHaveBeenCalledWith(projectPath);
        expect(cp.exec).not.toHaveBeenCalled();
        expect(mockResponse.send).toHaveBeenCalledWith(500, jasmine.any(Object));
    });

    it("sends 500 if prepare fails", function () {
        var projectPath = "hellow1",
            cmd = "build";

        spyOn(apiUtil, "isValidProject").andReturn(false);
        spyOn(cp, "exec").andCallFake(function (execString, args, callback) {
            callback("BAD TIMES");
        });

        project.get({
            connection: {
                setTimeout: jasmine.createSpy()
            },
            query: {
                path: projectPath,
                cmd: cmd,
                args: ""
            }
        }, mockResponse);

        expect(mockResponse.send).toHaveBeenCalledWith(500, jasmine.any(Object));

    });
});
<|endoftext|>


<commit_before>"use strict";

describe( "Taab services", function () {

  beforeEach( module( "trelloBlogApp" ) );
  beforeEach( module( "trelloBlogConfig" ) );

  describe( "Trello", function () {
    var service, $httpBackend, requestUrl;
    var response = {
      name: "Taab test",
      desc: "Taab description",
      lists: [],
      members: [],
      labelNames: [],
      cards: []
    };

    beforeEach( inject( function ( _$httpBackend_, Trello, config ) {
      $httpBackend = _$httpBackend_;

      service = Trello;
      requestUrl = "https://api.trello.com/1/boards/" + config.trello.board +
                   "/?key=" + config.trello.apiKey +
                   "&lists=open&cards=open&members=all";
    } ) );

    it( "should defined the correct interface", function () {
      expect( service.load ).toBeDefined();
      expect( service.blog ).toBeDefined();
    } );

    it( "should correctly initialized the blog", function () {
      var blog = service.blog();

      expect( blog.ready ).toBe( false );
      expect( blog.error ).toBeNull();

      // It should not defined other properties
      expect( Object.keys( blog ).length ).toBe( 2 );
    } );

    it( "should report if there is an error", function () {
      $httpBackend.expectGET( requestUrl ).respond( 404, "board not found" );

      service.load();
      $httpBackend.flush();

      var blog = service.blog();
      expect( blog.ready ).toBeFalsy();
      expect( blog.error ).toBeDefined();
    } );

    it( "should give you access to the blog information", function () {
      $httpBackend.expectGET( requestUrl ).respond( response );

      service.load();
      $httpBackend.flush();

      var blog = service.blog();
      expect( blog.ready ).toBeTruthy();
      expect( blog.name ).toEqual( response.name );
      expect( blog.desc ).toEqual( response.desc );
      expect( blog.lists ).toEqual( response.lists );
      expect( blog.members ).toEqual( response.members );
      expect( blog.labels ).toEqual( response.labelNames );
      expect( blog.cards ).toEqual( response.cards );
    } );
  } );
} );
<commit_msg>Trello service tested<commit_after>"use strict";

describe( "Taab services", function () {

  beforeEach( module( "trelloBlogApp" ) );
  beforeEach( module( "trelloBlogConfig" ) );

  describe( "Trello", function () {
    var service, $httpBackend, requestUrl;
    var response = {
      name: "Taab test",
      desc: "Taab description",
      lists: [],
      members: [],
      labelNames: [],
      cards: []
    };

    beforeEach( inject( function ( _$httpBackend_, Trello, config ) {
      $httpBackend = _$httpBackend_;

      service = Trello;
      requestUrl = "https://api.trello.com/1/boards/" + config.trello.board +
                   "/?key=" + config.trello.apiKey +
                   "&lists=open&cards=open&members=all";
    } ) );

    it( "should defined the correct interface", function () {
      expect( service.load ).toBeDefined();
      expect( service.blog ).toBeDefined();
    } );

    it( "should correctly initialized the blog", function () {
      var blog = service.blog();

      expect( blog.ready ).toBe( false );
      expect( blog.error ).toBeNull();

      // It should not defined other properties
      expect( Object.keys( blog ).length ).toBe( 2 );
    } );

    it( "should report if there is an error", function () {
      $httpBackend.expectGET( requestUrl ).respond( 404, "board not found" );

      service.load();
      $httpBackend.flush();

      var blog = service.blog();
      expect( blog.ready ).toBeFalsy();
      expect( blog.error ).toBeDefined();
    } );

    it( "should give you access to the blog information", function () {
      $httpBackend.expectGET( requestUrl ).respond( response );

      service.load();
      $httpBackend.flush();

      var blog = service.blog();
      expect( blog.ready ).toBeTruthy();
      expect( blog.name ).toEqual( response.name );
      expect( blog.desc ).toEqual( response.desc );
      expect( blog.lists ).toEqual( response.lists );
      expect( blog.members ).toEqual( response.members );
      expect( blog.labels ).toEqual( response.labelNames );
      expect( blog.cards ).toEqual( response.cards );
    } );

    it( "should sort the cards by due date", function () {
      $httpBackend.expectGET( requestUrl ).respond( {
        cards: [
          {due: "2014-03-06T12:00:00.000Z"},
          {due: "2014-04-06T15:00:00.000Z"},
          {due: "2014-04-06T12:00:00.000Z"}
        ]
      } );

      service.load();
      $httpBackend.flush();

      var blog = service.blog();
      expect( blog.cards[0].due ).toEqual( "2014-04-06T15:00:00.000Z" );
      expect( blog.cards[1].due ).toEqual( "2014-04-06T12:00:00.000Z" );
      expect( blog.cards[2].due ).toEqual( "2014-03-06T12:00:00.000Z" );
    } );

    it( "should add member information in each cards", function () {
      $httpBackend.expectGET( requestUrl ).respond( {
        cards: [
          {idMembers: [ "51dad2ce8cdcf73a320018c5" ], due: 1},
          {idMembers: [ "51843f636ef14b8a690062dc" ], due: 2},
          {idMembers: [ "51843f636ef14b8a690062dc", "51dad2ce8cdcf73a320018c5" ], due: 3}
        ],
        members: [
          { id: "51dad2ce8cdcf73a320018c5", username: "fmonniot" },
          { id: "51843f636ef14b8a690062dc", username: "nicolascarlo" }
        ]
      } );

      service.load();
      $httpBackend.flush();

      var blog = service.blog();
      expect( blog.cards[0].members[0].username ).toEqual( "nicolascarlo" );
      expect( blog.cards[0].members[1].username ).toEqual( "fmonniot" );
      expect( blog.cards[1].members[0].username ).toEqual( "nicolascarlo" );
      expect( blog.cards[2].members[0].username ).toEqual( "fmonniot" );
    } );
  } );
} );
<|endoftext|>


<commit_before>/* Copyright 2017 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {
  getDingbatsGlyphsUnicode,
  getGlyphsUnicode,
} from "../../src/core/glyphlist.js";
import {
  getNormalizedUnicodes,
  getUnicodeForGlyph,
  getUnicodeRangeFor,
  mapSpecialUnicodeValues,
  reverseIfRtl,
} from "../../src/core/unicode.js";

describe("unicode", function () {
  describe("mapSpecialUnicodeValues", function () {
    it("should not re-map normal Unicode values", function () {
      // A
      expect(mapSpecialUnicodeValues(0x0041)).toEqual(0x0041);
      // fi
      expect(mapSpecialUnicodeValues(0xfb01)).toEqual(0xfb01);
    });

    it("should re-map special Unicode values", function () {
      // copyrightsans => copyright
      expect(mapSpecialUnicodeValues(0xf8e9)).toEqual(0x00a9);
      // Private Use Area characters
      expect(mapSpecialUnicodeValues(0xffff)).toEqual(0);
    });
  });

  describe("getUnicodeForGlyph", function () {
    let standardMap, dingbatsMap;

    beforeAll(function () {
      standardMap = getGlyphsUnicode();
      dingbatsMap = getDingbatsGlyphsUnicode();
    });

    afterAll(function () {
      standardMap = dingbatsMap = null;
    });

    it("should get Unicode values for valid glyph names", function () {
      expect(getUnicodeForGlyph("A", standardMap)).toEqual(0x0041);
      expect(getUnicodeForGlyph("a1", dingbatsMap)).toEqual(0x2701);
    });

    it("should recover Unicode values from uniXXXX/uXXXX{XX} glyph names", function () {
      expect(getUnicodeForGlyph("uni0041", standardMap)).toEqual(0x0041);
      expect(getUnicodeForGlyph("u0041", standardMap)).toEqual(0x0041);

      expect(getUnicodeForGlyph("uni2701", dingbatsMap)).toEqual(0x2701);
      expect(getUnicodeForGlyph("u2701", dingbatsMap)).toEqual(0x2701);
    });

    it("should not get Unicode values for invalid glyph names", function () {
      expect(getUnicodeForGlyph("Qwerty", standardMap)).toEqual(-1);
      expect(getUnicodeForGlyph("Qwerty", dingbatsMap)).toEqual(-1);
    });
  });

  describe("getUnicodeRangeFor", function () {
    it("should get correct Unicode range", function () {
      // A (Basic Latin)
      expect(getUnicodeRangeFor(0x0041)).toEqual(0);
      // fi (Alphabetic Presentation Forms)
      expect(getUnicodeRangeFor(0xfb01)).toEqual(62);
    });

    it("should not get a Unicode range", function () {
      expect(getUnicodeRangeFor(0x05ff)).toEqual(-1);
    });
  });

  describe("getNormalizedUnicodes", function () {
    let NormalizedUnicodes;

    beforeAll(function () {
      NormalizedUnicodes = getNormalizedUnicodes();
    });

    afterAll(function () {
      NormalizedUnicodes = null;
    });

    it("should get normalized Unicode values for ligatures", function () {
      // fi => f + i
      expect(NormalizedUnicodes["\uFB01"]).toEqual("fi");
      // Arabic
      expect(NormalizedUnicodes["\u0675"]).toEqual("\u0627\u0674");
    });

    it("should not normalize standard characters", function () {
      expect(NormalizedUnicodes.A).toEqual(undefined);
    });
  });

  describe("reverseIfRtl", function () {
    let NormalizedUnicodes;

    function getGlyphUnicode(char) {
      if (NormalizedUnicodes[char] !== undefined) {
        return NormalizedUnicodes[char];
      }
      return char;
    }

    beforeAll(function () {
      NormalizedUnicodes = getNormalizedUnicodes();
    });

    afterAll(function () {
      NormalizedUnicodes = null;
    });

    it("should not reverse LTR characters", function () {
      const A = getGlyphUnicode("A");
      expect(reverseIfRtl(A)).toEqual("A");

      const fi = getGlyphUnicode("\uFB01");
      expect(reverseIfRtl(fi)).toEqual("fi");
    });

    it("should reverse RTL characters", function () {
      // Hebrew (no-op, since it's not a combined character)
      const heAlef = getGlyphUnicode("\u05D0");
      expect(reverseIfRtl(heAlef)).toEqual("\u05D0");
      // Arabic
      const arAlef = getGlyphUnicode("\u0675");
      expect(reverseIfRtl(arAlef)).toEqual("\u0674\u0627");
    });
  });
});
<commit_msg>Implement a unit test for `getCharUnicodeCategory` in `src/core/unicode.js` (PR 14428 follow-up)<commit_after>/* Copyright 2017 Mozilla Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import {
  getCharUnicodeCategory,
  getNormalizedUnicodes,
  getUnicodeForGlyph,
  getUnicodeRangeFor,
  mapSpecialUnicodeValues,
  reverseIfRtl,
} from "../../src/core/unicode.js";
import {
  getDingbatsGlyphsUnicode,
  getGlyphsUnicode,
} from "../../src/core/glyphlist.js";

describe("unicode", function () {
  describe("mapSpecialUnicodeValues", function () {
    it("should not re-map normal Unicode values", function () {
      // A
      expect(mapSpecialUnicodeValues(0x0041)).toEqual(0x0041);
      // fi
      expect(mapSpecialUnicodeValues(0xfb01)).toEqual(0xfb01);
    });

    it("should re-map special Unicode values", function () {
      // copyrightsans => copyright
      expect(mapSpecialUnicodeValues(0xf8e9)).toEqual(0x00a9);
      // Private Use Area characters
      expect(mapSpecialUnicodeValues(0xffff)).toEqual(0);
    });
  });

  describe("getCharUnicodeCategory", function () {
    it("should correctly determine the character category", function () {
      const tests = {
        // Whitespace
        " ": { isDiacritic: false, isWhitespace: true },
        "\t": { isDiacritic: false, isWhitespace: true },
        "\u2001": { isDiacritic: false, isWhitespace: true },
        "\uFEFF": { isDiacritic: false, isWhitespace: true },

        // Diacritic
        "\u0302": { isDiacritic: true, isWhitespace: false },
        "\u0344": { isDiacritic: true, isWhitespace: false },
        "\u0361": { isDiacritic: true, isWhitespace: false },

        // No whitespace or diacritic
        a: { isDiacritic: false, isWhitespace: false },
        1: { isDiacritic: false, isWhitespace: false },
      };
      for (const [character, expectation] of Object.entries(tests)) {
        expect(getCharUnicodeCategory(character)).toEqual(expectation);
      }
    });
  });

  describe("getUnicodeForGlyph", function () {
    let standardMap, dingbatsMap;

    beforeAll(function () {
      standardMap = getGlyphsUnicode();
      dingbatsMap = getDingbatsGlyphsUnicode();
    });

    afterAll(function () {
      standardMap = dingbatsMap = null;
    });

    it("should get Unicode values for valid glyph names", function () {
      expect(getUnicodeForGlyph("A", standardMap)).toEqual(0x0041);
      expect(getUnicodeForGlyph("a1", dingbatsMap)).toEqual(0x2701);
    });

    it("should recover Unicode values from uniXXXX/uXXXX{XX} glyph names", function () {
      expect(getUnicodeForGlyph("uni0041", standardMap)).toEqual(0x0041);
      expect(getUnicodeForGlyph("u0041", standardMap)).toEqual(0x0041);

      expect(getUnicodeForGlyph("uni2701", dingbatsMap)).toEqual(0x2701);
      expect(getUnicodeForGlyph("u2701", dingbatsMap)).toEqual(0x2701);
    });

    it("should not get Unicode values for invalid glyph names", function () {
      expect(getUnicodeForGlyph("Qwerty", standardMap)).toEqual(-1);
      expect(getUnicodeForGlyph("Qwerty", dingbatsMap)).toEqual(-1);
    });
  });

  describe("getUnicodeRangeFor", function () {
    it("should get correct Unicode range", function () {
      // A (Basic Latin)
      expect(getUnicodeRangeFor(0x0041)).toEqual(0);
      // fi (Alphabetic Presentation Forms)
      expect(getUnicodeRangeFor(0xfb01)).toEqual(62);
    });

    it("should not get a Unicode range", function () {
      expect(getUnicodeRangeFor(0x05ff)).toEqual(-1);
    });
  });

  describe("getNormalizedUnicodes", function () {
    let NormalizedUnicodes;

    beforeAll(function () {
      NormalizedUnicodes = getNormalizedUnicodes();
    });

    afterAll(function () {
      NormalizedUnicodes = null;
    });

    it("should get normalized Unicode values for ligatures", function () {
      // fi => f + i
      expect(NormalizedUnicodes["\uFB01"]).toEqual("fi");
      // Arabic
      expect(NormalizedUnicodes["\u0675"]).toEqual("\u0627\u0674");
    });

    it("should not normalize standard characters", function () {
      expect(NormalizedUnicodes.A).toEqual(undefined);
    });
  });

  describe("reverseIfRtl", function () {
    let NormalizedUnicodes;

    function getGlyphUnicode(char) {
      if (NormalizedUnicodes[char] !== undefined) {
        return NormalizedUnicodes[char];
      }
      return char;
    }

    beforeAll(function () {
      NormalizedUnicodes = getNormalizedUnicodes();
    });

    afterAll(function () {
      NormalizedUnicodes = null;
    });

    it("should not reverse LTR characters", function () {
      const A = getGlyphUnicode("A");
      expect(reverseIfRtl(A)).toEqual("A");

      const fi = getGlyphUnicode("\uFB01");
      expect(reverseIfRtl(fi)).toEqual("fi");
    });

    it("should reverse RTL characters", function () {
      // Hebrew (no-op, since it's not a combined character)
      const heAlef = getGlyphUnicode("\u05D0");
      expect(reverseIfRtl(heAlef)).toEqual("\u05D0");
      // Arabic
      const arAlef = getGlyphUnicode("\u0675");
      expect(reverseIfRtl(arAlef)).toEqual("\u0674\u0627");
    });
  });
});
<|endoftext|>


<commit_before>if(typeof(define) !== 'function') {
  var define = require('amdefine')(module);
}

define(['requirejs'], function(requirejs) {
  var suites = [];

  global.localStorage = require('localStorage');

  function stubWidgetView(util) {
    var calls = [], results = {};
    return util.extend(
      // stub state
      { _calls: calls, _results: results },
      // event emitter
      util.getEventEmitter('connect', 'disconnect', 'sync', 'reconnect'),
      // method stubs
      ['display',
       'setState',
       'redirectTo',
       'setUserAddress',
       'getLocation',
       'setLocation'
      ].reduce(function(stubs, method) {
        stubs[method] = function() {
          calls.push({
            method: method,
            args: util.toArray(arguments)
          });
          return results[method];
        };
        return stubs;
      }, {})
    );
  }

  function argEq(expected, actual) {
    for(var i=0;i<expected.length;i++) {
      if(expected[i] !== actual[i]) {
        return false;
      }
    }
    return true;
  }

  function expectCall(test, object, methodName, args) {
    for(var i=0;i<object._calls.length;i++) {
      var call = object._calls[i];
      if(call.method === methodName) {
        if((! args) || argEq(args, call.args)) {
          return test.assertAnd(true, true);
        }
      }
    }
    return test.assertAnd(true, false);
  }

  suites.push({
    name: "widget.js tests",
    desc: "widget controller implementation",
    setup: function(env) {
      var _this = this;
      requirejs([
        './src/lib/util',
        './src/lib/widget',
        './src/lib/sync',
        './src/lib/wireClient',
        './src/lib/baseClient'
      ], function(util, widget, sync, wireClient, baseClient) {
        env.widget = widget;
        env.view = stubWidgetView(util);
        env.widget.setView(env.view);
        env.sync = sync;
        env.wireClient = wireClient;
        env.baseClient = baseClient;

        env.view._results['getLocation'] = 'http://test.host/';
        _this.result(true);
      });
    },
    tests: [

      {
        desc: "widget.display sets up event handlers on the view",
        run: function(env) {
          env.widget.display({}, 'remotestorage-connect', {});
          this.assertAnd(env.view.hasHandler('connect'), true);
          this.assertAnd(env.view.hasHandler('sync'), true);
          this.assertAnd(env.view.hasHandler('disconnect'), true);
          this.assert(env.view.hasHandler('reconnect'), true);
        }
      },

      {
        desc: "widget.display sets up event handlers on sync, wireClient and baseClient",
        run: function(env) {
          env.widget.display({}, 'remotestorage-connect', {});
          this.assertAnd(env.sync.hasHandler('busy'), true);
          this.assertAnd(env.sync.hasHandler('ready'), true);
          this.assertAnd(env.sync.hasHandler('error'), true);
          this.assertAnd(env.sync.hasHandler('timeout'), true);
          this.assertAnd(env.wireClient.hasHandler('connected'), true);
          this.assertAnd(env.wireClient.hasHandler('disconnected'), true);
          this.assert(env.baseClient.hasHandler('error'), true);
        }
      },

      {
        desc: "widget.display strips all params from the fragment",
        run: function(env) {
          env.view._results['getLocation'] = 'http://test.host/#abc=def&user_address=foo@bar.baz';
          env.widget.display({}, 'remotestorage-connect', {});
          expectCall(this, env.view, 'setLocation', ['http://test.host/#']) &&
            expectCall(this, env.view, 'setUserAddress', ['foo@bar.baz']) &&
            this.result(true);
        }
      },

      {
        desc: "forwards sync busy / ready state to the view",
        run: function(env) {
          env.widget.display({}, 'remotestorage-connect', {});
          env.sync.emit('busy');
          if(! expectCall(this, env.view, 'setState', ['busy'])) {
            return;
          }
          env.sync.emit('ready');
          if(! expectCall(this, env.view, 'setState', ['connected'])) {
            return;
          }
          this.result(true);
        }
      },

      {
        desc: "forwards wireClient connected / disconnected state to the view",
        run: function(env) {
          env.widget.display({}, 'remotestorage-connect', {});
          // FIXME: won't work, because 'initialSync' causes errors
          // env.wireClient.emit('connected');
          // if(! expectCall(this, env.view, 'setState', ['connected'])) {
          //   return;
          // }
          env.wireClient.emit('disconnected');
          if(! expectCall(this, env.view, 'setState', ['initial'])) {
            return;
          }
          this.result(true);
        }
      }

    ]
  });

  return suites;
});
<commit_msg>fixed widget test<commit_after>if(typeof(define) !== 'function') {
  var define = require('amdefine')(module);
}

define(['requirejs'], function(requirejs) {
  var suites = [];

  global.localStorage = require('localStorage');

  function stubWidgetView(util) {
    var calls = [], results = {};
    return util.extend(
      // stub state
      { _calls: calls, _results: results },
      // event emitter
      util.getEventEmitter('connect', 'disconnect', 'sync', 'reconnect'),
      // method stubs
      ['display',
       'setState',
       'redirectTo',
       'setUserAddress',
       'getLocation',
       'setLocation'
      ].reduce(function(stubs, method) {
        stubs[method] = function() {
          calls.push({
            method: method,
            args: util.toArray(arguments)
          });
          return results[method];
        };
        return stubs;
      }, {})
    );
  }

  function argEq(expected, actual) {
    for(var i=0;i<expected.length;i++) {
      if(expected[i] !== actual[i]) {
        return false;
      }
    }
    return true;
  }

  function expectCall(test, object, methodName, args) {
    for(var i=0;i<object._calls.length;i++) {
      var call = object._calls[i];
      if(call.method === methodName) {
        if((! args) || argEq(args, call.args)) {
          return test.assertAnd(true, true);
        }
      }
    }
    return test.assertAnd(true, false);
  }

  suites.push({
    name: "widget.js tests",
    desc: "widget controller implementation",
    setup: function(env) {
      var _this = this;
      requirejs([
        './src/lib/util',
        './src/lib/widget',
        './src/lib/sync',
        './src/lib/wireClient',
        './src/lib/baseClient'
      ], function(util, widget, sync, wireClient, baseClient) {
        env.widget = widget;
        env.view = stubWidgetView(util);
        env.widget.setView(env.view);
        env.sync = sync;
        env.wireClient = wireClient;
        env.baseClient = baseClient;

        env.fakeRemoteStorage = {
          claimedModules: { foo: 'rw' }
        };

        env.view._results['getLocation'] = 'http://test.host/';
        _this.result(true);
      });
    },
    tests: [

      {
        desc: "widget.display sets up event handlers on the view",
        run: function(env) {
          env.widget.display(env.fakeRemoteStorage, 'remotestorage-connect', {});
          this.assertAnd(env.view.hasHandler('connect'), true);
          this.assertAnd(env.view.hasHandler('sync'), true);
          this.assertAnd(env.view.hasHandler('disconnect'), true);
          this.assert(env.view.hasHandler('reconnect'), true);
        }
      },

      {
        desc: "widget.display sets up event handlers on sync, wireClient and baseClient",
        run: function(env) {
          env.widget.display(env.fakeRemoteStorage, 'remotestorage-connect', {});
          this.assertAnd(env.sync.hasHandler('busy'), true);
          this.assertAnd(env.sync.hasHandler('ready'), true);
          this.assertAnd(env.sync.hasHandler('error'), true);
          this.assertAnd(env.sync.hasHandler('timeout'), true);
          this.assertAnd(env.wireClient.hasHandler('connected'), true);
          this.assertAnd(env.wireClient.hasHandler('disconnected'), true);
          this.assert(env.baseClient.hasHandler('error'), true);
        }
      },

      {
        desc: "widget.display strips all params from the fragment",
        run: function(env) {
          env.view._results['getLocation'] = 'http://test.host/#abc=def&user_address=foo@bar.baz';
          env.widget.display(env.fakeRemoteStorage, 'remotestorage-connect', {});
          expectCall(this, env.view, 'setLocation', ['http://test.host/#']) &&
            expectCall(this, env.view, 'setUserAddress', ['foo@bar.baz']) &&
            this.result(true);
        }
      },

      {
        desc: "forwards sync busy / ready state to the view",
        run: function(env) {
          env.widget.display(env.fakeRemoteStorage, 'remotestorage-connect', {});
          env.sync.emit('busy');
          if(! expectCall(this, env.view, 'setState', ['busy'])) {
            return;
          }
          env.sync.emit('ready');
          if(! expectCall(this, env.view, 'setState', ['connected'])) {
            return;
          }
          this.result(true);
        }
      },

      {
        desc: "forwards wireClient connected / disconnected state to the view",
        run: function(env) {
          env.widget.display(env.fakeRemoteStorage, 'remotestorage-connect', {});
          // FIXME: won't work, because 'initialSync' causes errors
          // env.wireClient.emit('connected');
          // if(! expectCall(this, env.view, 'setState', ['connected'])) {
          //   return;
          // }
          env.wireClient.emit('disconnected');
          if(! expectCall(this, env.view, 'setState', ['initial'])) {
            return;
          }
          this.result(true);
        }
      }

    ]
  });

  return suites;
});
<|endoftext|>