<commit_before>var chai = require('chai');
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
var assert = require('chai').assert;

var rewire = require('rewire');
// var Config = require('../dist/Config').Config;
var configMod = rewire('../dist/Config');

// muting the standard log output
configMod.__set__({
  Logger_1: {
    error: function() {}
  }
});

var Config = configMod.Config;

describe('Config', function() {
  var config;

  describe('#parseFileContent()', function () {

    beforeEach(function() {
      config = new Config();
    });

    it('should parse yaml content, if a yaml filepath is given', function () {
      var yamlTest = `
        test:
          - a
          - b
          - c
      `;

      var result = config.parseFileContent("fubar.yaml", yamlTest)

      assert.deepEqual(result.test, ["a", "b", "c"], "Parsed yaml content should include the complete array");
    });

    it('should fail if errorneous yaml content is delivered', function () {
      // missing bracket at the end
      var yamlTest = `{ "test": ["a", "b", "c" }`;

      assert.throws(function() { config.parseFileContent("fubar.yaml", yamlTest) }, "YAMLException", "Boom! as expected :)");
      // config.parseFileContent;
    });

    it('should parse json content, if a json filepath is given', function () {
      var jsonTest = `{ "test": ["a", "b", "c"]}`;

      var result = config.parseFileContent("fubar.json", jsonTest);

      assert.deepEqual(result.test, ["a", "b", "c"], "Parsed json content should include the complete array");
    });

    it('should fail if errorneous json content is delivered', function () {
      // missing bracket at the end
      var jsonTest = `{ "test": ["a", "b", "c" }`;

      assert.throws(function() { config.parseFileContent("fubar.json", jsonTest) }, "Unexpected", "Boom! as expected :)");
    });

  });

  describe('#resolveFile()', function () {

    it('should read the file content and return it parsed', function () {
      var jsonTest = `{ "test": ["a", "b", "c"] } `;
      var promise;

      configMod.__with__({
        fsreadfile: function (path) {
          return Promise.resolve(jsonTest);
        }
      })(function () {
        var config = new configMod.Config();
        promise = config.resolveFile("fubar.json");
      });

      return assert.eventually.deepEqual(promise, JSON.parse(jsonTest));
    });

    it('should reject on parseError', function () {
      var jsonTest = `{ "test": ["a", "b", "c" } `;
      var promise;

      configMod.__with__({
        fsreadfile: function (path) {
          return Promise.resolve(jsonTest);
        }
      })(function () {
        var config = new configMod.Config();
        promise = config.resolveFile("fubar.json");
      });

      return assert.isRejected(promise);
    });

  });
});
<commit_msg>USXP-649 adding more tests for Config<commit_after>var chai = require('chai');
var chaiAsPromised = require("chai-as-promised");
chai.use(chaiAsPromised);
var assert = require('chai').assert;

var rewire = require('rewire');
// var Config = require('../dist/Config').Config;
var configMod = rewire('../dist/Config');

// muting the standard log output
configMod.__set__({
  Logger_1: {
    error: function() {}
  }
});

var Config = configMod.Config;

describe('Config', function() {
  var config;

  describe('#parseFileContent()', function () {

    beforeEach(function() {
      config = new Config();
    });

    it('should parse yaml content, if a yaml filepath is given', function () {
      var yamlTest = `
        test:
          - a
          - b
          - c
      `;

      var result = config.parseFileContent("fubar.yaml", yamlTest)

      assert.deepEqual(result.test, ["a", "b", "c"], "Parsed yaml content should include the complete array");
    });

    it('should fail if errorneous yaml content is delivered', function () {
      // missing bracket at the end
      var yamlTest = `{ "test": ["a", "b", "c" }`;

      assert.throws(function() { config.parseFileContent("fubar.yaml", yamlTest) }, "YAMLException", "Boom! as expected :)");
      // config.parseFileContent;
    });

    it('should parse json content, if a json filepath is given', function () {
      var jsonTest = `{ "test": ["a", "b", "c"]}`;

      var result = config.parseFileContent("fubar.json", jsonTest);

      assert.deepEqual(result.test, ["a", "b", "c"], "Parsed json content should include the complete array");
    });

    it('should fail if errorneous json content is delivered', function () {
      // missing bracket at the end
      var jsonTest = `{ "test": ["a", "b", "c" }`;

      assert.throws(function() { config.parseFileContent("fubar.json", jsonTest) }, "Unexpected", "Boom! as expected :)");
    });

  });

  describe('#resolveFile()', function () {

    it('should read the file content and return it parsed', function () {
      var jsonTest = `{ "test": ["a", "b", "c"] } `;
      var result;

      configMod.__with__({
        fsreadfile: function (path) {
          return Promise.resolve(jsonTest);
        }
      })(function () {
        var config = new configMod.Config();
        result = config.resolveFile("fubar.json");
      });

      return assert.becomes(result, JSON.parse(jsonTest));
    });

    it('should reject on parseError', function () {
      var jsonTest = `{ "test": ["a", "b", "c" } `;
      var result;

      configMod.__with__({
        fsreadfile: function (path) {
          return Promise.resolve(jsonTest);
        }
      })(function () {
        var config = new configMod.Config();
        result = config.resolveFile("fubar.json");
      });

      return assert.isRejected(result);
    });

  });

  describe('#resolve()', function () {

    it('should just resolve the object if one is given', function () {
      var jsonTest = { "test": ["a", "b", "c"] };
      var result;

      config = new Config();
      result = config.resolve(jsonTest);

      return assert.becomes(result, jsonTest);
    });

    it('should see if theres an object in the given string', function () {
      var jsonTest = `{ "test": ["a", "b", "c"] }`;
      var result;

      config = new Config();
      result = config.resolve(jsonTest);

      return assert.becomes(result, JSON.parse(jsonTest));
    });

    it('should resolve the given string as path, if it is not a parsable object', function () {
      var jsonTest = `{ "test": ["a", "b", "c"] } `;
      var result;

      configMod.__with__({
        fsreadfile: function (path) {
          return Promise.resolve(jsonTest);
        }
      })(function () {
        var config = new configMod.Config();
        result = config.resolveFile("fubar.json");
      });

      return assert.becomes(result, JSON.parse(jsonTest));
    });

  });
});
<|endoftext|>


<commit_before>var path = require('path'),
    sys = require('sys'),
    assert = require('assert'),
    events = require('events'),
    http = require('http');

require.paths.unshift(path.join(__dirname, '..', 'lib'),
                      path.join(__dirname, 'vendor', 'vows', 'lib'));

var vows = require('vows'),
    cradle = require('cradle');

function status(code) {
    return function (res) {
        assert.equal(res._headers.status, code);
    };
}

var client = http.createClient(5984, '127.0.0.1');

function r(method, url, doc) {
    var promise = new(events.Promise);
    var request = client.request(method, url, {});

    if (doc) { request.write(JSON.stringify(doc)) }

    request.addListener('response', function (res) {
        var body = '';

        res.setBodyEncoding('utf8');
        res.addListener('data', function (chunk) {
            body += (chunk || '');
        }).addListener('end', function () {
            var obj, response;

            try { obj = JSON.parse(body) }
            catch (e) { return promise.emitError(e) }

            promise.emitSuccess(obj);
        });
    });
    request.close();
    return promise;
}

cradle.setup({ usePromises: true });

