<commit_before>/*
 Copyright 2017 Bitnami.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

'use strict';

const exec = require('child_process').exec;
const expect = require('chai').expect;
const fs = require('fs-extra');
const helpers = require('../lib/helpers');
const moment = require('moment');
const path = require('path');
const request = require('request');

function deployExample(cwd, example, callback) {
  fs.copy(`${__dirname}/../examples/${example}`, `${cwd}/${example}`, (err) => {
    if (err) throw err;
    fs.remove(`${cwd}/${example}/node_modules`, rmErr => {
      if (rmErr) throw rmErr;
      fs.mkdir(`${cwd}/${example}/node_modules`, mkdirErr => {
        if (mkdirErr) throw mkdirErr;
        fs.symlink(
          `${__dirname}/..`,
          `${cwd}/${example}/node_modules/serverless-kubeless`,
          (linkErr) => {
            if (linkErr) throw linkErr;
            exec('serverless deploy', { cwd: `${cwd}/${example}` }, (deployErr, stdout) => {
              if (deployErr) {
                console.error(`ERROR: ${example} failed to be deployed:\n${stdout}\n${deployErr}`);
              }
              callback();
            });
          }
        );
      });
    });
  });
}
function removeExample(cwd, example, callback) {
  exec('serverless remove', { cwd: `${cwd}/${example}` }, (removeErr) => {
    if (removeErr) throw removeErr;
    fs.remove(cwd, (rmErr) => {
      if (rmErr) throw rmErr;
      callback();
    });
  });
}

function getURL(info, regexp) {
  let URL = info.match(regexp || /URL:\s+(.*)/)[1];
  if (URL.match('API_URL')) {
    URL = URL.replace(
      'API_URL',
      helpers.getKubernetesAPIURL(helpers.loadKubeConfig()).replace(/:[0-9]+$/, ''));
  }
  return URL;
}

function postWithRedirect(url, body, callback) {
  request.post({ url, body, strictSSL: false }, (err, res) => {
    if (res.statusCode === 301) {
      request.post({ url: res.headers.location, body, strictSSL: false }, (errR, resR) => {
        callback(errR, resR);
      });
    } else {
      callback(err, res);
    }
  });
}

describe('Examples', () => {
  let cwd = null;

  describe('event-trigger-python', function () {
    this.timeout(10000);
    before(function (done) {
      this.timeout(300000);
      cwd = path.join('/tmp', moment().valueOf().toString());
      fs.mkdirSync(cwd);
      deployExample(cwd, 'event-trigger-python', done);
    });
    after(function (done) {
      this.timeout(300000);
      removeExample(cwd, 'event-trigger-python', done);
    });
    it('should get a submmited message "hello world"', (done) => {
      exec('kubeless topic publish --topic hello_topic --data "hello world"', (err, stdout) => {
        if (err) {
          console.error(stdout);
          throw err;
        }
        exec(
          'serverless logs -f events',
          { cwd: `${cwd}/event-trigger-python` },
          (eerr, logs) => {
            if (eerr) throw eerr;
            expect(logs).to.contain('hello world');
            done();
          }
        );
      });
    });
  });
  describe('get-python', function () {
    this.timeout(10000);
    before(function (done) {
      this.timeout(300000);
      cwd = path.join('/tmp', moment().valueOf().toString());
      fs.mkdirSync(cwd);
      deployExample(cwd, 'get-python', done);
    });
    after(function (done) {
      this.timeout(300000);
      removeExample(cwd, 'get-python', done);
    });
    it('should return a "hello world"', (done) => {
      exec('serverless invoke -f hello -l', { cwd: `${cwd}/get-python` }, (err, stdout) => {
        if (err) throw err;
        expect(stdout).to.contain('hello world');
        done();
      });
    });
  });
  describe('get-ruby', function () {
    this.timeout(10000);
    before(function (done) {
      this.timeout(300000);
      cwd = path.join('/tmp', moment().valueOf().toString());
      fs.mkdirSync(cwd);
      deployExample(cwd, 'get-ruby', done);
    });
    after(function (done) {
      this.timeout(300000);
      done();
      removeExample(cwd, 'get-ruby', done);
    });
    it('should return the latest kubeless version', (done) => {
      exec('serverless invoke -f version -l', { cwd: `${cwd}/get-ruby` }, (err, stdout) => {
        if (err) throw err;
        expect(stdout).to.match(/[0-9]+\.[0-9]+\.[0-9]+/);
        done();
      });
    });
  });
  describe('http-custom-path', function () {
    this.timeout(10000);
    before(function (done) {
      this.timeout(300000);
      cwd = path.join('/tmp', moment().valueOf().toString());
      fs.mkdirSync(cwd);
      deployExample(cwd, 'http-custom-path', () => {
        setTimeout(done, 15000);
      });
    });
    after(function (done) {
      this.timeout(300000);
      removeExample(cwd, 'http-custom-path', done);
    });
    it('should return a "hello world" in a subpath', (done) => {
      exec('serverless info', { cwd: `${cwd}/http-custom-path` }, (err, stdout) => {
        if (err) throw err;
        const URL = getURL(stdout);
        expect(URL).to.match(/.*\/hello/);
        request.get({ url: URL, strictSSL: false }, (gerr, res) => {
          if (gerr) throw gerr;
          expect(res.body).to.contain('hello world');
          done();
        });
      });
    });
  });
  describe('multi-python', function () {
    this.timeout(10000);
    before(function (done) {
      this.timeout(300000);
      cwd = path.join('/tmp', moment().valueOf().toString());
      fs.mkdirSync(cwd);
      deployExample(cwd, 'multi-python', done);
    });
    after(function (done) {
      this.timeout(300000);
      removeExample(cwd, 'multi-python', done);
    });
    it('should return "foo"', (done) => {
      exec(
        'serverless invoke -f foo -l --data \'{"hello": "world"}\'',
        { cwd: `${cwd}/multi-python` },
        (err, stdout) => {
          if (err) throw err;
          expect(stdout).to.contain('foo');
          done();
        }
      );
    });
    it('should return "bar"', (done) => {
      exec(
        'serverless invoke -f bar -l --data \'{"hello": "world"}\'',
        { cwd: `${cwd}/multi-python` },
        (err, stdout) => {
          if (err) throw err;
          expect(stdout).to.contain('bar');
          done();
        }
      );
    });
  });
  describe('post-nodejs', function () {
    this.timeout(10000);
    before(function (done) {
      this.timeout(300000);
      cwd = path.join('/tmp', moment().valueOf().toString());
      fs.mkdirSync(cwd);
      deployExample(cwd, 'post-nodejs', done);
    });
    after(function (done) {
      this.timeout(300000);
      removeExample(cwd, 'post-nodejs', done);
    });
    it('should return "Hello world"', (done) => {
      exec(
        'serverless invoke -f capitalize --data "hello world" -l',
        { cwd: `${cwd}/post-nodejs` },
        (err, stdout) => {
          if (err) throw err;
          expect(stdout).to.contain('Hello world');
          done();
        }
      );
    });
  });
  describe('post-python', function () {
    this.timeout(10000);
    before(function (done) {
      this.timeout(300000);
      cwd = path.join('/tmp', moment().valueOf().toString());
      fs.mkdirSync(cwd);
      deployExample(cwd, 'post-python', done);
    });
    after(function (done) {
      this.timeout(300000);
      removeExample(cwd, 'post-python', done);
    });
    it('should return a the request', (done) => {
      exec(
        'serverless invoke -f echo --data \'{"hello": "world"}\' -l',
        { cwd: `${cwd}/post-python` },
        (err, stdout) => {
          if (err) throw err;
          expect(stdout).to.contain('{ hello: \'world\' }');
          done();
        }
      );
    });
  });
  describe('post-ruby', function () {
    this.timeout(10000);
    before(function (done) {
      this.timeout(300000);
      cwd = path.join('/tmp', moment().valueOf().toString());
      fs.mkdirSync(cwd);
      deployExample(cwd, 'post-ruby', done);
    });
    after(function (done) {
      this.timeout(300000);
      removeExample(cwd, 'post-ruby', done);
    });
    it('should play ping-pong"', (done) => {
      exec(
        'serverless invoke -f ping --data "ping" -l',
        { cwd: `${cwd}/post-ruby` },
        (err, stdout) => {
          if (err) throw err;
          expect(stdout).to.contain('pong');
          done();
        }
      );
    });
  });
  describe('todo-app', function () {
    this.timeout(10000);
    let info = '';
    let id = null;

    before(function (done) {
      this.timeout(300000);
      cwd = path.join('/tmp', moment().valueOf().toString());
      fs.mkdirSync(cwd);
      // We need to deploy a MongoDB for the todo-app example
      exec(
        'curl -sL https://raw.githubusercontent.com/bitnami/bitnami-docker-mongodb/3.4.7-r0/kubernetes.yml',
        (err, manifest) => {
          if (err) {
            console.error('ERROR: Unable to download mongodb manifest');
          } else {
            fs.writeFile(`${cwd}/mongodb.yaml`, manifest, (werr) => {
              if (werr) throw werr;
              exec(`kubectl create -f ${cwd}/mongodb.yaml`, (kerr) => {
                if (kerr) {
                  console.error(`ERROR: Unable to deploy the mongoDB manifest: ${kerr.message}`);
                }
                const wait = setInterval(() => {
                  exec('kubectl get pods', (gerr, stdout) => {
                    if (gerr) throw gerr;
                    if (stdout.match(/mongodb-.*Running/)) {
                      clearInterval(wait);
                      deployExample(cwd, 'todo-app/backend', () => {
                        exec(
                          'serverless info',
                          { cwd: `${cwd}/todo-app/backend` },
                          (infoerr, output) => {
                            if (err) throw err;
                            info = output;
                            setTimeout(done, 15000);
                          }
                        );
                      });
                    }
                  });
                }, 2000);
              });
            });
          }
        }
      );
    });

    after(function (done) {
      this.timeout(300000);
      exec(`kubectl delete -f ${cwd}/mongodb.yaml`, (kerr) => {
        if (kerr) {
          console.error(`ERROR: Unable to remove the mongoDB manifest: ${kerr.message}`);
        }
        removeExample(cwd, 'todo-app/backend', done);
      });
      done();
    });
    it('should create a TODO', (done) => {
      const URL = getURL(info, /Service Information "create"\n(?:.*\n)*?URL:\s+(.*)/);
      expect(URL).to.match(/.*\/create/);
      postWithRedirect(URL, '{"body": "test"}', (err, res) => {
        if (err) throw err;
        const response = JSON.parse(res.body);
        expect(response).to.contain.keys(['body', 'id', 'updatedAt']);
        expect(response.body).to.be.eql('test');
        id = response.id;
        done();
      });
    });
    it('should read all the TODOs', (done) => {
      const URL = getURL(info, /Service Information "read-all"\n(?:.*\n)*?URL:\s+(.*)/);
      expect(URL).to.match(/.*\/read-all/);
      request.get({ url: URL, strictSSL: false }, (err, res) => {
        if (err) throw err;
        const response = JSON.parse(res.body);
        expect(response).to.be.an('array').with.length(1);
        expect(response[0]).to.contain.keys(['body', 'id', 'updatedAt']);
        expect(response[0].body).to.be.eql('test');
        done();
      });
    });
    it('should read one TODO', (done) => {
      const URL = getURL(info, /Service Information "read-one"\n(?:.*\n)*?URL:\s+(.*)/m);
      expect(URL).to.match(/.*\/read/);
      request.get({ url: `${URL}?id=${id}`, strictSSL: false }, (err, res) => {
        if (err) throw err;
        const response = JSON.parse(res.body);
        expect(response).to.contain.keys(['body', 'id', 'updatedAt']);
        expect(response.body).to.be.eql('test');
        done();
      });
    });
    it('should update one TODO', (done) => {
      const URL = getURL(info, /Service Information "update"\n(?:.*\n)*?URL:\s+(.*)/m);
      expect(URL).to.match(/.*\/update/);
      postWithRedirect(`${URL}?id=${id}`, '{"body": "new-test"}', (err, res) => {
        if (err) throw err;
        const response = JSON.parse(res.body);
        expect(response).to.contain.keys(['body', 'id', 'updatedAt']);
        expect(response.body).to.be.eql('new-test');
        id = response.id;
        done();
      });
    });
    it('should delete one TODO', (done) => {
      const URL = getURL(info, /Service Information "delete"\n(?:.*\n)*?URL:\s+(.*)/m);
      expect(URL).to.match(/.*\/delete/);
      request.get({ url: `${URL}?id=${id}`, strictSSL: false }, (err, res) => {
        if (err) throw err;
        const response = JSON.parse(res.body);
        expect(response).to.contain.keys(['body', 'id', 'updatedAt']);
        expect(response.body).to.be.eql('new-test');
        done();
      });
    });
  });
});
<commit_msg>Fix ruby test<commit_after>/*
 Copyright 2017 Bitnami.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
*/

