<commit_before>"use latest";

const _ = require('underscore');
const hbs = require('handlebars');
const async = require('async');
const request = require('request');
const cheerio = require('cheerio');

module.exports = (ctx, req, res) => {
  if (ctx.data && ctx.data.okta) {
    // The Okta tutorials are just raw HTML files in GitHub, no point in redirecting to it since it's unreadable.
    // Instead, we'll use this webtask as a proxy to serve the HTML within the page (in a modal dialog).
    return request.get('https://raw.githubusercontent.com' + ctx.data.okta.replace('/blob', ''), function(err, r, html) {
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(html
        .replace(/\"resources/g, '"https://raw.githubusercontent.com/okta/UserDocs/master/SAML_Docs/resources')
        .replace(/\"images/g, '"https://raw.githubusercontent.com/okta/UserDocs/master/SAML_Docs/images'));
    });
  }

  const View = `

        <title>Third Party SAML Configuration</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

            <input id="filter" type="text" class="form-control" placeholder="Filter in {{total}} tutorials from Auth0, Azure AD, Okta, OneLogin...">

          {{#if err}}

{{message}}

          {{else}}

                Source
                Application
                Actions

              </thread>

              {{#each links}}

                  {{type}}
                  {{text}}

              {{/each}}

          {{/if}}

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Thid Party Application

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

    `;

  getLinks((err, links) => {
    res.writeHead(200, { 'Content-Type': 'text/html' });

    const template = hbs.compile(View);
    res.end(template({
      err: err,
      links: links,
      total: links.length
    }));
  });
};

//
const getLinks = (done) => {
  const links = [];
  async.waterfall([
    (callback) => {
      request(`https://auth0.com/docs/saml-apps`, (err, res, html) => {
        if (err) {
          return callback(err);
        }

        if (res.statusCode !== 200) {
          return callback(new Error('Unexpected status code: ' + res.statusCode));
        }

        var $ = cheerio.load(html);
        $('section.docs-content h2').each((i, element) => {
          var header = $(element);
          links.push({
            text: header.text(),
            type: 'Auth0',
            url: 'https://auth0.com/docs/saml-apps' + header.find('span').attr('href')
          });
        });

        callback();
      });
    },
    (callback) => {
      const thirdParty = [{"id":"salesforce","name":"Salesforce","img_class":"salesforce","data_logo":"Salesforce","configRoute":"/add-ons/salesforce","callback":"https://login.salesforce.com"},{"id":"dropbox","name":"Dropbox","img_class":"dropbox","data_logo":"Dropbox","configRoute":"/add-ons/dropbox","callback":"https://www.dropbox.com/saml_login"},{"id":"sharepoint","name":"SharePoint","img_class":"microsoft-sharepoint-logo","data_logo":"Sharepoint","configRoute":"/add-ons/sharepoint"},{"id":"rms","name":"AD RMS","img_class":"windows-logo","data_logo":"Windows Server Active Directory RMS","configRoute":"/add-ons/rms"},{"id":"zendesk","name":"Zendesk","img_class":"zendesk","data_logo":"Zendesk","configRoute":"/add-ons/zendesk"},{"id":"box","name":"Box","img_class":"box","data_logo":"Box","configRoute":"/add-ons/box","callback":"https://sso.services.box.net/sp/ACS.saml2"},{"id":"echosign","name":"EchoSign","img_class":"echosign","data_logo":"AdobeEchoSign","configRoute":"/add-ons/echosign"},{"id":"springcm","name":"SpringCM","img_class":"springcm","data_logo":"SpringCM","configRoute":"/add-ons/springcm"},{"id":"newrelic","name":"New Relic","img_class":"newrelic","data_logo":"NewRelic","configRoute":"/add-ons/newrelic"},{"id":"egnyte","name":"Egnyte","img_class":"egnyte","data_logo":"Egnyte","configRoute":"/add-ons/egnyte"},{"id":"cloudbees","name":"CloudBees","img_class":"cloudbees","data_logo":"CloudBees","configRoute":"/add-ons/cloudbees","callback":"https://grandcentral.cloudbees.com/authenticate/saml/consume"},{"id":"mscrm","name":"Dynamics CRM","img_class":"mscrm","data_logo":"MicrosoftDynamicsCRM","configRoute":"/add-ons/mscrm"},{"id":"office365","name":"Office 365 (beta)","img_class":"office365","data_logo":"Office365","configRoute":"/add-ons/office365"},{"id":"zoom","name":"Zoom","img_class":"zoom","data_logo":"Zoom","configRoute":"/add-ons/zoom"},{"id":"concur","name":"Concur (beta)","img_class":"concur","data_logo":"Concur","configRoute":"/add-ons/concur","callback":"https://www.concursolutions.com/SAMLRedirector/ClientSAMLLogin.aspx"},{"id":"slack","name":"Slack","img_class":"slack","data_logo":"Slack","configRoute":"/add-ons/slack"}];
      thirdParty.forEach(a => {
        links.push({
          text: a.name,
          type: 'Auth0 (Third Party App)',
          url: 'https://manage.auth0.com/#/externalapps'
        });
      });

      callback();
    },
    (callback) => {
      request(`https://azure.microsoft.com/en-us/documentation/articles/active-directory-saas-tutorial-list/`, (err, res, html) => {
        if (err) {
          return callback(err);
        }

        if (res.statusCode !== 200) {
          return callback(new Error('Unexpected status code: ' + res.statusCode));
        }

        var $ = cheerio.load(html);
        $('div.wa-spacer-docContent table tbody tr a').each((i, element) => {
          var link = $(element);
          links.push({
            text: link.text(),
            type: 'Azure AD',
            url: link.attr('href')
          });
        });

        callback();
      });
    },
    (callback) => {
      request(`https://github.com/okta/UserDocs/tree/master/SAML_Docs`, (err, res, html) => {
        if (err) {
          return callback(err);
        }

        if (res.statusCode !== 200) {
          return callback(new Error('Unexpected status code: ' + res.statusCode));
        }

        var $ = cheerio.load(html);
        $('div.repository-content tr.js-navigation-item a').each((i, element) => {
          var link = $(element);
          if (link.attr('href').indexOf('.html') >= 0
            && (link.attr('href').indexOf('How-to-') >= 0 || link.attr('href').indexOf('Configuring-SAML-') >= 0)) {
            links.push({
              text: link.text()
                .replace('How-to-Enable-SAML-2.0-in-', '')
                .replace('How-to-Configure-SAML-for-', '')
                .replace('How-To-Configure-SAML-1.1-for-', '')
                .replace('How-To-Configure-SAML-2.0-for-', '')
                .replace('How-to-Configure-SAML-1.1-for-', '')
                .replace('How-to-Configure-SAML-2.0-for-', '')
                .replace('How-to-configure-SAML-2.0-for-', '')
                .replace('Configure-SAML-1.1-in-', '')
                .replace('Configure-SAML-2.0-in-', '')
                .replace('Configuring-SAML-2.0-in-', '')
                .replace('Configuring SAML SSO for', '')
                .replace('Configure-CustomSSO-for-', '')
                .replace('Configuring SAML SSO for', '')
                .replace('How-to-', '')
                .replace('-', ' ')
                .replace('.html', ''),
              type: 'Okta',
              url: '?okta=' + link.attr('href')
            });
          }
        });

        callback();
      });
    },
    (callback) => {
      async.each([1, 2, 3, 4], (index, cb) => {
        request(`https://onelogin.zendesk.com/hc/en-us/sections/200245384-Application-Integration-SAML-?page=${index}#articles`, (err, res, html) => {
          if (err) {
            return cb(err);
          }

          if (res.statusCode !== 200) {
            return cb(new Error('Unexpected status code: ' + res.statusCode));
          }

          var $ = cheerio.load(html);
          $('ul.article-list li a').each((i, element) => {
            var link = $(element);
            links.push({
              text: link.text().replace('Configuring SAML for ', ''),
              type: 'OneLogin',
              url: 'https://onelogin.zendesk.com' + link.attr('href')
            });
          });

          cb();
        });
      }, (err) => {
        return callback(err);
      });
  }], (err, context) => {
    done(err, _.sortBy(links, 'text'));
  });
};
<commit_msg>Remove remaining iframe logic<commit_after>"use latest";

const _ = require('underscore');
const hbs = require('handlebars');
const async = require('async');
const request = require('request');
const cheerio = require('cheerio');

module.exports = (ctx, req, res) => {
  if (ctx.data && ctx.data.okta) {
    // The Okta tutorials are just raw HTML files in GitHub, no point in redirecting to it since it's unreadable.
    // Instead, we'll use this webtask as a proxy to serve the HTML within the page (in a modal dialog).
    return request.get('https://raw.githubusercontent.com' + ctx.data.okta.replace('/blob', ''), function(err, r, html) {
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(html
        .replace(/\"resources/g, '"https://raw.githubusercontent.com/okta/UserDocs/master/SAML_Docs/resources')
        .replace(/\"images/g, '"https://raw.githubusercontent.com/okta/UserDocs/master/SAML_Docs/images'));
    });
  }

  const View = `

        <title>Third Party SAML Configuration</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

            <input id="filter" type="text" class="form-control" placeholder="Filter in {{total}} tutorials from Auth0, Azure AD, Okta, OneLogin...">

          {{#if err}}

{{message}}

          {{else}}

                Source
                Application
                Actions

              </thread>

              {{#each links}}

                  {{type}}
                  {{text}}

              {{/each}}

          {{/if}}

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Thid Party Application

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

    `;

  getLinks((err, links) => {
    res.writeHead(200, { 'Content-Type': 'text/html' });

    const template = hbs.compile(View);
    res.end(template({
      err: err,
      links: links,
      total: links.length
    }));
  });
};

//
const getLinks = (done) => {
  const links = [];
  async.waterfall([
    (callback) => {
      request(`https://auth0.com/docs/saml-apps`, (err, res, html) => {
        if (err) {
          return callback(err);
        }

        if (res.statusCode !== 200) {
          return callback(new Error('Unexpected status code: ' + res.statusCode));
        }

        var $ = cheerio.load(html);
        $('section.docs-content h2').each((i, element) => {
          var header = $(element);
          links.push({
            text: header.text(),
            type: 'Auth0',
            url: 'https://auth0.com/docs/saml-apps' + header.find('span').attr('href')
          });
        });

        callback();
      });
    },
    (callback) => {
      const thirdParty = [{"id":"salesforce","name":"Salesforce","img_class":"salesforce","data_logo":"Salesforce","configRoute":"/add-ons/salesforce","callback":"https://login.salesforce.com"},{"id":"dropbox","name":"Dropbox","img_class":"dropbox","data_logo":"Dropbox","configRoute":"/add-ons/dropbox","callback":"https://www.dropbox.com/saml_login"},{"id":"sharepoint","name":"SharePoint","img_class":"microsoft-sharepoint-logo","data_logo":"Sharepoint","configRoute":"/add-ons/sharepoint"},{"id":"rms","name":"AD RMS","img_class":"windows-logo","data_logo":"Windows Server Active Directory RMS","configRoute":"/add-ons/rms"},{"id":"zendesk","name":"Zendesk","img_class":"zendesk","data_logo":"Zendesk","configRoute":"/add-ons/zendesk"},{"id":"box","name":"Box","img_class":"box","data_logo":"Box","configRoute":"/add-ons/box","callback":"https://sso.services.box.net/sp/ACS.saml2"},{"id":"echosign","name":"EchoSign","img_class":"echosign","data_logo":"AdobeEchoSign","configRoute":"/add-ons/echosign"},{"id":"springcm","name":"SpringCM","img_class":"springcm","data_logo":"SpringCM","configRoute":"/add-ons/springcm"},{"id":"newrelic","name":"New Relic","img_class":"newrelic","data_logo":"NewRelic","configRoute":"/add-ons/newrelic"},{"id":"egnyte","name":"Egnyte","img_class":"egnyte","data_logo":"Egnyte","configRoute":"/add-ons/egnyte"},{"id":"cloudbees","name":"CloudBees","img_class":"cloudbees","data_logo":"CloudBees","configRoute":"/add-ons/cloudbees","callback":"https://grandcentral.cloudbees.com/authenticate/saml/consume"},{"id":"mscrm","name":"Dynamics CRM","img_class":"mscrm","data_logo":"MicrosoftDynamicsCRM","configRoute":"/add-ons/mscrm"},{"id":"office365","name":"Office 365 (beta)","img_class":"office365","data_logo":"Office365","configRoute":"/add-ons/office365"},{"id":"zoom","name":"Zoom","img_class":"zoom","data_logo":"Zoom","configRoute":"/add-ons/zoom"},{"id":"concur","name":"Concur (beta)","img_class":"concur","data_logo":"Concur","configRoute":"/add-ons/concur","callback":"https://www.concursolutions.com/SAMLRedirector/ClientSAMLLogin.aspx"},{"id":"slack","name":"Slack","img_class":"slack","data_logo":"Slack","configRoute":"/add-ons/slack"}];
      thirdParty.forEach(a => {
        links.push({
          text: a.name,
          type: 'Auth0 (Third Party App)',
          url: 'https://manage.auth0.com/#/externalapps'
        });
      });

      callback();
    },
    (callback) => {
      request(`https://azure.microsoft.com/en-us/documentation/articles/active-directory-saas-tutorial-list/`, (err, res, html) => {
        if (err) {
          return callback(err);
        }

        if (res.statusCode !== 200) {
          return callback(new Error('Unexpected status code: ' + res.statusCode));
        }

        var $ = cheerio.load(html);
        $('div.wa-spacer-docContent table tbody tr a').each((i, element) => {
          var link = $(element);
          links.push({
            text: link.text(),
            type: 'Azure AD',
            url: link.attr('href')
          });
        });

        callback();
      });
    },
    (callback) => {
      request(`https://github.com/okta/UserDocs/tree/master/SAML_Docs`, (err, res, html) => {
        if (err) {
          return callback(err);
        }

        if (res.statusCode !== 200) {
          return callback(new Error('Unexpected status code: ' + res.statusCode));
        }

        var $ = cheerio.load(html);
        $('div.repository-content tr.js-navigation-item a').each((i, element) => {
          var link = $(element);
          if (link.attr('href').indexOf('.html') >= 0
            && (link.attr('href').indexOf('How-to-') >= 0 || link.attr('href').indexOf('Configuring-SAML-') >= 0)) {
            links.push({
              text: link.text()
                .replace('How-to-Enable-SAML-2.0-in-', '')
                .replace('How-to-Configure-SAML-for-', '')
                .replace('How-To-Configure-SAML-1.1-for-', '')
                .replace('How-To-Configure-SAML-2.0-for-', '')
                .replace('How-to-Configure-SAML-1.1-for-', '')
                .replace('How-to-Configure-SAML-2.0-for-', '')
                .replace('How-to-configure-SAML-2.0-for-', '')
                .replace('Configure-SAML-1.1-in-', '')
                .replace('Configure-SAML-2.0-in-', '')
                .replace('Configuring-SAML-2.0-in-', '')
                .replace('Configuring SAML SSO for', '')
                .replace('Configure-CustomSSO-for-', '')
                .replace('Configuring SAML SSO for', '')
                .replace('How-to-', '')
                .replace('-', ' ')
                .replace('.html', ''),
              type: 'Okta',
              url: '?okta=' + link.attr('href')
            });
          }
        });

        callback();
      });
    },
    (callback) => {
      async.each([1, 2, 3, 4], (index, cb) => {
        request(`https://onelogin.zendesk.com/hc/en-us/sections/200245384-Application-Integration-SAML-?page=${index}#articles`, (err, res, html) => {
          if (err) {
            return cb(err);
          }

          if (res.statusCode !== 200) {
            return cb(new Error('Unexpected status code: ' + res.statusCode));
          }

          var $ = cheerio.load(html);
          $('ul.article-list li a').each((i, element) => {
            var link = $(element);
            links.push({
              text: link.text().replace('Configuring SAML for ', ''),
              type: 'OneLogin',
              url: 'https://onelogin.zendesk.com' + link.attr('href')
            });
          });

          cb();
        });
      }, (err) => {
        return callback(err);
      });
  }], (err, context) => {
    done(err, _.sortBy(links, 'text'));
  });
};
<|endoftext|>


<commit_before>import { load, all, exist, getUrl, parse } from './gh-emoji';
import tapeTest from 'tape';

const before = () => {};

const test = (title, cb) => {
  tapeTest(title, (...args) => {
    before();
    cb(...args);
  });
};

test('all() before load()', assert => {
  assert.equal(all(), null, 'must return null');
  assert.end();
});

test('load', assert => {
  load().then((emojis) => {
    assert.equal(typeof emojis, 'object', 'must resolve Object with emojis');
    assert.end();
  });
});

test('all() after load()', assert => {
  assert.equal(typeof all(), 'object', 'must return Object with emojis');
  assert.end();
});

test('exist', assert => {
  assert.ok(exist('8ball'), '8ball emoji exists');
  assert.ok(exist('aries'), 'aries emoji exists');
  assert.ok(!exist('fakeEmoji'), 'fakeEmoji emoji does not exists');
  assert.end();
});

test('getUrl', assert => {
  assert.ok(getUrl('angel').startsWith(
    'https://assets-cdn.github.com/images/icons/emoji/unicode/1f47c.png'),
    'angel emoji must return url'
  );
  assert.ok(getUrl('baby').startsWith(
    'https://assets-cdn.github.com/images/icons/emoji/unicode/1f476.png'),
    'baby emoji must return url'
  );
  assert.ok(!getUrl('fakeEmoji'), 'fakeEmoji emoji must not return url');
  assert.end();
});

test('parse', assert => {
  assert.ok(parse(':bicyclist:') === '',
    'string is properly parsed'
  );
  assert.ok(parse('foo :barber: bar :bell:').includes(
    'https://assets-cdn.github.com/images/icons/emoji/unicode/1f514.png'),
    'parsed string includes url of emoji'
  );
  assert.ok(parse('foo :barber: bar :bell:').includes(
    'https://assets-cdn.github.com/images/icons/emoji/unicode/1f488.png'),
    'parsed string includes url of emoji'
  );
  assert.end();
});
<commit_msg>Add test for no emoji present<commit_after>import { load, all, exist, getUrl, parse } from './gh-emoji';
import tapeTest from 'tape';

const before = () => {};

const test = (title, cb) => {
  tapeTest(title, (...args) => {
    before();
    cb(...args);
  });
};

test('all() before load()', assert => {
  assert.equal(all(), null, 'must return null');
  assert.end();
});

test('load', assert => {
  load().then((emojis) => {
    assert.equal(typeof emojis, 'object', 'must resolve Object with emojis');
    assert.end();
  });
});

test('all() after load()', assert => {
  assert.equal(typeof all(), 'object', 'must return Object with emojis');
  assert.end();
});

test('exist', assert => {
  assert.ok(exist('8ball'), '8ball emoji exists');
  assert.ok(exist('aries'), 'aries emoji exists');
  assert.ok(!exist('fakeEmoji'), 'fakeEmoji emoji does not exists');
  assert.end();
});

test('getUrl', assert => {
  assert.ok(getUrl('angel').startsWith(
    'https://assets-cdn.github.com/images/icons/emoji/unicode/1f47c.png'),
    'angel emoji must return url'
  );
  assert.ok(getUrl('baby').startsWith(
    'https://assets-cdn.github.com/images/icons/emoji/unicode/1f476.png'),
    'baby emoji must return url'
  );
  assert.ok(!getUrl('fakeEmoji'), 'fakeEmoji emoji must not return url');
  assert.end();
});

test('parse', assert => {
  assert.ok(parse('No emoji present') === 'No emoji present',
    'return the same string if no emoji is present'
  );
  assert.ok(parse(':bicyclist:') === '',
    'string is properly parsed'
  );
  assert.ok(parse('foo :barber: bar :bell:').includes(
    'https://assets-cdn.github.com/images/icons/emoji/unicode/1f514.png'),
    'parsed string includes url of emoji'
  );
  assert.ok(parse('foo :barber: bar :bell:').includes(
    'https://assets-cdn.github.com/images/icons/emoji/unicode/1f488.png'),
    'parsed string includes url of emoji'
  );
  assert.end();
});
<|endoftext|>


<commit_before>'use strict'

var test = require('tape')
var profanities = require('.')

test('profanities', function(t) {
  t.equal(typeof profanities, 'object', 'should be an array #1')
  t.equal(Array.isArray(profanities), true, 'should be an array #2')
  t.notEqual(profanities.indexOf('barf'), -1, 'should contain words')
  t.end()
})
<commit_msg>Add tests for different languages<commit_after>'use strict'

var test = require('tape')
var profanities = require('.')

var langs = ['ar-latn', 'es', 'fr', 'pt-br']

test('profanities', function(t) {
  t.equal(typeof profanities, 'object', 'should be an array #1')
  t.equal(Array.isArray(profanities), true, 'should be an array #2')
  t.notEqual(profanities.indexOf('barf'), -1, 'should contain words')

  langs.forEach(function(lang) {
    t.doesNotThrow(function() {
      require('./' + lang)
    }, 'Should support ' + lang)
  })

  t.end()
})
<|endoftext|>


<commit_before>'use strict';

var test = require('tape');
var tryjson = require('./index');

test('parsing valid json', function (t) {
    var obj, objs = [
        null,
        '',
        'txt',
        6,
        -0.2,
        1e6,
        1/3,
        [],
        {},
        true,
        false,
        [[[[[1]]]]],
        {a: 1, b: 2},
        ["a", 2, 3, null],
        [{a:1},{b:2},{c:[[3]]}],
    ];
    t.plan(3 * objs.length);
    objs.forEach(function (o) {
        var json = JSON.stringify(o);
        obj = tryjson.parse(json);
        t.equal(typeof o, typeof obj, json + ' should have the same type');
        t.equal(Array.isArray(o), Array.isArray(obj), json + ' should have the same array status');
        t.deepEqual(o, obj, json + ' should be deeply equal');
    });
});

test('parsing invalid json', function (t) {
    var obj, json = [
        'nul',
        "{'a':1,'b':2}",
        '{"a":1,"b"}',
        '["a",2,3,nul]',
        '{a:1,b:2}',
        '[1,2,3',
        '',
        JSON,
        0/0
    ];
    t.plan(json.length);
    json.forEach(function (s) {
        obj = tryjson.parse(s);
        t.ok(obj === undefined, s + ' should be undefined');
    });
});

test('strigifying valid objects', function (t) {
    var obj, objs = [
        null,
        '',
        'txt',
        6,
        -0.2,
        1e6,
        1/3,
        [],
        {},
        true,
        false,
        [[[[[1]]]]],
        {a: 1, b: 2},
        ["a", 2, 3, null],
        [{a:1},{b:2},{c:[[3]]}],
    ];
    t.plan(3 * objs.length);
    objs.forEach(function (o) {
        var json = tryjson.stringify(o);
        obj = JSON.parse(json);
        t.equal(typeof o, typeof obj, json + ' should have the same type');
        t.equal(Array.isArray(o), Array.isArray(obj), json + ' should have the same array status');
        t.deepEqual(o, obj, json + ' should be deeply equal');
    });
});

test('strigifying invalid objects', function (t) {
    var obj, json, objs = [
        {n: 1},
        {n: 2},
        {n: 3},
        null,
        0/0,
        undefined
    ];
    t.plan(objs.length);
    objs[0].a = objs[0];
    objs[1].a = [[[[[[[[[[objs[2]]]]]]]]]]];
    objs[2].a = {a: {a: {a: {a: {a: objs[1]}}}}};
    objs.forEach(function (s, i) {
        json = tryjson.stringify(s);
        obj = JSON.parse(json);
        t.ok(obj === null, 'object ' + i + ' should be null');
    });
});
<commit_msg>add tests for parsing with fallback<commit_after>'use strict';

var test = require('tape');
var tryjson = require('./index');

test('parsing valid json', function (t) {
    var obj, objs = [
        null,
        '',
        'txt',
        6,
        -0.2,
        1e6,
        1/3,
        [],
        {},
        true,
        false,
        [[[[[1]]]]],
        {a: 1, b: 2},
        ["a", 2, 3, null],
        [{a:1},{b:2},{c:[[3]]}],
    ];
    t.plan(3 * objs.length);
    objs.forEach(function (o) {
        var json = JSON.stringify(o);
        obj = tryjson.parse(json);
        t.equal(typeof o, typeof obj, json + ' should have the same type');
        t.equal(Array.isArray(o), Array.isArray(obj), json + ' should have the same array status');
        t.deepEqual(o, obj, json + ' should be deeply equal');
    });
});

test('parsing invalid json', function (t) {
    var obj, json = [
        'nul',
        "{'a':1,'b':2}",
        '{"a":1,"b"}',
        '["a",2,3,nul]',
        '{a:1,b:2}',
        '[1,2,3',
        '',
        JSON,
        0/0
    ];
    t.plan(json.length);
    json.forEach(function (s) {
        obj = tryjson.parse(s);
        t.ok(obj === undefined, s + ' should be undefined');
    });
});

test('strigifying valid objects', function (t) {
    var obj, objs = [
        null,
        '',
        'txt',
        6,
        -0.2,
        1e6,
        1/3,
        [],
        {},
        true,
        false,
        [[[[[1]]]]],
        {a: 1, b: 2},
        ["a", 2, 3, null],
        [{a:1},{b:2},{c:[[3]]}],
    ];
    t.plan(3 * objs.length);
    objs.forEach(function (o) {
        var json = tryjson.stringify(o);
        obj = JSON.parse(json);
        t.equal(typeof o, typeof obj, json + ' should have the same type');
        t.equal(Array.isArray(o), Array.isArray(obj), json + ' should have the same array status');
        t.deepEqual(o, obj, json + ' should be deeply equal');
    });
});

test('strigifying invalid objects', function (t) {
    var obj, json, objs = [
        {n: 1},
        {n: 2},
        {n: 3},
        null,
        0/0,
        undefined
    ];
    t.plan(objs.length);
    objs[0].a = objs[0];
    objs[1].a = [[[[[[[[[[objs[2]]]]]]]]]]];
    objs[2].a = {a: {a: {a: {a: {a: objs[1]}}}}};
    objs.forEach(function (s, i) {
        json = tryjson.stringify(s);
        obj = JSON.parse(json);
        t.ok(obj === null, 'object ' + i + ' should be null');
    });
});

test('parsing invalid json with fallback', function (t) {
    var obj, json = [
        'nul',
        "{'a':1,'b':2}",
        '{"a":1,"b"}',
        '["a",2,3,nul]',
        '{a:1,b:2}',
        '[1,2,3',
        '',
        JSON,
        0/0
    ], fallback = [
        null,
        undefined,
        '',
        {a: 1},
        JSON
    ];
    t.plan(json.length * fallback.length);
    json.forEach(function (s) {
        fallback.forEach( function (f) {
            obj = tryjson.parse(s, f);
            t.ok(obj === f, s + ' should be parsed to fallback');
        });
    });
});
<|endoftext|>


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

//Get hello function
function GetHello(args, options)
{
  //Get the name
  var name = args[0];

  //Get the hello word
  var hello = (options.idiom === 'english') ? 'Hello' : 'Hola';

  //Display
  console.log('>>>>>>> ' + hello + ' ' + name + '!');

  //Display done message
  nutty.display.done('');
}

//Add a basic command
nutty.add({
  command: 'hello',
  description: 'Get hello with your name',
  usage: 'myapp hello [your_name][options]',
  callback: GetHello,
  options: [
    { name: 'idiom', description: 'Set the idiom. Available idioms: english|spanish', default: 'english', mandatory: true }
  ]
});

//Run the CLI
nutty.run();
<commit_msg>test.js: updated test<commit_after>//Import nutty
var nutty = require('./index.js');

//Get hello function
function GetHello(args, options)
{
  //Get the name
  var name = args[0];

  //Get the hello word
  var hello = (options.idiom === 'english') ? 'Hello' : 'Hola';

  //Display
  console.log('>>>>>>> ' + hello + ' ' + name + '!');

  //Display done message
  nutty.display.done('');
}

//Set the CLI name
nutty.name('myapp');

//Set the CLI description
nutty.description('My test app');

//Set the CLI version
nutty.version('1.0.0');

//Add a basic command
nutty.add({
  command: 'hello',
  description: 'Get hello with your name',
  usage: 'myapp hello [your_name][options]',
  callback: GetHello,
  options: [
    { name: 'idiom', description: 'Set the idiom. Available idioms: english|spanish', default: 'english', mandatory: true }
  ]
});

//Run the CLI
nutty.run();
<|endoftext|>


<commit_before>/**
 * @author Félix Girault <felix.girault@gmail.com>
 * @license MIT
 */
'use strict';

var shallowCompare = require('react-addons-shallow-compare');
var assert = require('assert');
var decorate = require('./index');

/**
 *
 */
describe('pure-render-decorator', function() {
  function Component() {};
  decorate(Component);

  var component = new Component();
  component.props = { foo: 1 };
  component.state = { bar: 2 };

  /**
   *
   */
  it('should add a method named shouldComponentUpdate', function() {
    assert.ok('shouldComponentUpdate' in component);
    assert.ok(typeof component.shouldComponentUpdate === 'function');
  });

  /**
   *
   */
  it('should use shallowCompare to compare props and state', function() {
    assert.equal(
      component.shouldComponentUpdate({}, {}),
      shallowCompare(component, {}, {})
    );

    assert.equal(
      component.shouldComponentUpdate(
        component.props,
        component.state
      ),
      shallowCompare(
        component,
        component.props,
        component.state
      )
    );
  });
});
<commit_msg>Update tests.<commit_after>/**
 * @author Félix Girault <felix.girault@gmail.com>
 * @license MIT
 */
'use strict';

var assert = require('assert');
var decorate = require('./index');

/**
 *
 */
describe('pure-render-decorator', function() {
  function Component() {};
  decorate(Component);

  var component = new Component();
  component.props = { foo: 1 };
  component.state = { bar: 2 };

  it('should add a method named shouldComponentUpdate', function() {
    assert.ok('shouldComponentUpdate' in component);
    assert.ok(typeof component.shouldComponentUpdate === 'function');
  });

  it('should return true if the props and state are different', function() {
    assert.ok(component.shouldComponentUpdate({}, {}));
  });

  it('should return false if the props and state are reference-equals', function() {
    assert.ok(
      !component.shouldComponentUpdate(
        component.props,
        component.state
      )
    );
  });

  it('should return false if props and state are shallow-equals but different references', function() {
    assert.ok(
      !component.shouldComponentUpdate(
        { foo: 1 },
        { bar: 2 }
      )
    );
  });
});
<|endoftext|>


<commit_before>const tape = require('tape')
const wrappedMethods = require('./methods')

var tapeMock = (arg0, arg1, cb) => {
  cb = cb || arg1 || arg0 // `arg0` and `arg1` are optional in `tape`
  cb(testObjectMock)
  return [arg0, arg1, cb]
}
var testObjectMock = { end: function () {} }
wrappedMethods.forEach(elem => {
  testObjectMock[elem] = function () { return arguments }
})
global.flipTape = { tapeMock }
const flippedTape = require('.')

var arityToMethod = {
  1: ['fail', 'pass', 'skip'],
  2: ['ok', 'notOk', 'error'],
  3: ['equal', 'notEqual', 'deepEqual', 'notDeepEqual', 'deepLooseEqual', 'notDeepLooseEqual', 'throws', 'doesNotThrow', 'comment']
}

flippedTape(x => {
  tape('`String.prototype.test(cb)`', t => {
    t.plan(2)
    let cbArgument = null
    let cbMock = t => { cbArgument = t }

    let testOpts = {}
    let result = 'msg'.test(testOpts, cbMock)
    result[0] = result[0].toString()
    t.deepEqual(result, tapeMock('msg', testOpts, cbMock), '`tape` is attached to `String.prototype` as `test`')

    'msg'.test(cbMock)
    t.deepEqual(cbArgument, testObjectMock, 'test object is passed on to cb')
  })

  tape('`String.prototype.t(cb)`', t => {
    t.plan(1)

    let cbArgument = null
    let cbMock = t => { cbArgument = t }
    'msg'.t(cbMock)
    t.deepEqual(cbArgument, testObjectMock, 'test object is passed on to cb')
  })

  Object.keys(arityToMethod).forEach(arity => {
    arity = +arity
    arityToMethod[arity].forEach(method => {
      let args = callMethod(method, arity)

      tape('`String.prototype.' + method + '()`', t => {
        if (arity === 3) {
          t.equal(args[1].toString(), 'arg1', 'second argument is passed on')
        }

        if ([2, 3].includes(arity)) {
          t.equal(args[0].toString(), 'arg0', 'first argument is passed on')
        }

        t.equal(args[arity - 1].toString(), 'msg', 'message argument is passed on')

        t.end()
      })
    })
  })
})

function callMethod (method, arity) {
  if (arity === 3) return 'msg'[method]('arg0', 'arg1')
  if (arity === 2) return 'msg'[method]('arg0')
  return 'msg'[method]()
}
<commit_msg>check equality of results not of functions<commit_after>const tape = require('tape')
const wrappedMethods = require('./methods')

var tapeMock = (arg0, arg1, cb) => {
  cb = cb || arg1 || arg0 // `arg0` and `arg1` are optional in `tape`
  let res = cb(testObjectMock)
  return [arg0, arg1, res]
}
var testObjectMock = { end: function () {} }
wrappedMethods.forEach(elem => {
  testObjectMock[elem] = function () { return arguments }
})
global.flipTape = { tapeMock }
const flippedTape = require('.')

var arityToMethod = {
  1: ['fail', 'pass', 'skip'],
  2: ['ok', 'notOk', 'error'],
  3: ['equal', 'notEqual', 'deepEqual', 'notDeepEqual', 'deepLooseEqual', 'notDeepLooseEqual', 'throws', 'doesNotThrow', 'comment']
}

flippedTape(x => {
  tape('`String.prototype.test(cb)`', t => {
    t.plan(2)
    let cbArgument = null
    let cbMock = t => { cbArgument = t }

    let testOpts = {test: 123}
    let result = 'msg'.test(testOpts, cbMock)
    result[0] = result[0].toString()
    t.deepEqual(result, tapeMock('msg', testOpts, cbMock), '`tape` is attached to `String.prototype` as `test`')

    'msg'.test(cbMock)
    t.deepEqual(cbArgument, testObjectMock, 'test object is passed on to cb')
  })

  tape('`String.prototype.t(cb)`', t => {
    t.plan(1)

    let cbArgument = null
    let cbMock = t => { cbArgument = t }
    'msg'.t(cbMock)
    t.deepEqual(cbArgument, testObjectMock, 'test object is passed on to cb')
  })

  Object.keys(arityToMethod).forEach(arity => {
    arity = +arity
    arityToMethod[arity].forEach(method => {
      let args = callMethod(method, arity)

      tape('`String.prototype.' + method + '()`', t => {
        if (arity === 3) {
          t.equal(args[1].toString(), 'arg1', 'second argument is passed on')
        }

        if ([2, 3].includes(arity)) {
          t.equal(args[0].toString(), 'arg0', 'first argument is passed on')
        }

        t.equal(args[arity - 1].toString(), 'msg', 'message argument is passed on')

        t.end()
      })
    })
  })
})

function callMethod (method, arity) {
  if (arity === 3) return 'msg'[method]('arg0', 'arg1')
  if (arity === 2) return 'msg'[method]('arg0')
  return 'msg'[method]()
}
<|endoftext|>


<commit_before>/**
 * Baobab Deku Unit Tests
 * =======================
 *
 */
var assert = require('assert'),
    Baobab = require('baobab'),
    deku = require('deku'),
    lib = require('./index.js');

var createDispatcher = lib.createDispatcher,
    branch = lib.branch;

/**
 * Dispatcher.
 */
describe('#createDispatcher', function() {

  it('should work as expected.', function() {
    var tree = new Baobab({name: 'John', surname: 'Ney'}, {asynchronous: false});

    var dispatcher = createDispatcher(tree);

    var action = function(tree, name, surname) {
      tree.set('name', name);
      tree.set('surname', surname);
    };

    dispatcher(action, 'Jack', 'Davout');

    assert.deepEqual(tree.get(), {name: 'Jack', surname: 'Davout'});
  });
});

/**
 * Branching.
 */
describe('#branch', function() {

  it('should throw if the mapping is invalid.', function() {
    assert.throws(function() {
      branch(null, {});
    }, /invalid/);
  });
});
<commit_msg>branch tests<commit_after>/**
 * Baobab Deku Unit Tests
 * =======================
 *
 */
var assert = require('assert'),
    Baobab = require('baobab'),
    deku = require('deku'),
    lib = require('./index.js');

var createDispatcher = lib.createDispatcher,
    branch = lib.branch,
    render = deku.string.renderString,
    h = deku.element;

/**
 * Dispatcher.
 */
describe('#createDispatcher', function() {

  it('should work as expected.', function() {
    var tree = new Baobab({name: 'John', surname: 'Ney'}, {asynchronous: false});

    var dispatcher = createDispatcher(tree);

    var action = function(tree, name, surname) {
      tree.set('name', name);
      tree.set('surname', surname);
    };

    dispatcher(action, 'Jack', 'Davout');

    assert.deepEqual(tree.get(), {name: 'Jack', surname: 'Davout'});
  });
});

/**
 * Branching.
 */
describe('#branch', function() {

  it('should throw if the mapping is invalid.', function() {
    assert.throws(function() {
      branch(null, {});
    }, /invalid/);
  });

  it('should throw if the tree is not found in context.', function() {
    var tree = new Baobab({name: 'John'}, {asynchronous: false});

    var composedComponent = branch({name: ['name']}, function(model) {
      return h('div', null, ['Hello']);
    });

    assert.throws(function() {
      render(h(composedComponent));
    }, /tree in context/);
  });

  it('should properly pass props to the composed components.', function() {
    var tree = new Baobab({name: 'John'}, {asynchronous: false});

    var composedComponent = branch({name: ['name']}, function(model) {
      return h('div', null, model.props.name);
    });

    var html = render(h(composedComponent), {tree: tree});

    assert.strictEqual(html, '
John
');

    tree.set('name', 'Jack');

    var html = render(h(composedComponent), {tree: tree});

    assert.strictEqual(html, '
Jack
');
  });
});
<|endoftext|>


<commit_before>const assert = require('assert');
const fs = require("fs");
const geoIndex = require("./geojson-lookup");

function loadGeoJson()
{
    return  JSON.parse(fs.readFileSync("testdata.geojson", 'utf8'));
}

var geojs = loadGeoJson();

var geo = new geoIndex.Collection(["areaType","parentId"],geojs);

//Test Polygon lookup by point////
var resByPoint = geo.getByPoint(28.98066, 36.25222);
assert.equal(resByPoint.length, 2);
assert.equal(resByPoint[0].properties.areaId, 'a5-14');
assert.equal(resByPoint[1].properties.areaId, 'a5-0');

var resByProp = (geo.query("areaType", "!=" ,'1','get').and("parentId", "=", "null").or("areaType","=","3").get());
assert.equal(resByProp.length, 2 );
assert.equal(resByProp[0].properties.areaId, "a5-0" );
assert.equal(resByProp[1].properties.areaId, "a5-5" );

console.log("Passed..");<commit_msg>Fix path for test<commit_after>const assert = require('assert');
const fs = require("fs");
const geoIndex = require("./geojson-lookup");

function loadGeoJson()
{
    return  JSON.parse(fs.readFileSync("/home/travis/build/nestrom/geojson-lookup/testdata.geojson", 'utf8'));
}

var geojs = loadGeoJson();

var geo = new geoIndex.Collection(["areaType","parentId"],geojs);

//Test Polygon lookup by point////
var resByPoint = geo.getByPoint(28.98066, 36.25222);
assert.equal(resByPoint.length, 2);
assert.equal(resByPoint[0].properties.areaId, 'a5-14');
assert.equal(resByPoint[1].properties.areaId, 'a5-0');

var resByProp = (geo.query("areaType", "!=" ,'1','get').and("parentId", "=", "null").or("areaType","=","3").get());
assert.equal(resByProp.length, 2 );
assert.equal(resByProp[0].properties.areaId, "a5-0" );
assert.equal(resByProp[1].properties.areaId, "a5-5" );

console.log("Passed..");<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(break): 2017-7-17 09:17:28<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-24 00:34:25<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>import test from 'ava';
import fn from './';

test(async t => {
	t.is(await fn('com.apple.Safari'), 'Safari');
});
<commit_msg>tweak<commit_after>import test from 'ava';
import fn from '.';

test(async t => {
	t.is(await fn('com.apple.Safari'), 'Safari');
});
<|endoftext|>


<commit_before>/*eslint-disable no-multi-spaces, key-spacing*/

import {test} from 'tape';
import {parse, transition, create, throwError } from './';

const sample = [
    {ev: 'load',   from: 'none',      to: 'loading'},
    {ev: 'load',   from: 'loading',   to: 'loading'},
    {ev: 'load',   from: 'loaded',    to: 'reloading'},
    {ev: 'load',   from: 'reloading', to: 'reloading'},

    {ev: 'fail',   from: 'loading',   to: 'none'},
    {ev: 'fail',   from: 'saving',    to: 'changed'},
    {ev: 'fail',   from: 'reloading', to: 'loaded'},

    {ev: 'pass',   from: 'loading',   to: 'loaded'},
    {ev: 'pass',   from: 'loaded',    to: 'loaded'},
    {ev: 'pass',   from: 'saving',    to: 'loaded'},
    {ev: 'pass',   from: 'reloading', to: 'loaded'},

    {ev: 'change', from: 'loaded',    to: 'changed'},
    {ev: 'change', from: 'changed',   to: 'changed'},

    {ev: 'save',   from: 'changed',   to: 'saving'},
];

test('parse', t => {
    const fsm = parse(sample);

    t.same(fsm.EVENT, {
        load:   'load',
        fail:   'fail',
        pass:   'pass',
        change: 'change',
        save:   'save',
    }, 'events are as expected');

    t.same(fsm.STATE, {
        none:      'none',
        loading:   'loading',
        loaded:    'loaded',
        reloading: 'reloading',
        saving:    'saving',
        changed:   'changed',
    }, 'states are as expected');

    t.same(fsm.table, {
        load: {
            none:      'loading',
            loading:   'loading',
            loaded:    'reloading',
            reloading: 'reloading',
        },
        fail: {
            loading:   'none',
            saving:    'changed',
            reloading: 'loaded',
        },
        pass: {
            loading:   'loaded',
            loaded:    'loaded',
            saving:    'loaded',
            reloading: 'loaded',
        },
        change: {
            loaded:  'changed',
            changed: 'changed',
        },
        save: {
            changed: 'saving',
        },
    }, 'table is as expected');

    t.end();
});

test('throwError', t => {
    try {
        throwError('table', 'state', 'event');
    } catch (e) {
        t.is(e.name, 'Error', 'name');
        t.is(e.message, 'Invalid transition', 'message');
        t.is(e.table, 'table', 'table is table');
        t.is(e.state, 'state', 'state is state');
        t.is(e.event, 'event', 'event is event');
    }
    t.end();
});

test('transition', t => {
    const fsm = parse(sample);

    t.throws(() => { transition(throwError); }, Error, 'throws exception');

    try {
        transition(throwError);
    } catch (e) {
        t.is(e.table, undefined, 'table is undefined');
        t.is(e.state, undefined, 'state is undefined');
        t.is(e.event, undefined, 'event is undefined');
    }

    try {
        transition(throwError, fsm.table);
    } catch (e) {
        t.is(e.table, fsm.table, 'table is {}');
        t.is(e.state, undefined, 'state is undefined');
        t.is(e.event, undefined, 'event is undefined');
    }

    try {
        transition(throwError, fsm.table, undefined, fsm.EVENT.load);
    } catch (e) {
        t.is(e.table, fsm.table, 'table is {}');
        t.is(e.state, undefined, 'state is undefined');
        t.is(e.event, fsm.EVENT.load, 'event is load');
    }

    try {
        transition(throwError, fsm.table, fsm.STATE.none, fsm.EVENT.save);
    } catch (e) {
        t.is(e.table, fsm.table, 'table is {}');
        t.is(e.state, fsm.STATE.none, 'state is none');
        t.is(e.event, fsm.EVENT.save, 'event is save');
    }

    t.is(transition(throwError, fsm.table, fsm.STATE.none, fsm.EVENT.load),
         fsm.STATE.loading,
         'new state is loading');

    t.end();
});

test('create', t => {
    const p = parse(sample);
    const trans = create(p.table, p.STATE.none);

    t.is(trans(), p.STATE.none, 'initial state is none');
    t.is(trans(p.EVENT.load)(), p.STATE.loading, 'state is loading');

    t.end();
});
<commit_msg>improve test descriptions<commit_after>/*eslint-disable no-multi-spaces, key-spacing*/

import {test} from 'tape';
import {parse, transition, create, throwError } from './';

const sample = [
    {ev: 'load',   from: 'none',      to: 'loading'},
    {ev: 'load',   from: 'loading',   to: 'loading'},
    {ev: 'load',   from: 'loaded',    to: 'reloading'},
    {ev: 'load',   from: 'reloading', to: 'reloading'},

    {ev: 'fail',   from: 'loading',   to: 'none'},
    {ev: 'fail',   from: 'saving',    to: 'changed'},
    {ev: 'fail',   from: 'reloading', to: 'loaded'},

    {ev: 'pass',   from: 'loading',   to: 'loaded'},
    {ev: 'pass',   from: 'loaded',    to: 'loaded'},
    {ev: 'pass',   from: 'saving',    to: 'loaded'},
    {ev: 'pass',   from: 'reloading', to: 'loaded'},

    {ev: 'change', from: 'loaded',    to: 'changed'},
    {ev: 'change', from: 'changed',   to: 'changed'},

    {ev: 'save',   from: 'changed',   to: 'saving'},
];

test('parse', t => {
    const fsm = parse(sample);

    t.same(fsm.EVENT, {
        load:   'load',
        fail:   'fail',
        pass:   'pass',
        change: 'change',
        save:   'save',
    }, 'events are as expected');

    t.same(fsm.STATE, {
        none:      'none',
        loading:   'loading',
        loaded:    'loaded',
        reloading: 'reloading',
        saving:    'saving',
        changed:   'changed',
    }, 'states are as expected');

    t.same(fsm.table, {
        load: {
            none:      'loading',
            loading:   'loading',
            loaded:    'reloading',
            reloading: 'reloading',
        },
        fail: {
            loading:   'none',
            saving:    'changed',
            reloading: 'loaded',
        },
        pass: {
            loading:   'loaded',
            loaded:    'loaded',
            saving:    'loaded',
            reloading: 'loaded',
        },
        change: {
            loaded:  'changed',
            changed: 'changed',
        },
        save: {
            changed: 'saving',
        },
    }, 'table is as expected');

    t.end();
});

test('throwError', t => {
    try {
        throwError('table', 'state', 'event');
    } catch (e) {
        t.is(e.name, 'Error', 'name is Error');
        t.is(e.message, 'Invalid transition', 'message is Invalid transition');
        t.is(e.table, 'table', 'table is table');
        t.is(e.state, 'state', 'state is state');
        t.is(e.event, 'event', 'event is event');
    }
    t.end();
});

test('empty transition throws error', t => {
    try {
        transition(throwError);
    } catch (e) {
        t.is(e.table, undefined, 'table is undefined');
        t.is(e.state, undefined, 'state is undefined');
        t.is(e.event, undefined, 'event is undefined');
    }

    t.end();
});

test('incomplete transition throws error', t => {
    const fsm = parse(sample);

    try {
        transition(throwError, fsm.table);
    } catch (e) {
        t.is(e.table, fsm.table, 'table is {}');
        t.is(e.state, undefined, 'state is undefined');
        t.is(e.event, undefined, 'event is undefined');
    }

    try {
        transition(throwError, fsm.table, undefined, fsm.EVENT.load);
    } catch (e) {
        t.is(e.table, fsm.table, 'table is {}');
        t.is(e.state, undefined, 'state is undefined');
        t.is(e.event, fsm.EVENT.load, 'event is load');
    }

    t.end();
});

test('impossible transition throws error', t => {
    const fsm = parse(sample);

    try {
        transition(throwError, fsm.table, fsm.STATE.none, fsm.EVENT.save);
    } catch (e) {
        t.is(e.table, fsm.table, 'table is {}');
        t.is(e.state, fsm.STATE.none, 'state is none');
        t.is(e.event, fsm.EVENT.save, 'event is save');
    }

    t.end();
});

test('correct transition works', t => {
    const fsm = parse(sample);

    t.is(transition(throwError, fsm.table, fsm.STATE.none, fsm.EVENT.load),
         fsm.STATE.loading,
         'new state is loading');

    t.end();
});

test('create', t => {
    const p = parse(sample);
    const trans = create(p.table, p.STATE.none);

    t.is(trans(), p.STATE.none, 'initial state is none');
    t.is(trans(p.EVENT.load)(), p.STATE.loading, 'state is loading');

    t.end();
});
<|endoftext|>


<commit_before>import test from 'ava'
import path from 'path'
import assert from 'yeoman-assert'
import helpers from 'yeoman-test'

test('uses the right defaults on bare project', async (t) => { // eslint-disable-line
  const dir = await runGenerator(null, null, null)

  assert.file('package.json')

  assert.JSONFileContent('package.json', { // eslint-disable-line
    name: dir,
    version: '1.0.0',
    main: 'index.js',
    license: 'ISC',
    scripts: {
      test: 'echo \"Error: no test specified\" && exit 1'
    }
  })
})

test('uses prompt responses', async (t) => { // eslint-disable-line
  await runGenerator(
    {
      name: 'foo',
      description: 'lorem ipsum dolor',
      version: '9.9.9',
      main: 'app.js',
      repo: 'foo/bar',
      keywords: 'foo bar baz qux',
      author: 'foobar',
      license: 'MIT',
      test: 'ava --verbose'
    })

  assert.file('package.json')

  assert.JSONFileContent('package.json', {
    name: 'foo',
    description: 'lorem ipsum dolor',
    version: '9.9.9',
    main: 'app.js',
    repository: 'foo/bar',
    keywords: [
      'foo',
      'bar',
      'baz',
      'qux'
    ],
    author: 'foobar',
    license: 'MIT',
    scripts: {
      test: 'ava --verbose'
    }
  })
})

test('uses supplied defaults', async (t) => { // eslint-disable-line
  await runGenerator(
    null,
    {
      name: 'foo',
      description: 'lorem ipsum dolor',
      version: '9.9.9',
      main: 'app.js',
      repo: 'foo/bar',
      keywords: [
        'foo',
        'bar',
        'baz',
        'qux'
      ],
      author: 'foobar',
      license: 'MIT',
      test: 'ava --verbose'
    })

  assert.file('package.json')

  assert.JSONFileContent('package.json', {
    name: 'foo',
    description: 'lorem ipsum dolor',
    version: '9.9.9',
    main: 'app.js',
    repository: 'foo/bar',
    keywords: [
      'foo',
      'bar',
      'baz',
      'qux'
    ],
    author: 'foobar',
    license: 'MIT',
    scripts: {
      test: 'ava --verbose'
    }
  })
})

test('respects skip-* options', async (t) => { // eslint-disable-line
  await runGenerator(
    null,
    {
      'skip-name': true
    })

  assert.file('package.json')
  assert.JSONFileContent('package.json', { name: undefined, 'skip-name': undefined })
})

test('respects skip-test option', async (t) => { // eslint-disable-line
  await runGenerator(
    null,
    {
      'skip-test': true
    })

  assert.file('package.json')
  assert.JSONFileContent('package.json', { scripts: { test: undefined } })
})

function runGenerator(prompts, opts) {
  let basename

  return new Promise((resolve) => {
    helpers.run(path.join(__dirname, 'app'))
      .inTmpDir((d) => basename = path.basename(d))
      .withOptions(opts || {})
      .withPrompts(prompts || {})
      .on('end', () =>
        resolve(basename))
    })
}
<commit_msg>Add test for git repo inference (100% test coverage :tada:)<commit_after>import { execSync } from 'child_process'
import test from 'ava'
import path from 'path'
import assert from 'yeoman-assert'
import helpers from 'yeoman-test'

test('uses the right defaults on bare project', async (t) => { // eslint-disable-line
  const dir = await runGenerator(null, null, null)

  assert.file('package.json')

  assert.JSONFileContent('package.json', { // eslint-disable-line
    name: dir,
    version: '1.0.0',
    main: 'index.js',
    license: 'ISC',
    scripts: {
      test: 'echo \"Error: no test specified\" && exit 1'
    }
  })
})

test('uses prompt responses', async (t) => { // eslint-disable-line
  await runGenerator(
    {
      name: 'foo',
      description: 'lorem ipsum dolor',
      version: '9.9.9',
      main: 'app.js',
      repo: 'foo/bar',
      keywords: 'foo bar baz qux',
      author: 'foobar',
      license: 'MIT',
      test: 'ava --verbose'
    })

  assert.file('package.json')

  assert.JSONFileContent('package.json', {
    name: 'foo',
    description: 'lorem ipsum dolor',
    version: '9.9.9',
    main: 'app.js',
    repository: 'foo/bar',
    keywords: [
      'foo',
      'bar',
      'baz',
      'qux'
    ],
    author: 'foobar',
    license: 'MIT',
    scripts: {
      test: 'ava --verbose'
    }
  })
})

test('uses supplied defaults', async (t) => { // eslint-disable-line
  await runGenerator(
    null,
    {
      name: 'foo',
      description: 'lorem ipsum dolor',
      version: '9.9.9',
      main: 'app.js',
      repo: 'foo/bar',
      keywords: [
        'foo',
        'bar',
        'baz',
        'qux'
      ],
      author: 'foobar',
      license: 'MIT',
      test: 'ava --verbose'
    })

  assert.file('package.json')

  assert.JSONFileContent('package.json', {
    name: 'foo',
    description: 'lorem ipsum dolor',
    version: '9.9.9',
    main: 'app.js',
    repository: 'foo/bar',
    keywords: [
      'foo',
      'bar',
      'baz',
      'qux'
    ],
    author: 'foobar',
    license: 'MIT',
    scripts: {
      test: 'ava --verbose'
    }
  })
})

test('respects skip-* options', async (t) => { // eslint-disable-line
  await runGenerator(
    null,
    {
      'skip-name': true
    })

  assert.file('package.json')
  assert.JSONFileContent('package.json', { name: undefined, 'skip-name': undefined })
})

test('respects skip-test option', async (t) => { // eslint-disable-line
  await runGenerator(
    null,
    {
      'skip-test': true
    })

  assert.file('package.json')
  assert.JSONFileContent('package.json', { scripts: { test: undefined } })
})

test('infers repository field from git repo', async (t) => { // eslint-disable-line
  await runGenerator(
    null,
    null,
    (dir) => {
      execSync('git init', { cwd: dir })
      execSync('git remote add origin https://example.com/foo.git', { cwd: dir })
    })

  assert.file('package.json')
  assert.JSONFileContent('package.json', {
    repository: {
      type: 'git',
      url: 'https://example.com/foo.git'
    }
  })
})

function runGenerator(prompts, opts, pre) {
  let basename

  return new Promise((resolve) => {
    helpers.run(path.join(__dirname, 'app'))
      .inTmpDir((dir) => {
        if (pre) {
          pre(dir)
        }
        basename = path.basename(dir)
      })
      .withOptions(opts || {})
      .withPrompts(prompts || {})
      .on('end', () =>
        resolve(basename))
    })
}
<|endoftext|>


<commit_before>var useragent = require('./main.js');
var r = require('ua-parser');

var chrome = useragent.chrome('41.0.2228.0');
var chrome_advanced = useragent.chrome_advanced(version = '41.0.2228.0', webkit_version = '537.36');
var firefox = useragent.firefox('41.0');
var firefox_advanced = useragent.firefox_advanced(version = '41.0', gecko_version = '20100101');
var opera = useragent.opera('12.6');
var opera_advanced = useragent.opera_advanced(version = '12.6', presto_version = '2.12.388', opera_version = '9.80');

console.log('\n%s (%s): \t %s', r.parse(chrome).ua.toString(), r.parse(chrome).os.toString(), chrome);
console.log('%s \t (%s): \t %s', r.parse(firefox).ua.toString(), r.parse(firefox).os.toString(), firefox);
console.log('%s \t (%s): \t %s', r.parse(opera).ua.toString(), r.parse(opera).os.toString(), opera);

console.log('\n%s (%s): \t %s', r.parse(chrome_advanced).ua.toString(), r.parse(chrome_advanced).os.toString(), chrome_advanced);
console.log('%s \t (%s): \t %s', r.parse(firefox_advanced).ua.toString(), r.parse(firefox_advanced).os.toString(), firefox_advanced);
console.log('%s \t (%s): \t %s\n', r.parse(opera_advanced).ua.toString(), r.parse(opera_advanced).os.toString(), opera_advanced);
<commit_msg>remove tabs<commit_after>var useragent = require('./main.js');
var r = require('ua-parser');

var chrome = useragent.chrome('41.0.2228.0');
var chrome_advanced = useragent.chrome_advanced(version = '41.0.2228.0', webkit_version = '537.36');
var firefox = useragent.firefox('41.0');
var firefox_advanced = useragent.firefox_advanced(version = '41.0', gecko_version = '20100101');
var opera = useragent.opera('12.6');
var opera_advanced = useragent.opera_advanced(version = '12.6', presto_version = '2.12.388', opera_version = '9.80');

console.log('\n%s (%s): %s', r.parse(chrome).ua.toString(), r.parse(chrome).os.toString(), chrome);
console.log('%s \t (%s): %s', r.parse(firefox).ua.toString(), r.parse(firefox).os.toString(), firefox);
console.log('%s \t (%s): %s', r.parse(opera).ua.toString(), r.parse(opera).os.toString(), opera);

console.log('\n%s (%s): %s', r.parse(chrome_advanced).ua.toString(), r.parse(chrome_advanced).os.toString(), chrome_advanced);
console.log('%s \t (%s): %s', r.parse(firefox_advanced).ua.toString(), r.parse(firefox_advanced).os.toString(), firefox_advanced);
console.log('%s \t (%s): %s\n', r.parse(opera_advanced).ua.toString(), r.parse(opera_advanced).os.toString(), opera_advanced);
<|endoftext|>


<commit_before>const test = require('tape')
const fs = require('fs')
const path = require('path')
const load = require('load-json-file')
const write = require('write-json-file')
const chunk = require('lodash.chunk')
const turf = require('@turf/helpers')
const featureCollection = require('@turf/helpers').featureCollection
const PolyK = require('.')

const directories = {
  in: path.join(__dirname, 'test', 'in') + path.sep,
  out: path.join(__dirname, 'test', 'out') + path.sep
}

const fixtures = {}
fs.readdirSync(directories.in).forEach(filename => {
  const name = path.parse(filename).name
  fixtures[name] = load.sync(directories.in + filename)
})

/**
 * Convert GeoJSON Polygon to Polygon
 *
 * @param {Feature<Polygon>} polygon
 * @returns {number[]} Array Polygon
 */
function convertToArray (polygon) {
  return [].concat.apply([], polygon.geometry.coordinates[0])
}

/**
 * Convert Array Polygon to FeatureCollection GeoJSON Polygon
 *
 * @param {number[]} array
 * @returns {FeatureCollection<Polygon>}
 */
function convertToGeoJSON (array) {
  const geojson = featureCollection([])
  array.forEach((item) => {
    var coords = chunk(item, 2)
    coords.push(coords[0])
    geojson.features.push(turf.polygon([coords]))
  })
  return geojson
}

test('PolyK.Slice', t => {
  // Define fixtures
  const polygon = fixtures['polygon']
  const line = fixtures['line']
  const start = line.geometry.coordinates[0]
  const stop = line.geometry.coordinates[1]
  line.properties['stroke'] = '#f0f'
  line.properties['stroke-width'] = 6

  // Slice
  const sliced = PolyK.Slice(convertToArray(polygon), start[0], start[1], stop[0], stop[1])
  const results = convertToGeoJSON(sliced)
  results.features.push(line)

  // Save Results
  if (process.env.REGEN) {
    write.sync(directories.out + 'slice.geojson', results)
  }

  t.deepEquals(results, load.sync(directories.out + 'slice.geojson'))
  t.end()
})

test('PolyK.Raycast', t => {
  const polygon = fixtures['polygon']
  const start = fixtures['start'].geometry.coordinates
  const direction = fixtures['direction'].geometry.coordinates

  const raycast = PolyK.Raycast(convertToArray(polygon), start[0], start[1], direction[0], direction[1])

  if (process.env.REGEN) {
    write.sync(directories.out + 'raycast.json', raycast)
  }
  t.deepEquals(raycast, load.sync(directories.out + 'raycast.json'))
  t.end()
})
<commit_msg>Add more Raycast fixtures<commit_after>const test = require('tape')
const fs = require('fs')
const path = require('path')
const load = require('load-json-file')
const write = require('write-json-file')
const chunk = require('lodash.chunk')
const turf = require('@turf/helpers')
const featureCollection = require('@turf/helpers').featureCollection
const PolyK = require('.')

const directories = {
  in: path.join(__dirname, 'test', 'in') + path.sep,
  out: path.join(__dirname, 'test', 'out') + path.sep
}

const fixtures = {}
fs.readdirSync(directories.in).forEach(filename => {
  const name = path.parse(filename).name
  fixtures[name] = load.sync(directories.in + filename)
})

/**
 * Convert GeoJSON Polygon to Polygon
 *
 * @param {Feature<Polygon>} polygon
 * @returns {number[]} Array Polygon
 */
function convertToArray (polygon) {
  return [].concat.apply([], polygon.geometry.coordinates[0])
}

/**
 * Convert Array Polygon to FeatureCollection GeoJSON Polygon
 *
 * @param {number[]} array
 * @returns {FeatureCollection<Polygon>}
 */
function convertToGeoJSON (array) {
  const geojson = featureCollection([])
  array.forEach((item) => {
    var coords = chunk(item, 2)
    coords.push(coords[0])
    geojson.features.push(turf.polygon([coords]))
  })
  return geojson
}

test('PolyK.Slice', t => {
  // Define fixtures
  const polygon = fixtures['polygon']
  const line = fixtures['line']
  const start = line.geometry.coordinates[0]
  const stop = line.geometry.coordinates[1]
  line.properties['stroke'] = '#f0f'
  line.properties['stroke-width'] = 6

  // Slice
  const sliced = PolyK.Slice(convertToArray(polygon), start[0], start[1], stop[0], stop[1])

  // Save Results
  const results = turf.featureCollection([
    convertToGeoJSON(sliced),
    line
  ])
  if (process.env.REGEN) {
    write.sync(directories.out + 'slice.json', sliced)
    write.sync(directories.out + 'slice-results.geojson', results)
  }

  // Tests
  t.deepEquals(sliced, load.sync(directories.out + 'slice.json'))
  t.deepEquals(results, load.sync(directories.out + 'slice-results.geojson'))
  t.end()
})

test('PolyK.Raycast', t => {
  // Define fixtures
  const polygon = fixtures['polygon']
  const start = fixtures['start'].geometry.coordinates
  const direction = fixtures['direction'].geometry.coordinates

  // Raycast
  const raycast = PolyK.Raycast(convertToArray(polygon), start[0], start[1], direction[0], direction[1])

  // Save Results
  const results = turf.featureCollection([
    polygon,
    fixtures['start'],
    fixtures['direction'],
    turf.point([raycast.norm.x, raycast.norm.y], {norm: true}),
    turf.point([raycast.refl.x, raycast.refl.y], {refl: true})
  ])
  if (process.env.REGEN) {
    write.sync(directories.out + 'raycast.json', raycast)
    write.sync(directories.out + 'raycast-results.geojson', results)
  }

  // Tests
  t.deepEquals(raycast, load.sync(directories.out + 'raycast.json'))
  t.deepEquals(results, load.sync(directories.out + 'raycast-results.geojson'))
  t.end()
})
<|endoftext|>


<commit_before>"use strict";

/*  ------------------------------------------------------------------------ */

const [processPath, , exchangeId = null, exchangeSymbol = null] = process.argv.filter (x => !x.startsWith ('--'))
const ccxtFile = process.argv.includes ('--es6') ? 'ccxt.js' : 'ccxt-es5.js'

/*  ------------------------------------------------------------------------ */

const ccxt      = require ('./' + ccxtFile)
const countries = require ('./countries')

/*  ------------------------------------------------------------------------ */

const asTable   = require ('as-table')
const util      = require ('util')
const log       = require ('ololog')
const ansi      = require ('ansicolor').nice;
const fs        = require ('fs')

/*  ------------------------------------------------------------------------ */

const warn = log.bright.yellow.error // .error goes to stderr

/*  ------------------------------------------------------------------------ */

process.on ('uncaughtException',  e => { log.bright.red.error (e); process.exit (1) })
process.on ('unhandledRejection', e => { log.bright.red.error (e); process.exit (1) })

/*  ------------------------------------------------------------------------ */

log.bright ('\nTESTING', ccxtFile.magenta, { exchange: exchangeId || 'all', symbol: exchangeSymbol || 'all' }, '\n')

/*  ------------------------------------------------------------------------ */

let exchanges = {}
let proxies = [
    '',
    'https://cors-anywhere.herokuapp.com/',
    'https://crossorigin.me/',
    // 'http://cors-proxy.htmldriven.com/?url=', // we don't want this for now
]

// instantiate all exchanges
ccxt.exchanges.forEach (id => {
    exchanges[id] = new (ccxt)[id] ({ verbose: false })
})

// load api keys from config
let config = JSON.parse (fs.readFileSync ('./keys.json', 'utf8'))

// set up api keys appropriately
for (let id in config)
    for (let key in config[id])
        if (typeof exchanges[id] != 'undefined')
            exchanges[id][key] = config[id][key]

// move gdax to sandbox
exchanges['gdax'].urls['api'] = 'https://api-public.sandbox.gdax.com'

//-----------------------------------------------------------------------------

var countryName = function (code) {
    return ((typeof countries[code] !== 'undefined') ? countries[code] : code)
}

//-----------------------------------------------------------------------------

let sleep = (ms) => new Promise (resolve => setTimeout (resolve, ms));

//-----------------------------------------------------------------------------

let human_value = function (price) {
    return typeof price == 'undefined' ? 'N/A' : price
}

//-----------------------------------------------------------------------------

let testExchangeSymbolTicker = async (exchange, symbol) => {
    await sleep (exchange.rateLimit)
    log (exchange.id.green, symbol.green, 'fetching ticker...')
    let ticker = await exchange.fetchTicker (symbol)
    log (exchange.id.green, symbol.green, 'ticker',
        ticker['datetime'],
        'high: '    + human_value (ticker['high']),
        'low: '     + human_value (ticker['low']),
        'bid: '     + human_value (ticker['bid']),
        'ask: '     + human_value (ticker['ask']),
        'volume: '  + human_value (ticker['quoteVolume']))

    if (ticker['bid'] > ticker['ask'])
        log (this.id, symbol, 'ticker', 'bid is greater than ask!')

    return ticker;
}

let testExchangeSymbolOrderbook = async (exchange, symbol) => {
    await sleep (exchange.rateLimit)
    log (exchange.id.green, symbol.green, 'fetching order book...')
    let orderbook = await exchange.fetchOrderBook (symbol)
    log (exchange.id.green, symbol.green,
        orderbook['datetime'],
        'bid: '       + ((orderbook.bids.length > 0) ? human_value (orderbook.bids[0][0]) : 'N/A'),
        'bidVolume: ' + ((orderbook.bids.length > 0) ? human_value (orderbook.bids[0][1]) : 'N/A'),
        'ask: '       + ((orderbook.asks.length > 0) ? human_value (orderbook.asks[0][0]) : 'N/A'),
        'askVolume: ' + ((orderbook.asks.length > 0) ? human_value (orderbook.asks[0][1]) : 'N/A'))

    let bids = orderbook.bids
    if (bids.length > 1) {
        let first = 0
        let last = bids.length - 1
        if (bids[first][0] < bids[last][0])
            log (exchange.id, symbol, 'bids reversed!'.red.bright, bids[first][0], bids[last][0])
        else if (bids[first][0] > bids[last][0])
            log (exchange.id.green, symbol.green, 'bids ok')
    }
    let asks = orderbook.asks
    if (asks.length > 1) {
        let first = 0
        let last = asks.length - 1
        if (asks[first][0] > asks[last][0])
            log (exchange.id, symbol, 'asks reversed!'.red.bright, asks[first][0], asks[last][0])
        else if (asks[first][0] < asks[last][0])
            log (exchange.id.green, symbol.green, 'asks ok')
    }

    if (bids.length && asks.length)
        if (bids[0][0] > asks[0][0])
            log (this.id, symbol, 'order book', 'bid is greater than ask!'.red.bright)

    return orderbook
}

//-----------------------------------------------------------------------------

let testExchangeSymbolTrades = async (exchange, symbol) => {
    log (exchange.id.green, symbol.green, 'fetching trades...')
    let trades = await exchange.fetchTrades (symbol)
    log (exchange.id.green, symbol.green, 'fetched', Object.values (trades).length.toString ().green, 'trades')
    return trades
}

//-----------------------------------------------------------------------------

let testExchangeSymbol = async (exchange, symbol) => {

    await sleep (exchange.rateLimit)
    await testExchangeSymbolTicker (exchange, symbol)

    if (exchange.id == 'coinmarketcap') {

        // log (await exchange.fetchTickers ());
        log (await exchange.fetchGlobal ());

    } else {

        await testExchangeSymbolOrderbook (exchange, symbol)

        try {

            await testExchangeSymbolTrades (exchange, symbol)

        } catch (e) {

            if (e instanceof ccxt.ExchangeError) {
                warn (exchange.id, '[Exchange Error] ' + e.message)
            } else {
                throw e;
            }
        }
    }

    try {

        log (exchange.id.green, 'fetching all tickers at once...')
        let tickers = await exchange.fetchTickers ()
        log (exchange.id.green, 'fetched', Object.keys (tickers).length.toString ().green, 'tickers...')

    } catch (e) {

        if (e instanceof ccxt.ExchangeError) {
            log (exchange.id.green, 'fetching all tickers at once not supported.')
            // do nothing
        } else {
            throw e // rethrow
        }
    }
}

//-----------------------------------------------------------------------------

let testExchangeBalance = async (exchange, symbol) => {
    await sleep (exchange.rateLimit)
    log (exchange.id.green, 'fetching balance...')
    let balance = await exchange.fetchBalance ()

    let currencies = [
        'USD',
        'CNY',
        'EUR',
        'BTC',
        'ETH',
        'JPY',
        'LTC',
        'DASH',
        'DOGE',
        'UAH',
        'RUB',
    ]

    if ('info' in balance) {

        let result = currencies
            .filter (currency => (currency in balance) &&
                (typeof balance[currency]['total'] != 'undefined'))

        if (result.length > 0) {
            result = result.map (currency => currency + ': ' + human_value (balance[currency]['total']))
            if (exchange.currencies.length > result.length)
                result = result.join (', ') + ' + more...'
            else
                result = result.join (', ')

        } else {

            result = 'zero balance'
        }

        log (exchange.id.green, result)

    } else {

        log (exchange.id.green, exchange.omit (balance, 'info'))
    }
}

//-----------------------------------------------------------------------------

let loadExchange = async exchange => {
    let markets  = await exchange.loadMarkets ()
    let symbols = [
        'BTC/USD',
        'BTC/CNY',
        'BTC/EUR',
        'BTC/ETH',
        'ETH/BTC',
        'BTC/JPY',
        'ETH/EUR',
        'ETH/JPY',
        'ETH/CNY',
        'LTC/CNY',
        'DASH/BTC',
        'DOGE/BTC',
        'BTC/AUD',
        'BTC/PLN',
        'USD/SLL',
        'BTC/RUB',
        'BTC/UAH',
        'LTC/BTC',
    ]
    let result = exchange.symbols.filter (symbol => symbols.indexOf (symbol) >= 0)
    if (result.length > 0)
        if (exchange.symbols.length > result.length)
            result = result.join (', ') + ' + more...'
        else
            result = result.join (', ')
    log (exchange.id.green, exchange.symbols.length.toString ().bright.green, 'symbols', result)
}

//-----------------------------------------------------------------------------

let testExchange = async exchange => {

    let delay = exchange.rateLimit
    let symbol = exchange.symbols[0]
    let symbols = [
        'BTC/USD',
        'BTC/CNY',
        'BTC/EUR',
        'BTC/ETH',
        'ETH/BTC',
        'BTC/JPY',
        'LTC/BTC',
    ]
    for (let s in symbols) {
        if (exchange.symbols.includes (symbols[s])) {
            symbol = symbols[s]
            break
        }
    }

    log.green ('SYMBOL:', symbol)
    if ((symbol.indexOf ('.d') < 0)) {
        await testExchangeSymbol (exchange, symbol)
    }

    if (!exchange.apiKey || (exchange.apiKey.length < 1))
        return true

    await testExchangeBalance (exchange)

    // sleep (delay)
    // try {
    //     let marketSellOrder =
    //         await exchange.createMarketSellOrder (exchange.symbols[0], 1)
    //     console.log (exchange.id, 'ok', marketSellOrder)
    // } catch (e) {
    //     console.log (exchange.id, 'error', 'market sell', e)
    // }

    // sleep (delay)
    // try {
    //     let marketBuyOrder = await exchange.createMarketBuyOrder (exchange.symbols[0], 1)
    //     console.log (exchange.id, 'ok', marketBuyOrder)
    // } catch (e) {
    //     console.log (exchange.id, 'error', 'market buy', e)
    // }

    // sleep (delay)
    // try {
    //     let limitSellOrder = await exchange.createLimitSellOrder (exchange.symbols[0], 1, 3000)
    //     console.log (exchange.id, 'ok', limitSellOrder)
    // } catch (e) {
    //     console.log (exchange.id, 'error', 'limit sell', e)
    // }

    // sleep (delay)
    // try {
    //     let limitBuyOrder = await exchange.createLimitBuyOrder (exchange.symbols[0], 1, 3000)
    //     console.log (exchange.id, 'ok', limitBuyOrder)
    // } catch (e) {
    //     console.log (exchange.id, 'error', 'limit buy', e)
    // }

}

//-----------------------------------------------------------------------------

let printExchangesTable = function () {
    let astable = asTable.configure ({ delimiter: ' | ' })
    console.log (astable (Object.values (exchanges).map (exchange => {
        let website = Array.isArray (exchange.urls.www) ?
            exchange.urls.www[0] :
            exchange.urls.www
        let countries = Array.isArray (exchange.countries) ?
            exchange.countries.map (countryName).join (', ') :
            countryName (exchange.countries)
        let doc = Array.isArray (exchange.urls.doc) ?
            exchange.urls.doc[0] :
            exchange.urls.doc
        return {
            'id':        exchange.id,
            'name':      exchange.name,
            'countries': countries,
        }
    })))
}

//-----------------------------------------------------------------------------

let tryAllProxies = async function (exchange, proxies) {

    let currentProxy = 0
    let maxRetries   = proxies.length

    // a special case for ccex
    if (exchange.id == 'ccex')
        currentProxy = 1

    for (let numRetries = 0; numRetries < maxRetries; numRetries++) {

        try {

            exchange.proxy = proxies[currentProxy]
            await loadExchange (exchange)
            await testExchange (exchange)
            break

        } catch (e) {

            currentProxy = ++currentProxy % proxies.length
            if (e instanceof ccxt.DDoSProtection) {
                warn (exchange.id, '[DDoS Protection] ' + e.message)
            } else if (e instanceof ccxt.RequestTimeout) {
                warn (exchange.id, '[Request Timeout] ' + e.message)
            } else if (e instanceof ccxt.AuthenticationError) {
                warn (exchange.id, '[Authentication Error] ' + e.message)
            } else if (e instanceof ccxt.ExchangeNotAvailable) {
                warn (exchange.id, '[Exchange Not Available] ' + e.message)
            } else if (e instanceof ccxt.ExchangeError) {
                warn (exchange.id, '[Exchange Error] ' + e.message)
            } else {
                throw e;
            }
        }

    }
}

//-----------------------------------------------------------------------------

var test = async function () {

    // printExchangesTable ()

    if (exchangeId) {

        const exchange = exchanges[exchangeId]

        if (!exchange)
            throw new Error ('Exchange `' + exchangeId + '` not found')

        if (exchangeSymbol) {

            await loadExchange (exchange)
            await (exchangeSymbol == 'balance') ?
                testExchangeBalance (exchange) :
                testExchangeSymbol (exchange, exchangeSymbol)

        } else {

            await tryAllProxies (exchange, proxies)
        }

    } else {

        for (const id of Object.keys (exchanges)) {

            log.bright.green ('EXCHANGE:', id)
            const exchange = exchanges[id]
            await tryAllProxies (exchange, proxies)

        }
    }

    process.exit ();

} ()

<commit_msg>travis retrigger<commit_after>"use strict";

/*  ------------------------------------------------------------------------ */

const [processPath, , exchangeId = null, exchangeSymbol = null] = process.argv.filter (x => !x.startsWith ('--'))
const ccxtFile = process.argv.includes ('--es6') ? 'ccxt.js' : 'ccxt-es5.js'

/*  ------------------------------------------------------------------------ */

const ccxt      = require ('./' + ccxtFile)
const countries = require ('./countries')

/*  ------------------------------------------------------------------------ */

const asTable   = require ('as-table')
const util      = require ('util')
const log       = require ('ololog')
const ansi      = require ('ansicolor').nice;
const fs        = require ('fs')

/*  ------------------------------------------------------------------------ */

const warn = log.bright.yellow.error // .error goes to stderr

/*  ------------------------------------------------------------------------ */

process.on ('uncaughtException',  e => { log.bright.red.error (e); process.exit (1) })
process.on ('unhandledRejection', e => { log.bright.red.error (e); process.exit (1) })

/*  ------------------------------------------------------------------------ */

log.bright ('\nTESTING', ccxtFile.magenta, { exchange: exchangeId || 'all', symbol: exchangeSymbol || 'all' }, '\n')

/*  ------------------------------------------------------------------------ */

let exchanges = {}
let proxies = [
    '',
    'https://cors-anywhere.herokuapp.com/',
    'https://crossorigin.me/',
    // 'http://cors-proxy.htmldriven.com/?url=', // we don't want this for now
]

// instantiate all exchanges
ccxt.exchanges.forEach (id => {
    exchanges[id] = new (ccxt)[id] ({ verbose: false })
})

// load api keys from config
let config = JSON.parse (fs.readFileSync ('./keys.json', 'utf8'))

// set up api keys appropriately
for (let id in config)
    for (let key in config[id])
        if (typeof exchanges[id] != 'undefined')
            exchanges[id][key] = config[id][key]

// move gdax to sandbox
exchanges['gdax'].urls['api'] = 'https://api-public.sandbox.gdax.com'

//-----------------------------------------------------------------------------

var countryName = function (code) {
    return ((typeof countries[code] !== 'undefined') ? countries[code] : code)
}

//-----------------------------------------------------------------------------

let sleep = (ms) => new Promise (resolve => setTimeout (resolve, ms));

//-----------------------------------------------------------------------------

let human_value = function (price) {
    return typeof price == 'undefined' ? 'N/A' : price
}

//-----------------------------------------------------------------------------

let testExchangeSymbolTicker = async (exchange, symbol) => {
    await sleep (exchange.rateLimit)
    log (exchange.id.green, symbol.green, 'fetching ticker...')
    let ticker = await exchange.fetchTicker (symbol)
    log (exchange.id.green, symbol.green, 'ticker',
        ticker['datetime'],
        'high: '    + human_value (ticker['high']),
        'low: '     + human_value (ticker['low']),
        'bid: '     + human_value (ticker['bid']),
        'ask: '     + human_value (ticker['ask']),
        'volume: '  + human_value (ticker['quoteVolume']))

    if (ticker['bid'] > ticker['ask'])
        log (this.id, symbol, 'ticker', 'bid is greater than ask!')

    return ticker;
}

let testExchangeSymbolOrderbook = async (exchange, symbol) => {
    await sleep (exchange.rateLimit)
    log (exchange.id.green, symbol.green, 'fetching order book...')
    let orderbook = await exchange.fetchOrderBook (symbol)
    log (exchange.id.green, symbol.green,
        orderbook['datetime'],
        'bid: '       + ((orderbook.bids.length > 0) ? human_value (orderbook.bids[0][0]) : 'N/A'),
        'bidVolume: ' + ((orderbook.bids.length > 0) ? human_value (orderbook.bids[0][1]) : 'N/A'),
        'ask: '       + ((orderbook.asks.length > 0) ? human_value (orderbook.asks[0][0]) : 'N/A'),
        'askVolume: ' + ((orderbook.asks.length > 0) ? human_value (orderbook.asks[0][1]) : 'N/A'))

    let bids = orderbook.bids
    if (bids.length > 1) {
        let first = 0
        let last = bids.length - 1
        if (bids[first][0] < bids[last][0])
            log (exchange.id, symbol, 'bids reversed!'.red.bright, bids[first][0], bids[last][0])
        else if (bids[first][0] > bids[last][0])
            log (exchange.id.green, symbol.green, 'bids ok')
    }
    let asks = orderbook.asks
    if (asks.length > 1) {
        let first = 0
        let last = asks.length - 1
        if (asks[first][0] > asks[last][0])
            log (exchange.id, symbol, 'asks reversed!'.red.bright, asks[first][0], asks[last][0])
        else if (asks[first][0] < asks[last][0])
            log (exchange.id.green, symbol.green, 'asks ok')
    }

    if (bids.length && asks.length)
        if (bids[0][0] > asks[0][0])
            log (this.id, symbol, 'order book', 'bid is greater than ask!'.red.bright)

    return orderbook
}

//-----------------------------------------------------------------------------

let testExchangeSymbolTrades = async (exchange, symbol) => {
    log (exchange.id.green, symbol.green, 'fetching trades...')
    let trades = await exchange.fetchTrades (symbol)
    log (exchange.id.green, symbol.green, 'fetched', Object.values (trades).length.toString ().green, 'trades')
    return trades
}

//-----------------------------------------------------------------------------

let testExchangeSymbol = async (exchange, symbol) => {

    await sleep (exchange.rateLimit)
    await testExchangeSymbolTicker (exchange, symbol)

    if (exchange.id == 'coinmarketcap') {

        // log (await exchange.fetchTickers ());
        log (await exchange.fetchGlobal ());

    } else {

        await testExchangeSymbolOrderbook (exchange, symbol)

        try {

            await testExchangeSymbolTrades (exchange, symbol)

        } catch (e) {

            if (e instanceof ccxt.ExchangeError) {
                warn (exchange.id, '[Exchange Error] ' + e.message)
            } else {
                throw e;
            }
        }
    }

    try {

        log (exchange.id.green, 'fetching all tickers at once...')
        let tickers = await exchange.fetchTickers ()
        log (exchange.id.green, 'fetched', Object.keys (tickers).length.toString ().green, 'tickers...')

    } catch (e) {

        if (e instanceof ccxt.ExchangeError) {
            log (exchange.id.green, 'fetching all tickers at once not supported.')
            // do nothing
        } else {
            throw e // rethrow
        }
    }
}

//-----------------------------------------------------------------------------

let testExchangeBalance = async (exchange, symbol) => {
    await sleep (exchange.rateLimit)
    log (exchange.id.green, 'fetching balance...')
    let balance = await exchange.fetchBalance ()

    let currencies = [
        'USD',
        'CNY',
        'EUR',
        'BTC',
        'ETH',
        'JPY',
        'LTC',
        'DASH',
        'DOGE',
        'UAH',
        'RUB',
    ]

    if ('info' in balance) {

        let result = currencies
            .filter (currency => (currency in balance) &&
                (typeof balance[currency]['total'] != 'undefined'))

        if (result.length > 0) {
            result = result.map (currency => currency + ': ' + human_value (balance[currency]['total']))
            if (exchange.currencies.length > result.length)
                result = result.join (', ') + ' + more...'
            else
                result = result.join (', ')

        } else {

            result = 'zero balance'
        }

        log (exchange.id.green, result)

    } else {

        log (exchange.id.green, exchange.omit (balance, 'info'))
    }
}

//-----------------------------------------------------------------------------

let loadExchange = async exchange => {

    let markets  = await exchange.loadMarkets ()
    let symbols = [
        'BTC/USD',
        'BTC/CNY',
        'BTC/EUR',
        'BTC/ETH',
        'ETH/BTC',
        'BTC/JPY',
        'ETH/EUR',
        'ETH/JPY',
        'ETH/CNY',
        'LTC/CNY',
        'DASH/BTC',
        'DOGE/BTC',
        'BTC/AUD',
        'BTC/PLN',
        'USD/SLL',
        'BTC/RUB',
        'BTC/UAH',
        'LTC/BTC',
    ]

    let result = exchange.symbols.filter (symbol => symbols.indexOf (symbol) >= 0)
    if (result.length > 0)
        if (exchange.symbols.length > result.length)
            result = result.join (', ') + ' + more...'
        else
            result = result.join (', ')
    log (exchange.id.green, exchange.symbols.length.toString ().bright.green, 'symbols', result)
}

//-----------------------------------------------------------------------------

let testExchange = async exchange => {

    let delay = exchange.rateLimit
    let symbol = exchange.symbols[0]
    let symbols = [
        'BTC/USD',
        'BTC/CNY',
        'BTC/EUR',
        'BTC/ETH',
        'ETH/BTC',
        'BTC/JPY',
        'LTC/BTC',
    ]
    for (let s in symbols) {
        if (exchange.symbols.includes (symbols[s])) {
            symbol = symbols[s]
            break
        }
    }

    log.green ('SYMBOL:', symbol)
    if ((symbol.indexOf ('.d') < 0)) {
        await testExchangeSymbol (exchange, symbol)
    }

    if (!exchange.apiKey || (exchange.apiKey.length < 1))
        return true

    await testExchangeBalance (exchange)

    // sleep (delay)
    // try {
    //     let marketSellOrder =
    //         await exchange.createMarketSellOrder (exchange.symbols[0], 1)
    //     console.log (exchange.id, 'ok', marketSellOrder)
    // } catch (e) {
    //     console.log (exchange.id, 'error', 'market sell', e)
    // }

    // sleep (delay)
    // try {
    //     let marketBuyOrder = await exchange.createMarketBuyOrder (exchange.symbols[0], 1)
    //     console.log (exchange.id, 'ok', marketBuyOrder)
    // } catch (e) {
    //     console.log (exchange.id, 'error', 'market buy', e)
    // }

    // sleep (delay)
    // try {
    //     let limitSellOrder = await exchange.createLimitSellOrder (exchange.symbols[0], 1, 3000)
    //     console.log (exchange.id, 'ok', limitSellOrder)
    // } catch (e) {
    //     console.log (exchange.id, 'error', 'limit sell', e)
    // }

    // sleep (delay)
    // try {
    //     let limitBuyOrder = await exchange.createLimitBuyOrder (exchange.symbols[0], 1, 3000)
    //     console.log (exchange.id, 'ok', limitBuyOrder)
    // } catch (e) {
    //     console.log (exchange.id, 'error', 'limit buy', e)
    // }

}

//-----------------------------------------------------------------------------

let printExchangesTable = function () {
    let astable = asTable.configure ({ delimiter: ' | ' })
    console.log (astable (Object.values (exchanges).map (exchange => {
        let website = Array.isArray (exchange.urls.www) ?
            exchange.urls.www[0] :
            exchange.urls.www
        let countries = Array.isArray (exchange.countries) ?
            exchange.countries.map (countryName).join (', ') :
            countryName (exchange.countries)
        let doc = Array.isArray (exchange.urls.doc) ?
            exchange.urls.doc[0] :
            exchange.urls.doc
        return {
            'id':        exchange.id,
            'name':      exchange.name,
            'countries': countries,
        }
    })))
}

//-----------------------------------------------------------------------------

let tryAllProxies = async function (exchange, proxies) {

    let currentProxy = 0
    let maxRetries   = proxies.length

    // a special case for ccex
    if (exchange.id == 'ccex')
        currentProxy = 1

    for (let numRetries = 0; numRetries < maxRetries; numRetries++) {

        try {

            exchange.proxy = proxies[currentProxy]
            await loadExchange (exchange)
            await testExchange (exchange)
            break

        } catch (e) {

            currentProxy = ++currentProxy % proxies.length
            if (e instanceof ccxt.DDoSProtection) {
                warn (exchange.id, '[DDoS Protection] ' + e.message)
            } else if (e instanceof ccxt.RequestTimeout) {
                warn (exchange.id, '[Request Timeout] ' + e.message)
            } else if (e instanceof ccxt.AuthenticationError) {
                warn (exchange.id, '[Authentication Error] ' + e.message)
            } else if (e instanceof ccxt.ExchangeNotAvailable) {
                warn (exchange.id, '[Exchange Not Available] ' + e.message)
            } else if (e instanceof ccxt.ExchangeError) {
                warn (exchange.id, '[Exchange Error] ' + e.message)
            } else {
                throw e;
            }
        }

    }
}

//-----------------------------------------------------------------------------

var test = async function () {

    // printExchangesTable ()

    if (exchangeId) {

        const exchange = exchanges[exchangeId]

        if (!exchange)
            throw new Error ('Exchange `' + exchangeId + '` not found')

        if (exchangeSymbol) {

            await loadExchange (exchange)
            await (exchangeSymbol == 'balance') ?
                testExchangeBalance (exchange) :
                testExchangeSymbol (exchange, exchangeSymbol)

        } else {

            await tryAllProxies (exchange, proxies)
        }

    } else {

        for (const id of Object.keys (exchanges)) {

            log.bright.green ('EXCHANGE:', id)
            const exchange = exchanges[id]
            await tryAllProxies (exchange, proxies)

        }
    }

    process.exit ();

} ()

<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-7-24 00:28:25<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>var before = {
    setup: function () {
        cookies = document.cookie.split('; ')
        for (var i = 0, c; (c = (cookies)[i]) && (c = c.split('=')[0]); i++) {
            document.cookie = c + '=; expires=' + new Date(0).toUTCString();
        }

        $.cookie.defaults = {};
    }
};

module('read', before);

test('simple value', 1, function () {
    document.cookie = 'c=v';
    equal($.cookie('c'), 'v', 'should return value');
});

test('empty value', 1, function () {
    // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, which
    // resulted in a bug while reading such a cookie.
    $.cookie('c', '');
    equal($.cookie('c'), '', 'should return value');
});

test('simple value with expires', 1, function () {
  var tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate() + 5);
    document.cookie = 'c=testcookie; expires=' + tomorrow.toUTCString();
    equal($.cookie('c'), 'testcookie', 'should return value');
});

test('not existing', 1, function () {
    equal($.cookie('whatever'), null, 'should return null');
});

test('decode', 1, function () {
    document.cookie = encodeURIComponent(' c') + '=' + encodeURIComponent(' v');
    equal($.cookie(' c'), ' v', 'should decode key and value');
});

test('raw: true', 1, function () {
    document.cookie = 'c=%20v';
    equal($.cookie('c', { raw: true }), '%20v', 'should not decode value');
});

test('[] used in name', 1, function () {
  document.cookie = 'c[999]=foo';
  equal($.cookie('c[999]'), 'foo', 'should return value');
});

test('embedded equals', 1, function () {
  $.cookie('c', 'foo=bar', { raw: true });
  equal($.cookie('c', { raw: true }), 'foo=bar', 'should include the entire value');
});

test('defaults', 1, function () {
    document.cookie = 'c=%20v';
    $.cookie.defaults.raw = true;
    equal($.cookie('c'), '%20v', 'should use raw from defaults');
});

module('write', before);

test('String primitive', 1, function () {
    $.cookie('c', 'v');
    equal($.cookie('c'), 'v', 'should write value');
});

test('String object', 1, function () {
    $.cookie('c', new String('v'));
    equal($.cookie('c'), 'v', 'should write value');
});

test('value "[object Object]"', 1, function () {
    $.cookie('c', '[object Object]');
    equal($.cookie('c'), '[object Object]', 'should write value');
});

test('number', 1, function () {
    $.cookie('c', 1234);
    equal($.cookie('c'), '1234', 'should write value');
});

test('with expires 7 days from now', 1, function() {
  var seven_days_from_now = new Date();
  seven_days_from_now.setDate(seven_days_from_now.getDate() + 7);
  equal($.cookie('c', 'v', {expires:7}), 'c=v; expires='+seven_days_from_now.toUTCString(), 'should return the cookie string with expires');
});

test('with expires yesterday', 2, function() {
  var yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);
  equal($.cookie('c', 'v', {expires:-1}), 'c=v; expires='+yesterday.toUTCString(), 'should return the cookie string with expires');
  equal(document.cookie, '', 'should not save expired cookie');
});

test('return value', 1, function () {
    equal($.cookie('c', 'v'), 'c=v', 'should return written cookie string');
});

test('raw: true', 1, function () {
    equal($.cookie('c', ' v', { raw: true }).split('=')[1],
        ' v', 'should not encode');
});

test('defaults', 1, function () {
    $.cookie.defaults.raw = true;
    equal($.cookie('c', ' v').split('=')[1], ' v', 'should use raw from defaults');
});

module('delete', before);

test('delete', 2, function () {
    document.cookie = 'c=v';
    $.cookie('c', null);
    equal(document.cookie, '', 'should delete with null as value');

    document.cookie = 'c=v';
    $.cookie('c', undefined);
    equal(document.cookie, '', 'should delete with undefined as value');
});
<commit_msg>Rewriting pulled tests<commit_after>var before = {
    setup: function () {
        cookies = document.cookie.split('; ')
        for (var i = 0, c; (c = (cookies)[i]) && (c = c.split('=')[0]); i++) {
            document.cookie = c + '=; expires=' + new Date(0).toUTCString();
        }

        $.cookie.defaults = {};
    }
};

module('read', before);

test('simple value', 1, function () {
    document.cookie = 'c=v';
    equal($.cookie('c'), 'v', 'should return value');
});

test('empty value', 1, function () {
    // IE saves cookies with empty string as "c; ", e.g. without "=" as opposed to EOMB, which
    // resulted in a bug while reading such a cookie.
    $.cookie('c', '');
    equal($.cookie('c'), '', 'should return value');
});

test('not existing', 1, function () {
    equal($.cookie('whatever'), null, 'should return null');
});

test('decode', 1, function () {
    document.cookie = encodeURIComponent(' c') + '=' + encodeURIComponent(' v');
    equal($.cookie(' c'), ' v', 'should decode key and value');
});

test('raw: true', 1, function () {
    document.cookie = 'c=%20v';
    equal($.cookie('c', { raw: true }), '%20v', 'should not decode value');
});

test('[] used in name', 1, function () {
  document.cookie = 'c[999]=foo';
  equal($.cookie('c[999]'), 'foo', 'should return value');
});

test('embedded equals', 1, function () {
  $.cookie('c', 'foo=bar', { raw: true });
  equal($.cookie('c', { raw: true }), 'foo=bar', 'should include the entire value');
});

test('defaults', 1, function () {
    document.cookie = 'c=%20v';
    $.cookie.defaults.raw = true;
    equal($.cookie('c'), '%20v', 'should use raw from defaults');
});

module('write', before);

test('String primitive', 1, function () {
    $.cookie('c', 'v');
    equal($.cookie('c'), 'v', 'should write value');
});

test('String object', 1, function () {
    $.cookie('c', new String('v'));
    equal($.cookie('c'), 'v', 'should write value');
});

test('value "[object Object]"', 1, function () {
    $.cookie('c', '[object Object]');
    equal($.cookie('c'), '[object Object]', 'should write value');
});

test('number', 1, function () {
    $.cookie('c', 1234);
    equal($.cookie('c'), '1234', 'should write value');
});

test('expires option as days from now', 1, function() {
  var sevenDaysFromNow = new Date();
  sevenDaysFromNow.setDate(sevenDaysFromNow.getDate() + 7);
  equal($.cookie('c', 'v', { expires: 7 }), 'c=v; expires=' + sevenDaysFromNow.toUTCString(),
      'should write the cookie string with expires');
});

test('expires option as Date instance', 1, function() {
  var sevenDaysFromNow = new Date();
  sevenDaysFromNow.setDate(sevenDaysFromNow.getDate() + 7);
  equal($.cookie('c', 'v', { expires: sevenDaysFromNow }), 'c=v; expires=' + sevenDaysFromNow.toUTCString(),
      'should write the cookie string with expires');
});

test('invalid expires option (in the past)', 1, function() {
  var yesterday = new Date();
  yesterday.setDate(yesterday.getDate() - 1);
  $.cookie('c', 'v', { expires: yesterday });
  equal($.cookie('c'), null, 'should not save already expired cookie');
});

test('return value', 1, function () {
    equal($.cookie('c', 'v'), 'c=v', 'should return written cookie string');
});

test('raw option set to true', 1, function () {
    equal($.cookie('c', ' v', { raw: true }).split('=')[1],
        ' v', 'should not encode');
});

test('defaults', 1, function () {
    $.cookie.defaults.raw = true;
    equal($.cookie('c', ' v').split('=')[1], ' v', 'should use raw from defaults');
});

module('delete', before);

test('delete', 2, function () {
    document.cookie = 'c=v';
    $.cookie('c', null);
    equal(document.cookie, '', 'should delete with null as value');

    document.cookie = 'c=v';
    $.cookie('c', undefined);
    equal(document.cookie, '', 'should delete with undefined as value');
});
<|endoftext|>