vows.tell("Cradle", {
    setup: function () {
        r('GET', '/_all_dbs').wait().forEach(function (db) {
            r('DELETE', '/' + db).wait();
        });
        r('PUT', '/rabbits');
        r('PUT', '/pigs').wait();
        r('PUT', '/pigs/_design/pigs', {
            _id: '_design/pigs', views: {
                all: { map: "function (doc) { if (doc.color) emit(null, doc) }" }
            }
        });
        r('PUT', '/pigs/mike', {color: 'pink'});
        r('PUT', '/rabbits/alex', {color: 'blue'});
        r('PUT', '/pigs/bill', {color: 'blue'}).wait();
    },
    "Default connection settings": {
        setup: function () {
            cradle.setup({
                host: "http://cloudhead.io",
                port: 4242,
                milk: 'white'
            });
            return new(cradle.Connection);
        },
        "should be carried on to new Connections": function (c) {
            assert.equal(c.host, "http://cloudhead.io");
            assert.equal(c.port, 4242);
            assert.equal(c.options.milk, 'white');
            assert.equal(c.options.cache, true);
        },
        "with just a {} passed to a new Connection object": {
            setup: function () { return new(cradle.Connection)({milk: 'green'}) },
            "should override the defaults": function (c) {
                assert.equal(c.options.milk, 'green');
                assert.equal(c.port, 4242);
            }
        },
        "with a host and port passed to Connection": {
            setup: function () { return new(cradle.Connection)("255.255.0.0", 9696) },
            "should override the defaults": function (c) {
                assert.equal(c.host, '255.255.0.0');
                assert.equal(c.port, 9696);
            }
        },
        "with a host and port passed as a string to Connection": {
            setup: function () { return new(cradle.Connection)("8.8.8.8:4141") },
            "should override the defaults": function (c) {
                assert.equal(c.host, '8.8.8.8');
                assert.equal(c.port, 4141);
            }
        },
        "with a host, port and options passed to Connection": {
            setup: function () { return new(cradle.Connection)("4.4.4.4", 911, {raw: true}) },
            "should override the defaults": function (c) {
                assert.equal(c.host, '4.4.4.4');
                assert.equal(c.port, 911);
                assert.equal(c.options.raw, true);
            }
        }
    },

    //
    // Cache
    //
    "A Cradle connection (cache)": {
        setup: function () {
            return new(cradle.Connection)('127.0.0.1', 5984, {cache: true}).database('pigs');
        },
        "save()": {
            setup: function (db) {
                var promise = new(events.Promise);
                db.save('bob', {color: 'orange'})
                  .addCallback(function () { promise.emitSuccess(db) });
                return promise;
            },
            "should write through the cache": function (db) {
                assert.ok(db.cache.has('bob'));
            },
            "and": {
                setup: function (db) {
                    return db.save('bob', {size: 12});
                },
                "return a 201": status(201),
                "allow an overwrite": function (res) {
                   assert.match(res.rev, /^2/);
                }
            }
        },
        "remove()": {
            setup: function (db) {
                var promise = new(events.Promise);
                db.save('bruno', {}).addCallback(function () {
                    promise.emitSuccess(db);
                });
                return promise;
            },
            "shouldn't ask for a revision": {
                setup: function (db) {
                    var promise = new(events.Promise);
                    db.remove('bruno').addCallback(function () { promise.emitSuccess(db) });
                    return promise;
                },
                "and should purge the cache": function (db) {
                    assert.equal(db.cache.has('bruno'), false);
                },
                "and raise an exception if you use remove() without a rev": function (db) {
                    //assert.throws(db.remove('bruno'), Error);
                }
            }
        }
    },
    "A connection with continuation passing style": {
        setup: function () {
            //var promise = new(events.Promise);
            //var c = new(cradle.Connection)({usePromises: false});
            //c.database('badgers').save('robin', {})(function (res) {
            //    promise.emitSuccess(res);
            //});
            //return promise;
        },
        "should send requests one after the other": function (res) {
            //assert.ok(res.ok);
        }
    },
    "A Cradle connection (no-cache)": {
        setup: function () {
            return new(cradle.Connection)('127.0.0.1', 5984, {cache: false});
        },
        "queried for information": {
            setup: function (c) { return c.info() },

            "returns a 200": status(200),
            "returns the version number": function (info) {
                assert.ok(info);
                assert.match(info.version, /\d+\.\d+\.\d+/);
            }
        },
        "getting the list of databases": {
            setup: function (c) { return c.databases() },
            "returns an empty list": function (dbs) {
                assert.equal(dbs.length, 2);
                assert.ok(dbs instanceof Array);
            }
        },
        "create()": {
            setup: function (c) { return c.database('badgers').create() },
            "returns a 201": status(201),
            "creates a database": {
                setup: function (res, c) { return c.database('badgers').exists() },
                "it exists": function (res) { assert.ok(res) }
            }
        },
        "destroy()": {
            setup: function (c) { return c.database('rabbits').destroy() },
            "returns a 200": status(200),
            "destroys a database": {
                setup: function (res, c) { return c.database('rabbits').exists() },
                "it doesn't exist anymore": function (res) { assert.ok(! res) }
            }
        },
        "a database": {
            setup: function (c) { return c.database('pigs') },

            "info()": {
                setup: function (db) { return db.info() },
                "returns a 200": status(200),
                "returns database info": function (info) {
                    assert.equal(info['db_name'], 'pigs');
                }
            },
            "fetching a document by id (GET)": {
                setup: function (db) { return db.get('mike') },
                "returns a 200": status(200),
                "returns the document": function (res) {
                    assert.equal(res.id, 'mike');
                }
            },
            "save() with an id and document": {
                "should PUT the document, with the id": {
                    setup: function (db) {
                        return db.save('joe', {gender: 'male'});
                    },
                    "returns a 201": status(201),
                    "returns the revision": function (res) {
                        assert.ok(res.rev);
                    }
                },
                "without an id (POST)": {}
            },
            "save() with a _design id": {
                "should save the doc as a design": {
                    setup: function (db) {
                        return db.save('_design/horses', {
                            all: {
                                map: function (doc) {
                                    if (doc.speed == 72) emit(null, doc);
                                }
                            }
                        });
                    },
                    "returns a 201": status(201),
                    "returns the revision": function (res) {
                        assert.ok(res.rev);
                    },
                    "which can be queried": {
                        setup: function (res, db) {
                            return db.view('horses/all');
                        },
                        "returns a 200": status(200)
                    }
                }
            },
            "calling save() with an array": {
                setup: function (db) {
                    return db.save([{_id: 'tom'}, {_id: 'flint'}]);
                },
                "returns an array of document ids and revs": function (res) {
                    assert.equal(res[0].id, 'tom');
                    assert.equal(res[1].id, 'flint');
                },
                "should bulk insert the documents": {
                    setup: function (res, db) {
                        var promise = new(events.Promise);
                        db.get('tom').addCallback(function (tom) {
                            db.get('flint').addCallback(function (flint) {
                                promise.emitSuccess(tom, flint);
                            });
                        });
                        return promise;
                    },
                    "which can then be retrieved": function (tom, flint) {
                        assert.ok(tom._id);
                        assert.ok(flint._id);
                    }
                }
            },
            "getting all documents": {
                setup: function (db) {
                    return db.all();
                },
                "returns a 200": status(200),
                "returns a list of all docs": function (res) {
                    assert.ok(res.rows);
                }
            },
            "updating a document (PUT)": {
                setup: function (db) {
                    var promise = new(events.Promise);
                    db.get('mike').addCallback(function (doc) {
                        db.save('mike', doc.rev,
                            {color: doc.color, age: 13}).addCallback(function (res) {
                            promise.emitSuccess(res);
                        });
                    });
                    return promise;
                },
                "returns a 201": status(201),
                "returns the revision": function (res) {
                    assert.ok(res.rev);
                    assert.match(res.rev, /^2/);
                },

                "returns the updated document": function (res) {
                    //assert.equal(res.age, 13);
                }
            },
            "deleting a document (DELETE)": {
                setup: function (db) {
                    var promise = new(events.Promise);
                    db.get('bill').addCallback(function (res) {
                        db.remove('bill', res.rev).addCallback(function (res) {
                            promise.emitSuccess(res);
                        });
                    });
                    return promise;
                },
                "returns a 200": status(200)
            },
            "querying a view": {
                setup: function (db) {
                    return db.view('pigs/all');
                },
                "returns a 200": status(200),
                "returns view results": function (res) {
                    assert.ok(res.rows);
                    assert.equal(res.rows.length, 2);
                },
                "with options": {

                },
                "with a start & end key": {

                }
            }
        }
    }
});
<commit_msg>Let's not blindly delete ALL local databases without warning. Just the ones we create. Some people may have data locally. :)<commit_after>var path = require('path'),
    sys = require('sys'),
    assert = require('assert'),
    events = require('events'),
    http = require('http');

require.paths.unshift(path.join(__dirname, '..', 'lib'),
                      path.join(__dirname, 'vendor', 'vows', 'lib'));

var vows = require('vows'),
    cradle = require('cradle');

function status(code) {
    return function (res) {
        assert.equal(res._headers.status, code);
    };
}

var client = http.createClient(5984, '127.0.0.1');

function r(method, url, doc) {
    var promise = new(events.Promise);
    var request = client.request(method, url, {});

    if (doc) { request.write(JSON.stringify(doc)) }

    request.addListener('response', function (res) {
        var body = '';

        res.setBodyEncoding('utf8');
        res.addListener('data', function (chunk) {
            body += (chunk || '');
        }).addListener('end', function () {
            var obj, response;

            try { obj = JSON.parse(body) }
            catch (e) { return promise.emitError(e) }

            promise.emitSuccess(obj);
        });
    });
    request.close();
    return promise;
}

cradle.setup({ usePromises: true });

vows.tell("Cradle", {
    setup: function () {
        ['rabbits', 'pigs','badgers'].forEach(function (db) {
            r('DELETE', '/' + db).wait();
        });
        r('PUT', '/rabbits');
        r('PUT', '/pigs').wait();
        r('PUT', '/pigs/_design/pigs', {
            _id: '_design/pigs', views: {
                all: { map: "function (doc) { if (doc.color) emit(null, doc) }" }
            }
        });
        r('PUT', '/pigs/mike', {color: 'pink'});
        r('PUT', '/rabbits/alex', {color: 'blue'});
        r('PUT', '/pigs/bill', {color: 'blue'}).wait();
    },
    "Default connection settings": {
        setup: function () {
            cradle.setup({
                host: "http://cloudhead.io",
                port: 4242,
                milk: 'white'
            });
            return new(cradle.Connection);
        },
        "should be carried on to new Connections": function (c) {
            assert.equal(c.host, "http://cloudhead.io");
            assert.equal(c.port, 4242);
            assert.equal(c.options.milk, 'white');
            assert.equal(c.options.cache, true);
        },
        "with just a {} passed to a new Connection object": {
            setup: function () { return new(cradle.Connection)({milk: 'green'}) },
            "should override the defaults": function (c) {
                assert.equal(c.options.milk, 'green');
                assert.equal(c.port, 4242);
            }
        },
        "with a host and port passed to Connection": {
            setup: function () { return new(cradle.Connection)("255.255.0.0", 9696) },
            "should override the defaults": function (c) {
                assert.equal(c.host, '255.255.0.0');
                assert.equal(c.port, 9696);
            }
        },
        "with a host and port passed as a string to Connection": {
            setup: function () { return new(cradle.Connection)("8.8.8.8:4141") },
            "should override the defaults": function (c) {
                assert.equal(c.host, '8.8.8.8');
                assert.equal(c.port, 4141);
            }
        },
        "with a host, port and options passed to Connection": {
            setup: function () { return new(cradle.Connection)("4.4.4.4", 911, {raw: true}) },
            "should override the defaults": function (c) {
                assert.equal(c.host, '4.4.4.4');
                assert.equal(c.port, 911);
                assert.equal(c.options.raw, true);
            }
        }
    },

    //
    // Cache
    //
    "A Cradle connection (cache)": {
        setup: function () {
            return new(cradle.Connection)('127.0.0.1', 5984, {cache: true}).database('pigs');
        },
        "save()": {
            setup: function (db) {
                var promise = new(events.Promise);
                db.save('bob', {color: 'orange'})
                  .addCallback(function () { promise.emitSuccess(db) });
                return promise;
            },
            "should write through the cache": function (db) {
                assert.ok(db.cache.has('bob'));
            },
            "and": {
                setup: function (db) {
                    return db.save('bob', {size: 12});
                },
                "return a 201": status(201),
                "allow an overwrite": function (res) {
                   assert.match(res.rev, /^2/);
                }
            }
        },
        "remove()": {
            setup: function (db) {
                var promise = new(events.Promise);
                db.save('bruno', {}).addCallback(function () {
                    promise.emitSuccess(db);
                });
                return promise;
            },
            "shouldn't ask for a revision": {
                setup: function (db) {
                    var promise = new(events.Promise);
                    db.remove('bruno').addCallback(function () { promise.emitSuccess(db) });
                    return promise;
                },
                "and should purge the cache": function (db) {
                    assert.equal(db.cache.has('bruno'), false);
                },
                "and raise an exception if you use remove() without a rev": function (db) {
                    //assert.throws(db.remove('bruno'), Error);
                }
            }
        }
    },
    "A connection with continuation passing style": {
        setup: function () {
            //var promise = new(events.Promise);
            //var c = new(cradle.Connection)({usePromises: false});
            //c.database('badgers').save('robin', {})(function (res) {
            //    promise.emitSuccess(res);
            //});
            //return promise;
        },
        "should send requests one after the other": function (res) {
            //assert.ok(res.ok);
        }
    },
    "A Cradle connection (no-cache)": {
        setup: function () {
            return new(cradle.Connection)('127.0.0.1', 5984, {cache: false});
        },
        "queried for information": {
            setup: function (c) { return c.info() },

            "returns a 200": status(200),
            "returns the version number": function (info) {
                assert.ok(info);
                assert.match(info.version, /\d+\.\d+\.\d+/);
            }
        },
        "getting the list of databases": {
            setup: function (c) { return c.databases() },
            "returns an empty list": function (dbs) {
                assert.equal(dbs.length, 2);
                assert.ok(dbs instanceof Array);
            }
        },
        "create()": {
            setup: function (c) { return c.database('badgers').create() },
            "returns a 201": status(201),
            "creates a database": {
                setup: function (res, c) { return c.database('badgers').exists() },
                "it exists": function (res) { assert.ok(res) }
            }
        },
        "destroy()": {
            setup: function (c) { return c.database('rabbits').destroy() },
            "returns a 200": status(200),
            "destroys a database": {
                setup: function (res, c) { return c.database('rabbits').exists() },
                "it doesn't exist anymore": function (res) { assert.ok(! res) }
            }
        },
        "a database": {
            setup: function (c) { return c.database('pigs') },

            "info()": {
                setup: function (db) { return db.info() },
                "returns a 200": status(200),
                "returns database info": function (info) {
                    assert.equal(info['db_name'], 'pigs');
                }
            },
            "fetching a document by id (GET)": {
                setup: function (db) { return db.get('mike') },
                "returns a 200": status(200),
                "returns the document": function (res) {
                    assert.equal(res.id, 'mike');
                }
            },
            "save() with an id and document": {
                "should PUT the document, with the id": {
                    setup: function (db) {
                        return db.save('joe', {gender: 'male'});
                    },
                    "returns a 201": status(201),
                    "returns the revision": function (res) {
                        assert.ok(res.rev);
                    }
                },
                "without an id (POST)": {}
            },
            "save() with a _design id": {
                "should save the doc as a design": {
                    setup: function (db) {
                        return db.save('_design/horses', {
                            all: {
                                map: function (doc) {
                                    if (doc.speed == 72) emit(null, doc);
                                }
                            }
                        });
                    },
                    "returns a 201": status(201),
                    "returns the revision": function (res) {
                        assert.ok(res.rev);
                    },
                    "which can be queried": {
                        setup: function (res, db) {
                            return db.view('horses/all');
                        },
                        "returns a 200": status(200)
                    }
                }
            },
            "calling save() with an array": {
                setup: function (db) {
                    return db.save([{_id: 'tom'}, {_id: 'flint'}]);
                },
                "returns an array of document ids and revs": function (res) {
                    assert.equal(res[0].id, 'tom');
                    assert.equal(res[1].id, 'flint');
                },
                "should bulk insert the documents": {
                    setup: function (res, db) {
                        var promise = new(events.Promise);
                        db.get('tom').addCallback(function (tom) {
                            db.get('flint').addCallback(function (flint) {
                                promise.emitSuccess(tom, flint);
                            });
                        });
                        return promise;
                    },
                    "which can then be retrieved": function (tom, flint) {
                        assert.ok(tom._id);
                        assert.ok(flint._id);
                    }
                }
            },
            "getting all documents": {
                setup: function (db) {
                    return db.all();
                },
                "returns a 200": status(200),
                "returns a list of all docs": function (res) {
                    assert.ok(res.rows);
                }
            },
            "updating a document (PUT)": {
                setup: function (db) {
                    var promise = new(events.Promise);
                    db.get('mike').addCallback(function (doc) {
                        db.save('mike', doc.rev,
                            {color: doc.color, age: 13}).addCallback(function (res) {
                            promise.emitSuccess(res);
                        });
                    });
                    return promise;
                },
                "returns a 201": status(201),
                "returns the revision": function (res) {
                    assert.ok(res.rev);
                    assert.match(res.rev, /^2/);
                },

                "returns the updated document": function (res) {
                    //assert.equal(res.age, 13);
                }
            },
            "deleting a document (DELETE)": {
                setup: function (db) {
                    var promise = new(events.Promise);
                    db.get('bill').addCallback(function (res) {
                        db.remove('bill', res.rev).addCallback(function (res) {
                            promise.emitSuccess(res);
                        });
                    });
                    return promise;
                },
                "returns a 200": status(200)
            },
            "querying a view": {
                setup: function (db) {
                    return db.view('pigs/all');
                },
                "returns a 200": status(200),
                "returns view results": function (res) {
                    assert.ok(res.rows);
                    assert.equal(res.rows.length, 2);
                },
                "with options": {

                },
                "with a start & end key": {

                }
            }
        }
    }
});
<|endoftext|>