'use strict';

const exec = require('child_process').exec;
const expect = require('chai').expect;
const fs = require('fs-extra');
const helpers = require('../lib/helpers');
const moment = require('moment');
const path = require('path');
const request = require('request');

function deployExample(cwd, example, callback) {
  fs.copy(`${__dirname}/../examples/${example}`, `${cwd}/${example}`, (err) => {
    if (err) throw err;
    fs.remove(`${cwd}/${example}/node_modules`, rmErr => {
      if (rmErr) throw rmErr;
      fs.mkdir(`${cwd}/${example}/node_modules`, mkdirErr => {
        if (mkdirErr) throw mkdirErr;
        fs.symlink(
          `${__dirname}/..`,
          `${cwd}/${example}/node_modules/serverless-kubeless`,
          (linkErr) => {
            if (linkErr) throw linkErr;
            exec('serverless deploy', { cwd: `${cwd}/${example}` }, (deployErr, stdout) => {
              if (deployErr) {
                console.error(`ERROR: ${example} failed to be deployed:\n${stdout}\n${deployErr}`);
              }
              callback();
            });
          }
        );
      });
    });
  });
}
function removeExample(cwd, example, callback) {
  exec('serverless remove', { cwd: `${cwd}/${example}` }, (removeErr) => {
    if (removeErr) throw removeErr;
    fs.remove(cwd, (rmErr) => {
      if (rmErr) throw rmErr;
      callback();
    });
  });
}

function getURL(info, regexp) {
  let URL = info.match(regexp || /URL:\s+(.*)/)[1];
  if (URL.match('API_URL')) {
    URL = URL.replace(
      'API_URL',
      helpers.getKubernetesAPIURL(helpers.loadKubeConfig()).replace(/:[0-9]+$/, ''));
  }
  return URL;
}

function postWithRedirect(url, body, callback) {
  request.post({ url, body, strictSSL: false }, (err, res) => {
    if (res.statusCode === 301) {
      request.post({ url: res.headers.location, body, strictSSL: false }, (errR, resR) => {
        callback(errR, resR);
      });
    } else {
      callback(err, res);
    }
  });
}