<commit_before>/**
 * Copyright (c) Baidu Inc. All rights reserved.
 *
 * This source code is licensed under the MIT license.
 * See LICENSE file in the project root for license information.
 *
 * @file 元素节点类
 */

var guid = require('../util/guid');
var removeEl = require('../browser/remove-el');
var changeExprCompare = require('../runtime/change-expr-compare');
var changesIsInDataRef = require('../runtime/changes-is-in-data-ref');
var evalExpr = require('../runtime/eval-expr');
var LifeCycle = require('./life-cycle');
var NodeType = require('./node-type');
var reverseElementChildren = require('./reverse-element-children');
var isDataChangeByElement = require('./is-data-change-by-element');
var getPropHandler = require('./get-prop-handler');
var elementOwnCreate = require('./element-own-create');
var elementOwnDetach = require('./element-own-detach');
var elementOwnDispose = require('./element-own-dispose');
var elementOwnOnEl = require('./element-own-on-el');
var elementOwnToPhase = require('./element-own-to-phase');
var elementOwnAttached = require('./element-own-attached');
var elementOwnLeave = require('./element-own-leave');
var elementInitTagName = require('./element-init-tag-name');
var nodeSBindInit = require('./node-s-bind-init');
var nodeSBindUpdate = require('./node-s-bind-update');
var handleProp = require('./handle-prop');
var warnSetHTML = require('./warn-set-html');
var getNodePath = require('./get-node-path');

/**
 * 元素节点类
 *
 * @class
 * @param {Object} aNode 抽象节点
 * @param {Component} owner 所属组件环境
 * @param {Model=} scope 所属数据环境
 * @param {Node} parent 父亲节点
 * @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象
 */
function Element(aNode, owner, scope, parent, reverseWalker) {
    this.aNode = aNode;
    this.owner = owner;
    this.scope = scope;
    this.parent = parent;

    this.lifeCycle = LifeCycle.start;
    this.children = [];
    this._elFns = [];
    this.parentComponent = parent.nodeType === NodeType.CMPT
        ? parent
        : parent.parentComponent;

    this.id = guid();

    elementInitTagName(this);

    nodeSBindInit(this, aNode.directives.bind);
    this.lifeCycle = LifeCycle.inited;

    // #[begin] reverse
    if (reverseWalker) {
        var currentNode = reverseWalker.current;

        if (!currentNode) {
            throw new Error('[SAN REVERSE ERROR] Element not found. \nPaths: '
                + getNodePath(this).join(' > '));
        }

        if (currentNode.nodeType !== 1) {
            throw new Error('[SAN REVERSE ERROR] Element type not match, expect 1 but '
                + currentNode.nodeType + '.\nPaths: '
                + getNodePath(this).join(' > '));
        }

        if (currentNode.tagName.toLowerCase() !== this.tagName) {
            throw new Error('[SAN REVERSE ERROR] Element tagName not match, expect '
                + this.tagName + ' but meat ' + currentNode.tagName.toLowerCase() + '.\nPaths: '
                + getNodePath(this).join(' > '));
        }

        this.el = currentNode;
        reverseWalker.goNext();

        reverseElementChildren(this);

        this._attached();
    }
    // #[end]
}

Element.prototype.nodeType = NodeType.ELEM;

/**
 * 将元素attach到页面
 *
 * @param {HTMLElement} parentEl 要添加到的父元素
 * @param {HTMLElement＝} beforeEl 要添加到哪个元素之前
 */
Element.prototype.attach = function (parentEl, beforeEl) {
    if (!this.lifeCycle.attached) {
        this._create();
        insertBefore(this.el, parentEl, beforeEl);

        if (!this._contentReady) {
            var htmlDirective = this.aNode.directives.html;

            if (htmlDirective) {
                this.el.innerHTML = evalExpr(htmlDirective.value, this.scope, this.owner);
            }
            else {
                for (var i = 0; i < this.aNode.children.length; i++) {
                    var child = createNode(this.aNode.children[i], this);
                    this.children.push(child);
                    child.attach(this.el);
                }
            }

            this._contentReady = 1;
        }

        this._attached();
    }
};

Element.prototype.detach = elementOwnDetach;
Element.prototype.dispose = elementOwnDispose;
Element.prototype._create = elementOwnCreate;
Element.prototype._toPhase = elementOwnToPhase;
Element.prototype._onEl = elementOwnOnEl;
Element.prototype._leave = elementOwnLeave;

/**
 * 视图更新
 *
 * @param {Array} changes 数据变化信息
 */
Element.prototype._update = function (changes) {
    if (!changesIsInDataRef(changes, this.aNode.hotspot.data)) {
        return;
    }

    // update s-bind
    var me = this;
    nodeSBindUpdate(
        this,
        this.aNode.directives.bind,
        changes,
        function (name, value) {
            if (name in me.aNode.hotspot.props) {
                return;
            }

            getPropHandler(me.tagName, name).prop(me.el, value, name, me);
        }
    );

    // update prop
    var dynamicProps = this.aNode.hotspot.dynamicProps;
    for (var i = 0, l = dynamicProps.length; i < l; i++) {
        var prop = dynamicProps[i];

        for (var j = 0, changeLen = changes.length; j < changeLen; j++) {
            var change = changes[j];

            if (!isDataChangeByElement(change, this, prop.name)
                && (
                    changeExprCompare(change.expr, prop.expr, this.scope)
                    || prop.hintExpr && changeExprCompare(change.expr, prop.hintExpr, this.scope)
                )
            ) {
                handleProp(this, evalExpr(prop.expr, this.scope, this.owner), prop);
                break;
            }
        }
    }

    // update content
    var htmlDirective = this.aNode.directives.html;
    if (htmlDirective) {
        var len = changes.length;
        while (len--) {
            if (changeExprCompare(changes[len].expr, htmlDirective.value, this.scope)) {
                // #[begin] error
                warnSetHTML(this.el);
                // #[end]

                this.el.innerHTML = evalExpr(htmlDirective.value, this.scope, this.owner);
                break;
            }
        }
    }
    else {
        for (var i = 0; i < this.children.length; i++) {
            this.children[i]._update(changes);
        }
    }
};

/**
 * 执行完成attached状态的行为
 */
Element.prototype._attached = elementOwnAttached;

exports = module.exports = Element;
<commit_msg>remove unuse require<commit_after>/**
 * Copyright (c) Baidu Inc. All rights reserved.
 *
 * This source code is licensed under the MIT license.
 * See LICENSE file in the project root for license information.
 *
 * @file 元素节点类
 */

var guid = require('../util/guid');
var changeExprCompare = require('../runtime/change-expr-compare');
var changesIsInDataRef = require('../runtime/changes-is-in-data-ref');
var evalExpr = require('../runtime/eval-expr');
var LifeCycle = require('./life-cycle');
var NodeType = require('./node-type');
var reverseElementChildren = require('./reverse-element-children');
var isDataChangeByElement = require('./is-data-change-by-element');
var getPropHandler = require('./get-prop-handler');
var elementOwnCreate = require('./element-own-create');
var elementOwnDetach = require('./element-own-detach');
var elementOwnDispose = require('./element-own-dispose');
var elementOwnOnEl = require('./element-own-on-el');
var elementOwnToPhase = require('./element-own-to-phase');
var elementOwnAttached = require('./element-own-attached');
var elementOwnLeave = require('./element-own-leave');
var elementInitTagName = require('./element-init-tag-name');
var nodeSBindInit = require('./node-s-bind-init');
var nodeSBindUpdate = require('./node-s-bind-update');
var handleProp = require('./handle-prop');
var warnSetHTML = require('./warn-set-html');
var getNodePath = require('./get-node-path');

/**
 * 元素节点类
 *
 * @class
 * @param {Object} aNode 抽象节点
 * @param {Component} owner 所属组件环境
 * @param {Model=} scope 所属数据环境
 * @param {Node} parent 父亲节点
 * @param {DOMChildrenWalker?} reverseWalker 子元素遍历对象
 */
function Element(aNode, owner, scope, parent, reverseWalker) {
    this.aNode = aNode;
    this.owner = owner;
    this.scope = scope;
    this.parent = parent;

    this.lifeCycle = LifeCycle.start;
    this.children = [];
    this._elFns = [];
    this.parentComponent = parent.nodeType === NodeType.CMPT
        ? parent
        : parent.parentComponent;

    this.id = guid();

    elementInitTagName(this);

    nodeSBindInit(this, aNode.directives.bind);
    this.lifeCycle = LifeCycle.inited;

    // #[begin] reverse
    if (reverseWalker) {
        var currentNode = reverseWalker.current;

        if (!currentNode) {
            throw new Error('[SAN REVERSE ERROR] Element not found. \nPaths: '
                + getNodePath(this).join(' > '));
        }

        if (currentNode.nodeType !== 1) {
            throw new Error('[SAN REVERSE ERROR] Element type not match, expect 1 but '
                + currentNode.nodeType + '.\nPaths: '
                + getNodePath(this).join(' > '));
        }

        if (currentNode.tagName.toLowerCase() !== this.tagName) {
            throw new Error('[SAN REVERSE ERROR] Element tagName not match, expect '
                + this.tagName + ' but meat ' + currentNode.tagName.toLowerCase() + '.\nPaths: '
                + getNodePath(this).join(' > '));
        }

        this.el = currentNode;
        reverseWalker.goNext();

        reverseElementChildren(this);

        this._attached();
    }
    // #[end]
}

Element.prototype.nodeType = NodeType.ELEM;

/**
 * 将元素attach到页面
 *
 * @param {HTMLElement} parentEl 要添加到的父元素
 * @param {HTMLElement＝} beforeEl 要添加到哪个元素之前
 */
Element.prototype.attach = function (parentEl, beforeEl) {
    if (!this.lifeCycle.attached) {
        this._create();
        insertBefore(this.el, parentEl, beforeEl);

        if (!this._contentReady) {
            var htmlDirective = this.aNode.directives.html;

            if (htmlDirective) {
                this.el.innerHTML = evalExpr(htmlDirective.value, this.scope, this.owner);
            }
            else {
                for (var i = 0; i < this.aNode.children.length; i++) {
                    var child = createNode(this.aNode.children[i], this);
                    this.children.push(child);
                    child.attach(this.el);
                }
            }

            this._contentReady = 1;
        }

        this._attached();
    }
};

Element.prototype.detach = elementOwnDetach;
Element.prototype.dispose = elementOwnDispose;
Element.prototype._create = elementOwnCreate;
Element.prototype._toPhase = elementOwnToPhase;
Element.prototype._onEl = elementOwnOnEl;
Element.prototype._leave = elementOwnLeave;

/**
 * 视图更新
 *
 * @param {Array} changes 数据变化信息
 */
Element.prototype._update = function (changes) {
    if (!changesIsInDataRef(changes, this.aNode.hotspot.data)) {
        return;
    }

    // update s-bind
    var me = this;
    nodeSBindUpdate(
        this,
        this.aNode.directives.bind,
        changes,
        function (name, value) {
            if (name in me.aNode.hotspot.props) {
                return;
            }

            getPropHandler(me.tagName, name).prop(me.el, value, name, me);
        }
    );

    // update prop
    var dynamicProps = this.aNode.hotspot.dynamicProps;
    for (var i = 0, l = dynamicProps.length; i < l; i++) {
        var prop = dynamicProps[i];

        for (var j = 0, changeLen = changes.length; j < changeLen; j++) {
            var change = changes[j];

            if (!isDataChangeByElement(change, this, prop.name)
                && (
                    changeExprCompare(change.expr, prop.expr, this.scope)
                    || prop.hintExpr && changeExprCompare(change.expr, prop.hintExpr, this.scope)
                )
            ) {
                handleProp(this, evalExpr(prop.expr, this.scope, this.owner), prop);
                break;
            }
        }
    }

    // update content
    var htmlDirective = this.aNode.directives.html;
    if (htmlDirective) {
        var len = changes.length;
        while (len--) {
            if (changeExprCompare(changes[len].expr, htmlDirective.value, this.scope)) {
                // #[begin] error
                warnSetHTML(this.el);
                // #[end]

                this.el.innerHTML = evalExpr(htmlDirective.value, this.scope, this.owner);
                break;
            }
        }
    }
    else {
        for (var i = 0; i < this.children.length; i++) {
            this.children[i]._update(changes);
        }
    }
};

/**
 * 执行完成attached状态的行为
 */
Element.prototype._attached = elementOwnAttached;

exports = module.exports = Element;
<|endoftext|>


<commit_before>/**
 * @author  Hyperandroid  ||  http://hyperandroid.com/
 *
 * MouseEvent is a class to hold necessary information of every mouse event related to concrete
 * scene graph Actors.
 *
 * Here it is also the logic to on mouse events, pump the correct event to the appropiate scene
 * graph Actor.
 *
 * 20101008 Hyperandroid. changed event scope from CAAT.director.canvas to window. Works under
 *          al major browsers on linux and win7. Thanks @alteredq for this tip.
 *
 * TODO: add events for event pumping:
 *  + cancelBubling
 *
 **/
(function() {
	CAAT.MouseEvent = function() {
		this.point= new CAAT.Point();
		this.screenPoint= new CAAT.Point();
		return this;
	};

	CAAT.MouseEvent.prototype= {
		screenPoint:	null,
		point:			null,
		modifiers:		0,
		time:			0,
		source:			null,

		SHIFT:			16,
		CONTROL:		17,
		ALT:			18,

		SHIFT_MASK:		1,
		CONTROL_MASK:	2,
		ALT_MASK:		4,

		init : function( x,y,modifiers,source,screenPoint ) {
			this.point.set(x,y);
			this.modifiers= modifiers;
			this.source= source;
			this.screenPoint= screenPoint;
			return this;
		},
		isAltDown : function() {
			return this.modifiers&this.ALT_MASK;
		},
		isControlDown : function() {
			return this.modifiers&this.CONTROL_MASK;
		},
		isShiftDown : function() {
			return this.modifiers&this.SHIFT_MASK;
		}
	};
})();

CAAT.lastSelectedActor=  null;
CAAT.mousePoint=         null;
CAAT.prevMousePoint=     null;
CAAT.screenMousePoint=   null;
CAAT.mouseDown=          false;
CAAT.modifiers=          0;
CAAT.dragging=           false;
CAAT.targetDirector=     null;
CAAT.DRAG_THRESHOLD_X=   5;
CAAT.DRAG_THRESHOLD_Y=   5;
CAAT.DEBUG=              false;

CAAT.getCanvasCoord= function __getCanvasCoord(point, e) {
	var posx = 0;
	var posy = 0;
	if (!e) e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}

    var pposx;
    var pposy;
    var i;

    for( i=0; i<CAAT.director.length; i++ ) {
        pposx= posx;
        pposy= posy;

    	pposx-= CAAT.director[i].canvas.offsetLeft;
    	pposy-= CAAT.director[i].canvas.offsetTop;

        if ( CAAT.director[i].contains(pposx, pposy) ) {
            CAAT.targetDirector= CAAT.director[i];
            point.set(pposx,pposy);
            CAAT.screenMousePoint.set(pposx, pposy);
            return;
        }
    }

    CAAT.targetDirector=null;
};

CAAT.GlobalDisableEvents= function __GlobalDisableEvents()
{
    //console.log("(CAAT.MouseEvent) Disabling CAAT event capture");

    window.removeEventListener('keydown', CAAT.MouseEvent.prototype.keyDownFunc);
    window.removeEventListener('keyup', CAAT.MouseEvent.prototype.keyUpFunc);
    window.removeEventListener('mousedown', CAAT.MouseEvent.prototype.mouseDownFunc);
    window.removeEventListener('mouseup', CAAT.MouseEvent.prototype.mouseUpFunc);
    window.removeEventListener('mousemove', CAAT.MouseEvent.prototype.mouseMoveFunc);
    window.removeEventListener('mouseover', CAAT.MouseEvent.prototype.mouseOverFunc);
    window.removeEventListener('mouseout', CAAT.MouseEvent.prototype.mouseOutFunc);
    window.removeEventListener('dblclick', CAAT.MouseEvent.prototype.dblClickFunc);
}