describe('Examples', () => {
  let cwd = null;

  describe('event-trigger-python', function () {
    this.timeout(10000);
    before(function (done) {
      this.timeout(300000);
      cwd = path.join('/tmp', moment().valueOf().toString());
      fs.mkdirSync(cwd);
      deployExample(cwd, 'event-trigger-python', done);
    });
    after(function (done) {
      this.timeout(300000);
      removeExample(cwd, 'event-trigger-python', done);
    });
    it('should get a submmited message "hello world"', (done) => {
      exec('kubeless topic publish --topic hello_topic --data "hello world"', (err, stdout) => {
        if (err) {
          console.error(stdout);
          throw err;
        }
        exec(
          'serverless logs -f events',
          { cwd: `${cwd}/event-trigger-python` },
          (eerr, logs) => {
            if (eerr) throw eerr;
            expect(logs).to.contain('hello world');
            done();
          }
        );
      });
    });
  });
  describe('get-python', function () {
    this.timeout(10000);
    before(function (done) {
      this.timeout(300000);
      cwd = path.join('/tmp', moment().valueOf().toString());
      fs.mkdirSync(cwd);
      deployExample(cwd, 'get-python', done);
    });
    after(function (done) {
      this.timeout(300000);
      removeExample(cwd, 'get-python', done);
    });
    it('should return a "hello world"', (done) => {
      exec('serverless invoke -f hello -l', { cwd: `${cwd}/get-python` }, (err, stdout) => {
        if (err) throw err;
        expect(stdout).to.contain('hello world');
        done();
      });
    });
  });
  describe('get-ruby', function () {
    this.timeout(10000);
    before(function (done) {
      this.timeout(300000);
      cwd = path.join('/tmp', moment().valueOf().toString());
      fs.mkdirSync(cwd);
      deployExample(cwd, 'get-ruby', done);
    });
    after(function (done) {
      this.timeout(300000);
      removeExample(cwd, 'get-ruby', done);
    });
    it('should return the latest kubeless version', (done) => {
      exec('serverless invoke -f version -l', { cwd: `${cwd}/get-ruby` }, (err, stdout) => {
        if (err) throw err;
        expect(stdout).to.match(/[0-9]+\.[0-9]+\.[0-9]+/);
        done();
      });
    });
  });
  describe('http-custom-path', function () {
    this.timeout(10000);
    before(function (done) {
      this.timeout(300000);
      cwd = path.join('/tmp', moment().valueOf().toString());
      fs.mkdirSync(cwd);
      deployExample(cwd, 'http-custom-path', () => {
        setTimeout(done, 15000);
      });
    });
    after(function (done) {
      this.timeout(300000);
      removeExample(cwd, 'http-custom-path', done);
    });
    it('should return a "hello world" in a subpath', (done) => {
      exec('serverless info', { cwd: `${cwd}/http-custom-path` }, (err, stdout) => {
        if (err) throw err;
        const URL = getURL(stdout);
        expect(URL).to.match(/.*\/hello/);
        request.get({ url: URL, strictSSL: false }, (gerr, res) => {
          if (gerr) throw gerr;
          expect(res.body).to.contain('hello world');
          done();
        });
      });
    });
  });
  describe('multi-python', function () {
    this.timeout(10000);
    before(function (done) {
      this.timeout(300000);
      cwd = path.join('/tmp', moment().valueOf().toString());
      fs.mkdirSync(cwd);
      deployExample(cwd, 'multi-python', done);
    });
    after(function (done) {
      this.timeout(300000);
      removeExample(cwd, 'multi-python', done);
    });
    it('should return "foo"', (done) => {
      exec(
        'serverless invoke -f foo -l --data \'{"hello": "world"}\'',
        { cwd: `${cwd}/multi-python` },
        (err, stdout) => {
          if (err) throw err;
          expect(stdout).to.contain('foo');
          done();
        }
      );
    });
    it('should return "bar"', (done) => {
      exec(
        'serverless invoke -f bar -l --data \'{"hello": "world"}\'',
        { cwd: `${cwd}/multi-python` },
        (err, stdout) => {
          if (err) throw err;
          expect(stdout).to.contain('bar');
          done();
        }
      );
    });
  });
  describe('post-nodejs', function () {
    this.timeout(10000);
    before(function (done) {
      this.timeout(300000);
      cwd = path.join('/tmp', moment().valueOf().toString());
      fs.mkdirSync(cwd);
      deployExample(cwd, 'post-nodejs', done);
    });
    after(function (done) {
      this.timeout(300000);
      removeExample(cwd, 'post-nodejs', done);
    });
    it('should return "Hello world"', (done) => {
      exec(
        'serverless invoke -f capitalize --data "hello world" -l',
        { cwd: `${cwd}/post-nodejs` },
        (err, stdout) => {
          if (err) throw err;
          expect(stdout).to.contain('Hello world');
          done();
        }
      );
    });
  });
  describe('post-python', function () {
    this.timeout(10000);
    before(function (done) {
      this.timeout(300000);
      cwd = path.join('/tmp', moment().valueOf().toString());
      fs.mkdirSync(cwd);
      deployExample(cwd, 'post-python', done);
    });
    after(function (done) {
      this.timeout(300000);
      removeExample(cwd, 'post-python', done);
    });
    it('should return a the request', (done) => {
      exec(
        'serverless invoke -f echo --data \'{"hello": "world"}\' -l',
        { cwd: `${cwd}/post-python` },
        (err, stdout) => {
          if (err) throw err;
          expect(stdout).to.contain('{ hello: \'world\' }');
          done();
        }
      );
    });
  });
  describe('post-ruby', function () {
    this.timeout(10000);
    before(function (done) {
      this.timeout(300000);
      cwd = path.join('/tmp', moment().valueOf().toString());
      fs.mkdirSync(cwd);
      deployExample(cwd, 'post-ruby', done);
    });
    after(function (done) {
      this.timeout(300000);
      removeExample(cwd, 'post-ruby', done);
    });
    it('should play ping-pong"', (done) => {
      exec(
        'serverless invoke -f ping --data "ping" -l',
        { cwd: `${cwd}/post-ruby` },
        (err, stdout) => {
          if (err) throw err;
          expect(stdout).to.contain('pong');
          done();
        }
      );
    });
  });
  describe('todo-app', function () {
    this.timeout(10000);
    let info = '';
    let id = null;

    before(function (done) {
      this.timeout(300000);
      cwd = path.join('/tmp', moment().valueOf().toString());
      fs.mkdirSync(cwd);
      // We need to deploy a MongoDB for the todo-app example
      exec(
        'curl -sL https://raw.githubusercontent.com/bitnami/bitnami-docker-mongodb/3.4.7-r0/kubernetes.yml',
        (err, manifest) => {
          if (err) {
            console.error('ERROR: Unable to download mongodb manifest');
          } else {
            fs.writeFile(`${cwd}/mongodb.yaml`, manifest, (werr) => {
              if (werr) throw werr;
              exec(`kubectl create -f ${cwd}/mongodb.yaml`, (kerr) => {
                if (kerr) {
                  console.error(`ERROR: Unable to deploy the mongoDB manifest: ${kerr.message}`);
                }
                const wait = setInterval(() => {
                  exec('kubectl get pods', (gerr, stdout) => {
                    if (gerr) throw gerr;
                    if (stdout.match(/mongodb-.*Running/)) {
                      clearInterval(wait);
                      deployExample(cwd, 'todo-app/backend', () => {
                        exec(
                          'serverless info',
                          { cwd: `${cwd}/todo-app/backend` },
                          (infoerr, output) => {
                            if (err) throw err;
                            info = output;
                            setTimeout(done, 15000);
                          }
                        );
                      });
                    }
                  });
                }, 2000);
              });
            });
          }
        }
      );
    });

    after(function (done) {
      this.timeout(300000);
      exec(`kubectl delete -f ${cwd}/mongodb.yaml`, (kerr) => {
        if (kerr) {
          console.error(`ERROR: Unable to remove the mongoDB manifest: ${kerr.message}`);
        }
        removeExample(cwd, 'todo-app/backend', done);
      });
      done();
    });
    it('should create a TODO', (done) => {
      const URL = getURL(info, /Service Information "create"\n(?:.*\n)*?URL:\s+(.*)/);
      expect(URL).to.match(/.*\/create/);
      postWithRedirect(URL, '{"body": "test"}', (err, res) => {
        if (err) throw err;
        const response = JSON.parse(res.body);
        expect(response).to.contain.keys(['body', 'id', 'updatedAt']);
        expect(response.body).to.be.eql('test');
        id = response.id;
        done();
      });
    });
    it('should read all the TODOs', (done) => {
      const URL = getURL(info, /Service Information "read-all"\n(?:.*\n)*?URL:\s+(.*)/);
      expect(URL).to.match(/.*\/read-all/);
      request.get({ url: URL, strictSSL: false }, (err, res) => {
        if (err) throw err;
        const response = JSON.parse(res.body);
        expect(response).to.be.an('array').with.length(1);
        expect(response[0]).to.contain.keys(['body', 'id', 'updatedAt']);
        expect(response[0].body).to.be.eql('test');
        done();
      });
    });
    it('should read one TODO', (done) => {
      const URL = getURL(info, /Service Information "read-one"\n(?:.*\n)*?URL:\s+(.*)/m);
      expect(URL).to.match(/.*\/read/);
      request.get({ url: `${URL}?id=${id}`, strictSSL: false }, (err, res) => {
        if (err) throw err;
        const response = JSON.parse(res.body);
        expect(response).to.contain.keys(['body', 'id', 'updatedAt']);
        expect(response.body).to.be.eql('test');
        done();
      });
    });
    it('should update one TODO', (done) => {
      const URL = getURL(info, /Service Information "update"\n(?:.*\n)*?URL:\s+(.*)/m);
      expect(URL).to.match(/.*\/update/);
      postWithRedirect(`${URL}?id=${id}`, '{"body": "new-test"}', (err, res) => {
        if (err) throw err;
        const response = JSON.parse(res.body);
        expect(response).to.contain.keys(['body', 'id', 'updatedAt']);
        expect(response.body).to.be.eql('new-test');
        id = response.id;
        done();
      });
    });
    it('should delete one TODO', (done) => {
      const URL = getURL(info, /Service Information "delete"\n(?:.*\n)*?URL:\s+(.*)/m);
      expect(URL).to.match(/.*\/delete/);
      request.get({ url: `${URL}?id=${id}`, strictSSL: false }, (err, res) => {
        if (err) throw err;
        const response = JSON.parse(res.body);
        expect(response).to.contain.keys(['body', 'id', 'updatedAt']);
        expect(response.body).to.be.eql('new-test');
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>// Webflow code to submit form

const verification = (t, e, n, i) => {
	let r = null, k = /e(-)?mail/i, _ = /^\S+@\S+$/;
	return e === 'password' ? r = 'Passwords cannot be submitted.' : getAttribute(t,'required') && (i ? (k.test(n) || k.test(getAttribute(t,'type'))) && (_.test(i) || (r = 'Please enter a valid email address for: ' + n)) : r = 'Please fill out the required field: ' + n), r
}

const conversion = (e, n) => {
	let i = null
	for (r=0; r<e[0].elements.length; r++) {
		console.log('test #1')
		const o = e[0].elements[r][0]
		if (!o) continue
		let a = getElementById(o),
			s = getAttribute(a,'type'),
			u = getAttribute(a,'data-name') || getAttribute(a,'name') || 'Field ' + (r + 1),
			l = getValue(a)
		console.log('test #2')
		if (s === 'checkbox' && (l = isChecked(a)), s === 'radio') {
			if (n[u] === null || typeof n[u] == 'string' || s == 'submit') return;
			l = getValue(e.find('input[name="' + getAttribute(a,'name') + '"]:checked')) || null
		}
		console.log('test #3')
		typeof l == 'string' && (l = l.trim()), n[u] = l, i = i || verification(a, s, u, l)
		console.log('test #4')
	}
	return n = n || {}, i
}

const createForm = () => {
	let formData = {
		name: page() === 'Event' ? 'Event Registration' : 'Custom Charge',
		source: window.location.href,
		test: false,
		fields: {},
		dolphin: false
	}
	let error = conversion(page() === 'Event' ? getElementById(eventForm) : getElementById(customForm), formData.fields)
	if (error) {
		throw error
	}
	console.log(formData)
	return formData
}<commit_msg>Update.<commit_after>// Webflow code to submit form

const verification = (t, e, n, i) => {
	let r = null, k = /e(-)?mail/i, _ = /^\S+@\S+$/;
	return e === 'password' ? r = 'Passwords cannot be submitted.' : getAttribute(t,'required') && (i ? (k.test(n) || k.test(getAttribute(t,'type'))) && (_.test(i) || (r = 'Please enter a valid email address for: ' + n)) : r = 'Please fill out the required field: ' + n), r
}

const conversion = (e, n) => {
	let i = null
	for (r=0; r<e[0].elements.length; r++) {
		console.log('test #1')
		const o = e[0].elements[r][0]
		if (!o) continue
		console.log(o)
		let a = getElementById(o),
			s = getAttribute(a,'type'),
			u = getAttribute(a,'data-name') || getAttribute(a,'name') || 'Field ' + (r + 1),
			l = getValue(a)
		console.log('test #2')
		if (s === 'checkbox' && (l = isChecked(a)), s === 'radio') {
			if (n[u] === null || typeof n[u] == 'string' || s == 'submit') return;
			l = getValue(e.find('input[name="' + getAttribute(a,'name') + '"]:checked')) || null
		}
		console.log('test #3')
		typeof l == 'string' && (l = l.trim()), n[u] = l, i = i || verification(a, s, u, l)
		console.log('test #4')
	}
	return n = n || {}, i
}

const createForm = () => {
	let formData = {
		name: page() === 'Event' ? 'Event Registration' : 'Custom Charge',
		source: window.location.href,
		test: false,
		fields: {},
		dolphin: false
	}
	let error = conversion(page() === 'Event' ? getElementById(eventForm) : getElementById(customForm), formData.fields)
	if (error) {
		throw error
	}
	console.log(formData)
	return formData
}<|endoftext|>


<commit_before>'use strict'

const t = require('tap')
const factory = require('../')

t.test('issue-63', (t) => {
  t.plan(1)
  const fmw = factory()

  fmw.on('GET', '/foo/:id(a', function () {})
})
<commit_msg>Update issue-63 test case<commit_after>'use strict'

const t = require('tap')
const factory = require('../')

t.test('issue-63', (t) => {
  t.plan(1)

  const fmw = factory()

  t.throws(function () {
    fmw.on('GET', '/foo/:id(a', function () {})
  })
})
<|endoftext|>


<commit_before>const assert = require('assert');
const sinon = require('sinon');

const Downspout = require('../../lib/Downspout');

describe('lib/Downspout', () => {
  beforeEach(() => {
    sinon.stub(Downspout, '_getDefaultIsNoisy', () => true);
  });

  afterEach(() => {
    Downspout._getDefaultIsNoisy.restore();
  });

  describe('constructor', () => {
    it('should be created by only use-case logics', () => {
      const downspout = new Downspout({
        createFoo: () => {},
      });
      assert.strictEqual(downspout instanceof Downspout, true);
    });
  });

  describe('Emitting events by use-case executions', () => {
    it('should emit a "resolved" event after an use-case execution', done => {
      const downspout = new Downspout({
        createFoo: () => 'FOO',
      });
      downspout.on('execution:resolved', ({ result }) => {
        assert.strictEqual(result, 'FOO');
        done();
      });
      downspout.execute('createFoo');
    });

    it('should emit some "execution:resolved" events after some use-case executions', done => {
      let counter = 0;
      const downspout = new Downspout({
        count: () => counter += 1,
      });

      const results = [];
      downspout.on('execution:resolved', ({ result }) => {
        results.push(result);
        if (results.length === 3) {
          assert.deepStrictEqual([1, 2, 3], results);
          done();
        }
      });

      downspout.execute('count');
      downspout.execute('count');
      downspout.execute('count');
    });

    it('should emit a "rejected" event after an use-case execution failure', done => {
      const downspout = new Downspout({
        createFoo: () => { throw new Error('FOO?'); },
      }, { isNoisy: false });
      downspout.on('execution:rejected', ({ error }) => {
        assert.strictEqual(error.message, 'FOO?');
        done();
      });
      downspout.execute('createFoo');
    });

    it('should not execute use-cases after an use-case execution failure', done => {
      let results = [];
      const downspout = new Downspout({
        ng: () => { throw new Error('NG'); },
        ok: () => 'OK',
      }, { isNoisy: false });
      downspout.on('execution:rejected', ({ error }) => {
        results.push(error.message);
      });
      downspout.on('execution:resolved', ({ result }) => {
        results.push(result);
      });

      downspout.execute('ng');
      downspout.execute('ok');

      setTimeout(() => {
        assert.deepStrictEqual(results, ['NG']);
        done();
      }, 100);
    });
  });

  describe('Queuing of use-case executions', () => {
    it('should wait the previous use-case execution', done => {
      const downspout = new Downspout({
        first: () => new Promise(resolved => {
          setTimeout(resolved, 100);
        }),
        second: () => {},
        third: () => {},
      });

      const results = [];
      downspout.on('execution:resolved', ({ useCaseName }) => {
        results.push(useCaseName);
        if (results.length === 3) {
          assert.deepStrictEqual(results, ['first', 'second', 'third']);
          done();
        }
      });

      downspout.execute('first');
      downspout.execute('second');
      downspout.execute('third');
    });
  });

  describe('Use-case arguments', () => {
    it('can receive arguments in each use-cases', done => {
      const downspout = new Downspout({
        add: (context, a, b) => a + b
      });
      downspout.on('execution:resolved', ({ result }) => {
        assert.strictEqual(result, 3);
        done();
      });
      downspout.execute('add', 1, 2);
    });
  });

  describe('Fork other use-cases', () => {
    it('can execute other use-case by using the `utils.fork`', done => {
      const downspout = new Downspout({
        lockUIs: () => 'LOCKED',
        unlockUIs: () => 'UNLOCKED',
        addTodos: (context, todos) => todos,
        fetchTodos: ({ utils }) => {
          utils.fork('lockUIs');

          setTimeout(() => {
            utils.fork('addTodos', ['TODO1', 'TODO2']);
            utils.fork('unlockUIs');
          }, 100);

          return 'START_FETCHING';
        },
      });

      const results = [];
      downspout.on('execution:resolved', ({ result }) => {
        results.push(result);
        if (results.length === 4) {
          assert.deepStrictEqual(results, ['START_FETCHING', 'LOCKED', ['TODO1', 'TODO2'], 'UNLOCKED']);
          done();
        }
      });

      downspout.execute('fetchTodos');
    });

    it('should be executed in the order in which they are called', done => {
      const downspout = new Downspout({
        first: () => {},
        second: ({ utils }) => {
          utils.fork('forth');
          utils.fork('fifth');
        },
        third: () => {},
        forth: () => {},
        fifth: () => {},
      });

      const results = [];
      downspout.on('execution:resolved', ({ useCaseName }) => {
        results.push(useCaseName);
        if (results.length === 5) {
          assert.deepStrictEqual(results, ['first', 'second', 'third', 'forth', 'fifth']);
          done();
        }
      });

      downspout.execute('first');
      downspout.execute('second');
      downspout.execute('third');
    });
  });

  describe('Using the `routes` option', () => {
    it('can execute one use-case via plural routes', done => {
      const downspout = new Downspout({
        createTodo: (context, title) => title,
      }, {
        routes: {
          CLICK_TODO_REGISTRATION_BUTTON_1: 'createTodo',
          CLICK_TODO_REGISTRATION_BUTTON_2: 'createTodo',
        },
      });

      const results = [];
      downspout.on('execution:resolved', ({ result }) => {
        results.push(result);
        if (results.length === 2) {
          assert.deepStrictEqual(results, ['Yaruzo!', 'Ashita kara ganbaru..']);
          done();
        }
      });

      downspout.dispatch('CLICK_TODO_REGISTRATION_BUTTON_1', 'Yaruzo!');
      downspout.dispatch('CLICK_TODO_REGISTRATION_BUTTON_2', 'Ashita kara ganbaru..');
    });

    it('can set fixed arguments', done => {
      const downspout = new Downspout({
        changePage: (context, pageId) => pageId,
      }, {
        routes: {
          CLICK_HOME_BUTTON: ['changePage', 'HOME'],
          CLICK_TODOS_BUTTON: ['changePage', 'TODOS'],
        },
      });

      const results = [];
      downspout.on('execution:resolved', ({ result }) => {
        results.push(result);
        if (results.length === 3) {
          assert.deepStrictEqual(results, ['TOP', 'HOME', 'TODOS']);
          done();
        }
      });

      downspout.execute('changePage', 'TOP');
      downspout.dispatch('CLICK_HOME_BUTTON');
      downspout.dispatch('CLICK_TODOS_BUTTON');
    });
  });

  describe('Using the `context` option', () => {
    it('should share the passed object in use-cases', done => {
      const dependedSingletonInstances = {
        fooModel: { value: 0 },
      };

      const downspout = new Downspout({
        updateFoo: (context, value) => {
          context.fooModel.value = value;
        },
        doubleFoo: (context) => {
          context.fooModel.value *= 2;
        },
      }, {
        context: dependedSingletonInstances,
      });

      const results = [];
      downspout.on('execution:resolved', ({ context }) => {
        results.push(context.fooModel.value);
        if (results.length === 2) {
          assert.deepStrictEqual(results, [3, 6]);
          done();
        }
      });

      downspout.execute('updateFoo', 3);
      downspout.execute('doubleFoo');
    });
  });

  describe('EVENT_NAMES', () => {
    it('USE_CASE_EXECUTION_RESOLVED', done => {
      const downspout = new Downspout({
        foo: () => {},
      });
      downspout.on(Downspout.EVENT_NAMES.USE_CASE_EXECUTION_RESOLVED, () => {
        done();
      });
      downspout.execute('foo');
    });

    it('USE_CASE_EXECUTION_REJECTED', done => {
      const downspout = new Downspout({
        foo: () => { throw new Error(''); },
      }, { isNoisy: false });
      downspout.on(Downspout.EVENT_NAMES.USE_CASE_EXECUTION_REJECTED, () => {
        done();
      });
      downspout.execute('foo');
    });
  });

  describe('generateExecutor', () => {
    it('can generate a bound function', done => {
      const downspout = new Downspout({
        foo: () => {},
      });
      downspout.on('execution:resolved', ({ useCaseName }) => {
        assert.strictEqual(useCaseName, 'foo');
        done();
      });

      const execute = downspout.generateExecutor();
      execute('foo');
    });
  });

  describe('generateDispatcher', () => {
    it('can generate a bound function', done => {
      const downspout = new Downspout({
        foo: () => {},
      }, {
        routes: {
          CLICK_FOO: 'foo',
        },
      });
      downspout.on('execution:resolved', ({ useCaseName }) => {
        assert.strictEqual(useCaseName, 'foo');
        done();
      });

      const dispatch = downspout.generateDispatcher();
      dispatch('CLICK_FOO');
    });
  });
});
<commit_msg>Fix a test case name<commit_after>const assert = require('assert');
const sinon = require('sinon');

const Downspout = require('../../lib/Downspout');

describe('lib/Downspout', () => {
  beforeEach(() => {
    sinon.stub(Downspout, '_getDefaultIsNoisy', () => true);
  });

  afterEach(() => {
    Downspout._getDefaultIsNoisy.restore();
  });

  describe('constructor', () => {
    it('should be created by only use-case logics', () => {
      const downspout = new Downspout({
        createFoo: () => {},
      });
      assert.strictEqual(downspout instanceof Downspout, true);
    });
  });

  describe('Emitting events by use-case executions', () => {
    it('should emit a "resolved" event after an use-case execution', done => {
      const downspout = new Downspout({
        createFoo: () => 'FOO',
      });
      downspout.on('execution:resolved', ({ result }) => {
        assert.strictEqual(result, 'FOO');
        done();
      });
      downspout.execute('createFoo');
    });

    it('should emit some "execution:resolved" events after some use-case executions', done => {
      let counter = 0;
      const downspout = new Downspout({
        count: () => counter += 1,
      });

      const results = [];
      downspout.on('execution:resolved', ({ result }) => {
        results.push(result);
        if (results.length === 3) {
          assert.deepStrictEqual([1, 2, 3], results);
          done();
        }
      });

      downspout.execute('count');
      downspout.execute('count');
      downspout.execute('count');
    });

    it('should emit a "rejected" event after an use-case execution failure', done => {
      const downspout = new Downspout({
        createFoo: () => { throw new Error('FOO?'); },
      }, { isNoisy: false });
      downspout.on('execution:rejected', ({ error }) => {
        assert.strictEqual(error.message, 'FOO?');
        done();
      });
      downspout.execute('createFoo');
    });

    it('should not execute use-cases after an use-case execution failure', done => {
      let results = [];
      const downspout = new Downspout({
        ng: () => { throw new Error('NG'); },
        ok: () => 'OK',
      }, { isNoisy: false });
      downspout.on('execution:rejected', ({ error }) => {
        results.push(error.message);
      });
      downspout.on('execution:resolved', ({ result }) => {
        results.push(result);
      });

      downspout.execute('ng');
      downspout.execute('ok');

      setTimeout(() => {
        assert.deepStrictEqual(results, ['NG']);
        done();
      }, 100);
    });
  });

  describe('Queuing of use-case executions', () => {
    it('should wait the previous use-case execution', done => {
      const downspout = new Downspout({
        first: () => new Promise(resolved => {
          setTimeout(resolved, 100);
        }),
        second: () => {},
        third: () => {},
      });

      const results = [];
      downspout.on('execution:resolved', ({ useCaseName }) => {
        results.push(useCaseName);
        if (results.length === 3) {
          assert.deepStrictEqual(results, ['first', 'second', 'third']);
          done();
        }
      });

      downspout.execute('first');
      downspout.execute('second');
      downspout.execute('third');
    });
  });

  describe('Use-case arguments', () => {
    it('can receive arguments in each use-cases', done => {
      const downspout = new Downspout({
        add: (context, a, b) => a + b
      });
      downspout.on('execution:resolved', ({ result }) => {
        assert.strictEqual(result, 3);
        done();
      });
      downspout.execute('add', 1, 2);
    });
  });

  describe('Fork other use-cases', () => {
    it('can execute other use-case by using the `utils.fork`', done => {
      const downspout = new Downspout({
        lockUIs: () => 'LOCKED',
        unlockUIs: () => 'UNLOCKED',
        addTodos: (context, todos) => todos,
        fetchTodos: ({ utils }) => {
          utils.fork('lockUIs');

          setTimeout(() => {
            utils.fork('addTodos', ['TODO1', 'TODO2']);
            utils.fork('unlockUIs');
          }, 100);

          return 'START_FETCHING';
        },
      });

      const results = [];
      downspout.on('execution:resolved', ({ result }) => {
        results.push(result);
        if (results.length === 4) {
          assert.deepStrictEqual(results, ['START_FETCHING', 'LOCKED', ['TODO1', 'TODO2'], 'UNLOCKED']);
          done();
        }
      });

      downspout.execute('fetchTodos');
    });

    it('should be executed in the order in which they are called', done => {
      const downspout = new Downspout({
        first: () => {},
        second: ({ utils }) => {
          utils.fork('forth');
          utils.fork('fifth');
        },
        third: () => {},
        forth: () => {},
        fifth: () => {},
      });

      const results = [];
      downspout.on('execution:resolved', ({ useCaseName }) => {
        results.push(useCaseName);
        if (results.length === 5) {
          assert.deepStrictEqual(results, ['first', 'second', 'third', 'forth', 'fifth']);
          done();
        }
      });

      downspout.execute('first');
      downspout.execute('second');
      downspout.execute('third');
    });
  });

  describe('Using the `routes` option', () => {
    it('can execute one use-case via plural routes', done => {
      const downspout = new Downspout({
        createTodo: (context, title) => title,
      }, {
        routes: {
          CLICK_TODO_REGISTRATION_BUTTON_1: 'createTodo',
          CLICK_TODO_REGISTRATION_BUTTON_2: 'createTodo',
        },
      });

      const results = [];
      downspout.on('execution:resolved', ({ result }) => {
        results.push(result);
        if (results.length === 2) {
          assert.deepStrictEqual(results, ['Yaruzo!', 'Ashita kara ganbaru..']);
          done();
        }
      });

      downspout.dispatch('CLICK_TODO_REGISTRATION_BUTTON_1', 'Yaruzo!');
      downspout.dispatch('CLICK_TODO_REGISTRATION_BUTTON_2', 'Ashita kara ganbaru..');
    });

    it('can set fixed arguments', done => {
      const downspout = new Downspout({
        changePage: (context, pageId) => pageId,
      }, {
        routes: {
          CLICK_HOME_BUTTON: ['changePage', 'HOME'],
          CLICK_TODOS_BUTTON: ['changePage', 'TODOS'],
        },
      });

      const results = [];
      downspout.on('execution:resolved', ({ result }) => {
        results.push(result);
        if (results.length === 3) {
          assert.deepStrictEqual(results, ['TOP', 'HOME', 'TODOS']);
          done();
        }
      });

      downspout.execute('changePage', 'TOP');
      downspout.dispatch('CLICK_HOME_BUTTON');
      downspout.dispatch('CLICK_TODOS_BUTTON');
    });
  });

  describe('Using the `context` option', () => {
    it('should share the passed object among all use-cases', done => {
      const dependedSingletonInstances = {
        fooModel: { value: 0 },
      };

      const downspout = new Downspout({
        updateFoo: (context, value) => {
          context.fooModel.value = value;
        },
        doubleFoo: (context) => {
          context.fooModel.value *= 2;
        },
      }, {
        context: dependedSingletonInstances,
      });

      const results = [];
      downspout.on('execution:resolved', ({ context }) => {
        results.push(context.fooModel.value);
        if (results.length === 2) {
          assert.deepStrictEqual(results, [3, 6]);
          done();
        }
      });

      downspout.execute('updateFoo', 3);
      downspout.execute('doubleFoo');
    });
  });

  describe('EVENT_NAMES', () => {
    it('USE_CASE_EXECUTION_RESOLVED', done => {
      const downspout = new Downspout({
        foo: () => {},
      });
      downspout.on(Downspout.EVENT_NAMES.USE_CASE_EXECUTION_RESOLVED, () => {
        done();
      });
      downspout.execute('foo');
    });

    it('USE_CASE_EXECUTION_REJECTED', done => {
      const downspout = new Downspout({
        foo: () => { throw new Error(''); },
      }, { isNoisy: false });
      downspout.on(Downspout.EVENT_NAMES.USE_CASE_EXECUTION_REJECTED, () => {
        done();
      });
      downspout.execute('foo');
    });
  });

  describe('generateExecutor', () => {
    it('can generate a bound function', done => {
      const downspout = new Downspout({
        foo: () => {},
      });
      downspout.on('execution:resolved', ({ useCaseName }) => {
        assert.strictEqual(useCaseName, 'foo');
        done();
      });

      const execute = downspout.generateExecutor();
      execute('foo');
    });
  });

  describe('generateDispatcher', () => {
    it('can generate a bound function', done => {
      const downspout = new Downspout({
        foo: () => {},
      }, {
        routes: {
          CLICK_FOO: 'foo',
        },
      });
      downspout.on('execution:resolved', ({ useCaseName }) => {
        assert.strictEqual(useCaseName, 'foo');
        done();
      });

      const dispatch = downspout.generateDispatcher();
      dispatch('CLICK_FOO');
    });
  });
});
<|endoftext|>


<commit_before>/**
 * localize.test.js
 */
/* eslint-disable no-magic-numbers, max-nested-callbacks */

import {JSDOM} from "jsdom";
import {assert} from "chai";
import {afterEach, beforeEach, describe, it} from "mocha";
import sinon from "sinon";
import {browser} from "./mocha/setup.js";
import {EXT_LOCALE} from "../src/mjs/constant.js";
import * as mjs from "../src/mjs/localize.js";

describe("localize", () => {
  /**
   * create jsdom
   * @returns {Object} - jsdom instance
   */
  const createJsdom = () => {
    const domstr = "<!DOCTYPE html>";
    const opt = {
      runScripts: "dangerously",
    };
    return new JSDOM(domstr, opt);
  };
  beforeEach(() => {
    global.browser = browser;
  });
  afterEach(() => {
    delete global.browser;
  });

  it("should get browser object", () => {
    assert.isObject(browser, "browser");
  });

  describe("localize attribute value", () => {
    const func = mjs.localizeAttr;
    const globalKeys = ["Node", "NodeList"];
    let window, document;
    beforeEach(() => {
      const dom = createJsdom();
      window = dom && dom.window;
      document = window && window.document;
      for (const key of globalKeys) {
        global[key] = window[key];
      }
      global.window = window;
      global.document = document;
    });
    afterEach(() => {
      window = null;
      document = null;
      for (const key of globalKeys) {
        delete global[key];
      }
      delete global.window;
      delete global.document;
    });

    it("should not call function if no argument given", async () => {
      const i = browser.i18n.getMessage.callCount;
      await func();
      assert.strictEqual(browser.i18n.getMessage.callCount, i, "not called");
    });

    it("should not call function if argument is not an element", async () => {
      const i = browser.i18n.getMessage.callCount;
      await func("foo");
      assert.strictEqual(browser.i18n.getMessage.callCount, i, "not called");
    });

    it("should set attribute", async () => {
      const id = "foo";
      const attrs = {
        alt: "alt",
        ariaLabel: "aria-label",
        href: "href",
        placeholder: "placeholder",
        title: "title",
      };
      const items = Object.entries(attrs);
      const p = document.createElement("p");
      const body = document.querySelector("body");
      for (const [key, value] of items) {
        p.setAttribute(value, "bar");
        browser.i18n.getMessage.withArgs(`${id}_${key}`)
          .returns(`${id}_${key}`);
      }
      p.setAttribute("data-i18n", id);
      body.appendChild(p)
      await func(p);
      for (const [key, value] of items) {
        assert.strictEqual(p.getAttribute(value), `${id}_${key}`, `${value}`);
      }
      browser.i18n.getMessage.flush();
    });

    it("should not set attribute", async () => {
      const id = "";
      const attrs = {
        alt: "alt",
        ariaLabel: "aria-label",
        href: "href",
        placeholder: "placeholder",
        title: "title",
      };
      const items = Object.entries(attrs);
      const p = document.createElement("p");
      const body = document.querySelector("body");
      for (const [key, value] of items) {
        p.setAttribute(value, "bar");
      }
      p.setAttribute("data-i18n", id);
      body.appendChild(p)
      await func(p);
      for (const [key, value] of items) {
        assert.strictEqual(p.getAttribute(value), "bar", `${value}`);
      }
      browser.i18n.getMessage.flush();
    });
  });

  describe("localize html", () => {
    const func = mjs.localizeHtml;
    const globalKeys = ["Node", "NodeList"];
    let window, document;
    beforeEach(() => {
      const dom = createJsdom();
      window = dom && dom.window;
      document = window && window.document;
      for (const key of globalKeys) {
        global[key] = window[key];
      }
      global.window = window;
      global.document = document;
    });
    afterEach(() => {
      window = null;
      document = null;
      for (const key of globalKeys) {
        delete global[key];
      }
      delete global.window;
      delete global.document;
    });

    it("should not set value", async () => {
      browser.i18n.getMessage.withArgs(EXT_LOCALE).returns("");
      window.func = func;
      await window.func();
      const root = document.documentElement;
      assert.isNull(root.getAttribute("lang"), "lang");
      browser.i18n.getMessage.flush();
    });

    it("should set value", async () => {
      browser.i18n.getMessage.withArgs(EXT_LOCALE).returns("en");
      window.func = func;
      await window.func();
      const root = document.documentElement;
      assert.strictEqual(root.lang, "en", "lang");
      browser.i18n.getMessage.flush();
    });

    it("should set value", async () => {
      browser.i18n.getMessage.withArgs(EXT_LOCALE).returns("en");
      browser.i18n.getMessage.withArgs("foo", "bar").returns("baz");
      const body = document.querySelector("body");
      const p = document.createElement("p");
      p.setAttribute("data-i18n", "foo,bar");
      body.appendChild(p);
      window.func = func;
      await window.func();
      const root = document.documentElement;
      assert.strictEqual(root.lang, "en", "lang");
      assert.strictEqual(p.textContent, "baz", "content");
      browser.i18n.getMessage.flush();
    });

    it("should set value", async () => {
      browser.i18n.getMessage.withArgs(EXT_LOCALE).returns("en");
      browser.i18n.getMessage.withArgs("foo", "bar").returns("");
      const body = document.querySelector("body");
      const p = document.createElement("p");
      p.setAttribute("data-i18n", "foo,bar");
      p.textContent = "baz";
      body.appendChild(p);
      window.func = func;
      await window.func();
      const root = document.documentElement;
      assert.strictEqual(root.lang, "en", "lang");
      assert.strictEqual(p.textContent, "baz", "content");
      browser.i18n.getMessage.flush();
    });
  });
});
<commit_msg>Update test/localize.test.js<commit_after>/**
 * localize.test.js
 */
/* eslint-disable no-magic-numbers, max-nested-callbacks */

import {JSDOM} from "jsdom";
import {assert} from "chai";
import {afterEach, beforeEach, describe, it} from "mocha";
import {browser} from "./mocha/setup.js";
import {EXT_LOCALE} from "../src/mjs/constant.js";
import * as mjs from "../src/mjs/localize.js";

describe("localize", () => {
  /**
   * create jsdom
   * @returns {Object} - jsdom instance
   */
  const createJsdom = () => {
    const domstr = "<!DOCTYPE html>";
    const opt = {
      runScripts: "dangerously",
    };
    return new JSDOM(domstr, opt);
  };
  beforeEach(() => {
    global.browser = browser;
  });
  afterEach(() => {
    delete global.browser;
  });

  it("should get browser object", () => {
    assert.isObject(browser, "browser");
  });

  describe("localize attribute value", () => {
    const func = mjs.localizeAttr;
    const globalKeys = ["Node", "NodeList"];
    let window, document;
    beforeEach(() => {
      const dom = createJsdom();
      window = dom && dom.window;
      document = window && window.document;
      for (const key of globalKeys) {
        global[key] = window[key];
      }
      global.window = window;
      global.document = document;
    });
    afterEach(() => {
      window = null;
      document = null;
      for (const key of globalKeys) {
        delete global[key];
      }
      delete global.window;
      delete global.document;
    });

    it("should not call function if no argument given", async () => {
      const i = browser.i18n.getMessage.callCount;
      await func();
      assert.strictEqual(browser.i18n.getMessage.callCount, i, "not called");
    });

    it("should not call function if argument is not an element", async () => {
      const i = browser.i18n.getMessage.callCount;
      await func("foo");
      assert.strictEqual(browser.i18n.getMessage.callCount, i, "not called");
    });

    it("should set attribute", async () => {
      const id = "foo";
      const attrs = {
        alt: "alt",
        ariaLabel: "aria-label",
        href: "href",
        placeholder: "placeholder",
        title: "title",
      };
      const items = Object.entries(attrs);
      const p = document.createElement("p");
      const body = document.querySelector("body");
      for (const [key, value] of items) {
        p.setAttribute(value, "bar");
        browser.i18n.getMessage.withArgs(`${id}_${key}`)
          .returns(`${id}_${key}`);
      }
      p.setAttribute("data-i18n", id);
      body.appendChild(p);
      await func(p);
      for (const [key, value] of items) {
        assert.strictEqual(p.getAttribute(value), `${id}_${key}`, `${value}`);
      }
      browser.i18n.getMessage.flush();
    });

    it("should not set attribute", async () => {
      const id = "";
      const attrs = {
        alt: "alt",
        ariaLabel: "aria-label",
        href: "href",
        placeholder: "placeholder",
        title: "title",
      };
      const items = Object.values(attrs);
      const p = document.createElement("p");
      const body = document.querySelector("body");
      for (const value of items) {
        p.setAttribute(value, "bar");
      }
      p.setAttribute("data-i18n", id);
      body.appendChild(p);
      await func(p);
      for (const value of items) {
        assert.strictEqual(p.getAttribute(value), "bar", `${value}`);
      }
      browser.i18n.getMessage.flush();
    });
  });

  describe("localize html", () => {
    const func = mjs.localizeHtml;
    const globalKeys = ["Node", "NodeList"];
    let window, document;
    beforeEach(() => {
      const dom = createJsdom();
      window = dom && dom.window;
      document = window && window.document;
      for (const key of globalKeys) {
        global[key] = window[key];
      }
      global.window = window;
      global.document = document;
    });
    afterEach(() => {
      window = null;
      document = null;
      for (const key of globalKeys) {
        delete global[key];
      }
      delete global.window;
      delete global.document;
    });

    it("should not set value", async () => {
      browser.i18n.getMessage.withArgs(EXT_LOCALE).returns("");
      window.func = func;
      await window.func();
      const root = document.documentElement;
      assert.isNull(root.getAttribute("lang"), "lang");
      browser.i18n.getMessage.flush();
    });

    it("should set value", async () => {
      browser.i18n.getMessage.withArgs(EXT_LOCALE).returns("en");
      window.func = func;
      await window.func();
      const root = document.documentElement;
      assert.strictEqual(root.lang, "en", "lang");
      browser.i18n.getMessage.flush();
    });

    it("should set value", async () => {
      browser.i18n.getMessage.withArgs(EXT_LOCALE).returns("en");
      browser.i18n.getMessage.withArgs("foo", "bar").returns("baz");
      const body = document.querySelector("body");
      const p = document.createElement("p");
      p.setAttribute("data-i18n", "foo,bar");
      body.appendChild(p);
      window.func = func;
      await window.func();
      const root = document.documentElement;
      assert.strictEqual(root.lang, "en", "lang");
      assert.strictEqual(p.textContent, "baz", "content");
      browser.i18n.getMessage.flush();
    });

    it("should set value", async () => {
      browser.i18n.getMessage.withArgs(EXT_LOCALE).returns("en");
      browser.i18n.getMessage.withArgs("foo", "bar").returns("");
      const body = document.querySelector("body");
      const p = document.createElement("p");
      p.setAttribute("data-i18n", "foo,bar");
      p.textContent = "baz";
      body.appendChild(p);
      window.func = func;
      await window.func();
      const root = document.documentElement;
      assert.strictEqual(root.lang, "en", "lang");
      assert.strictEqual(p.textContent, "baz", "content");
      browser.i18n.getMessage.flush();
    });
  });
});
<|endoftext|>


<commit_before>import test from 'ava';
import testContainer from './_test-container';
import MDUContainer from '../lib/mdu-container';

test("MDUContainer interface check", testContainer, MDUContainer, {
    platform: "LINUX64",
    product: "FIREFOX",
    version: "LATEST"
});

test("Get Checksums rejects", (t) => {
    const container = new MDUContainer({});

    return t.throws(container.getChecksums(), Error, "No checksums available");
});
<commit_msg>chore: upgrade tests<commit_after>import test from 'ava';
import testContainer from './_test-container';
import MDUContainer from '../lib/mdu-container';

test("MDUContainer interface check", testContainer, MDUContainer, {
    platform: "LINUX64",
    product: "FIREFOX",
    version: "LATEST"
});

test("Get Checksums rejects", (t) => {
    const container = new MDUContainer({});

    return t.throwsAsync(container.getChecksums(), Error, "No checksums available");
});
<|endoftext|>


<commit_before>// PARSING TESTS
// =============
//
// TODO: add moar samples

define([ 'ractive', 'samples/parse' ], function ( Ractive, tests ) {

	return function () {

		module( 'Parse' );

		var runTest = function ( theTest ) {
			test( theTest.name, function ( t ) {
				if (theTest.error) {
					var error;

					try {
						Ractive.parse( theTest.template, theTest.options );
					} catch (e) {
						error = e;
					}

					t.equal( error.name, 'ParseError' )
					t.ok( error.stack );
					t.equal( error.message, theTest.error );
				} else {
					var parsed = Ractive.parse( theTest.template, theTest.options );

					t.deepEqual( parsed, theTest.parsed );
				}
			});
		};

		for ( var i=0; i<tests.length; i+=1 ) {
			runTest( tests[i] );
		}

	};

});
<commit_msg>Re-throw non-ParseErrors<commit_after>// PARSING TESTS
// =============
//
// TODO: add moar samples

define([ 'ractive', 'samples/parse' ], function ( Ractive, tests ) {

	return function () {

		module( 'Parse' );

		var runTest = function ( theTest ) {
			test( theTest.name, function ( t ) {
				if (theTest.error) {
					var error;

					try {
						Ractive.parse( theTest.template, theTest.options );
					} catch (e) {
						error = e;
					}

					if (error.name !== 'ParseError') {
						throw error;
					}

					t.ok( error.stack );
					t.equal( error.message, theTest.error );
				} else {
					var parsed = Ractive.parse( theTest.template, theTest.options );

					t.deepEqual( parsed, theTest.parsed );
				}
			});
		};

		for ( var i=0; i<tests.length; i+=1 ) {
			runTest( tests[i] );
		}

	};

});
<|endoftext|>


<commit_before>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2014, Joyent, Inc.
 */

var test = require('tap').test;
var libuuid = require('libuuid');
function uuid() {
    return (libuuid.create());
}
var util = require('util');
var common = require('./common');
var vasync = require('vasync');

var TAP_CONF = {
    timeout: 'Infinity '
};

///--- Globals

var client, server, NET_UUID, NIC_TAG_NAME, NIC_TAG, NETWORK1, NETWORK2, POOL;

// -- Network helpers

function createTestNicTag(cb) {
    NIC_TAG_NAME =  'nictag_test_' +  process.pid;
    client.napi.createNicTag(NIC_TAG_NAME, function (err, res) {
        if (err) {
            return cb(err);
        } else {
            NIC_TAG = res;
            return cb(null, res);
        }
    });
}

function deleteTestNicTag(cb) {
    client.napi.deleteNicTag(NIC_TAG_NAME, function (err) {
        return cb(err);
    });
}

function createTestNetwork(id, vlan_id, cb) {
    var params = {
        name: 'network-test-' + id,
        vlan_id: vlan_id,
        subnet: '10.99.99.0/24',
        provision_start_ip: '10.99.99.5',
        provision_end_ip: '10.99.99.250',
        nic_tag: NIC_TAG_NAME
    };

    client.napi.createNetwork(params, cb);
}

function deleteTestNetwork(net, cb) {
    client.napi.deleteNetwork(net.uuid, { force: true }, cb);
}

function createTestPool(cb) {
    var params = {
        name: 'network_pool' + process.pid,
        networks: [ NETWORK1.uuid ]
    };

    client.napi.createNetworkPool(params.name, params, function (err, res) {
        if (err) {
            return cb(err);
        } else {
            POOL = res;
            return cb(null, res);
        }
    });
}

function deleteTestPool(cb) {
    client.napi.deleteNetworkPool(POOL.uuid, function (err) {
        return cb(err);
    });
}

// --- Test helper:

function checkNetwork(t, net) {
    t.ok(net, 'Network OK');
    t.ok(net.name, 'Network name OK');
    t.ok(net.id, 'Network id OK');
    t.ok(net['public'] !== undefined, 'Network public');
}

test('setup', TAP_CONF, function (t) {
    common.setup(function (err, _client, _server) {
        t.ifError(err);
        t.ok(_client);
        if (!process.env.SDC_SETUP_TESTS) {
            t.ok(_server);
            server = _server;
        }
        client = _client;

        vasync.pipeline({ funcs: [
            function createTag(_, next) {
                createTestNicTag(next);
            },
            function createNetwork1(_, next) {
                createTestNetwork(process.pid, 0, function (err2, net1) {
                    NETWORK1 = net1;
                    next(err2);
                });
            },
            function createNetwork2(_, next) {
                createTestNetwork(process.pid + 1, 99, function (err2, net2) {
                    NETWORK2 = net2;
                    next(err2);
                });
            },
            function createPool(_, next) {
                createTestPool(next);
            }
        ] }, function (err2) {
            t.ifError(err2);
            t.end();
        });
    });
});

test('list networks', function (t) {
    var poolFound = false;
    var netFound  = false;

    client.get('/my/networks', function (err, req, res, body) {
        t.ifError(err, 'GET /my/networks error');
        t.equal(res.statusCode, 200, 'GET /my/networks status');
        common.checkHeaders(t, res.headers);
        t.ok(body, 'GET /my/networks body');
        t.ok(Array.isArray(body), 'GET /my/networks body is an array');
        t.ok(body.length, 'GET /my/networks body array has elements');

        body.forEach(function (n) {
            t.ok(n.id !== NETWORK1.uuid, 'should not list network in pool');
            checkNetwork(t, n);
            if (n.id === POOL.uuid) {
                poolFound = true;
            }
            if (n.id === NETWORK2.uuid) {
                netFound = true;
            }
        });

        t.ok(poolFound);
        t.ok(netFound);

        // This will likely be our default setup external network
        NET_UUID = body[0].id;
        t.end();
    });
});

test('get network', function (t) {
    client.get('/my/networks/' + NET_UUID, function (err, req, res, body) {
        t.ifError(err, 'GET /my/networks/' + NET_UUID + ' error');
        t.equal(res.statusCode, 200, 'GET /my/networks/smartos status');
        common.checkHeaders(t, res.headers);
        t.ok(body, 'GET /my/networks/smartos body');
        checkNetwork(t, body);
        t.end();
    });
});

test('get network (404)', function (t) {
    client.get('/my/networks/' + uuid(), function (err) {
        t.ok(err, 'GET /my/networks/ error');
        t.equal(err.statusCode, 404, 'GET /my/networks/ status');
        t.equal(err.restCode, 'ResourceNotFound', 'GET /my/networks/ restCode');
        t.ok(err.message, 'GET /my/networks/ error message');
        t.end();
    });
});

test('teardown', function (t) {
    vasync.pipeline({ funcs: [
        function deletePool(_, next) {
            deleteTestPool(next);
        },
        function deleteNetwork1(_, next) {
            deleteTestNetwork(NETWORK1, next);
        },
        function deleteNetwork2(_, next) {
            deleteTestNetwork(NETWORK2, next);
        },
        function deleteTag(_, next) {
            deleteTestNicTag(next);
        }
    ] }, function (err) {
        t.ifError(err);

        client.teardown(function (err2) {
            t.ifError(err2, 'client teardown error');

            if (!process.env.SDC_SETUP_TESTS) {
                var cli = server._clients;
                Object.keys(cli).forEach(function (c) {
                    if (cli[c].client && cli[c].client.close) {
                        cli[c].client.close();
                    }
                });
                cli.ufds.client.removeAllListeners('close');

                server.close(function () {
                    t.end();
                });
            } else {
                t.end();
            }
        });
    });
});
<commit_msg>PUBAPI-1043 - switch subnets used in network tests so they don't overlap (due to NAPI-203).<commit_after>/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2014, Joyent, Inc.
 */

var test = require('tap').test;
var libuuid = require('libuuid');
function uuid() {
    return (libuuid.create());
}
var util = require('util');
var common = require('./common');
var vasync = require('vasync');

var TAP_CONF = {
    timeout: 'Infinity '
};

///--- Globals

var client, server, NET_UUID, NIC_TAG_NAME, NIC_TAG, NETWORK1, NETWORK2, POOL;

// -- Network helpers

function createTestNicTag(cb) {
    NIC_TAG_NAME =  'nictag_test_' +  process.pid;
    client.napi.createNicTag(NIC_TAG_NAME, function (err, res) {
        if (err) {
            return cb(err);
        } else {
            NIC_TAG = res;
            return cb(null, res);
        }
    });
}

function deleteTestNicTag(cb) {
    client.napi.deleteNicTag(NIC_TAG_NAME, function (err) {
        return cb(err);
    });
}

function createTestNetwork(id, octet, cb) {
    var params = {
        name: 'network-test-' + id,
        vlan_id: 59,
        subnet: '10.99.' + octet + '.0/24',
        provision_start_ip: '10.99.' + octet + '.5',
        provision_end_ip: '10.99.' + octet + '.250',
        nic_tag: NIC_TAG_NAME
    };

    client.napi.createNetwork(params, cb);
}

function deleteTestNetwork(net, cb) {
    client.napi.deleteNetwork(net.uuid, { force: true }, cb);
}

function createTestPool(cb) {
    var params = {
        name: 'network_pool' + process.pid,
        networks: [ NETWORK1.uuid ]
    };

    client.napi.createNetworkPool(params.name, params, function (err, res) {
        if (err) {
            return cb(err);
        } else {
            POOL = res;
            return cb(null, res);
        }
    });
}

function deleteTestPool(cb) {
    client.napi.deleteNetworkPool(POOL.uuid, function (err) {
        return cb(err);
    });
}

// --- Test helper:

function checkNetwork(t, net) {
    t.ok(net, 'Network OK');
    t.ok(net.name, 'Network name OK');
    t.ok(net.id, 'Network id OK');
    t.ok(net['public'] !== undefined, 'Network public');
}

test('setup', TAP_CONF, function (t) {
    common.setup(function (err, _client, _server) {
        t.ifError(err);
        t.ok(_client);
        if (!process.env.SDC_SETUP_TESTS) {
            t.ok(_server);
            server = _server;
        }
        client = _client;

        vasync.pipeline({ funcs: [
            function createTag(_, next) {
                createTestNicTag(next);
            },
            function createNetwork1(_, next) {
                createTestNetwork(process.pid, 90, function (err2, net1) {
                    NETWORK1 = net1;
                    next(err2);
                });
            },
            function createNetwork2(_, next) {
                createTestNetwork(process.pid + 1, 91, function (err2, net2) {
                    NETWORK2 = net2;
                    next(err2);
                });
            },
            function createPool(_, next) {
                createTestPool(next);
            }
        ] }, function (err2) {
            t.ifError(err2);
            t.end();
        });
    });
});

test('list networks', function (t) {
    var poolFound = false;
    var netFound  = false;

    client.get('/my/networks', function (err, req, res, body) {
        t.ifError(err, 'GET /my/networks error');
        t.equal(res.statusCode, 200, 'GET /my/networks status');
        common.checkHeaders(t, res.headers);
        t.ok(body, 'GET /my/networks body');
        t.ok(Array.isArray(body), 'GET /my/networks body is an array');
        t.ok(body.length, 'GET /my/networks body array has elements');

        body.forEach(function (n) {
            t.ok(n.id !== NETWORK1.uuid, 'should not list network in pool');
            checkNetwork(t, n);
            if (n.id === POOL.uuid) {
                poolFound = true;
            }
            if (n.id === NETWORK2.uuid) {
                netFound = true;
            }
        });

        t.ok(poolFound);
        t.ok(netFound);

        // This will likely be our default setup external network
        NET_UUID = body[0].id;
        t.end();
    });
});

test('get network', function (t) {
    client.get('/my/networks/' + NET_UUID, function (err, req, res, body) {
        t.ifError(err, 'GET /my/networks/' + NET_UUID + ' error');
        t.equal(res.statusCode, 200, 'GET /my/networks/smartos status');
        common.checkHeaders(t, res.headers);
        t.ok(body, 'GET /my/networks/smartos body');
        checkNetwork(t, body);
        t.end();
    });
});

test('get network (404)', function (t) {
    client.get('/my/networks/' + uuid(), function (err) {
        t.ok(err, 'GET /my/networks/ error');
        t.equal(err.statusCode, 404, 'GET /my/networks/ status');
        t.equal(err.restCode, 'ResourceNotFound', 'GET /my/networks/ restCode');
        t.ok(err.message, 'GET /my/networks/ error message');
        t.end();
    });
});

test('teardown', function (t) {
    vasync.pipeline({ funcs: [
        function deletePool(_, next) {
            deleteTestPool(next);
        },
        function deleteNetwork1(_, next) {
            deleteTestNetwork(NETWORK1, next);
        },
        function deleteNetwork2(_, next) {
            deleteTestNetwork(NETWORK2, next);
        },
        function deleteTag(_, next) {
            deleteTestNicTag(next);
        }
    ] }, function (err) {
        t.ifError(err);

        client.teardown(function (err2) {
            t.ifError(err2, 'client teardown error');

            if (!process.env.SDC_SETUP_TESTS) {
                var cli = server._clients;
                Object.keys(cli).forEach(function (c) {
                    if (cli[c].client && cli[c].client.close) {
                        cli[c].client.close();
                    }
                });
                cli.ufds.client.removeAllListeners('close');

                server.close(function () {
                    t.end();
                });
            } else {
                t.end();
            }
        });
    });
});
<|endoftext|>


<commit_before>
require('should');

// Utils
// -----

// cheating with hygene:

global.Hyperloop = {
  defineClass: function (name) {
    return new ClassInterface(name);
  },
  method: function (receiver, name) {
    return {
      call: function () {
        var args = Array.prototype.slice.call(arguments);
        return String(receiver) + ' # ' + name + [''].concat(args).join('/');
      }
    };
  }
};

// cheating for undefined identifiers:

global.MyClass = 'MyClass';

// simple faker:

var receiver = {
  toString: function () { return '{RECEIVER}' },
  method: function () { return this },
  cast: function (to) { return '@' + to }
};

// fake meta-class

function ClassInterface (name) {
  this._name = name;
  this._methods = [];
  this._implements = [];
  this._protocols = [];
}

ClassInterface.prototype.toString = function () {
  return '{' + this._name + '}';
};

ClassInterface.prototype.implements = function (parent) {
  this._implements.push(parent);
  return this;
};

ClassInterface.prototype.protocol = function (protocol) {
  this._protocols.push(protocol);
  return this;
};

ClassInterface.prototype.build = function () {
  return {
    name: this._name,
    implements: this._implements,
    protocols: this._protocols,
    methods: this._methods,
  };
};

// Tests
// -----

describe "Objective-C" {

  describe "Macro name collisions" {
    it "should not happen on 'use'" {
      var use = 42;

      use.should.eql(42);
    }

    it "should not happen on 'as'" {
      var as = 42;

      as.should.eql(42);
    }
  }

  describe "Use macro" {
    it "should work" {
      (use hyperloop).should.eql('use hyperloop');
    }
  }

  describe "Method invocation" {
    it "should work with no argument" {
      receiver@method().should.eql('{RECEIVER} # method');
    }

    it "should work with 1 argument" {
      receiver@method('arg').should.eql('{RECEIVER} # method:/arg');
    }

    it "should work with more than one argument" {
      receiver@method('arg1', withPieces:'arg2').should.eql('{RECEIVER} # method:withPieces:/arg1/arg2');
    }
  }

  describe "Casting" {
    it "should work with literals" {
      (receiver as 'Literal').should.eql('@Literal');
    }

    it "should work with identifiers" {
      (receiver as AClass).should.eql('@AClass');
    }

    it "should work with pointers" {
      // No space
      (receiver as (AClass*)).should.eql('@AClass *');
      // With space
      (receiver as (AClass *)).should.eql('@AClass *');
      // More than one star, no spaces
      (receiver as (AClass**)).should.eql('@AClass * *');
      // More than one star, with spaces
      (receiver as (AClass * *)).should.eql('@AClass * *');
      // More than one as parens
      (receiver as ((AClass *) *)).should.eql('@AClass * *');
    }
  }

  describe "Classes" {
    // We could have used `.properties` instead of `.eql` to test only specified
    // properties. This is way more verbose, but also way more solid.

    it "should work with empty classes" {
      var clazz = class native MyClass {};

      clazz.should.eql({
        name: 'MyClass',
        implements: [],
        protocols: [],
        methods: []
      });
    }

    it "should work with `extends`" {
      var clazz = class native MyClass extends NSObject {};

      clazz.should.eql({
        name: 'MyClass',
        implements: [ 'NSObject' ],
        protocols: [],
        methods: []
      });
    }

    it "should work with `implements`" {
      var clazz = class native MyClass implements NSObject {};

      clazz.should.eql({
        name: 'MyClass',
        implements: [ 'NSObject' ],
        protocols: [],
        methods: []
      });
    }

    it "should work with `protocol`" {
      var clazz = class native MyClass protocol NSProtocol {};

      clazz.should.eql({
        name: 'MyClass',
        implements: [],
        protocols: [ 'NSProtocol' ],
        methods: []
      });
    }

    it "should work with `protocol` and `extends`" {
      var clazz = class native MyClass extends NSObject protocol NSProtocol {};

      clazz.should.eql({
        name: 'MyClass',
        implements: [ 'NSObject' ],
        protocols: [ 'NSProtocol' ],
        methods: []
      });
    }

    TODO "method with no arguments"
    TODO "method with one argument"
    TODO "method with more than one argument"
    TODO "automatic method argument casting"

  }

}
<commit_msg>Extended tests for `use`<commit_after>
require('should');

// Utils
// -----

// cheating with hygene:

global.Hyperloop = {
  defineClass: function (name) {
    return new ClassInterface(name);
  },
  method: function (receiver, name) {
    return {
      call: function () {
        var args = Array.prototype.slice.call(arguments);
        return String(receiver) + ' # ' + name + [''].concat(args).join('/');
      }
    };
  }
};

// cheating for undefined identifiers:

global.MyClass = 'MyClass';

// simple faker:

var receiver = {
  toString: function () { return '{RECEIVER}' },
  method: function () { return this },
  cast: function (to) { return '@' + to }
};

// fake meta-class

function ClassInterface (name) {
  this._name = name;
  this._methods = [];
  this._implements = [];
  this._protocols = [];
}

ClassInterface.prototype.toString = function () {
  return '{' + this._name + '}';
};

ClassInterface.prototype.implements = function (parent) {
  this._implements.push(parent);
  return this;
};

ClassInterface.prototype.protocol = function (protocol) {
  this._protocols.push(protocol);
  return this;
};

ClassInterface.prototype.build = function () {
  return {
    name: this._name,
    implements: this._implements,
    protocols: this._protocols,
    methods: this._methods,
  };
};

// Tests
// -----

describe "Objective-C" {

  describe "Macro name collisions" {
    it "should not happen on 'use'" {
      var use = 42;

      use.should.eql(42);
    }

    it "should not happen on 'as'" {
      var as = 42;

      as.should.eql(42);
    }
  }

  describe "Use macro" {
    it "should work for Hyperloop" {
      (use hyperloop).should.eql('use hyperloop');
    }

    it "should work for ES5 Strict Mode" {
      (use strict).should.eql('use strict');
    }
  }

  describe "Method invocation" {
    it "should work with no argument" {
      receiver@method().should.eql('{RECEIVER} # method');
    }

    it "should work with 1 argument" {
      receiver@method('arg').should.eql('{RECEIVER} # method:/arg');
    }

    it "should work with more than one argument" {
      receiver@method('arg1', withPieces:'arg2').should.eql('{RECEIVER} # method:withPieces:/arg1/arg2');
    }
  }

  describe "Casting" {
    it "should work with literals" {
      (receiver as 'Literal').should.eql('@Literal');
    }

    it "should work with identifiers" {
      (receiver as AClass).should.eql('@AClass');
    }

    it "should work with pointers" {
      // No space
      (receiver as (AClass*)).should.eql('@AClass *');
      // With space
      (receiver as (AClass *)).should.eql('@AClass *');
      // More than one star, no spaces
      (receiver as (AClass**)).should.eql('@AClass * *');
      // More than one star, with spaces
      (receiver as (AClass * *)).should.eql('@AClass * *');
      // More than one as parens
      (receiver as ((AClass *) *)).should.eql('@AClass * *');
    }
  }

  describe "Classes" {
    // We could have used `.properties` instead of `.eql` to test only specified
    // properties. This is way more verbose, but also way more solid.

    it "should work with empty classes" {
      var clazz = class native MyClass {};

      clazz.should.eql({
        name: 'MyClass',
        implements: [],
        protocols: [],
        methods: []
      });
    }

    it "should work with `extends`" {
      var clazz = class native MyClass extends NSObject {};

      clazz.should.eql({
        name: 'MyClass',
        implements: [ 'NSObject' ],
        protocols: [],
        methods: []
      });
    }

    it "should work with `implements`" {
      var clazz = class native MyClass implements NSObject {};

      clazz.should.eql({
        name: 'MyClass',
        implements: [ 'NSObject' ],
        protocols: [],
        methods: []
      });
    }

    it "should work with `protocol`" {
      var clazz = class native MyClass protocol NSProtocol {};

      clazz.should.eql({
        name: 'MyClass',
        implements: [],
        protocols: [ 'NSProtocol' ],
        methods: []
      });
    }

    it "should work with `protocol` and `extends`" {
      var clazz = class native MyClass extends NSObject protocol NSProtocol {};

      clazz.should.eql({
        name: 'MyClass',
        implements: [ 'NSObject' ],
        protocols: [ 'NSProtocol' ],
        methods: []
      });
    }

    TODO "method with no arguments"
    TODO "method with one argument"
    TODO "method with more than one argument"
    TODO "automatic method argument casting"

  }

}
<|endoftext|>


<commit_before>'use strict';

var gdal = require('../lib/gdal.js');
var path = require('path');
var assert = require('chai').assert;

describe('Open', function() {
	afterEach(gc);

	describe('ESRI Shapefile', function() {
		var filename, ds;

		it('should not throw', function() {
			filename = path.join(__dirname, "data/shp/sample.shp");
			ds = gdal.open(filename);
		});
		it('should be able to read layer count', function() {
			assert.equal(ds.layers.count(), 1);
		});

		describe('layer', function() {
			var layer;
			before(function() { layer = ds.layers.get(0); });
			it('should have all fields defined', function() {
				assert.equal(layer.fields.count(), 8);
				assert.deepEqual(layer.fields.getNames(), [
					'path',
					'name',
					'type',
					'long_name',
					'fips_num',
					'fips',
					'state_fips',
					'state_abbr'
				]);
			});
			describe('field properties', function() {
				var integerDs = gdal.open(path.join(__dirname, 'data/shp/sample_int64.shp'));
				var integerLayer = integerDs.layers.get(0);

				it('should evaluate datatypes', function() {
					assert.equal(integerLayer.fields.get(0).type, 'string');
					assert.equal(integerLayer.fields.get(3).type, 'integer64');
					assert.equal(integerLayer.fields.get(5).type, 'real');
					assert.equal(integerLayer.fields.get(10).type, 'date');
				})
			});
			describe('features', function() {
				it('should be readable', function() {
					assert.equal(layer.features.count(), 23);
					var feature = layer.features.get(0);
					var fields = feature.fields.toObject();

					assert.deepEqual(fields, {
						'fips': 'US56029',
						'fips_num': '56029',
						'long_name': 'Park County',
						'name': 'Park',
						'path': 'US.WY.PARK',
						'state_abbr': 'WY',
						'state_fips': '56',
						'type': 'County'
					});
				});
			});

			describe('integer64 fields', function() {
				it('should be readable', function() {
					var integerDs = gdal.open(path.join(__dirname, "data/shp/sample_int64.shp"));
					var integerLayer = integerDs.layers.get(0);

					assert.equal(integerLayer.features.get(0).fields.get(3), 1);
				});
			});
		});
	});
});<commit_msg>Only test for integer64 if GDAL >= 2.0.<commit_after>'use strict';

var gdal = require('../lib/gdal.js');
var path = require('path');
var assert = require('chai').assert;

describe('Open', function() {
	afterEach(gc);

	describe('ESRI Shapefile', function() {
		var filename, ds;

		it('should not throw', function() {
			filename = path.join(__dirname, "data/shp/sample.shp");
			ds = gdal.open(filename);
		});
		it('should be able to read layer count', function() {
			assert.equal(ds.layers.count(), 1);
		});

		describe('layer', function() {
			var layer;
			before(function() { layer = ds.layers.get(0); });
			it('should have all fields defined', function() {
				assert.equal(layer.fields.count(), 8);
				assert.deepEqual(layer.fields.getNames(), [
					'path',
					'name',
					'type',
					'long_name',
					'fips_num',
					'fips',
					'state_fips',
					'state_abbr'
				]);
			});
			describe('field properties', function() {
				var integerDs = gdal.open(path.join(__dirname, 'data/shp/sample_int64.shp'));
				var integerLayer = integerDs.layers.get(0);

				it('should evaluate datatypes', function() {
					var version_major = Number(gdal.version.split('.')[0]);
					assert.equal(integerLayer.fields.get(0).type, 'string');
					assert.equal(integerLayer.fields.get(3).type, version_major >= 2 ? 'integer64' : 'integer');
					assert.equal(integerLayer.fields.get(5).type, 'real');
					assert.equal(integerLayer.fields.get(10).type, 'date');
				})
			});
			describe('features', function() {
				it('should be readable', function() {
					assert.equal(layer.features.count(), 23);
					var feature = layer.features.get(0);
					var fields = feature.fields.toObject();

					assert.deepEqual(fields, {
						'fips': 'US56029',
						'fips_num': '56029',
						'long_name': 'Park County',
						'name': 'Park',
						'path': 'US.WY.PARK',
						'state_abbr': 'WY',
						'state_fips': '56',
						'type': 'County'
					});
				});
			});

			describe('integer64 fields', function() {
				it('should be readable', function() {
					var integerDs = gdal.open(path.join(__dirname, "data/shp/sample_int64.shp"));
					var integerLayer = integerDs.layers.get(0);

					assert.equal(integerLayer.features.get(0).fields.get(3), 1);
				});
			});
		});
	});
});<|endoftext|>


<commit_before>LinkedGrid = function(columns, rows, debug) {
  this.debug = debug | false;

  this.columns = columns;
  this.rows = rows;

  this.colors = [];

  this.cells = [columns * rows]; // array with cell objects
  this.maxCellIndex = -1; // max used cell index
  this.field = [columns][rows]; // 2d array with cell references
};

LinkedGrid.prototype.constructor = LinkedGrid;

LinkedGrid.prototype.setSize = function(columns, rows) {
  this.columns = columns;
  this.rows = rows;
};

LinkedGrid.prototype.addCellColor = function(color) {
  this.colors.push(color);
  return this.colors.length - 1;
};

LinkedGrid.prototype.addCell = function(column, row, colorIndex) {
  // we need a free place in the cells array
  if (this.maxCellIndex < this.cells.length) {
    console.log("free place in cells array");

  } else if (debug == true) {
    console.log("no free place in cells array");
  }
};
<commit_msg>more logic and some changes<commit_after>LinkedGrid = function(columns, rows, debug) {
  this.debug = debug | false;

  this.columns = columns;
  this.rows = rows;

  this.colors = [];

  this.cells = new Array(this.columns * this.rows); // array with cell objects
  for (var i = 0; i < this.columns * this.rows; i++) {
    this.cells[i] = null;
  }
  this.maxCellIndex = -1; // maximal used cell index

  this.field = new Array(this.columns); // 2d array with cell references
  for (var column = 0; column < columns; column++) {
    this.field[column] = new Array(this.rows);
    for (var row = 0; row < rows; row++) {
      this.field[column][row] = null;
    }
  }
};

LinkedGrid.prototype.constructor = LinkedGrid;

LinkedGrid.prototype.setSize = function(columns, rows) {
  this.columns = columns;
  this.rows = rows;
};

LinkedGrid.prototype.addCellColor = function(color) {
  this.colors.push(color);
  return this.colors.length - 1;
};

LinkedGrid.prototype.addCell = function(column, row, colorIndex) {
  // we need a free place in the cells array
  if (this.maxCellIndex < this.cells.length && this.field[column][row] === null) {
    if (this.debug == true)
      console.log("free place in cells array to add");

    this.cells[this.maxCellIndex] = {
      gfx: "reference todo",
      column: column,
      row: row,
      colorIndex: colorIndex
    };
    this.field[column][row] = this.cells[this.maxCellIndex];
    this.maxCellIndex++;

    return true;
  } else if (this.debug == true) {
    console.log("no free place in cells array to add");
  }
  return false;
};

LinkedGrid.prototype.removeCell = function(column, row) {
  // we need a field cell which is set
  if (this.maxCellIndex > -1 && this.field[column][row] !== null) {
    if (this.debug == true)
      console.log("valid place in cells array to remove");

    this.field[column][row] = null;
    // todo remove pixi.js gfx object
    // todo remove cell object

    return true;
  } else if (this.debug == true) {
    console.log("invalid place in cells array to remove");
  }
  return false;
};

LinkedGrid.prototype.moveCell = function(sColumn, sRow, tColumn, tRow) {
  // we have to determine if the source cell is not set and the target cell is free
  console.log(this.field[sColumn][sRow], this.field[tColumn][tRow]);
};
<|endoftext|>


<commit_before>var tape = require('tape');
var d3   = require('../');

tape('draw function of \'polygons\' draws correctly', function(test){
	var _3d = d3._3d().primitiveType('POLYGONS');
	var data = [
		[[5,0,2],[6,4,1],[4,5,8],[1,5,9],[1,0,1]]
	];
	test.deepEqual(_3d.draw(_3d(data)[0]), 'M1,0L1,-5L4,-5L6,-4L5,0Z');
	test.end();
});

tape.only('polygons are getting drawn clockwise', function(test){
    var _3d = d3._3d().primitiveType('POLYGONS');
    var data = [
        [[5,0,2],[6,4,1],[4,5,8],[1,5,9],[1,0,1]],
        [[1,0,1],[5,0,2],[6,4,1],[4,5,8],[1,5,9]],
        [[1,5,9],[4,5,8],[6,4,1],[5,0,2],[1,0,1]],
    ];
    test.deepEqual(_3d(data)[0].cw, true);
    test.deepEqual(_3d(data)[1].cw, true);
    test.deepEqual(_3d(data)[2].cw, false);
    test.end();
});
<commit_msg>remove .only<commit_after>var tape = require('tape');
var d3   = require('../');

tape('draw function of \'polygons\' draws correctly', function(test){
	var _3d = d3._3d().primitiveType('POLYGONS');
	var data = [
		[[5,0,2],[6,4,1],[4,5,8],[1,5,9],[1,0,1]]
	];
	test.deepEqual(_3d.draw(_3d(data)[0]), 'M1,0L1,-5L4,-5L6,-4L5,0Z');
	test.end();
});

tape('polygons are getting drawn clockwise', function(test){
    var _3d = d3._3d().primitiveType('POLYGONS');
    var data = [
        [[5,0,2],[6,4,1],[4,5,8],[1,5,9],[1,0,1]],
        [[1,0,1],[5,0,2],[6,4,1],[4,5,8],[1,5,9]],
        [[1,5,9],[4,5,8],[6,4,1],[5,0,2],[1,0,1]],
    ];
    test.deepEqual(_3d(data)[0].cw, true);
    test.deepEqual(_3d(data)[1].cw, true);
    test.deepEqual(_3d(data)[2].cw, false);
    test.end();
});
<|endoftext|>


<commit_before>module.exports = {
  'Log in as admin' : function (client) {
    client
      .url(client.launch_url)
      .waitForElementVisible('body', 200)
      .assert.title('Ajankohtaiset kilpailut - Kisakone')
      .click('#login_link')
      .waitForElementVisible('#login_form', 200)
      .setValue('#loginUsernameInput', 'admin')
      .setValue('#loginPassword', 'adminpass')
      .click('#loginSubmit')
      .pause(200)
      .waitForElementVisible('td#content', 200)
      .assert.containsText('td#content', 'Olet nyt kirjautunut sisään')
      .assert.containsText('.loginbox', 'Olet kirjautuneena tunnuksella')
  },

  'Create event' : function (client) {
    client
      .url(client.launch_url)
      .assert.containsText('.loginbox', 'Omat tiedot')
      .assert.containsText('td#content', 'Ajankohtaiset kilpailut')
      .click('ul#mainmenu li:nth-child(4)')
      .waitForElementVisible('td#content', 200)
      .assert.containsText('td#submenucontainer', 'Uusi kilpailu')
      .click('#submenucontainer li:nth-child(6)')
      .waitForElementVisible('td#content', 200)
      .assert.containsText('td#content', 'Luo uusi kilpailu')
      .setValue('#name', 'test event')
      .setValue('#venueField', 'test venue')
      .setValue('#tournament', 'test tournament')
      .setValue('#level', 'test level')
      .setValue('#start', '2020-06-30')
      .setValue('#duration', '2')
      .setValue('#playerlimit', '2')
      .setValue('#signup_start', '2020-06-28 09:00')
      .setValue('#signup_end', '2020-06-29 21:00')
      .setValue('#contact', 'test contact')
      .setValue('#td', 'admin')
      .submitForm('form#eventform')
      .waitForElementVisible('td#content', 200)
      .assert.containsText('td#content', 'Tietojen muokkaus on tehty onnistuneesti.')
  }
}
<commit_msg>tests: event noted as broken<commit_after>/* this is TODO, fails now */

module.exports = {
  'Log in as admin' : function (client) {
    client
      .url(client.launch_url)
      .waitForElementVisible('body', 200)
      .assert.title('Ajankohtaiset kilpailut - Kisakone')
      .click('#login_link')
      .waitForElementVisible('#login_form', 200)
      .setValue('#loginUsernameInput', 'admin')
      .setValue('#loginPassword', 'adminpass')
      .click('#loginSubmit')
      .pause(200)
      .waitForElementVisible('td#content', 200)
      .assert.containsText('td#content', 'Olet nyt kirjautunut sisään')
      .assert.containsText('.loginbox', 'Olet kirjautuneena tunnuksella')
  },

  'Create event' : function (client) {
    client
      .url(client.launch_url)
      .assert.containsText('.loginbox', 'Omat tiedot')
      .assert.containsText('td#content', 'Ajankohtaiset kilpailut')
      .click('ul#mainmenu li:nth-child(4)')
      .waitForElementVisible('td#content', 200)
      .assert.containsText('td#submenucontainer', 'Uusi kilpailu')
      .click('#submenucontainer li:nth-child(6)')
      .waitForElementVisible('td#content', 200)
      .assert.containsText('td#content', 'Luo uusi kilpailu')
      .setValue('#name', 'test event')
      .setValue('#venueField', 'test venue')
      .setValue('#tournament', 'test tournament')
      .setValue('#level', 'test level')
      .setValue('#start', '2020-06-30')
      .setValue('#duration', '2')
      .setValue('#playerlimit', '2')
      .setValue('#signup_start', '2020-06-28 09:00')
      .setValue('#signup_end', '2020-06-29 21:00')
      .setValue('#contact', 'test contact')
      .setValue('#td', 'admin')
      .submitForm('form#eventform')
      .waitForElementVisible('td#content', 200)
      .assert.containsText('td#content', 'Tietojen muokkaus on tehty onnistuneesti.')
  }
}
<|endoftext|>