CAAT.GlobalEnableEvents= function __GlobalEnableEvents() {

    CAAT.mousePoint=      new CAAT.Point();
    CAAT.prevMousePoint=     new CAAT.Point();
    CAAT.screenMousePoint=   new CAAT.Point();

    window.addEventListener('keydown',
        function(evt,c) {
            var key = (evt.which) ? evt.which : event.keyCode;
            switch( key ) {
            case CAAT.MouseEvent.prototype.SHIFT:
                CAAT.modifiers|=CAAT.MouseEvent.prototype.SHIFT_MASK;
                break;
            case CAAT.MouseEvent.prototype.CONTROL:
                CAAT.modifiers|=CAAT.MouseEvent.prototype.CONTROL_MASK;
                break;
            case CAAT.MouseEvent.prototype.ALT:
                CAAT.modifiers|=CAAT.MouseEvent.prototype.ALT_MASK;
                break;
            }
        },
        false);

    window.addEventListener('keyup',
        function(evt,c) {
            var key = (evt.which) ? evt.which : event.keyCode;
            switch( key ) {
            case CAAT.MouseEvent.prototype.SHIFT:
                CAAT.modifiers&=~CAAT.MouseEvent.prototype.SHIFT_MASK;
                break;
            case CAAT.MouseEvent.prototype.CONTROL:
                CAAT.modifiers&=~CAAT.MouseEvent.prototype.CONTROL_MASK;
                break;
            case CAAT.MouseEvent.prototype.ALT:
                CAAT.modifiers&=~CAAT.MouseEvent.prototype.ALT_MASK;
                break;
            case 68:    // D
                if ( CAAT.DEBUG ) {
                    if ( null!=CAAT.targetDirector ) {
                        CAAT.targetDirector.debug= !CAAT.targetDirector.debug;
                    }
                }
                break;
            }
        },
        false );

    window.addEventListener('mouseup',
            function(e) {
                CAAT.mouseDown = false;
                if (null != CAAT.lastSelectedActor) {
                    CAAT.lastSelectedActor.mouseUp(
                            new CAAT.MouseEvent().init(
                                    CAAT.lastSelectedActor.rpoint.x,
                                    CAAT.lastSelectedActor.rpoint.y,
                                    CAAT.modifiers,
                                    CAAT.lastSelectedActor,
                                    CAAT.screenMousePoint));
                }

                if (!CAAT.dragging) {
                    if (null != CAAT.lastSelectedActor) {
                        CAAT.lastSelectedActor.mouseClick(
                                new CAAT.MouseEvent().init(
                                        CAAT.lastSelectedActor.rpoint.x,
                                        CAAT.lastSelectedActor.rpoint.y,
                                        CAAT.modifiers,
                                        CAAT.lastSelectedActor,
                                        CAAT.screenMousePoint));
                    }
                } else {
                    CAAT.dragging = false;
                }
            },
            false);

    window.addEventListener('mousedown',
            function(e) {

                CAAT.getCanvasCoord(CAAT.mousePoint, e);

                if ( null==CAAT.targetDirector ) {
                    return;
                }
                CAAT.mouseDown = true;
                CAAT.lastSelectedActor = CAAT.targetDirector.findActorAtPosition(CAAT.mousePoint);
                var px= CAAT.mousePoint.x;
                var py= CAAT.mousePoint.y;

                if (null != CAAT.lastSelectedActor) {
                    // to calculate mouse drag threshold
                    CAAT.prevMousePoint.x= px;
                    CAAT.prevMousePoint.y= py;
                    CAAT.lastSelectedActor.mouseDown(
                            new CAAT.MouseEvent().init(
                                    CAAT.lastSelectedActor.rpoint.x,
                                    CAAT.lastSelectedActor.rpoint.y,
                                    CAAT.modifiers,
                                    CAAT.lastSelectedActor,
                                    CAAT.screenMousePoint));
                }
            },
            false);

    window.addEventListener('mouseover',
            function(e) {
                CAAT.getCanvasCoord(CAAT.mousePoint, e);

                if ( null==CAAT.targetDirector ) {
                    return;
                }

                CAAT.lastSelectedActor = CAAT.targetDirector.findActorAtPosition(CAAT.mousePoint);
                if (null != CAAT.lastSelectedActor) {
                    CAAT.lastSelectedActor.mouseEnter(
                            new CAAT.MouseEvent().init(
                                    CAAT.lastSelectedActor.rpoint.x,
                                    CAAT.lastSelectedActor.rpoint.y,
                                    CAAT.modifiers,
                                    CAAT.lastSelectedActor,
                                    CAAT.screenMousePoint));
                }
            },
            false);

    window.addEventListener('mouseout',
            function(e) {
                if (null != CAAT.lastSelectedActor) {
                    CAAT.lastSelectedActor.mouseExit(new CAAT.MouseEvent().init(0, 0, CAAT.modifiers, CAAT.lastSelectedActor, CAAT.screenMousePoint));
                    CAAT.lastSelectedActor = null;
                }
                CAAT.mouseDown = false;
            },
            false);

    window.addEventListener('mousemove',
            function(e) {

                CAAT.getCanvasCoord(CAAT.mousePoint, e);
                if ( null==CAAT.targetDirector ) {
                    return;
                }

                // drag
                if (CAAT.mouseDown && null != CAAT.lastSelectedActor) {

                    // check for mouse move threshold.
                    if ( !CAAT.dragging ) {
                        if ( Math.abs(CAAT.prevMousePoint.x-CAAT.mousePoint.x)< CAAT.DRAG_THRESHOLD_X &&
                             Math.abs(CAAT.prevMousePoint.y-CAAT.mousePoint.y)< CAAT.DRAG_THRESHOLD_Y ) {
                            return;
                        }
                    }

                    CAAT.dragging = true;
                    if (null != CAAT.lastSelectedActor.parent) {
                        CAAT.lastSelectedActor.parent.inverseTransformCoord(CAAT.mousePoint);
                    }
                    CAAT.lastSelectedActor.mouseDrag(
                            new CAAT.MouseEvent().init(
                                    CAAT.mousePoint.x,
                                    CAAT.mousePoint.y,
                                    CAAT.modifiers,
                                    CAAT.lastSelectedActor,
                                    CAAT.screenMousePoint));
                    return;
                }

                var lactor = CAAT.targetDirector.findActorAtPosition(CAAT.mousePoint);

                // cambiamos de actor.
                if (lactor != CAAT.lastSelectedActor) {
                    if (null != CAAT.lastSelectedActor) {
                        CAAT.lastSelectedActor.mouseExit(
                                new CAAT.MouseEvent().init(
                                        CAAT.mousePoint.x,
                                        CAAT.mousePoint.y,
                                        CAAT.modifiers,
                                        CAAT.lastSelectedActor,
                                        CAAT.screenMousePoint));
                    }
                    if (null != lactor) {
                        lactor.mouseEnter(
                                new CAAT.MouseEvent().init(
                                        lactor.rpoint.x,
                                        lactor.rpoint.y,
                                        CAAT.modifiers,
                                        lactor,
                                        CAAT.screenMousePoint));
                    }
                }
                CAAT.lastSelectedActor = lactor;
                if (null != lactor) {
                    CAAT.lastSelectedActor.mouseMove(
                            new CAAT.MouseEvent().init(
                                    CAAT.lastSelectedActor.rpoint.x,
                                    CAAT.lastSelectedActor.rpoint.y,
                                    CAAT.modifiers,
                                    CAAT.lastSelectedActor,
                                    CAAT.screenMousePoint));
                }
            },
            false);

    window.addEventListener("dblclick", function(e) {
        CAAT.getCanvasCoord(CAAT.mousePoint, e);
        if (null != CAAT.lastSelectedActor) {
            CAAT.lastSelectedActor.mouseDblClick(
                    new CAAT.MouseEvent().init(
                            CAAT.lastSelectedActor.rpoint.x,
                            CAAT.lastSelectedActor.rpoint.y,
                            CAAT.modifiers,
                            CAAT.lastSelectedActor,
                            CAAT.screenMousePoint));
        }
    }, false);
};<commit_msg>Added CAAT.log(str) function.<commit_after>/**
 * @author  Hyperandroid  ||  http://hyperandroid.com/
 *
 * MouseEvent is a class to hold necessary information of every mouse event related to concrete
 * scene graph Actors.
 *
 * Here it is also the logic to on mouse events, pump the correct event to the appropiate scene
 * graph Actor.
 *
 * 20101008 Hyperandroid. changed event scope from CAAT.director.canvas to window. Works under
 *          al major browsers on linux and win7. Thanks @alteredq for this tip.
 *
 * TODO: add events for event pumping:
 *  + cancelBubling
 *
 **/
(function() {
	CAAT.MouseEvent = function() {
		this.point= new CAAT.Point();
		this.screenPoint= new CAAT.Point();
		return this;
	};

	CAAT.MouseEvent.prototype= {
		screenPoint:	null,
		point:			null,
		modifiers:		0,
		time:			0,
		source:			null,

		SHIFT:			16,
		CONTROL:		17,
		ALT:			18,

		SHIFT_MASK:		1,
		CONTROL_MASK:	2,
		ALT_MASK:		4,

		init : function( x,y,modifiers,source,screenPoint ) {
			this.point.set(x,y);
			this.modifiers= modifiers;
			this.source= source;
			this.screenPoint= screenPoint;
			return this;
		},
		isAltDown : function() {
			return this.modifiers&this.ALT_MASK;
		},
		isControlDown : function() {
			return this.modifiers&this.CONTROL_MASK;
		},
		isShiftDown : function() {
			return this.modifiers&this.SHIFT_MASK;
		}
	};
})();

CAAT.lastSelectedActor=  null;
CAAT.mousePoint=         null;
CAAT.prevMousePoint=     null;
CAAT.screenMousePoint=   null;
CAAT.mouseDown=          false;
CAAT.modifiers=          0;
CAAT.dragging=           false;
CAAT.targetDirector=     null;
CAAT.DRAG_THRESHOLD_X=   5;
CAAT.DRAG_THRESHOLD_Y=   5;
CAAT.DEBUG=              false;

CAAT.getCanvasCoord= function __getCanvasCoord(point, e) {
	var posx = 0;
	var posy = 0;
	if (!e) e = window.event;
	if (e.pageX || e.pageY) 	{
		posx = e.pageX;
		posy = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		posx = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		posy = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}

    var pposx;
    var pposy;
    var i;

    for( i=0; i<CAAT.director.length; i++ ) {
        pposx= posx;
        pposy= posy;

    	pposx-= CAAT.director[i].canvas.offsetLeft;
    	pposy-= CAAT.director[i].canvas.offsetTop;

        if ( CAAT.director[i].contains(pposx, pposy) ) {
            CAAT.targetDirector= CAAT.director[i];
            point.set(pposx,pposy);
            CAAT.screenMousePoint.set(pposx, pposy);
            return;
        }
    }

    CAAT.targetDirector=null;
};

CAAT.log= function(msg) {
    if (console) {
        console.log(msg);
    }
}

CAAT.GlobalDisableEvents= function __GlobalDisableEvents()
{
    CAAT.log("(CAAT.MouseEvent) Disabling CAAT event capture");

    window.removeEventListener('keydown', CAAT.MouseEvent.prototype.keyDownFunc);
    window.removeEventListener('keyup', CAAT.MouseEvent.prototype.keyUpFunc);
    window.removeEventListener('mousedown', CAAT.MouseEvent.prototype.mouseDownFunc);
    window.removeEventListener('mouseup', CAAT.MouseEvent.prototype.mouseUpFunc);
    window.removeEventListener('mousemove', CAAT.MouseEvent.prototype.mouseMoveFunc);
    window.removeEventListener('mouseover', CAAT.MouseEvent.prototype.mouseOverFunc);
    window.removeEventListener('mouseout', CAAT.MouseEvent.prototype.mouseOutFunc);
    window.removeEventListener('dblclick', CAAT.MouseEvent.prototype.dblClickFunc);
}

CAAT.GlobalEnableEvents= function __GlobalEnableEvents() {

    CAAT.log("(CAAT.MouseEvent) Enabling CAAT event capture")

    CAAT.mousePoint=      new CAAT.Point();
    CAAT.prevMousePoint=     new CAAT.Point();
    CAAT.screenMousePoint=   new CAAT.Point();

    window.addEventListener('keydown',
        function(evt,c) {
            var key = (evt.which) ? evt.which : event.keyCode;
            switch( key ) {
            case CAAT.MouseEvent.prototype.SHIFT:
                CAAT.modifiers|=CAAT.MouseEvent.prototype.SHIFT_MASK;
                break;
            case CAAT.MouseEvent.prototype.CONTROL:
                CAAT.modifiers|=CAAT.MouseEvent.prototype.CONTROL_MASK;
                break;
            case CAAT.MouseEvent.prototype.ALT:
                CAAT.modifiers|=CAAT.MouseEvent.prototype.ALT_MASK;
                break;
            }
        },
        false);

    window.addEventListener('keyup',
        function(evt,c) {
            var key = (evt.which) ? evt.which : event.keyCode;
            switch( key ) {
            case CAAT.MouseEvent.prototype.SHIFT:
                CAAT.modifiers&=~CAAT.MouseEvent.prototype.SHIFT_MASK;
                break;
            case CAAT.MouseEvent.prototype.CONTROL:
                CAAT.modifiers&=~CAAT.MouseEvent.prototype.CONTROL_MASK;
                break;
            case CAAT.MouseEvent.prototype.ALT:
                CAAT.modifiers&=~CAAT.MouseEvent.prototype.ALT_MASK;
                break;
            case 68:    // D
                if ( CAAT.DEBUG ) {
                    if ( null!=CAAT.targetDirector ) {
                        CAAT.targetDirector.debug= !CAAT.targetDirector.debug;
                    }
                }
                break;
            }
        },
        false );

    window.addEventListener('mouseup',
            function(e) {
                CAAT.mouseDown = false;
                if (null != CAAT.lastSelectedActor) {
                    CAAT.lastSelectedActor.mouseUp(
                            new CAAT.MouseEvent().init(
                                    CAAT.lastSelectedActor.rpoint.x,
                                    CAAT.lastSelectedActor.rpoint.y,
                                    CAAT.modifiers,
                                    CAAT.lastSelectedActor,
                                    CAAT.screenMousePoint));
                }

                if (!CAAT.dragging) {
                    if (null != CAAT.lastSelectedActor) {
                        CAAT.lastSelectedActor.mouseClick(
                                new CAAT.MouseEvent().init(
                                        CAAT.lastSelectedActor.rpoint.x,
                                        CAAT.lastSelectedActor.rpoint.y,
                                        CAAT.modifiers,
                                        CAAT.lastSelectedActor,
                                        CAAT.screenMousePoint));
                    }
                } else {
                    CAAT.dragging = false;
                }
            },
            false);

    window.addEventListener('mousedown',
            function(e) {

                CAAT.getCanvasCoord(CAAT.mousePoint, e);

                if ( null==CAAT.targetDirector ) {
                    return;
                }
                CAAT.mouseDown = true;
                CAAT.lastSelectedActor = CAAT.targetDirector.findActorAtPosition(CAAT.mousePoint);
                var px= CAAT.mousePoint.x;
                var py= CAAT.mousePoint.y;

                if (null != CAAT.lastSelectedActor) {
                    // to calculate mouse drag threshold
                    CAAT.prevMousePoint.x= px;
                    CAAT.prevMousePoint.y= py;
                    CAAT.lastSelectedActor.mouseDown(
                            new CAAT.MouseEvent().init(
                                    CAAT.lastSelectedActor.rpoint.x,
                                    CAAT.lastSelectedActor.rpoint.y,
                                    CAAT.modifiers,
                                    CAAT.lastSelectedActor,
                                    CAAT.screenMousePoint));
                }
            },
            false);

    window.addEventListener('mouseover',
            function(e) {
                CAAT.getCanvasCoord(CAAT.mousePoint, e);

                if ( null==CAAT.targetDirector ) {
                    return;
                }

                CAAT.lastSelectedActor = CAAT.targetDirector.findActorAtPosition(CAAT.mousePoint);
                if (null != CAAT.lastSelectedActor) {
                    CAAT.lastSelectedActor.mouseEnter(
                            new CAAT.MouseEvent().init(
                                    CAAT.lastSelectedActor.rpoint.x,
                                    CAAT.lastSelectedActor.rpoint.y,
                                    CAAT.modifiers,
                                    CAAT.lastSelectedActor,
                                    CAAT.screenMousePoint));
                }
            },
            false);

    window.addEventListener('mouseout',
            function(e) {
                if (null != CAAT.lastSelectedActor) {
                    CAAT.lastSelectedActor.mouseExit(new CAAT.MouseEvent().init(0, 0, CAAT.modifiers, CAAT.lastSelectedActor, CAAT.screenMousePoint));
                    CAAT.lastSelectedActor = null;
                }
                CAAT.mouseDown = false;
            },
            false);

    window.addEventListener('mousemove',
            function(e) {

                CAAT.getCanvasCoord(CAAT.mousePoint, e);
                if ( null==CAAT.targetDirector ) {
                    return;
                }

                // drag
                if (CAAT.mouseDown && null != CAAT.lastSelectedActor) {

                    // check for mouse move threshold.
                    if ( !CAAT.dragging ) {
                        if ( Math.abs(CAAT.prevMousePoint.x-CAAT.mousePoint.x)< CAAT.DRAG_THRESHOLD_X &&
                             Math.abs(CAAT.prevMousePoint.y-CAAT.mousePoint.y)< CAAT.DRAG_THRESHOLD_Y ) {
                            return;
                        }
                    }

                    CAAT.dragging = true;
                    if (null != CAAT.lastSelectedActor.parent) {
                        CAAT.lastSelectedActor.parent.inverseTransformCoord(CAAT.mousePoint);
                    }
                    CAAT.lastSelectedActor.mouseDrag(
                            new CAAT.MouseEvent().init(
                                    CAAT.mousePoint.x,
                                    CAAT.mousePoint.y,
                                    CAAT.modifiers,
                                    CAAT.lastSelectedActor,
                                    CAAT.screenMousePoint));
                    return;
                }

                var lactor = CAAT.targetDirector.findActorAtPosition(CAAT.mousePoint);

                // cambiamos de actor.
                if (lactor != CAAT.lastSelectedActor) {
                    if (null != CAAT.lastSelectedActor) {
                        CAAT.lastSelectedActor.mouseExit(
                                new CAAT.MouseEvent().init(
                                        CAAT.mousePoint.x,
                                        CAAT.mousePoint.y,
                                        CAAT.modifiers,
                                        CAAT.lastSelectedActor,
                                        CAAT.screenMousePoint));
                    }
                    if (null != lactor) {
                        lactor.mouseEnter(
                                new CAAT.MouseEvent().init(
                                        lactor.rpoint.x,
                                        lactor.rpoint.y,
                                        CAAT.modifiers,
                                        lactor,
                                        CAAT.screenMousePoint));
                    }
                }
                CAAT.lastSelectedActor = lactor;
                if (null != lactor) {
                    CAAT.lastSelectedActor.mouseMove(
                            new CAAT.MouseEvent().init(
                                    CAAT.lastSelectedActor.rpoint.x,
                                    CAAT.lastSelectedActor.rpoint.y,
                                    CAAT.modifiers,
                                    CAAT.lastSelectedActor,
                                    CAAT.screenMousePoint));
                }
            },
            false);

    window.addEventListener("dblclick", function(e) {
        CAAT.getCanvasCoord(CAAT.mousePoint, e);
        if (null != CAAT.lastSelectedActor) {
            CAAT.lastSelectedActor.mouseDblClick(
                    new CAAT.MouseEvent().init(
                            CAAT.lastSelectedActor.rpoint.x,
                            CAAT.lastSelectedActor.rpoint.y,
                            CAAT.modifiers,
                            CAAT.lastSelectedActor,
                            CAAT.screenMousePoint));
        }
    }, false);
};<|endoftext|>


<commit_before>'use strict';
const fs = require("fs");
const async = require("async");
let Mongo = require("soajs.core.modules").mongo;

let lib = {
	basic: (config, dataPath, mongoConnection, cb) => {
		let colName = config.colName;
		let condAnchor = config.condAnchor;
		let objId = config.objId;
		let records = [];
		fs.readdirSync(dataPath).forEach(function (file) {
			let rec = require(dataPath + file);
			//TODO: validate env
			records.push(rec);
		});
		if (records && Array.isArray(records) && records.length > 0) {
			mongoConnection.dropCollection(colName, () => {
				async.each(
					records,
					(e, cb) => {
						let condition = {[condAnchor]: e[condAnchor]};
						e[objId] = mongoConnection.ObjectId(e[objId]);
						mongoConnection.update(colName, condition, e, {'upsert': true}, (error, result) => {
							console.log(colName, error);
							return cb();
						});
					},
					() => {
						return cb();
					});
			});
		}
		else
			return cb();
	},
	oauth: (dataPath, mongoConnection, cb) => {
		let records = [];
		fs.readdirSync(dataPath).forEach(function (file) {
			let rec = require(dataPath + file);
			//TODO: validate oauth
			records.push(rec);
		});
		if (records && Array.isArray(records) && records.length > 0) {
			mongoConnection.dropCollection("oauth_token", () => {
				async.each(
					records,
					(e, cb) => {
						let condition = {token: e.token};
						e._id = mongoConnection.ObjectId(e._id);
						if (e && e.user && e.user._id)
							e.user._id = mongoConnection.ObjectId(e.user._id);
						mongoConnection.update("oauth_token", condition, e, {'upsert': true}, (error, result) => {
							console.log("oauth_token", error);
							return cb();
						});
					},
					() => {
						return cb();
					});
			});
		}
		else
			return cb();
	},
	users: (dataPath, profile, cb) => {
		let records = [];
		fs.readdirSync(dataPath).forEach(function (file) {
			let rec = require(dataPath + file);
			//TODO: validate user
			records.push(rec);
		});
		if (records && Array.isArray(records) && records.length > 0) {
			async.each(
				records,
				(e, cb) => {
					profile.name = e.tenant.code + "_urac";
					let mongoConnection = new Mongo(profile);
					mongoConnection.dropCollection("users", () => {
						let condition = {email: e.email};
						e._id = mongoConnection.ObjectId(e._id);
						mongoConnection.update("users", condition, e, {'upsert': true}, (error, result) => {
							console.log("users", error);
							mongoConnection.closeDb();
							return cb();
						});
					});
				},
				() => {
					return cb();
				});
		}
		else
			return cb();
	},
	groups: (dataPath, profile, cb) => {
		let records = [];
		fs.readdirSync(dataPath).forEach(function (file) {
			let rec = require(dataPath + file);
			//TODO: validate group
			records.push(rec);
		});
		if (records && Array.isArray(records) && records.length > 0) {
			async.each(
				records,
				(e, cb) => {
					profile.name = e.tenant.code + "_urac";
					let mongoConnection = new Mongo(profile);
					mongoConnection.dropCollection("groups", () => {
						let condition = {code: e.code};
						e._id = mongoConnection.ObjectId(e._id);
						mongoConnection.update("groups", condition, e, {'upsert': true}, (error, result) => {
							console.log("groups", error);
							mongoConnection.closeDb();
							return cb();
						});
					});
				},
				() => {
					return cb();
				});
		}
		else
			return cb();
	},
	tokens: (dataPath, profile, cb) => {
		let records = [];
		fs.readdirSync(dataPath).forEach(function (file) {
			let rec = require(dataPath + file);
			//TODO: validate token
			records.push(rec);
		});
		if (records && Array.isArray(records) && records.length > 0) {
			async.each(
				records,
				(e, cb) => {
					profile.name = "TES0" + "_urac";
					let mongoConnection = new Mongo(profile);
					mongoConnection.dropCollection("tokens", () => {
						let condition = {code: e.code};
						e._id = mongoConnection.ObjectId(e._id);
						mongoConnection.update("tokens", condition, e, {'upsert': true}, (error, result) => {
							console.log("tokens", error, result);
							mongoConnection.closeDb();
							return cb();
						});
					});
				},
				() => {
					return cb();
				});
		}
		else
			return cb();
	}
};

module.exports = (profilePath, dataPath, callback) => {
	let profile;
	//check if profile is found
	fs.stat(profilePath, (error) => {
		if (error) {
			return callback(null, 'Profile not found!');
		}

		//read  mongo profile file
		profile = require(profilePath);
		//use soajs.core.modules to create a connection to core_provision database
		let mongoConnection = new Mongo(profile);
		async.series([
				function (cb) {
					//check for environment data
					if (fs.existsSync(dataPath + "environment/")) {
						let config = {
							"colName": "environment",
							"condAnchor": "code",
							"objId": "_id"
						};
						return lib.basic(config, dataPath + "environment/", mongoConnection, cb);
						//return lib.environment(dataPath + "environment/", mongoConnection, cb);
					}
					else
						return cb(null);
				},
				function (cb) {
					//check for environment data
					if (fs.existsSync(dataPath + "hosts/")) {
						let config = {
							"colName": "hosts",
							"condAnchor": "name",
							"objId": "_id"
						};
						return lib.basic(config, dataPath + "hosts/", mongoConnection, cb);
						//return lib.hosts(dataPath + "hosts/", mongoConnection, cb);
					}
					else
						return cb(null);
				},
				function (cb) {
					//check for products data
					if (fs.existsSync(dataPath + "products/")) {
						let config = {
							"colName": "products",
							"condAnchor": "code",
							"objId": "_id"
						};
						return lib.basic(config, dataPath + "products/", mongoConnection, cb);
						//return lib.product(dataPath + "products/", mongoConnection, cb);
					}
					else
						return cb(null);
				},
				function (cb) {
					//check for products data
					if (fs.existsSync(dataPath + "resources/")) {
						let config = {
							"colName": "resources",
							"condAnchor": "code",
							"objId": "_id"
						};
						return lib.basic(config, dataPath + "resources/", mongoConnection, cb);
						//return lib.resources(dataPath + "resources/", mongoConnection, cb);
					}
					else
						return cb(null);
				},
				function (cb) {
					//check for products data
					if (fs.existsSync(dataPath + "services/")) {
						let config = {
							"colName": "services",
							"condAnchor": "code",
							"objId": "_id"
						};
						return lib.basic(config, dataPath + "services/", mongoConnection, cb);
						//return lib.services(dataPath + "services/", mongoConnection, cb);
					}
					else
						return cb(null);
				},
				function (cb) {
					//check for products data
					if (fs.existsSync(dataPath + "products/")) {
						let config = {
							"colName": "products",
							"condAnchor": "code",
							"objId": "_id"
						};
						return lib.basic(config, dataPath + "products/", mongoConnection, cb);
						//return lib.product(dataPath + "products/", mongoConnection, cb);
					}
					else
						return cb(null);
				},
				function (cb) {
					//check for tenants data
					if (fs.existsSync(dataPath + "tenants/")) {
						let config = {
							"colName": "tenants",
							"condAnchor": "code",
							"objId": "_id"
						};
						return lib.basic(config, dataPath + "tenants/", mongoConnection, cb);
						//return lib.tenant(dataPath + "tenants/", mongoConnection, cb);
					}
					else
						return cb(null);
				},
				function (cb) {
					//check for tenants data
					if (fs.existsSync(dataPath + "oauth/")) {
						return lib.oauth(dataPath + "oauth/", mongoConnection, cb);
					}
					else
						return cb(null);
				},
				function (cb) {
					//check for users data
					if (fs.existsSync(dataPath + "urac/users/")) {
						return lib.users(dataPath + "urac/users/", profile, cb);
					}
					else
						return cb(null);
				},
				function (cb) {
					//check for groups data
					if (fs.existsSync(dataPath + "urac/groups/")) {
						return lib.groups(dataPath + "urac/groups/", profile, cb);
					}
					else
						return cb(null);
				},
				function (cb) {
					//check for tokens data
					if (fs.existsSync(dataPath + "urac/tokens/")) {
						return lib.tokens(dataPath + "urac/tokens/", profile, cb);
					}
					else
						return cb(null);
				}
			],
			() => {
				mongoConnection.closeDb();
				return callback(null, "MongoDb Soajs Data custom done!");
			});
	});
};<commit_msg>fixed importer<commit_after>'use strict';
const fs = require("fs");
const async = require("async");
let Mongo = require("soajs.core.modules").mongo;

let lib = {
	basic: (config, dataPath, mongoConnection, cb) => {
		let colName = config.colName;
		let condAnchor = config.condAnchor;
		let objId = config.objId;
		let records = [];
		fs.readdirSync(dataPath).forEach(function (file) {
			let rec = require(dataPath + file);
			//TODO: validate env
			records.push(rec);
		});
		if (records && Array.isArray(records) && records.length > 0) {
			mongoConnection.dropCollection(colName, () => {
				async.each(
					records,
					(e, cb) => {
						let condition = {[condAnchor]: e[condAnchor]};
						e[objId] = mongoConnection.ObjectId(e[objId]);
						mongoConnection.update(colName, condition, e, {'upsert': true}, (error, result) => {
							console.log(colName, error);
							return cb();
						});
					},
					() => {
						return cb();
					});
			});
		} else
		{
			mongoConnection.dropCollection(colName, () => {
				return cb();
			});
		}
	},
	oauth: (dataPath, mongoConnection, cb) => {
		let records = [];
		fs.readdirSync(dataPath).forEach(function (file) {
			let rec = require(dataPath + file);
			//TODO: validate oauth
			records.push(rec);
		});
		if (records && Array.isArray(records) && records.length > 0) {
			mongoConnection.dropCollection("oauth_token", () => {
				async.each(
					records,
					(e, cb) => {
						let condition = {token: e.token};
						e._id = mongoConnection.ObjectId(e._id);
						if (e && e.user && e.user._id)
							e.user._id = mongoConnection.ObjectId(e.user._id);
						mongoConnection.update("oauth_token", condition, e, {'upsert': true}, (error, result) => {
							console.log("oauth_token", error);
							return cb();
						});
					},
					() => {
						return cb();
					});
			});
		} else
			return cb();
	},
	users: (dataPath, profile, cb) => {
		let records = [];
		fs.readdirSync(dataPath).forEach(function (file) {
			let rec = require(dataPath + file);
			//TODO: validate user
			records.push(rec);
		});
		if (records && Array.isArray(records) && records.length > 0) {
			async.each(
				records,
				(e, cb) => {
					profile.name = e.tenant.code + "_urac";
					let mongoConnection = new Mongo(profile);
					mongoConnection.dropCollection("users", () => {
						let condition = {email: e.email};
						e._id = mongoConnection.ObjectId(e._id);
						mongoConnection.update("users", condition, e, {'upsert': true}, (error, result) => {
							console.log("users", error);
							mongoConnection.closeDb();
							return cb();
						});
					});
				},
				() => {
					return cb();
				});
		} else
			return cb();
	},
	groups: (dataPath, profile, cb) => {
		let records = [];
		fs.readdirSync(dataPath).forEach(function (file) {
			let rec = require(dataPath + file);
			//TODO: validate group
			records.push(rec);
		});
		if (records && Array.isArray(records) && records.length > 0) {
			async.each(
				records,
				(e, cb) => {
					profile.name = e.tenant.code + "_urac";
					let mongoConnection = new Mongo(profile);
					mongoConnection.dropCollection("groups", () => {
						let condition = {code: e.code};
						e._id = mongoConnection.ObjectId(e._id);
						mongoConnection.update("groups", condition, e, {'upsert': true}, (error, result) => {
							console.log("groups", error);
							mongoConnection.closeDb();
							return cb();
						});
					});
				},
				() => {
					return cb();
				});
		} else
			return cb();
	},
	tenants: (dataPath, mongoConnection, cb) => {
		let records = [];
		fs.readdirSync(dataPath).forEach(function (file) {
			let rec = require(dataPath + file);
			//TODO: validate env
			records.push(rec);
		});
		if (records && Array.isArray(records) && records.length > 0) {
			mongoConnection.dropCollection("tenants", () => {
				async.each(
					records,
					(e, cb) => {
						let condition = {["code"]: e["code"]};
						e["_id"] = mongoConnection.ObjectId(e["_id"]);
						e.applications.forEach(app => {
							app.appId = mongoConnection.ObjectId(app.appId);
						});
						mongoConnection.update('tenants', condition, e, {'upsert': true}, (error, result) => {
							console.log('tenants', error);
							return cb();
						});
					},
					() => {
						return cb();
					});
			});
		} else
		{
			mongoConnection.dropCollection(colName, () => {
				return cb();
			});
		}
	}
};

module.exports = (profilePath, dataPath, callback) => {
	let profile;
	//check if profile is found
	fs.stat(profilePath, (error) => {
		if (error) {
			return callback(null, 'Profile not found!');
		}

		//read  mongo profile file
		profile = require(profilePath);
		//use soajs.core.modules to create a connection to core_provision database
		let mongoConnection = new Mongo(profile);
		async.series([
				function (cb) {
					//check for environment data
					if (fs.existsSync(dataPath + "environment/")) {
						let config = {
							"colName": "environment",
							"condAnchor": "code",
							"objId": "_id"
						};
						return lib.basic(config, dataPath + "environment/", mongoConnection, cb);
					} else
						return cb(null);
				},
				function (cb) {
					//check for environment data
					if (fs.existsSync(dataPath + "hosts/")) {
						let config = {
							"colName": "hosts",
							"condAnchor": "name",
							"objId": "_id"
						};
						return lib.basic(config, dataPath + "hosts/", mongoConnection, cb);
					} else
						return cb(null);
				},
				function (cb) {
					//check for products data
					if (fs.existsSync(dataPath + "products/")) {
						let config = {
							"colName": "products",
							"condAnchor": "code",
							"objId": "_id"
						};
						return lib.basic(config, dataPath + "products/", mongoConnection, cb);
					} else
						return cb(null);
				},
				function (cb) {
					//check for products data
					if (fs.existsSync(dataPath + "resources/")) {
						let config = {
							"colName": "resources",
							"condAnchor": "name",
							"objId": "_id"
						};
						return lib.basic(config, dataPath + "resources/", mongoConnection, cb);
					} else
						return cb(null);
				},
				function (cb) {
					//check for products data
					if (fs.existsSync(dataPath + "services/")) {
						let config = {
							"colName": "services",
							"condAnchor": "name",
							"objId": "_id"
						};
						return lib.basic(config, dataPath + "services/", mongoConnection, cb);
					} else
						return cb(null);
				},
				function (cb) {
					//check for tenants data
					if (fs.existsSync(dataPath + "tenants/")) {
						return lib.tenants( dataPath + "tenants/", mongoConnection, cb);
					} else
						return cb(null);
				},
				function (cb) {
					//check for tenants data
					if (fs.existsSync(dataPath + "oauth/")) {
						return lib.oauth(dataPath + "oauth/", mongoConnection, cb);
					} else
						return cb(null);
				},
				function (cb) {
					//check for users data
					if (fs.existsSync(dataPath + "urac/users/")) {
						return lib.users(dataPath + "urac/users/", profile, cb);
					} else
						return cb(null);
				},
				function (cb) {
					//check for groups data
					if (fs.existsSync(dataPath + "urac/groups/")) {
						return lib.groups(dataPath + "urac/groups/", profile, cb);
					} else
						return cb(null);
				}
			],
			() => {
				mongoConnection.closeDb();
				return callback(null, "MongoDb Soajs Data custom done!");
			});
	});
};<|endoftext|>


<commit_before>var expect = require("chai").expect;
var ajaxWrapper = require("../js/helpers/ajaxWrapper");
var config = require("../js/config/config");

var expectAsync = require("./helpers/expectAsync");
var HttpServer = require("./helpers/HttpServer").HttpServer;

var server = new HttpServer(config.localTestserverURI);
config.apiURL = "http://" + server.address + ":" + server.port + "/";

describe("ajaxWrapper", function () {

  beforeEach(function (done) {
    this.server = server
      .setup({
        "name": "Marathon"
      }, 200)
      .start(done);
  });

  afterEach(function (done) {
    this.server.stop(done);
  });

  describe("on GET request", function () {

    it("returns a JSON object on success", function (done) {
      ajaxWrapper({
        method: "GET",
        url: config.apiURL
      })
      .success(function (response) {
        expectAsync(function () {
          expect(response.body.name).to.equal("Marathon");
        }, done);
      })
      .error(function () {
        done(new Error("I should not be called"));
      });
    });

    it("defaults to GET when no method is supplied", function (done) {
      ajaxWrapper({
        url: config.apiURL
      })
      .success(function (response) {
        expectAsync(function () {
          expect(response.body.name).to.equal("Marathon");
        }, done);
      })
      .error(function () {
        done(new Error("I should not be called"));
      });
    });

    it("handles failure gracefully", function (done) {
      this.server.setup({message: "Guru Meditation"}, 404);

      ajaxWrapper({
        method: "GET",
        url: config.apiURL + "/foo/bar"
      })
      .success(function () {
        done(new Error("I should not be called"));
      })
      .error(function (error) {
        expectAsync(function () {
          expect(error.body.message).to.equal("Guru Meditation");
        }, done);
      });
    });

  });

  describe("on concurrent request", function () {

    it("should timeout on second request", function (done) {
      var responses = 0;
      var timeoutId;
      var initialTimeout = this.timeout();
      this.timeout(50);

      var increaseResponses = function () {
        responses++;
        if (responses === 2) {
          clearTimeout(timeoutId);
          done(new Error("Second request should never be fulfilled"));
        }
      };

      ajaxWrapper({
        method: "GET",
        url: config.apiURL + "/concurrent"
      })
      .success(increaseResponses);

      ajaxWrapper({
        method: "GET",
        url: config.apiURL + "/concurrent"
      })
      .success(increaseResponses);

      timeoutId = setTimeout(() => {
        this.timeout(initialTimeout);
        done();
      }, 25);
    });

    it("should not timeout with flag set", function (done) {
      var responses = 0;

      function increaseResponses() {
        responses++;
        if (responses === 2) {
          done();
        }
      }

      ajaxWrapper({
        method: "GET",
        url: config.apiURL + "/concurrent",
        concurrent: true
      })
      .success(increaseResponses);

      ajaxWrapper({
        method: "GET",
        url: config.apiURL + "/concurrent",
        concurrent: true
      })
      .success(increaseResponses);
    });

  });

  describe("on POST request", function () {

    beforeEach(function () {
      this.server.setup(null, 200, true);
    });

    it("sends the correct payload", function (done) {
      var payload = {"key": "value"};

      ajaxWrapper({
        method: "POST",
        url: config.apiURL,
        data: payload
      })
        .success(function (response) {
          expectAsync(function (done) {
            expect(response.body.method).to.equal("POST");
            expect(response.body.payload).to.equal(JSON.stringify(payload));
          }, done);
        })
        .error(function () {
          done(new Error("I should not be called"));
        });
    });

    it("handles failure gracefully", function (done) {
      var payload = {"key": "value"};

      this.server.setup({message: "Guru Meditation"}, 404);

      ajaxWrapper({
        method: "POST",
        url: config.apiURL + "/foo/bar",
        data: payload
      })
        .success(function () {
          done(new Error("I should not be called"));
        })
        .error(function (error) {
          expectAsync(function () {
            expect(error.body.message).to.equal("Guru Meditation");
          }, done);
        });
    });

  });

  describe("on PUT request", function () {

    beforeEach(function () {
      this.server.setup(null, 200, true);
    });

    it("sends the correct payload with a PUT", function (done) {

      var payload = {"key": "value"};

      ajaxWrapper({
        method: "PUT",
        url: config.apiURL,
        data: payload
      })
        .success(response => {
          expectAsync(() => {
            expect(response.body.method).to.equal("PUT");
            expect(response.body.payload).to.equal(JSON.stringify(payload));
          }, done);
        })
        .error(() => {
          done(new Error("I should not be called"));
        });
    });

  });

  describe("on DELETE request", function () {

    beforeEach(function () {
      this.server.setup(null, 200, true);
    });

    it("returns the right response for a DELETE", function (done) {

      ajaxWrapper({
        method: "DELETE",
        url: config.apiURL + "/foo/bar",
        data: null
      })
        .success(response => {
          expectAsync(() => {
            expect(response.body.method).to.equal("DELETE");
          }, done);
        })
        .error(() => {
          done(new Error("I should not be called"));
        });
    });
  })

});
<commit_msg>Refactor ajaxWrapper tests to use nock<commit_after>var expect = require("chai").expect;
var ajaxWrapper = require("../js/helpers/ajaxWrapper");
var config = require("../js/config/config");

var expectAsync = require("./helpers/expectAsync");
var nock = require("nock");

var server = config.localTestserverURI;
config.apiURL = `http://${server.address}:${server.port}/`;

describe("ajaxWrapper", function () {

  describe("on GET request", function () {

    it("returns a JSON object on success", function (done) {
      nock(config.apiURL)
        .get("/")
        .reply(200, {"name": "Marathon"});

      ajaxWrapper({
        method: "GET",
        url: config.apiURL
      })
        .success(function (response) {
          expectAsync(function () {
            expect(response.body.name).to.equal("Marathon");
          }, done);
        });
    });

    it("defaults to GET when no method is supplied", function (done) {
      nock(config.apiURL)
        .get("/")
        .reply(200, {"name": "Marathon"});

      ajaxWrapper({
        url: config.apiURL
      })
        .success(function (response) {
          expectAsync(function () {
            expect(response.body.name).to.equal("Marathon");
          }, done);
        });
    });

    it("handles failure gracefully", function (done) {
      nock(config.apiURL)
        .get("/foo/bar")
        .reply(404, {"message": "Guru Meditation"});

      ajaxWrapper({
        method: "GET",
        url: config.apiURL + "foo/bar"
      })
        .success(() => {
          done(new Error("Success should not be called on 404"));
        })
        .error(function (error) {
          expectAsync(function () {
            expect(error.body.message).to.equal("Guru Meditation");
          }, done);
        });
    });

  });

  describe("on concurrent request", function () {

    it("should timeout on second request", function (done) {
      var responses = 0;
      var timeoutId;
      var initialTimeout = this.timeout();
      this.timeout(50);

      var increaseResponses = function () {
        responses++;
        if (responses === 2) {
          clearTimeout(timeoutId);
          done(new Error("Second request should never be fulfilled"));
        }
      };

      nock(config.apiURL)
        .get("/concurrent")
        .twice()
        .reply(200);

      ajaxWrapper({
        method: "GET",
        url: config.apiURL + "concurrent"
      })
      .success(increaseResponses);

      ajaxWrapper({
        method: "GET",
        url: config.apiURL + "concurrent"
      })
      .success(increaseResponses);

      timeoutId = setTimeout(() => {
        this.timeout(initialTimeout);
        done();
      }, 25);
    });

    it("should not timeout with flag set", function (done) {
      var responses = 0;

      function increaseResponses() {
        responses++;
        if (responses === 2) {
          done();
        }
      }

      nock(config.apiURL)
        .get("/concurrent")
        .twice()
        .reply(200);

      ajaxWrapper({
        method: "GET",
        url: config.apiURL + "concurrent",
        concurrent: true
      })
      .success(increaseResponses);

      ajaxWrapper({
        method: "GET",
        url: config.apiURL + "concurrent",
        concurrent: true
      })
      .success(increaseResponses);
    });

  });

  describe("on POST request", function () {

    it("sends the correct payload", function (done) {
      var payload = {"key": "value"};

      nock(config.apiURL)
        .post("/")
        .reply(200, function (uri, requestBody) {
          return {
            method: "POST",
            payload: requestBody
          };
        });

      ajaxWrapper({
        method: "POST",
        url: config.apiURL,
        data: payload
      })
        .success(function (response) {
          expectAsync(function (done) {
            expect(response.body.method).to.equal("POST");
            expect(response.body.payload).to.equal(JSON.stringify(payload));
          }, done);
        });
    });

    it("handles failure gracefully", function (done) {
      var payload = {"key": "value"};

      nock(config.apiURL)
        .post("/foo/bar")
        .reply(404, {message: "Guru Meditation"});

      ajaxWrapper({
        method: "POST",
        url: config.apiURL + "foo/bar",
        data: payload
      })
        .error(function (error) {
          expectAsync(function () {
            expect(error.body.message).to.equal("Guru Meditation");
          }, done);
        });
    });

  });

  describe("on PUT request", function () {

    it("sends the correct payload with a PUT", function (done) {

      var payload = {"key": "value"};

      nock(config.apiURL)
        .put("/")
        .reply(200, function (uri, requestBody) {
          return {
            method: "PUT",
            payload: requestBody
          };
        });

      ajaxWrapper({
        method: "PUT",
        url: config.apiURL,
        data: payload
      })
        .success(response => {
          expectAsync(() => {
            expect(response.body.method).to.equal("PUT");
            expect(response.body.payload).to.equal(JSON.stringify(payload));
          }, done);
        });
    });

  });

  describe("on DELETE request", function () {

    it("returns the right response for a DELETE", function (done) {

      nock(config.apiURL)
        .delete("/foo/bar")
        .reply(200, function (uri, requestBody) {
          return {
            method: "DELETE",
            payload: requestBody
          };
        });

      ajaxWrapper({
        method: "DELETE",
        url: config.apiURL + "foo/bar",
        data: null
      })
        .success(response => {
          expectAsync(() => {
            expect(response.body.method).to.equal("DELETE");
            expect(response.body.payload).to.be.empty;
          }, done);
        });
    });
  })

});
<|endoftext|>