<commit_before>var util = require("util");
var Kirra = require("./kirra-client.js");
var MessageProcessor = require("./message-processor.js");
var MessageStore = require("./message-store.js");
var MandrillGateway = require("./mandrill-gateway.js");

var kirraBaseUrl = "http://localhost/services/api-v2/";
var assert = require("assert");
var kirraApplicationId = 'demo-cloudfier-examples-expenses';
var kirraEntity = 'expenses.Employee';

suite('EBUI', function() {
    var messageStore = new MessageStore('localhost', 27017, 'testdb', '', '');
    var collectedUserNotifications = [];
    var emailGateway = { replyToSender : function(message, errorMessage) {
        collectedUserNotifications.push({ errorMessage: errorMessage, message: message });
    } };

    suite('Kirra Client', function() {
        var suite = this;
        suite.kirra = new Kirra("http://localhost/services/api-v2/", kirraApplicationId)

        var objectId;
        test('createInstance', function(done) {
            suite.kirra.createInstance({
                entity: 'expenses.Employee',
                values: { name: "John Doe" }
            }).then(function(instance) {
                objectId = instance.objectId;
                assert.equal("John Doe", instance.values.name);
            }).then(done, done);
        });

        test('updateInstance', function(done) {
            suite.kirra.updateInstance({
                entity: 'expenses.Employee',
                objectId: objectId,
                values: { name: "John Moe" }
            }).then(function(instance) {
                assert.equal("John Moe", instance.values.name);
            }).then(done, done);
        });
    });

    suite('MandrillGateway', function() {
        var mandrillGateway = new MandrillGateway();
        test('handleInboundEmail', function() {
            var events = [
                {
                    msg: {
                        email: "inbox@domain.com",
                        from_email: "fromEmail@domain.com",
                        from_name: "From Name",
                        from_email: "fromEmail@domain.com",
                        to: "toEmail@domain.com",
                        subject: "This is the subject",
                        text: "Line 1\nLine 2\nLine 3",
                        headers: {
                            "Message-Id" : "message-id"
                        }
                    }
                }
            ];
            var req = { body: { mandrill_events: JSON.stringify(events) } };
            var res = { send: function(status) { this.status = status; } };
            var messageStore = { messages : [], saveMessage : function (message) { this.messages.push(message); } };
            mandrillGateway.handleInboundEmail(req, res, messageStore);
            assert.equal(1, messageStore.messages.length);
            var message = messageStore.messages[0];
            assert.equal("Pending", message.status);
            assert.equal("fromEmail@domain.com", message.fromEmail);
            assert.equal("From Name", message.fromName);
            assert.equal("inbox@domain.com", message.account);
            assert.equal("toEmail@domain.com", message.toEmail);
            assert.equal("This is the subject", message.subject);
            assert.equal("Line 1\nLine 2\nLine 3", message.text);
            assert.equal("message-id", message._contextMessageId);
            assert.equal(204, res.status);
        });

    });

    suite('MessageProcessor', function() {

        var messageProcessor = new MessageProcessor(emailGateway, messageStore, kirraBaseUrl);

        test('makeEmailForInstance', function(){
            assert.equal("expenses_Employee-2.myapp@inbox.cloudfier.com", messageProcessor.makeEmailForInstance({entity: 'expenses.Employee', application: 'myapp', instanceId: 2}));
        });

        test('processPendingMessage - invalid', function(done) {
            messageStore.saveMessage({ }).then(function (m) {
                return messageProcessor.processPendingMessage(m);
            }).then(function(m) {
                assert.equal("Invalid", m.status);
            }).then(done, done);
        });

        test('processPendingMessage - valid', function(done) {
            messageStore.saveMessage({ application : kirraApplicationId, entity : kirraEntity, values: { name: "John Bonham"} }).then(function (m) {
                return messageProcessor.processPendingMessage(m);
            }).then(function(m) {
                assert.equal("Processed", m.status);
            }).then(done, done);
        });

        test('parseMessage - entity account', function() {
            var message = {
                account : 'namespace_Entity.myapplication@domain',
                text: 'This is a message'
            };
            messageProcessor.parseMessage(message);
            assert.equal("myapplication", message.application);
            assert.equal("namespace.Entity", message.entity);
            assert.equal(undefined, message.instanceId);
        });

        test('parseMessage - instance account', function() {
            var message = {
                account : 'namespace_Entity-1234.myapplication@domain',
                text: 'This is a message'
            };
            messageProcessor.parseMessage(message);
            assert.equal("myapplication", message.application);
            assert.equal("namespace.Entity", message.entity);
            assert.equal('1234', message.instanceId);
        });

        test('parseMessage - values', function() {
            var message = {
                account : 'namespace_Entity-myapplication@domain',
                subject: 'subject',
                text: 'Line 1\nLine 2\n--\nField1: value1\nField2: value2\n'
            };
            messageProcessor.parseMessage(message);
            assert.ok(message.values);
            assert.equal("value1", message.values.Field1);
            assert.equal("value2", message.values.Field2);
            assert.equal("Line 1\nLine 2\n", message.comment);
        });

        test('parseMessage - values mixed with comment', function() {
            var message = {
                account : 'namespace_Entity-myapplication@domain',
                subject: 'subject',
                text: 'Line 1\nLine 2\n--\nField1: value1\nField2: value2\n--\nLine 3\nLine 4'
            };
            messageProcessor.parseMessage(message);
            assert.ok(message.values);
            assert.equal("value1", message.values.Field1);
            assert.equal("value2", message.values.Field2);
            assert.equal("Line 1\nLine 2\nLine 3\nLine 4\n", message.comment);
        });
    });
});
<commit_msg>more tests<commit_after>var util = require("util");
var Kirra = require("./kirra-client.js");
var MessageProcessor = require("./message-processor.js");
var MessageStore = require("./message-store.js");
var MandrillGateway = require("./mandrill-gateway.js");

var kirraBaseUrl = "http://localhost/services/api-v2/";
var assert = require("assert");
var kirraApplicationId = 'demo-cloudfier-examples-expenses';
var kirraEntity = 'expenses.Employee';

suite('EBUI', function() {
    var messageStore = new MessageStore('localhost', 27017, 'testdb', '', '');
    var collectedUserNotifications = [];
    var emailGateway = { replyToSender : function(message, errorMessage) {
        collectedUserNotifications.push({ errorMessage: errorMessage, message: message });
    } };

    suite('Kirra Client', function() {
        var suite = this;
        suite.kirra = new Kirra("http://localhost/services/api-v2/", kirraApplicationId)

        var objectId;
        test('createInstance', function(done) {
            suite.kirra.createInstance({
                entity: 'expenses.Employee',
                values: { name: "John Doe" }
            }).then(function(instance) {
                objectId = instance.objectId;
                assert.equal("John Doe", instance.values.name);
            }).then(done, done);
        });

        test('updateInstance', function(done) {
            suite.kirra.updateInstance({
                entity: 'expenses.Employee',
                objectId: objectId,
                values: { name: "John Moe" }
            }).then(function(instance) {
                assert.equal("John Moe", instance.values.name);
            }).then(done, done);
        });
    });

    suite('MandrillGateway', function() {
        var mandrillGateway = new MandrillGateway();
        test('handleInboundEmail', function() {
            var events = [
                {
                    msg: {
                        email: "inbox@domain.com",
                        from_email: "fromEmail@domain.com",
                        from_name: "From Name",
                        from_email: "fromEmail@domain.com",
                        to: "toEmail@domain.com",
                        subject: "This is the subject",
                        text: "Line 1\nLine 2\nLine 3",
                        headers: {
                            "Message-Id" : "message-id"
                        }
                    }
                }
            ];
            var req = { body: { mandrill_events: JSON.stringify(events) } };
            var res = { send: function(status) { this.status = status; } };
            var messageStore = { messages : [], saveMessage : function (message) { this.messages.push(message); } };
            mandrillGateway.handleInboundEmail(req, res, messageStore);
            assert.equal(1, messageStore.messages.length);
            var message = messageStore.messages[0];
            assert.equal("Pending", message.status);
            assert.equal("fromEmail@domain.com", message.fromEmail);
            assert.equal("From Name", message.fromName);
            assert.equal("inbox@domain.com", message.account);
            assert.equal("toEmail@domain.com", message.toEmail);
            assert.equal("This is the subject", message.subject);
            assert.equal("Line 1\nLine 2\nLine 3", message.text);
            assert.equal("message-id", message._contextMessageId);
            assert.equal(204, res.status);
        });

    });

    suite('MessageProcessor', function() {

        var messageProcessor = new MessageProcessor(emailGateway, messageStore, kirraBaseUrl);

        test('makeEmailForInstance', function(){
            assert.equal("expenses_Employee-2.myapp@inbox.cloudfier.com", messageProcessor.makeEmailForInstance({entity: 'expenses.Employee', application: 'myapp', instanceId: 2}));
        });

        test('processPendingMessage - invalid', function(done) {
            messageStore.saveMessage({ }).then(function (m) {
                return messageProcessor.processPendingMessage(m);
            }).then(function(m) {
                assert.equal("Invalid", m.status);
            }).then(done, done);
        });

        test('processPendingMessage - valid', function(done) {
            messageStore.saveMessage({ application : kirraApplicationId, entity : kirraEntity, values: { name: "John Bonham"} }).then(function (m) {
                return messageProcessor.processPendingMessage(m);
            }).then(function(m) {
                assert.equal("Processed", m.status);
            }).then(done, done);
        });

        test('processPendingMessage - missing required field', function(done) {
            messageStore.saveMessage({
                application : kirraApplicationId,
                entity : kirraEntity,
                values: {}
            }).then(function (m) {
                return messageProcessor.processPendingMessage(m);
            }).then(function(m) {
                assert.equal("Failure", m.status);
                assert.ok(m.error);
                assert.equal("A value is required for Name", m.error.message);
            }).then(done, done);
        });

        test('parseMessage - entity account', function() {
            var message = {
                account : 'namespace_Entity.myapplication@domain',
                text: 'This is a message'
            };
            messageProcessor.parseMessage(message);
            assert.equal("myapplication", message.application);
            assert.equal("namespace.Entity", message.entity);
            assert.equal(undefined, message.instanceId);
        });

        test('parseMessage - instance account', function() {
            var message = {
                account : 'namespace_Entity-1234.myapplication@domain',
                text: 'This is a message'
            };
            messageProcessor.parseMessage(message);
            assert.equal("myapplication", message.application);
            assert.equal("namespace.Entity", message.entity);
            assert.equal('1234', message.instanceId);
        });

        test('parseMessage - values', function() {
            var message = {
                account : 'namespace_Entity-myapplication@domain',
                subject: 'subject',
                text: 'Line 1\nLine 2\n--\nField1: value1\nField2: value2\n'
            };
            messageProcessor.parseMessage(message);
            assert.ok(message.values);
            assert.equal("value1", message.values.Field1);
            assert.equal("value2", message.values.Field2);
            assert.equal("Line 1\nLine 2\n", message.comment);
        });

        test('parseMessage - values mixed with comment', function() {
            var message = {
                account : 'namespace_Entity-myapplication@domain',
                subject: 'subject',
                text: 'Line 1\nLine 2\n--\nField1: value1\nField2: value2\n--\nLine 3\nLine 4'
            };
            messageProcessor.parseMessage(message);
            assert.ok(message.values);
            assert.equal("value1", message.values.Field1);
            assert.equal("value2", message.values.Field2);
            assert.equal("Line 1\nLine 2\nLine 3\nLine 4\n", message.comment);
        });
    });
});
<|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 01:35: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 test      = require('tape').test
  , stream    = require('readable-stream')
  , duplexer  = require('./')
  , http      = require('http')
  , util      = require('util')

function MyWritable(t) {
  stream.Writable.call(this)
  this._t = t
}

util.inherits(MyWritable, stream.Writable)

MyWritable.prototype._write = function(chunk, enc, cb) {
  this._t.equal(chunk.toString(), 'writable')
  cb()
}

function MyReadable() {
  stream.Readable.call(this)
}

util.inherits(MyReadable, stream.Readable)

MyReadable.prototype._read = function(n) {
  this.push('readable')
  this.push(null)
}

test('basically works', function(t) {
  t.plan(2)

  var writable = new MyWritable(t)
    , readable = new MyReadable()
    , instance

  instance = duplexer(writable, readable)

  instance.on('data', function(chunk) {
    t.equal(chunk.toString(), 'readable')
  })

  instance.end('writable')
})

test('end event', function(t) {
  t.plan(2)

  var writable = new stream.PassThrough()
    , instance

  instance = duplexer(writable, writable)

  instance.on('data', function(chunk) {
    t.equal(chunk.toString(), 'a message')
  })

  instance.on('end', function() {
    t.ok(true, 'end happened')
  })

  instance.end('a message')
})

test('objectMode', function(t) {
  t.plan(1)

  var writable = new stream.PassThrough({ objectMode: true })
    , instance

  instance = duplexer(writable, writable, { objectMode: true })

  instance.on('data', function(chunk) {
    t.deepEqual(chunk, { hello: 'world' })
  })

  instance.end({ hello: 'world' })
})

test('pass through error events', function(t) {
  // two because it must listen for both readable and
  // writable
  t.plan(2)

  var writable = new stream.PassThrough()
    , instance

  instance = duplexer(writable, writable)

  instance.on('error', function(err) {
    t.ok(err, 'an error is emitted')
  })

  writable.emit('error', new Error('fake!'))
})

test('late hook', function(t) {
  t.plan(2)

  var writable = new stream.PassThrough()

    // nothing here, let's hook them up later
    , instance = duplexer()

  instance.on('data', function(chunk) {
    t.equal(chunk.toString(), 'writable')
  })

  instance.on('end', function() {
    t.ok(true, 'end happened')
  })

  instance.end('writable')

  // separate hooks for writable
  instance.hookWritable(writable)
  // and readable
  instance.hookReadable(writable)
})

test('late hook reversed', function(t) {
  t.plan(1)

  var writable = new stream.PassThrough()

    // nothing here, let's hook them up later
    , instance = duplexer()

  instance.on('data', function(chunk) {
    t.equal(chunk.toString(), 'writable')
  })

  instance.end('writable')

  // separate hooks for redable
  instance.hookReadable(writable)
  // and writable
  instance.hookWritable(writable)
})

test('late hook multiple writes', function(t) {
  t.plan(4)

  var writable = new stream.PassThrough()

    // nothing here, let's hook them up later
    , instance = duplexer()
    , expected = ['a', 'b', 'c']

  instance.on('data', function(chunk) {
    t.equal(chunk.toString(), expected.shift())
  })

  instance.on('end', function() {
    t.ok(true, 'end happened')
  })

  instance.write('a')
  instance.write('b')
  instance.end('c')

  // separate hooks for writable
  instance.hookWritable(writable)
  // and readable
  instance.hookReadable(writable)
})

test('shortcut hook', function(t) {
  t.plan(1)

  var writable = new stream.PassThrough()

    // nothing here, let's hook them up later
    , instance = duplexer()

  instance.on('data', function(chunk) {
    t.equal(chunk.toString(), 'writable')
  })

  instance.end('writable')

  // single hook for both!
  instance.hook(writable, writable)
})

test('double hook', function(t) {
  t.plan(2)

  var writable = new MyWritable(t)
    , readable = new stream.Readable()

    // nothing here, let's hook them up later
    , instance = duplexer()

  writable._write = function(chunk, enc, cb) {
    t.equal(chunk.toString(), 'writable')
    cb()
  }

  readable._read = function(n) {
  }

  instance.hook(writable, readable)

  t.test('writable', function(t) {
    var thrown = false

    try {
      instance.hookWritable(writable)
    } catch(err) {
      thrown = true
    }

    t.assert(thrown, 'must have thrown')

    t.end()
  })

  t.test('readable', function(t) {
    var thrown = false

    try {
      instance.hookReadable(readable)
    } catch(err) {
      thrown = true
    }

    t.assert(thrown, 'must have thrown')

    t.end()
  })

  t.end()
})

if (process.browser) {
  return
}

// everything after this line will not be executed
// in the browser

test('HTTP support', function(t) {
  t.plan(1)

  var server   = http.createServer()
    , instance = duplexer()

  function handle(req, res) {
    req.pipe(res)
  }

  server.on('request', handle)

  server.on('listening', function() {

    var request = http.request({
        host: 'localhost'
      , port: server.address().port
      , method: 'POST'
      , path: '/'
    })

    request.on('response', function(res) {
      instance.hookReadable(res)
    })

    instance.hookWritable(request)

    instance.end('a message')
  })

  server.listen(0)

  instance.on('data', function(chunk) {
    t.equal(chunk.toString(), 'a message')
    server.close()
  })
})

test('HTTP support with delayed open', function(t) {
  t.plan(1)

  var server   = http.createServer()
    , instance = duplexer()

  function handle(req, res) {
    req.pipe(res)
  }

  server.on('request', handle)

  server.on('listening', function() {

    var request = http.request({
        host: 'localhost'
      , port: server.address().port
      , method: 'POST'
      , path: '/'
    })

    request.on('response', function(res) {
      instance.hookReadable(res)
    })

    instance.hookWritable(request)
  })

  server.listen(0)

  instance.on('data', function(chunk) {
    t.equal(chunk.toString(), 'a message')
    server.close()
  })

  instance.end('a message')
})

test('works with a child process', function(t) {
  t.plan(1)

  var echo     = require('child_process').spawn('cat', [], {
                   stdio: ['pipe', 'pipe', process.stderr]
                 })
    , instance = duplexer(echo.stdin, echo.stdout)

  instance.on('data', function(chunk) {
    t.equal(chunk.toString(), 'a message')
  })

  instance.end('a message')
})
<commit_msg>Added one more test for finish event.<commit_after>
var test      = require('tape').test
  , stream    = require('readable-stream')
  , duplexer  = require('./')
  , http      = require('http')
  , util      = require('util')

function MyWritable(t) {
  stream.Writable.call(this)
  this._t = t
}

util.inherits(MyWritable, stream.Writable)

MyWritable.prototype._write = function(chunk, enc, cb) {
  this._t.equal(chunk.toString(), 'writable')
  cb()
}

function MyReadable() {
  stream.Readable.call(this)
}

util.inherits(MyReadable, stream.Readable)

MyReadable.prototype._read = function(n) {
  this.push('readable')
  this.push(null)
}

test('basically works', function(t) {
  t.plan(2)

  var writable = new MyWritable(t)
    , readable = new MyReadable()
    , instance

  instance = duplexer(writable, readable)

  instance.on('data', function(chunk) {
    t.equal(chunk.toString(), 'readable')
  })

  instance.end('writable')
})

test('end event', function(t) {
  t.plan(2)

  var writable = new stream.PassThrough()
    , instance

  instance = duplexer(writable, writable)

  instance.on('data', function(chunk) {
    t.equal(chunk.toString(), 'a message')
  })

  instance.on('end', function() {
    t.ok(true, 'end happened')
  })

  instance.end('a message')
})

test('finish event after end', function(t) {
  t.plan(2)

  var writable = new stream.PassThrough()
    , instance

  instance = duplexer(writable, writable)

  instance.on('data', function(chunk) {
    t.equal(chunk.toString(), 'a message')
  })

  instance.on('finish', function() {
    t.ok(true, 'finish happened')
  })

  instance.end('a message')
})

test('objectMode', function(t) {
  t.plan(1)

  var writable = new stream.PassThrough({ objectMode: true })
    , instance

  instance = duplexer(writable, writable, { objectMode: true })

  instance.on('data', function(chunk) {
    t.deepEqual(chunk, { hello: 'world' })
  })

  instance.end({ hello: 'world' })
})

test('pass through error events', function(t) {
  // two because it must listen for both readable and
  // writable
  t.plan(2)

  var writable = new stream.PassThrough()
    , instance

  instance = duplexer(writable, writable)

  instance.on('error', function(err) {
    t.ok(err, 'an error is emitted')
  })

  writable.emit('error', new Error('fake!'))
})

test('late hook', function(t) {
  t.plan(2)

  var writable = new stream.PassThrough()

    // nothing here, let's hook them up later
    , instance = duplexer()

  instance.on('data', function(chunk) {
    t.equal(chunk.toString(), 'writable')
  })

  instance.on('end', function() {
    t.ok(true, 'end happened')
  })

  instance.end('writable')

  // separate hooks for writable
  instance.hookWritable(writable)
  // and readable
  instance.hookReadable(writable)
})

test('late hook reversed', function(t) {
  t.plan(1)

  var writable = new stream.PassThrough()

    // nothing here, let's hook them up later
    , instance = duplexer()

  instance.on('data', function(chunk) {
    t.equal(chunk.toString(), 'writable')
  })

  instance.end('writable')

  // separate hooks for redable
  instance.hookReadable(writable)
  // and writable
  instance.hookWritable(writable)
})

test('late hook multiple writes', function(t) {
  t.plan(4)

  var writable = new stream.PassThrough()

    // nothing here, let's hook them up later
    , instance = duplexer()
    , expected = ['a', 'b', 'c']

  instance.on('data', function(chunk) {
    t.equal(chunk.toString(), expected.shift())
  })

  instance.on('end', function() {
    t.ok(true, 'end happened')
  })

  instance.write('a')
  instance.write('b')
  instance.end('c')

  // separate hooks for writable
  instance.hookWritable(writable)
  // and readable
  instance.hookReadable(writable)
})

test('shortcut hook', function(t) {
  t.plan(1)

  var writable = new stream.PassThrough()

    // nothing here, let's hook them up later
    , instance = duplexer()

  instance.on('data', function(chunk) {
    t.equal(chunk.toString(), 'writable')
  })

  instance.end('writable')

  // single hook for both!
  instance.hook(writable, writable)
})

test('double hook', function(t) {
  t.plan(2)

  var writable = new MyWritable(t)
    , readable = new stream.Readable()

    // nothing here, let's hook them up later
    , instance = duplexer()

  writable._write = function(chunk, enc, cb) {
    t.equal(chunk.toString(), 'writable')
    cb()
  }

  readable._read = function(n) {
  }

  instance.hook(writable, readable)

  t.test('writable', function(t) {
    var thrown = false

    try {
      instance.hookWritable(writable)
    } catch(err) {
      thrown = true
    }

    t.assert(thrown, 'must have thrown')

    t.end()
  })

  t.test('readable', function(t) {
    var thrown = false

    try {
      instance.hookReadable(readable)
    } catch(err) {
      thrown = true
    }

    t.assert(thrown, 'must have thrown')

    t.end()
  })

  t.end()
})

if (process.browser) {
  return
}

// everything after this line will not be executed
// in the browser

test('HTTP support', function(t) {
  t.plan(1)

  var server   = http.createServer()
    , instance = duplexer()

  function handle(req, res) {
    req.pipe(res)
  }

  server.on('request', handle)

  server.on('listening', function() {

    var request = http.request({
        host: 'localhost'
      , port: server.address().port
      , method: 'POST'
      , path: '/'
    })

    request.on('response', function(res) {
      instance.hookReadable(res)
    })

    instance.hookWritable(request)

    instance.end('a message')
  })

  server.listen(0)

  instance.on('data', function(chunk) {
    t.equal(chunk.toString(), 'a message')
    server.close()
  })
})

test('HTTP support with delayed open', function(t) {
  t.plan(1)

  var server   = http.createServer()
    , instance = duplexer()

  function handle(req, res) {
    req.pipe(res)
  }

  server.on('request', handle)

  server.on('listening', function() {

    var request = http.request({
        host: 'localhost'
      , port: server.address().port
      , method: 'POST'
      , path: '/'
    })

    request.on('response', function(res) {
      instance.hookReadable(res)
    })

    instance.hookWritable(request)
  })

  server.listen(0)

  instance.on('data', function(chunk) {
    t.equal(chunk.toString(), 'a message')
    server.close()
  })

  instance.end('a message')
})

test('works with a child process', function(t) {
  t.plan(1)

  var echo     = require('child_process').spawn('cat', [], {
                   stdio: ['pipe', 'pipe', process.stderr]
                 })
    , instance = duplexer(echo.stdin, echo.stdout)

  instance.on('data', function(chunk) {
    t.equal(chunk.toString(), 'a message')
  })

  instance.end('a message')
})
<|endoftext|>


<commit_before>// get the application server module
var parser = require('./auth.js');
var assert = require('chai').assert;
var expect = require('chai').expect;
var config = require('config');

const USERNAME_SEF = (process.env.USERNAME_SEF) ?
    process.env.USERNAME_SEF :
    config.get('sef.username');
const PASSWORD_SEF = (process.env.PASSWORD_SEF) ?
    (process.env.PASSWORD_SEF) :
    config.get('sef.password');
const USERNAME_ICARUS = (process.env.USERNAME_ICARUS) ?
    (process.env.USERNAME_ICARUS) :
    config.get('sef.username');
const PASSWORD_ICARUS = (process.env.PASSWORD_ICARUS) ?
    (process.env.PASSWORD_ICARUS) :
    config.get('sef.password');

describe('Module', function () {

    it('should throw error on wrong username', function () {
        assert.throw(function () {
            new parser('worng_username', '')
        }, Error);
    })
});

describe('Icarus Parser', function () {

    var self = this;

    before(function () {
        expect(USERNAME_ICARUS).to.exist;
        expect(PASSWORD_ICARUS).to.exist;
        this.parser = new parser(USERNAME_ICARUS, PASSWORD_ICARUS);
    });

    it('should only test in the MPES department', function () {
        expect(this.parser.getDepartmentName()).equals('Μηχανικών Πληροφοριακών και Επικοινωνιακών συστημάτων');
        expect(this.parser.getSessionInfo().username).equals(USERNAME_ICARUS);
    });

    it('should authenticate', function (done) {
        this.timeout(10000);
        this.parser.authenticate(function (err, response) {
            expect(err).to.not.exist;
            expect(response).to.exist;

            expect(response.authenticated).to.be.true;
            expect(response.document).to.not.be.null;
            expect(response.cookie).to.not.be.null;

            self.cookie = response.cookie;
            self.document = response.document;

            done();
        });
    });

    it('should not authenticate user with wrong credentials', function (done) {
        this.timeout(10000);
        var parser_wrong = new parser(USERNAME_ICARUS, 'wrong_password');
        parser_wrong.authenticate(function (err, response) {
            expect(err).to.not.exist;
            expect(response).to.exist;

            expect(response.authenticated).to.be.false;
            expect(response.cookie).not.to.be.null;

            done();
        });
    });

    it('should return analytic grades', function (done) {
        expect(self.document).to.exist;
        this.parser.getAnalyticGrades(self.document, function (err, response) {
            expect(err).to.not.exist;
            expect(response).to.exist;

            expect(response).to.have.length.above(2);
            expect(response[0]).to.have.deep.property('id');
            expect(response[0]).to.have.deep.property('title');
            expect(response[0]).to.have.deep.property('cemester');
            expect(response[0]).to.have.deep.property('applyDate');
            expect(response[0]).to.have.deep.property('examDate');
            expect(response[0]).to.have.deep.property('mark');
            expect(response[0]).to.have.deep.property('status');

            done();
        })
    });

    it('should return succeeded grades', function (done) {
        expect(self.document).to.exist;
        this.parser.getSucceededGrades(self.document, function (err, response) {
            expect(err).to.not.exist;
            expect(response).to.exist;

            expect(response).to.have.length.above(2);
            expect(response[0]).to.have.deep.property('id');
            expect(response[0]).to.have.deep.property('title');
            expect(response[0]).to.have.deep.property('cemester');
            expect(response[0]).to.have.deep.property('applyDate');
            expect(response[0]).to.have.deep.property('examDate');
            expect(response[0]).to.have.deep.property('mark');
            expect(response[0]).to.have.deep.property('status');

            done();
        })
    })

});

describe('Sef Parser', function () {

    var self = this;

    before(function () {
        expect(USERNAME_SEF).to.exist;
        expect(PASSWORD_SEF).to.exist;
        this.parser = new parser(USERNAME_SEF, PASSWORD_SEF);
    });

    it('should only test in the MATH or SAXM department', function () {
        expect(this.parser.getDepartmentName()).equals('Μαθηματικό');
        expect(this.parser.getSessionInfo().username).equals(USERNAME_SEF);
    });

    it('should authenticate', function (done) {
        this.timeout(10000);
        this.parser.authenticate(function (err, response) {
            expect(err).to.not.exist;
            expect(response).to.exist;

            expect(response.authenticated).to.be.true;
            expect(response.document).to.not.be.null;
            expect(response.cookie).to.not.be.null;

            self.cookie = response.cookie;
            self.document = response.document;

            done();
        });
    });

    it('should not authenticate user with wrong credentials', function (done) {
        this.timeout(10000);
        var parser_wrong = new parser(USERNAME_SEF, 'wrong_password');
        parser_wrong.authenticate(function (err, response) {
            expect(err).to.not.exist;
            expect(response).to.exist;

            expect(response.authenticated).to.be.false;

            done();
        });
    });

    it('should return analytic grades', function (done) {
        expect(self.document).to.exist;
        this.parser.getAnalyticGrades(self.document, function (err, response) {
            expect(err).to.not.exist;
            expect(response).to.exist;

            done();
        })
    })

});

<commit_msg>Added more tests<commit_after>// get the application server module
var parser = require('./auth.js');
var assert = require('chai').assert;
var expect = require('chai').expect;
var config = require('config');

const USERNAME_SEF = (process.env.USERNAME_SEF) ?
    process.env.USERNAME_SEF :
    config.get('sef.username');
const PASSWORD_SEF = (process.env.PASSWORD_SEF) ?
    (process.env.PASSWORD_SEF) :
    config.get('sef.password');
const USERNAME_ICARUS = (process.env.USERNAME_ICARUS) ?
    (process.env.USERNAME_ICARUS) :
    config.get('sef.username');
const PASSWORD_ICARUS = (process.env.PASSWORD_ICARUS) ?
    (process.env.PASSWORD_ICARUS) :
    config.get('sef.password');

describe('Module', function () {

    it('should throw error on wrong username', function () {
        assert.throw(function () {
            new parser('worng_username', '')
        }, Error);
    })
});

describe('Icarus Parser', function () {

    var self = this;

    before(function () {
        expect(USERNAME_ICARUS).to.exist;
        expect(PASSWORD_ICARUS).to.exist;
        this.parser = new parser(USERNAME_ICARUS, PASSWORD_ICARUS);
    });

    it('should only test in the MPES department', function () {
        expect(this.parser.getDepartmentName()).equals('Μηχανικών Πληροφοριακών και Επικοινωνιακών συστημάτων');
        expect(this.parser.getSessionInfo().username).equals(USERNAME_ICARUS);
    });

    it('should authenticate', function (done) {
        this.timeout(10000);
        this.parser.authenticate(function (err, response) {
            expect(err).to.not.exist;
            expect(response).to.exist;

            expect(response.authenticated).to.be.true;
            expect(response.document).to.not.be.null;
            expect(response.cookie).to.not.be.null;

            self.cookie = response.cookie;
            self.document = response.document;

            done();
        });
    });

    it('should not authenticate user with wrong credentials', function (done) {
        this.timeout(10000);
        var parser_wrong = new parser(USERNAME_ICARUS, 'wrong_password');
        parser_wrong.authenticate(function (err, response) {
            expect(err).to.not.exist;
            expect(response).to.exist;

            expect(response.authenticated).to.be.false;
            expect(response.cookie).not.to.be.null;

            done();
        });
    });

    it('should return analytic grades', function (done) {
        expect(self.document).to.exist;
        this.parser.getAnalyticGrades(self.document, function (err, response) {
            expect(err).to.not.exist;
            expect(response).to.exist;

            expect(response).to.have.length.above(2);
            expect(response[0]).to.have.deep.property('id');
            expect(response[0]).to.have.deep.property('title');
            expect(response[0]).to.have.deep.property('cemester');
            expect(response[0]).to.have.deep.property('applyDate');
            expect(response[0]).to.have.deep.property('examDate');
            expect(response[0]).to.have.deep.property('mark');
            expect(response[0]).to.have.deep.property('status');

            done();
        })
    });

    it('should return succeeded grades', function (done) {
        expect(self.document).to.exist;
        this.parser.getSucceededGrades(self.document, function (err, response) {
            expect(err).to.not.exist;
            expect(response).to.exist;

            expect(response).to.have.length.above(2);
            expect(response[0]).to.have.deep.property('id');
            expect(response[0]).to.have.deep.property('title');
            expect(response[0]).to.have.deep.property('cemester');
            expect(response[0]).to.have.deep.property('applyDate');
            expect(response[0]).to.have.deep.property('examDate');
            expect(response[0]).to.have.deep.property('mark');
            expect(response[0]).to.have.deep.property('status');

            done();
        })
    })

    it('should return user details', function (done) {
        expect(self.document).to.exist;
        this.parser.getUserDetails(self.document, self.cookie, function (err, res) {
            expect(err).to.be.null;
            expect(res).to.exist;

            expect(res).to.have.property('id');
            expect(res).to.have.property('name');
            expect(res).to.have.property('status');

            done();
        })
    });

});

describe('Sef Parser', function () {

    var self = this;

    before(function () {
        expect(USERNAME_SEF).to.exist;
        expect(PASSWORD_SEF).to.exist;
        this.parser = new parser(USERNAME_SEF, PASSWORD_SEF);
    });

    it('should only test in the MATH or SAXM department', function () {
        expect(this.parser.getDepartmentName()).equals('Μαθηματικό');
        expect(this.parser.getSessionInfo().username).equals(USERNAME_SEF);
    });

    it('should authenticate', function (done) {
        this.timeout(10000);
        this.parser.authenticate(function (err, response) {
            expect(err).to.not.exist;
            expect(response).to.exist;

            expect(response.authenticated).to.be.true;
            expect(response.document).to.not.be.null;
            expect(response.cookie).to.not.be.null;

            self.cookie = response.cookie;
            self.document = response.document;

            done();
        });
    });

    it('should not authenticate user with wrong credentials', function (done) {
        this.timeout(10000);
        var parser_wrong = new parser(USERNAME_SEF, 'wrong_password');
        parser_wrong.authenticate(function (err, response) {
            expect(err).to.not.exist;
            expect(response).to.exist;

            expect(response.authenticated).to.be.false;

            done();
        });
    });

    it('should return analytic grades', function (done) {
        expect(self.document).to.exist;
        this.parser.getAnalyticGrades(self.document, function (err, response) {
            expect(err).not.to.exist;
            expect(response).to.exist;

            expect(response).to.have.length.above(2);
            expect(response[0]).to.have.deep.property('id');
            expect(response[0]).to.have.deep.property('title');
            expect(response[0]).to.have.deep.property('applyDate');
            expect(response[0]).to.have.deep.property('examDate');
            expect(response[0]).to.have.deep.property('mark');
            expect(response[0]).to.have.deep.property('status');

            done();
        })
    })

    it('should return succeeded grades', function (done) {
        expect(self.document).to.exist;
        this.parser.getSucceededGrades(self.document, function (err, response) {
            expect(err).to.not.exist;
            expect(response).to.exist;

            expect(response).to.have.length.above(2);
            expect(response[0]).to.have.deep.property('id');
            expect(response[0]).to.have.deep.property('title');
            expect(response[0]).to.have.deep.property('ects');
            expect(response[0]).to.have.deep.property('certificate');
            expect(response[0]).to.have.deep.property('applyDate');
            expect(response[0]).to.have.deep.property('examDate');
            expect(response[0]).to.have.deep.property('mark');
            expect(response[0]).to.have.deep.property('status');

            done();
        })
    });

    it('should return user details', function (done) {
        expect(self.document).to.exist;
        this.parser.getUserDetails(self.document, self.cookie, function (err, res) {
            expect(err).to.be.null;
            expect(res).to.exist;

            expect(res).to.have.property('id');
            expect(res).to.have.property('name');
            expect(res).to.have.property('father');
            expect(res).to.have.property('address');
            expect(res).to.have.property('phone');

            done();
        })
    });

});
<|endoftext|>


<commit_before>var assert = require('assert');

describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
        assert.equal(-1, [1,2,3].indexOf(5));
    });
});var assert = require('assert');

describe('#indexOf()', function(){
    it('should return -1 when the value is not present', function(){
        assert.equal(-1, [1,2,3].indexOf(5));
    });
});<commit_msg>Delete test file<commit_after><|endoftext|>


<commit_before>var assert = require("assert"),
    Chiasm = require("chiasm"),
    ChiasmDsvDataset = require("./index");

// Use this shim so d3.csv and d3.json work.
XMLHttpRequest = require("xhr2");

describe("chiasm-dsv-dataset", function () {

  it("Should parse sample CSV data.", function(done) {
    var chiasm = Chiasm();
    chiasm.plugins.dsvDataset = ChiasmDsvDataset;

    chiasm.setConfig({
      dsv: {
        plugin: "dsvDataset",
        state: {
          path: "http://bl.ocks.org/curran/raw/b6e1d23c16dc76371a92/iris"
        }
      }
    });

    chiasm.getComponent("dsv").then(function (dsv){
      dsv.when("dataset", function (dataset){

        assert.equal(dataset.data.length, 150);
        assert.equal(dataset.metadata.columns.length, 5);

        var row = dataset.data[0];
        assert.equal(typeof row.sepal_length, "number");
        assert.equal(typeof row.sepal_width,  "number");
        assert.equal(typeof row.petal_length, "number");
        assert.equal(typeof row.petal_width,  "number");
        assert.equal(typeof row.class,        "string");
        done();
      });
    });
  });
});
<commit_msg>Explicitly expose XMLHTTPRequest on global object. Closes #1<commit_after>var assert = require("assert"),
    Chiasm = require("chiasm"),
    ChiasmDsvDataset = require("./index");

// Use this shim so d3.csv and d3.json work.
global.XMLHttpRequest = require("xhr2");

describe("chiasm-dsv-dataset", function () {

  it("Should parse sample CSV data.", function(done) {
    var chiasm = Chiasm();
    chiasm.plugins.dsvDataset = ChiasmDsvDataset;

    chiasm.setConfig({
      dsv: {
        plugin: "dsvDataset",
        state: {
          path: "http://bl.ocks.org/curran/raw/b6e1d23c16dc76371a92/iris"
        }
      }
    });

    chiasm.getComponent("dsv").then(function (dsv){
      dsv.when("dataset", function (dataset){

        assert.equal(dataset.data.length, 150);
        assert.equal(dataset.metadata.columns.length, 5);

        var row = dataset.data[0];
        assert.equal(typeof row.sepal_length, "number");
        assert.equal(typeof row.sepal_width,  "number");
        assert.equal(typeof row.petal_length, "number");
        assert.equal(typeof row.petal_width,  "number");
        assert.equal(typeof row.class,        "string");
        done();
      });
    });
  });
});
<|endoftext|>


<commit_before>var tape             = require('tape')
  , EE               = require('events').EventEmitter
  , util             = require('util')

  , isStream         = require('./')
  , isReadable       = require('./').isReadable
  , isWritable       = require('./').isWritable
  , isDuplex         = require('./').isDuplex

  , CoreStreams      = require('stream')
  , ReadableStream10 = require('./readable-stream-1.0/')
  , ReadableStream11 = require('./readable-stream-1.1/')

function test (pass, type, stream) {
  tape('isStream('  + type + ')', function (t) {
    t.plan(1)
    t.ok(pass === isStream(stream), type)
  })
}

function testReadable (pass, type, stream) {
  tape('isReadable('  + type + ')', function (t) {
    t.plan(1)
    t.ok(pass === isReadable(stream), type)
  })
}

function testWritable (pass, type, stream) {
  tape('isWritable('  + type + ')', function (t) {
    t.plan(1)
    t.ok(pass === isWritable(stream), type)
  })
}

function testDuplex (pass, type, stream) {
  tape('isDuplex('  + type + ')', function (t) {
    t.plan(1)
    t.ok(pass === isDuplex(stream), type)
  })
}

[ true, false, 0, 1, 1.0, 'string', {}, function foo () {} ].forEach(function (o) {
  test(false, 'non-stream / primitive: ' + (JSON.stringify(o) || o.toString()), o)
})

test(false, 'fake stream obj', { pipe: function () {} })

;(function () {

  // looks like a stream!

  function Stream () {
    EE.call(this)
  }
  util.inherits(Stream, EE)
  Stream.prototype.pipe = function () {}
  Stream.Stream = Stream

  test(false, 'fake stream "new Stream()"', new Stream())

}())

test(true, 'CoreStreams.Stream', new (CoreStreams.Stream)())
test(true, 'CoreStreams.Readable', new (CoreStreams.Readable)())
test(true, 'CoreStreams.Writable', new (CoreStreams.Writable)())
test(true, 'CoreStreams.Duplex', new (CoreStreams.Duplex)())
test(true, 'CoreStreams.Transform', new (CoreStreams.Transform)())
test(true, 'CoreStreams.PassThrough', new (CoreStreams.PassThrough)())

test(true, 'ReadableStream10.Readable', new (ReadableStream10.Readable)())
test(true, 'ReadableStream10.Writable', new (ReadableStream10.Writable)())
test(true, 'ReadableStream10.Duplex', new (ReadableStream10.Duplex)())
test(true, 'ReadableStream10.Transform', new (ReadableStream10.Transform)())
test(true, 'ReadableStream10.PassThrough', new (ReadableStream10.PassThrough)())

test(true, 'ReadableStream11.Readable', new (ReadableStream11.Readable)())
test(true, 'ReadableStream11.Writable', new (ReadableStream11.Writable)())
test(true, 'ReadableStream11.Duplex', new (ReadableStream11.Duplex)())
test(true, 'ReadableStream11.Transform', new (ReadableStream11.Transform)())
test(true, 'ReadableStream11.PassThrough', new (ReadableStream11.PassThrough)())

testReadable(false, 'CoreStreams.Stream', new (CoreStreams.Stream)())
testReadable(true, 'CoreStreams.Readable', new (CoreStreams.Readable)())
testReadable(false, 'CoreStreams.Writable', new (CoreStreams.Writable)())
testReadable(true, 'CoreStreams.Duplex', new (CoreStreams.Duplex)())
testReadable(true, 'CoreStreams.Transform', new (CoreStreams.Transform)())
testReadable(true, 'CoreStreams.PassThrough', new (CoreStreams.PassThrough)())

testReadable(true, 'ReadableStream10.Readable', new (ReadableStream10.Readable)())
testReadable(false, 'ReadableStream10.Writable', new (ReadableStream10.Writable)())
testReadable(true, 'ReadableStream10.Duplex', new (ReadableStream10.Duplex)())
testReadable(true, 'ReadableStream10.Transform', new (ReadableStream10.Transform)())
testReadable(true, 'ReadableStream10.PassThrough', new (ReadableStream10.PassThrough)())

testReadable(true, 'ReadableStream11.Readable', new (ReadableStream11.Readable)())
testReadable(false, 'ReadableStream11.Writable', new (ReadableStream11.Writable)())
testReadable(true, 'ReadableStream11.Duplex', new (ReadableStream11.Duplex)())
testReadable(true, 'ReadableStream11.Transform', new (ReadableStream11.Transform)())
testReadable(true, 'ReadableStream11.PassThrough', new (ReadableStream11.PassThrough)())

testWritable(false, 'CoreStreams.Stream', new (CoreStreams.Stream)())
testWritable(false, 'CoreStreams.Readable', new (CoreStreams.Readable)())
testWritable(true, 'CoreStreams.Writable', new (CoreStreams.Writable)())
testWritable(true, 'CoreStreams.Duplex', new (CoreStreams.Duplex)())
testWritable(true, 'CoreStreams.Transform', new (CoreStreams.Transform)())
testWritable(true, 'CoreStreams.PassThrough', new (CoreStreams.PassThrough)())

testWritable(false, 'ReadableStream10.Readable', new (ReadableStream10.Readable)())
testWritable(true, 'ReadableStream10.Writable', new (ReadableStream10.Writable)())
testWritable(true, 'ReadableStream10.Duplex', new (ReadableStream10.Duplex)())
testWritable(true, 'ReadableStream10.Transform', new (ReadableStream10.Transform)())
testWritable(true, 'ReadableStream10.PassThrough', new (ReadableStream10.PassThrough)())

testWritable(false, 'ReadableStream11.Readable', new (ReadableStream11.Readable)())
testWritable(true, 'ReadableStream11.Writable', new (ReadableStream11.Writable)())
testWritable(true, 'ReadableStream11.Duplex', new (ReadableStream11.Duplex)())
testWritable(true, 'ReadableStream11.Transform', new (ReadableStream11.Transform)())
testWritable(true, 'ReadableStream11.PassThrough', new (ReadableStream11.PassThrough)())

testDuplex(false, 'CoreStreams.Stream', new (CoreStreams.Stream)())
testDuplex(false, 'CoreStreams.Readable', new (CoreStreams.Readable)())
testDuplex(false, 'CoreStreams.Writable', new (CoreStreams.Writable)())
testDuplex(true, 'CoreStreams.Duplex', new (CoreStreams.Duplex)())
testDuplex(true, 'CoreStreams.Transform', new (CoreStreams.Transform)())
testDuplex(true, 'CoreStreams.PassThrough', new (CoreStreams.PassThrough)())

testDuplex(false, 'ReadableStream10.Readable', new (ReadableStream10.Readable)())
testDuplex(false, 'ReadableStream10.Writable', new (ReadableStream10.Writable)())
testDuplex(true, 'ReadableStream10.Duplex', new (ReadableStream10.Duplex)())
testDuplex(true, 'ReadableStream10.Transform', new (ReadableStream10.Transform)())
testDuplex(true, 'ReadableStream10.PassThrough', new (ReadableStream10.PassThrough)())

testDuplex(false, 'ReadableStream11.Readable', new (ReadableStream11.Readable)())
testDuplex(false, 'ReadableStream11.Writable', new (ReadableStream11.Writable)())
testDuplex(true, 'ReadableStream11.Duplex', new (ReadableStream11.Duplex)())
testDuplex(true, 'ReadableStream11.Transform', new (ReadableStream11.Transform)())
testDuplex(true, 'ReadableStream11.PassThrough', new (ReadableStream11.PassThrough)())

;[ CoreStreams, ReadableStream10, ReadableStream11 ].forEach(function (p) {
  [ 'Stream', 'Readable', 'Writable', 'Duplex', 'Transform', 'PassThrough' ].forEach(function (k) {
    if (!p[k])
      return

    function SubStream () {
      p[k].call(this)
    }
    util.inherits(SubStream, p[k])

    test(true, 'Stream subclass: ' + p.name + '.' + k, new SubStream())

  })
})

<commit_msg>falsey tests<commit_after>var tape             = require('tape')
  , EE               = require('events').EventEmitter
  , util             = require('util')

  , isStream         = require('./')
  , isReadable       = require('./').isReadable
  , isWritable       = require('./').isWritable
  , isDuplex         = require('./').isDuplex

  , CoreStreams      = require('stream')
  , ReadableStream10 = require('./readable-stream-1.0/')
  , ReadableStream11 = require('./readable-stream-1.1/')

function test (pass, type, stream) {
  tape('isStream('  + type + ')', function (t) {
    t.plan(1)
    t.ok(pass === isStream(stream), type)
  })
}

function testReadable (pass, type, stream) {
  tape('isReadable('  + type + ')', function (t) {
    t.plan(1)
    t.ok(pass === isReadable(stream), type)
  })
}

function testWritable (pass, type, stream) {
  tape('isWritable('  + type + ')', function (t) {
    t.plan(1)
    t.ok(pass === isWritable(stream), type)
  })
}

function testDuplex (pass, type, stream) {
  tape('isDuplex('  + type + ')', function (t) {
    t.plan(1)
    t.ok(pass === isDuplex(stream), type)
  })
}

[ undefined, null, '', true, false, 0, 1, 1.0, 'string', {}, function foo () {} ].forEach(function (o) {
  test(false, 'non-stream / primitive: ' + (JSON.stringify(o) || (o && o.toString()) || o), o)
})

test(false, 'fake stream obj', { pipe: function () {} })

;(function () {

  // looks like a stream!

  function Stream () {
    EE.call(this)
  }
  util.inherits(Stream, EE)
  Stream.prototype.pipe = function () {}
  Stream.Stream = Stream

  test(false, 'fake stream "new Stream()"', new Stream())

}())

test(true, 'CoreStreams.Stream', new (CoreStreams.Stream)())
test(true, 'CoreStreams.Readable', new (CoreStreams.Readable)())
test(true, 'CoreStreams.Writable', new (CoreStreams.Writable)())
test(true, 'CoreStreams.Duplex', new (CoreStreams.Duplex)())
test(true, 'CoreStreams.Transform', new (CoreStreams.Transform)())
test(true, 'CoreStreams.PassThrough', new (CoreStreams.PassThrough)())

test(true, 'ReadableStream10.Readable', new (ReadableStream10.Readable)())
test(true, 'ReadableStream10.Writable', new (ReadableStream10.Writable)())
test(true, 'ReadableStream10.Duplex', new (ReadableStream10.Duplex)())
test(true, 'ReadableStream10.Transform', new (ReadableStream10.Transform)())
test(true, 'ReadableStream10.PassThrough', new (ReadableStream10.PassThrough)())

test(true, 'ReadableStream11.Readable', new (ReadableStream11.Readable)())
test(true, 'ReadableStream11.Writable', new (ReadableStream11.Writable)())
test(true, 'ReadableStream11.Duplex', new (ReadableStream11.Duplex)())
test(true, 'ReadableStream11.Transform', new (ReadableStream11.Transform)())
test(true, 'ReadableStream11.PassThrough', new (ReadableStream11.PassThrough)())

testReadable(false, 'CoreStreams.Stream', new (CoreStreams.Stream)())
testReadable(true, 'CoreStreams.Readable', new (CoreStreams.Readable)())
testReadable(false, 'CoreStreams.Writable', new (CoreStreams.Writable)())
testReadable(true, 'CoreStreams.Duplex', new (CoreStreams.Duplex)())
testReadable(true, 'CoreStreams.Transform', new (CoreStreams.Transform)())
testReadable(true, 'CoreStreams.PassThrough', new (CoreStreams.PassThrough)())

testReadable(true, 'ReadableStream10.Readable', new (ReadableStream10.Readable)())
testReadable(false, 'ReadableStream10.Writable', new (ReadableStream10.Writable)())
testReadable(true, 'ReadableStream10.Duplex', new (ReadableStream10.Duplex)())
testReadable(true, 'ReadableStream10.Transform', new (ReadableStream10.Transform)())
testReadable(true, 'ReadableStream10.PassThrough', new (ReadableStream10.PassThrough)())

testReadable(true, 'ReadableStream11.Readable', new (ReadableStream11.Readable)())
testReadable(false, 'ReadableStream11.Writable', new (ReadableStream11.Writable)())
testReadable(true, 'ReadableStream11.Duplex', new (ReadableStream11.Duplex)())
testReadable(true, 'ReadableStream11.Transform', new (ReadableStream11.Transform)())
testReadable(true, 'ReadableStream11.PassThrough', new (ReadableStream11.PassThrough)())

testWritable(false, 'CoreStreams.Stream', new (CoreStreams.Stream)())
testWritable(false, 'CoreStreams.Readable', new (CoreStreams.Readable)())
testWritable(true, 'CoreStreams.Writable', new (CoreStreams.Writable)())
testWritable(true, 'CoreStreams.Duplex', new (CoreStreams.Duplex)())
testWritable(true, 'CoreStreams.Transform', new (CoreStreams.Transform)())
testWritable(true, 'CoreStreams.PassThrough', new (CoreStreams.PassThrough)())

testWritable(false, 'ReadableStream10.Readable', new (ReadableStream10.Readable)())
testWritable(true, 'ReadableStream10.Writable', new (ReadableStream10.Writable)())
testWritable(true, 'ReadableStream10.Duplex', new (ReadableStream10.Duplex)())
testWritable(true, 'ReadableStream10.Transform', new (ReadableStream10.Transform)())
testWritable(true, 'ReadableStream10.PassThrough', new (ReadableStream10.PassThrough)())

testWritable(false, 'ReadableStream11.Readable', new (ReadableStream11.Readable)())
testWritable(true, 'ReadableStream11.Writable', new (ReadableStream11.Writable)())
testWritable(true, 'ReadableStream11.Duplex', new (ReadableStream11.Duplex)())
testWritable(true, 'ReadableStream11.Transform', new (ReadableStream11.Transform)())
testWritable(true, 'ReadableStream11.PassThrough', new (ReadableStream11.PassThrough)())

testDuplex(false, 'CoreStreams.Stream', new (CoreStreams.Stream)())
testDuplex(false, 'CoreStreams.Readable', new (CoreStreams.Readable)())
testDuplex(false, 'CoreStreams.Writable', new (CoreStreams.Writable)())
testDuplex(true, 'CoreStreams.Duplex', new (CoreStreams.Duplex)())
testDuplex(true, 'CoreStreams.Transform', new (CoreStreams.Transform)())
testDuplex(true, 'CoreStreams.PassThrough', new (CoreStreams.PassThrough)())

testDuplex(false, 'ReadableStream10.Readable', new (ReadableStream10.Readable)())
testDuplex(false, 'ReadableStream10.Writable', new (ReadableStream10.Writable)())
testDuplex(true, 'ReadableStream10.Duplex', new (ReadableStream10.Duplex)())
testDuplex(true, 'ReadableStream10.Transform', new (ReadableStream10.Transform)())
testDuplex(true, 'ReadableStream10.PassThrough', new (ReadableStream10.PassThrough)())

testDuplex(false, 'ReadableStream11.Readable', new (ReadableStream11.Readable)())
testDuplex(false, 'ReadableStream11.Writable', new (ReadableStream11.Writable)())
testDuplex(true, 'ReadableStream11.Duplex', new (ReadableStream11.Duplex)())
testDuplex(true, 'ReadableStream11.Transform', new (ReadableStream11.Transform)())
testDuplex(true, 'ReadableStream11.PassThrough', new (ReadableStream11.PassThrough)())

;[ CoreStreams, ReadableStream10, ReadableStream11 ].forEach(function (p) {
  [ 'Stream', 'Readable', 'Writable', 'Duplex', 'Transform', 'PassThrough' ].forEach(function (k) {
    if (!p[k])
      return

    function SubStream () {
      p[k].call(this)
    }
    util.inherits(SubStream, p[k])

    test(true, 'Stream subclass: ' + p.name + '.' + k, new SubStream())

  })
})

<|endoftext|>


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

var png = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
var html = 'data:text/html;charset=utf-8,<!DOCTYPE%20html><title>Embedded%20Window<%2Ftitle><%2Fhead>
42<%2Fh1><%2Fbody><%2Fhtml>';
var svg = 'data:image/svg+xml;base64,PD94bWwgdmVyzeiBNMyw2djJoMThWNkgzeiIvPjwvZz4KPC9zdmc+Cgo=';

test('Regexp returns parts of data-uri for image/png', t => {
	t.ok(png.match(regex()));
	t.ok(regex().test(png));
	t.is(regex().exec(png)[1], 'data:');
	t.is(regex().exec(png)[2], 'image/png');
	t.is(regex().exec(png)[3], 'base64');
	t.is(regex().exec(png)[4].slice(0, 3), 'iVB');

	t.end();
});

test('Regexp returns parts of data-uri for html', t => {
	t.ok(html.match(regex()));
	t.ok(regex().test(html));
	t.is(regex().exec(html)[1], 'data:');
	t.is(regex().exec(html)[2], 'text/html');
	t.is(regex().exec(html)[3], 'charset=utf-8');
	t.is(regex().exec(html)[4].slice(0, 3), '<!D');

	t.end();
});

test('Regexp returns parts of data-uri for svg', t => {
	t.ok(svg.match(regex()));
	t.ok(regex().test(svg));
	t.is(regex().exec(svg)[1], 'data:');
	t.is(regex().exec(svg)[2], 'image/svg+xml');
	t.is(regex().exec(svg)[3], 'base64');
	t.is(regex().exec(svg)[4].slice(0, 3), 'PD9');

	t.end();
});
<commit_msg>Add semicol<commit_after>import test from 'ava';
import regex from './';

var png = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';
var html = 'data:text/html;charset=utf-8,<!DOCTYPE%20html><title>Embedded%20Window<%2Ftitle><%2Fhead>
42<%2Fh1><%2Fbody><%2Fhtml>';
var svg = 'data:image/svg+xml;base64,PD94bWwgdmVyzeiBNMyw2djJoMThWNkgzeiIvPjwvZz4KPC9zdmc+Cgo=';

test('Regexp returns parts of data-uri for image/png', t => {
	t.ok(png.match(regex()));
	t.ok(regex().test(png));
	t.is(regex().exec(png)[1], 'data:');
	t.is(regex().exec(png)[2], 'image/png');
	t.is(regex().exec(png)[3], 'base64');
	t.is(regex().exec(png)[4].slice(0, 3), 'iVB');

	t.end();
});

test('Regexp returns parts of data-uri for html', t => {
	t.ok(html.match(regex()));
	t.ok(regex().test(html));
	t.is(regex().exec(html)[1], 'data:');
	t.is(regex().exec(html)[2], 'text/html');
	t.is(regex().exec(html)[3], 'charset=utf-8');
	t.is(regex().exec(html)[4].slice(0, 3), '<!D');

	t.end();
});

test('Regexp returns parts of data-uri for svg', t => {
	t.ok(svg.match(regex()));
	t.ok(regex().test(svg));
	t.is(regex().exec(svg)[1], 'data:');
	t.is(regex().exec(svg)[2], 'image/svg+xml');
	t.is(regex().exec(svg)[3], 'base64');
	t.is(regex().exec(svg)[4].slice(0, 3), 'PD9');

	t.end();
});
<|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 10:45: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>var execSync = require('child_process').execSync;
var assert = require('assert');
var glob = require('glob');
var path = require('path');
var fs = require('fs');

var files = glob.sync('exercises/*/solution/solution.js');

files.forEach(function (file) {
  var name = path.basename(path.dirname(path.dirname(file)));
  execSync('./kick-off-koa.js select ' + name);
  var submission = execSync('./kick-off-koa.js run ' + file).toString();
  var result = fs.readFileSync(file.replace(/\.js$/, '.txt'), 'utf8');
  assert(submission === result);
});
<commit_msg>update test<commit_after>var execSync = require('child_process').execSync;
var assert = require('assert');
var glob = require('glob');
var path = require('path');
var fs = require('fs');

var files = glob.sync('exercises/*/solution/solution.js');

files.forEach(function (file) {
  var name = path.basename(path.dirname(path.dirname(file)));
  execSync('./kick-off-koa.js select ' + name);
  var submission = execSync('./kick-off-koa.js run ' + file).toString();
  var result = fs.readFileSync(file.replace(/\.js$/, '.txt'), 'utf8');
  assert(submission === result);

  // check verify output include solution file
  var v = execSync('./kick-off-koa.js verify ' + file).toString();
  var solution = fs.readFileSync(file, 'utf8');
  assert(v.replace(/\s*/g, '').indexOf(solution.replace(/\s*/g, '')) >= 0);
});
<|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 08:54:27<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 { Vector,sum,product } = require("./vecto");

/* Tests for creation of Vector */

//: constructor(?shape[],?array[])

//case 1 : constructor(shape,arr)
let v1 = new Vector([2,3],[[1,2,3],[4,5,6]]);
console.log(v1);
//Expected output : v1 = { array:[[1,2,3],[4,5,6]], dim:2, shape:[2,3], size:6, flat:[1,2,3,4,5,6] };

//case 2 : constructor(shape)
let v2 = new Vector([2,3]);
console.log(v2);
//Expected output : v2 = { array:[], dim:2, shape:[2,3], size:6, flat:[] }
// at this point the array and flat for v2 are empty arrays,
// you've to call this.arrange() explicitly.

//case 3 : constructor(array)
let v3 = new Vector([],[[1,2,3],[4,5,6]]);
console.log(v3);
//Expected output : v3 = { array:[[1,2,3],[4,5,6]], dim:2, shape:[2,3], size:6, flat:[1,2,3,4,5,6] }

//case 4 : constructor()
let v4 = new Vector();
console.log(v4);
//Expected output : v4 = { array:[], dim:1, shape:[], size:0, flat:[] }

//: Vector.array(array)

let v5 = Vector.array([[1,2,3],[4,5,6]]);
console.log(v5);
//Expected output : v5 = { array:[[1,2,3],[4,5,6]], dim:2, shape:[2,3], size:6, flat:[1,2,3,4,5,6] }

//: Vector.zeroes(shape)

let v6 = Vector.zeroes([2,3]);
console.log(v6);
//Expected output : v6 = { array:[[0,0,0],[0,0,0]], dim:2, shape:[2,3], size:6, flat:[0,0,0,0,0,0,] }

/* Tests for Vector.flatten(ndarr,target_arr) */
let v7 = [[[1,2,3],[4,5,6],[8,9,10]],[[2,3,4],[6,9,1],[4,5,2]],[[4,5,6],[1,4,1],[4,6,8]]];
let tar1 = [];0
Vector.flatten(v7,tar1);
console.log(tar1);
//Expected output : [1,2,3,4,5,6,8,9,10,2,3,4,6,9,1,4,5,2,4,5,6,1,4,1,4,6,8]

/* Tests for Vector_object.arrange(?elems_arr,?fill_style) */

let v8 = new Vector([2,2,3]);
v8.arrange([1,2,3,4,5,6,7]);
console.log(v8.array);

v8.arrange();
console.log(v8.array);

v8.arrange([2]);
console.log(v8.array);

/* Tests for Vector_object.resize(new_shape[]) */
let v9 = new Vector([2,2,3]);
v9.arrange([4]);
console.log(v9.array);
v9.resize([2,9,5]);
console.log(v9.array);

/* Tests for Vector_object.reshape(new_shape[]) */
let v10 = new Vector([2,3]);
v10.arrange();
console.log(v10.array);
v10.reshape([6,2]);
console.log(v10.array);

/* Tests for Vector.fill(len,fill_style,...args) */

let v11 = Vector.fill(8);
console.log(v11);
//Expected output : [random array of length 8];

v11 = Vector.fill(8,"linear",1);
console.log(v11);
//Expected output : [1,1,1,1,1,1,1,1]

v11 = Vector.fill(8,"linear",0.1,0.9,0.1);
console.log(v11);
//Expected output : [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8]

v11 = Vector.fill(8,"linear",10,20);
console.log(v11);
//Expected output : [10,11,12,13,14,15,16,17]

/* Tests for product(arr1,arr2)*/
let v12 = [[1,2,3],[3,4,1]],
v13 = [10,10,10];
console.log(product(v12,v13));

let v14 = [[2,1,5],[6,7,8]];
console.log(product(v12,v14));

let v15 = [2,3,4];
console.log(product(v13,v15));

let v16 = [4,5,6,7,8];
console.log(product(v12,v16));

let v17 = [[1,2],[4,5]];
console.log(product(v12,v17));

console.log(product(v12,4));
console.log(product(v12,v17));

/* Tests for sum(arr1,?arr2) */

/* Tests for Vector.add(v2) */

<commit_msg>:bug::sparkles:<commit_after>const { Vector,sum,product } = require("./vecto");

/* Tests for creation of Vector */

//: constructor(?shape[],?array[])

//case 1 : constructor(shape,arr)
let v1 = new Vector([2,3],[[1,2,3],[4,5,6]]);
console.log(v1);
//Expected output : v1 = { array:[[1,2,3],[4,5,6]], dim:2, shape:[2,3], size:6, flat:[1,2,3,4,5,6] };

//case 2 : constructor(shape)
let v2 = new Vector([2,3]);
console.log(v2);
//Expected output : v2 = { array:[], dim:2, shape:[2,3], size:6, flat:[] }
// at this point the array and flat for v2 are empty arrays,
// you've to call this.arrange() explicitly.

//case 3 : constructor(array)
let v3 = new Vector([],[[1,2,3],[4,5,6]]);
console.log(v3);
//Expected output : v3 = { array:[[1,2,3],[4,5,6]], dim:2, shape:[2,3], size:6, flat:[1,2,3,4,5,6] }

//case 4 : constructor()
let v4 = new Vector();
console.log(v4);
//Expected output : v4 = { array:[], dim:1, shape:[], size:0, flat:[] }

//: Vector.array(array)

let v5 = Vector.array([[1,2,3],[4,5,6]]);
console.log(v5);
//Expected output : v5 = { array:[[1,2,3],[4,5,6]], dim:2, shape:[2,3], size:6, flat:[1,2,3,4,5,6] }

//: Vector.zeroes(shape)

let v6 = Vector.zeroes([2,3]);
console.log(v6);
//Expected output : v6 = { array:[[0,0,0],[0,0,0]], dim:2, shape:[2,3], size:6, flat:[0,0,0,0,0,0,] }

/* Tests for Vector.flatten(ndarr,target_arr) */
let v7 = [[[1,2,3],[4,5,6],[8,9,10]],[[2,3,4],[6,9,1],[4,5,2]],[[4,5,6],[1,4,1],[4,6,8]]];
let tar1 = [];
Vector.flatten(v7,tar1);
console.log(tar1);
//Expected output : [1,2,3,4,5,6,8,9,10,2,3,4,6,9,1,4,5,2,4,5,6,1,4,1,4,6,8]

/* Tests for Vector_object.arrange(?elems_arr,?fill_style) */

let v8 = new Vector([2,2,3]);
v8.arrange([1,2,3,4,5,6,7]);
console.log(v8.array);

v8.arrange();
console.log(v8.array);

v8.arrange([2]);
console.log(v8.array);

/* Tests for Vector_object.resize(new_shape[]) */
let v9 = new Vector([2,2,3]);
v9.arrange([4]);
console.log(v9.array);
v9.resize([2,9,5]);
console.log(v9.array);

/* Tests for Vector_object.reshape(new_shape[]) */
let v10 = new Vector([2,3]);
v10.arrange();
console.log(v10.array);
v10.reshape([6,2]);
console.log(v10.array);

/* Tests for Vector.fill(len,fill_style,...args) */

let v11 = Vector.fill(8);
console.log(v11);
//Expected output : [random array of length 8];

v11 = Vector.fill(8,"linear",1);
console.log(v11);
//Expected output : [1,1,1,1,1,1,1,1]

v11 = Vector.fill(8,"linear",0.1,0.9,0.1);
console.log(v11);
//Expected output : [0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8]

v11 = Vector.fill(8,"linear",10,20);
console.log(v11);
//Expected output : [10,11,12,13,14,15,16,17]

/* Tests for product(arr1,arr2)*/
let v12 = [[1,2,3],[3,4,1]],
v13 = [10,10,10];
console.log(product(v12,v13));

let v14 = [[2,1,5],[6,7,8]];
console.log(product(v12,v14));

let v15 = [2,3,4];
console.log(product(v13,v15));

let v16 = [4,5,6,7,8];
console.log(product(v12,v16));

let v17 = [[1,2],[4,5]];
console.log(product(v12,v17));

console.log(product(v12,4));
console.log(product(v12,v17));

/* Tests for sum(arr1,?arr2) */

/* Tests for Vector.add(v2) */

<|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-12-4 02:04:59<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>//initialize all of our variables
var app, base, concat, directory, gulp, gutil, hostname, path, refresh, sass, uglify, imagemin, minifyCSS, del, browserSync, autoprefixer, gulpSequence, shell, sourceMaps, plumber, ghPages, spritesmith;

var autoPrefixBrowserList = ['last 2 versions', '> 2%'];

//load all of our dependencies
//add more here if you want to include more libraries
gulp        = require('gulp');
gutil       = require('gulp-util');
concat      = require('gulp-concat');
uglify      = require('gulp-uglify');
sass        = require('gulp-sass');
sourceMaps  = require('gulp-sourcemaps');
imagemin    = require('gulp-imagemin');
minifyCSS   = require('gulp-minify-css');
browserSync = require('browser-sync');
autoprefixer = require('gulp-autoprefixer');
gulpSequence = require('gulp-sequence').use(gulp);
shell       = require('gulp-shell');
plumber     = require('gulp-plumber');
ghPages     = require('gulp-gh-pages');
spritesmith = require('gulp.spritesmith');

gulp.task('browserSync', function() {
    browserSync({
        server: {
            baseDir: "app/"
        },
        options: {
            reloadDelay: 250
        },
        notify: false
    });
});

//compressing images & handle SVG files
gulp.task('images', function() {
    gulp.src(['app/images/**/*', '!app/images/README', '!app/images/sprites/*.*'])
        //prevent pipe breaking caused by errors from gulp plugins
        .pipe(plumber())
        .pipe(imagemin({ optimizationLevel: 5, progressive: true, interlaced: true }))
        .pipe(gulp.dest('app/images'));
});

//compressing images & handle SVG files
gulp.task('images-deploy', function() {
    gulp.src(['app/images/**/*', '!app/images/README', '!app/images/sprites/*.*'])
        //prevent pipe breaking caused by errors from gulp plugins
        .pipe(plumber())
        .pipe(gulp.dest('dist/images'));
});

//collecting sprites to build a sprite map
gulp.task('sprite', function() {
    var spriteData =
        gulp.src(['app/images/sprites/*.jpg', 'app/images/sprites/*.png'])
            //prevent pipe breaking caused by errors from gulp plugins
            .pipe(plumber())
            .pipe(spritesmith({
              imgName: 'sprite.png',
              imgPath: '/images/sprite.png',
              cssName: '_sprite.scss'
            }));
    //output back to app folder to be compressed
    spriteData.img.pipe(gulp.dest('app/images'));
    //output back to app folder to get minified
    spriteData.css.pipe(gulp.dest('app/styles/scss/general'));
});

//compiling our Javascripts
gulp.task('scripts', function() {
    //this is where our dev JS scripts are
    return gulp.src(['app/scripts/src/_includes/**/*.js', 'app/scripts/src/**/*.js'])
                //prevent pipe breaking caused by errors from gulp plugins
                .pipe(plumber())
                //this is the filename of the compressed version of our JS
                .pipe(concat('app.js'))
                //catch errors
                .on('error', gutil.log)
                //compress :D
                .pipe(uglify())
                //where we will store our finalized, compressed script
                .pipe(gulp.dest('app/scripts'))
                //notify browserSync to refresh
                .pipe(browserSync.reload({stream: true}));
});

//compiling our Javascripts for deployment
gulp.task('scripts-deploy', function() {
    //this is where our dev JS scripts are
    return gulp.src(['app/scripts/src/_includes/**/*.js', 'app/scripts/src/**/*.js'])
                //prevent pipe breaking caused by errors from gulp plugins
                .pipe(plumber())
                //this is the filename of the compressed version of our JS
                .pipe(concat('app.js'))
                //compress :D
                .pipe(uglify())
                //where we will store our finalized, compressed script
                .pipe(gulp.dest('dist/scripts'));
});

//compiling our SCSS files
gulp.task('styles', function() {
    //the initializer / master SCSS file, which will just be a file that imports everything
    return gulp.src('app/styles/scss/init.scss')
                //prevent pipe breaking caused by errors from gulp plugins
                .pipe(plumber({
                  errorHandler: function (err) {
                    console.log(err);
                    this.emit('end');
                  }
                }))
                //get sourceMaps ready
                .pipe(sourceMaps.init())
                //include SCSS and list every "include" folder
                .pipe(sass({
                      errLogToConsole: true,
                      includePaths: [
                          'app/styles/scss/'
                      ]
                }))
                .pipe(autoprefixer({
                   browsers: autoPrefixBrowserList,
                   cascade:  true
                }))
                //catch errors
                .on('error', gutil.log)
                //the final filename of our combined css file
                .pipe(concat('styles.css'))
                //get our sources via sourceMaps
                .pipe(sourceMaps.write())
                //where to save our final, compressed css file
                .pipe(gulp.dest('app/styles'))
                //notify browserSync to refresh
                .pipe(browserSync.reload({stream: true}));
});

//compiling our SCSS files for deployment
gulp.task('styles-deploy', function() {
    //the initializer / master SCSS file, which will just be a file that imports everything
    return gulp.src('app/styles/scss/init.scss')
                .pipe(plumber())
                //include SCSS includes folder
                .pipe(sass({
                      includePaths: [
                          'app/styles/scss',
                      ]
                }))
                .pipe(autoprefixer({
                  browsers: autoPrefixBrowserList,
                  cascade:  true
                }))
                //the final filename of our combined css file
                .pipe(concat('styles.css'))
                .pipe(minifyCSS())
                //where to save our final, compressed css file
                .pipe(gulp.dest('dist/styles'));
});

//basically just keeping an eye on all HTML files
gulp.task('html', function() {
    //watch any and all HTML files and refresh when something changes
    return gulp.src('app/*.html')
        .pipe(plumber())
        .pipe(browserSync.reload({stream: true}))
        //catch errors
        .on('error', gutil.log);
});

//migrating over all HTML files for deployment
gulp.task('html-deploy', function() {
    //grab everything, which should include htaccess, robots, etc
    gulp.src('app/*')
        //prevent pipe breaking caused by errors from gulp plugins
        .pipe(plumber())
        .pipe(gulp.dest('dist'));

    //grab any hidden files too
    gulp.src('app/.*')
        //prevent pipe breaking caused by errors from gulp plugins
        .pipe(plumber())
        .pipe(gulp.dest('dist'));

    gulp.src('app/fonts/**/*')
        //prevent pipe breaking caused by errors from gulp plugins
        .pipe(plumber())
        .pipe(gulp.dest('dist/fonts'));

    //grab all of the styles
    gulp.src(['app/styles/*.css', '!app/styles/styles.css'])
        //prevent pipe breaking caused by errors from gulp plugins
        .pipe(plumber())
        .pipe(gulp.dest('dist/styles'));
});

//cleans our dist directory in case things got deleted
gulp.task('clean', function() {
    return shell.task([
      'rm -rf dist'
    ]);
});

//create folders using shell
gulp.task('scaffold', function() {
  return shell.task([
      'mkdir dist',
      'mkdir dist/fonts',
      'mkdir dist/images',
      'mkdir dist/scripts',
      'mkdir dist/styles'
    ]
  );
});

//cherry-pick latest commit to gh-pages branch
gulp.task('ghpages-deploy', function() {
  return gulp.src('./dist/**/*')
    .pipe(ghPages());
});

//this is our master task when you run `gulp` in CLI / Terminal
//this is the main watcher to use when in active development
//  this will:
//  startup the web server
//  generate sprite sheet
//  compress all scripts and SCSS files
gulp.task('default', ['browserSync', 'sprite', 'scripts', 'styles'], function() {
    //a list of watchers, so it will watch all of the following files waiting for changes
    gulp.watch('app/scripts/src/**', ['scripts']);
    gulp.watch('app/styles/scss/**', ['styles']);
    gulp.watch('app/images/**', ['sprite', 'images']);
    gulp.watch('app/*.html', ['html']);
});

//this is our deployment task, it will set everything for deployment-ready files
gulp.task('deploy', gulpSequence('clean', 'scaffold', 'sprite', ['scripts-deploy', 'styles-deploy', 'images-deploy'], 'html-deploy', 'ghpages-deploy'));
<commit_msg>Remove image processing from default gulp<commit_after>//initialize all of our variables
var app, base, concat, directory, gulp, gutil, hostname, path, refresh, sass, uglify, imagemin, minifyCSS, del, browserSync, autoprefixer, gulpSequence, shell, sourceMaps, plumber, ghPages, spritesmith;

var autoPrefixBrowserList = ['last 2 versions', '> 2%'];

//load all of our dependencies
//add more here if you want to include more libraries
gulp        = require('gulp');
gutil       = require('gulp-util');
concat      = require('gulp-concat');
uglify      = require('gulp-uglify');
sass        = require('gulp-sass');
sourceMaps  = require('gulp-sourcemaps');
imagemin    = require('gulp-imagemin');
minifyCSS   = require('gulp-minify-css');
browserSync = require('browser-sync');
autoprefixer = require('gulp-autoprefixer');
gulpSequence = require('gulp-sequence').use(gulp);
shell       = require('gulp-shell');
plumber     = require('gulp-plumber');
ghPages     = require('gulp-gh-pages');
spritesmith = require('gulp.spritesmith');

gulp.task('browserSync', function() {
    browserSync({
        server: {
            baseDir: "app/"
        },
        options: {
            reloadDelay: 250
        },
        notify: false
    });
});

//compressing images & handle SVG files
gulp.task('images', function() {
    gulp.src(['app/images/**/*', '!app/images/README', '!app/images/sprites/*.*'])
        //prevent pipe breaking caused by errors from gulp plugins
        .pipe(plumber())
        .pipe(imagemin({ optimizationLevel: 5, progressive: true, interlaced: true }))
        .pipe(gulp.dest('app/images'));
});

//compressing images & handle SVG files
gulp.task('images-deploy', function() {
    gulp.src(['app/images/**/*', '!app/images/README', '!app/images/sprites/*.*'])
        //prevent pipe breaking caused by errors from gulp plugins
        .pipe(plumber())
        .pipe(gulp.dest('dist/images'));
});

//collecting sprites to build a sprite map
gulp.task('sprite', function() {
    var spriteData =
        gulp.src(['app/images/sprites/*.jpg', 'app/images/sprites/*.png'])
            //prevent pipe breaking caused by errors from gulp plugins
            .pipe(plumber())
            .pipe(spritesmith({
              imgName: 'sprite.png',
              imgPath: '/images/sprite.png',
              cssName: '_sprite.scss'
            }));
    //output back to app folder to be compressed
    spriteData.img.pipe(gulp.dest('app/images'));
    //output back to app folder to get minified
    spriteData.css.pipe(gulp.dest('app/styles/scss/general'));
});

//compiling our Javascripts
gulp.task('scripts', function() {
    //this is where our dev JS scripts are
    return gulp.src(['app/scripts/src/_includes/**/*.js', 'app/scripts/src/**/*.js'])
                //prevent pipe breaking caused by errors from gulp plugins
                .pipe(plumber())
                //this is the filename of the compressed version of our JS
                .pipe(concat('app.js'))
                //catch errors
                .on('error', gutil.log)
                //compress :D
                .pipe(uglify())
                //where we will store our finalized, compressed script
                .pipe(gulp.dest('app/scripts'))
                //notify browserSync to refresh
                .pipe(browserSync.reload({stream: true}));
});

//compiling our Javascripts for deployment
gulp.task('scripts-deploy', function() {
    //this is where our dev JS scripts are
    return gulp.src(['app/scripts/src/_includes/**/*.js', 'app/scripts/src/**/*.js'])
                //prevent pipe breaking caused by errors from gulp plugins
                .pipe(plumber())
                //this is the filename of the compressed version of our JS
                .pipe(concat('app.js'))
                //compress :D
                .pipe(uglify())
                //where we will store our finalized, compressed script
                .pipe(gulp.dest('dist/scripts'));
});

//compiling our SCSS files
gulp.task('styles', function() {
    //the initializer / master SCSS file, which will just be a file that imports everything
    return gulp.src('app/styles/scss/init.scss')
                //prevent pipe breaking caused by errors from gulp plugins
                .pipe(plumber({
                  errorHandler: function (err) {
                    console.log(err);
                    this.emit('end');
                  }
                }))
                //get sourceMaps ready
                .pipe(sourceMaps.init())
                //include SCSS and list every "include" folder
                .pipe(sass({
                      errLogToConsole: true,
                      includePaths: [
                          'app/styles/scss/'
                      ]
                }))
                .pipe(autoprefixer({
                   browsers: autoPrefixBrowserList,
                   cascade:  true
                }))
                //catch errors
                .on('error', gutil.log)
                //the final filename of our combined css file
                .pipe(concat('styles.css'))
                //get our sources via sourceMaps
                .pipe(sourceMaps.write())
                //where to save our final, compressed css file
                .pipe(gulp.dest('app/styles'))
                //notify browserSync to refresh
                .pipe(browserSync.reload({stream: true}));
});

//compiling our SCSS files for deployment
gulp.task('styles-deploy', function() {
    //the initializer / master SCSS file, which will just be a file that imports everything
    return gulp.src('app/styles/scss/init.scss')
                .pipe(plumber())
                //include SCSS includes folder
                .pipe(sass({
                      includePaths: [
                          'app/styles/scss',
                      ]
                }))
                .pipe(autoprefixer({
                  browsers: autoPrefixBrowserList,
                  cascade:  true
                }))
                //the final filename of our combined css file
                .pipe(concat('styles.css'))
                .pipe(minifyCSS())
                //where to save our final, compressed css file
                .pipe(gulp.dest('dist/styles'));
});

//basically just keeping an eye on all HTML files
gulp.task('html', function() {
    //watch any and all HTML files and refresh when something changes
    return gulp.src('app/*.html')
        .pipe(plumber())
        .pipe(browserSync.reload({stream: true}))
        //catch errors
        .on('error', gutil.log);
});

//migrating over all HTML files for deployment
gulp.task('html-deploy', function() {
    //grab everything, which should include htaccess, robots, etc
    gulp.src('app/*')
        //prevent pipe breaking caused by errors from gulp plugins
        .pipe(plumber())
        .pipe(gulp.dest('dist'));

    //grab any hidden files too
    gulp.src('app/.*')
        //prevent pipe breaking caused by errors from gulp plugins
        .pipe(plumber())
        .pipe(gulp.dest('dist'));

    gulp.src('app/fonts/**/*')
        //prevent pipe breaking caused by errors from gulp plugins
        .pipe(plumber())
        .pipe(gulp.dest('dist/fonts'));

    //grab all of the styles
    gulp.src(['app/styles/*.css', '!app/styles/styles.css'])
        //prevent pipe breaking caused by errors from gulp plugins
        .pipe(plumber())
        .pipe(gulp.dest('dist/styles'));
});

//cleans our dist directory in case things got deleted
gulp.task('clean', function() {
    return shell.task([
      'rm -rf dist'
    ]);
});

//create folders using shell
gulp.task('scaffold', function() {
  return shell.task([
      'mkdir dist',
      'mkdir dist/fonts',
      'mkdir dist/images',
      'mkdir dist/scripts',
      'mkdir dist/styles'
    ]
  );
});

//cherry-pick latest commit to gh-pages branch
gulp.task('ghpages-deploy', function() {
  return gulp.src('./dist/**/*')
    .pipe(ghPages());
});

//this is our master task when you run `gulp` in CLI / Terminal
//this is the main watcher to use when in active development
//  this will:
//  startup the web server
//  generate sprite sheet
//  compress all scripts and SCSS files
gulp.task('default', ['browserSync', 'sprite', 'scripts', 'styles'], function() {
    //a list of watchers, so it will watch all of the following files waiting for changes
    gulp.watch('app/scripts/src/**', ['scripts']);
    gulp.watch('app/styles/scss/**', ['styles']);
    gulp.watch('app/images/sprites/**', ['sprite']);
    gulp.watch('app/*.html', ['html']);
});

//this is our deployment task, it will set everything for deployment-ready files
gulp.task('deploy', gulpSequence('clean', 'scaffold', 'sprite', ['scripts-deploy', 'styles-deploy', 'images-deploy'], 'html-deploy', 'ghpages-deploy'));
<|endoftext|>


<commit_before>'use strict';
/**
 * Import plugins
 */
var gulp          = require('gulp'),
    $             = require('gulp-load-plugins')(),
    config        = require('./gulp_config.json'),
    browserSync   = require('browser-sync'),
    runSequence   = require('run-sequence'),
    argv          = require('yargs').argv,

require(config.tasks + 'server')(gulp, $, config, browserSync, runSequence);   // $ gulp serve
require(config.tasks + 'gh-pages')(gulp, $, config);                           // $ gulp deploy

<commit_msg>Add default task<commit_after>'use strict';
/**
 * Import plugins
 */
var gulp          = require('gulp'),
    $             = require('gulp-load-plugins')(),
    config        = require('./gulp_config.json'),
    browserSync   = require('browser-sync'),
    runSequence   = require('run-sequence'),
    argv          = require('yargs').argv,

require(config.tasks + 'server')(gulp, $, config, browserSync, runSequence);   // $ gulp serve
require(config.tasks + 'gh-pages')(gulp, $, config);                           // $ gulp deploy

/**
 * Default task
 */
gulp.task('default', ['serve']);<|endoftext|>


<commit_before>import Tour from '../../src/models/tour';
import { range, map } from 'lodash';
import TourData from '../../src/tours';
import User from '../../src/models/user';
jest.mock('../../src/models/user', () => ({
  replayTour: jest.fn(),
  viewedTour: jest.fn(function(t){
    this.viewed_tour_specs = [{ id: t.id, view_count: 1 }];
  }),
}));

describe('Tour Model', () => {
  it('can be created', () => {
    const tour = new Tour({
      id: 2, steps: map(
        range(0, 4), i => ({ id: i, title: `step ${i}`, content: `# Step num ${i}` })
      ),
    });
    expect(tour).toBeInstanceOf(Tour);
    expect(tour.steps).toHaveLength(4);
  });

  it('initializes from JSON', () => {
    const tour = Tour.forIdentifier('teacher-calendar');
    expect(tour).toBeInstanceOf(Tour);
    expect(tour.serialize()).toMatchObject(TourData['teacher-calendar']);
  });

  it('can find by audience_tags', () => {
    expect(Tour.forAudienceTags(['foo', 'bar'])).toEqual([]);
    const tours = Tour.forAudienceTags(['teacher', 'foo']);
    expect(tours.length).toBeGreaterThan(0);
    expect(map(tours, 'id')).toContain('teacher-calendar');
  });

  it('finds all', () => {
    expect(Tour.all.length).toBeGreaterThan(10);
  });

  it('finds others in the same group', () => {
    const tour = new Tour();
    expect(tour.othersInGroup).toEqual([]);
    tour.group_id = 'bad';
    expect(tour.othersInGroup).toEqual([]);
    tour.group_id = 'homework';
    expect(tour.othersInGroup.length).toBeGreaterThan(2);
  });

  it ('replays itself and others in group', () => {
    const tour = Tour.forIdentifier('homework-assignment-editor');
    tour.play();
    expect(tour.isEnabled).toBeTruthy();
    expect(Tour.forIdentifier('add-homework-select-exercises').isEnabled).toBeTruthy();
  });

  it ('marks itself viewed', () => {
    const tour = Tour.forIdentifier('homework-assignment-editor');
    tour.markViewed({ exitedEarly: false });
    expect(User.viewedTour).toHaveBeenCalledWith(tour, { exitedEarly: false });
    expect(tour.isEnabled).toBeFalsy();
  });

  it ('marks others in group as viewed when canceled early', () => {
    const tour = Tour.forIdentifier('homework-assignment-editor');
    tour.markViewed({ exitedEarly: true });
    expect(tour.isEnabled).toBeFalsy();
    expect(Tour.forIdentifier('add-homework-select-exercises').isEnabled).toBeFalsy();
  });

  it('calculates when an autoplay tour is viewable', () => {
    User.viewed_tour_stats = [];
    const tour = Tour.forIdentifier('question-library-super');
    expect(tour.autoplay).toBe(true);
    expect(tour.isViewed).toBe(false);
    expect(tour.standalone).toBe(true);
    expect(tour.isViewable).toBe(true);

    User.viewed_tour_stats = [{ id: 'question-library-super', view_count: 1 }];
    expect(tour.isViewable).toBe(false);
  });

});
<commit_msg>update spec<commit_after>import Tour from '../../src/models/tour';
import { range, map } from 'lodash';
import TourData from '../../src/tours';
import User from '../../src/models/user';
jest.mock('../../src/models/user', () => ({
  replayTour: jest.fn(),
  viewedTour: jest.fn(function(t){
    this.viewed_tour_stats = [{ identifier: t.id, view_count: 1 }];
  }),
}));

describe('Tour Model', () => {
  it('can be created', () => {
    const tour = new Tour({
      id: 2, steps: map(
        range(0, 4), i => ({ id: i, title: `step ${i}`, content: `# Step num ${i}` })
      ),
    });
    expect(tour).toBeInstanceOf(Tour);
    expect(tour.steps).toHaveLength(4);
  });

  it('initializes from JSON', () => {
    const tour = Tour.forIdentifier('teacher-calendar');
    expect(tour).toBeInstanceOf(Tour);
    expect(tour.serialize()).toMatchObject(TourData['teacher-calendar']);
  });

  it('can find by audience_tags', () => {
    expect(Tour.forAudienceTags(['foo', 'bar'])).toEqual([]);
    const tours = Tour.forAudienceTags(['teacher', 'foo']);
    expect(tours.length).toBeGreaterThan(0);
    expect(map(tours, 'id')).toContain('teacher-calendar');
  });

  it('finds all', () => {
    expect(Tour.all.length).toBeGreaterThan(10);
  });

  it('finds others in the same group', () => {
    const tour = new Tour();
    expect(tour.othersInGroup).toEqual([]);
    tour.group_id = 'bad';
    expect(tour.othersInGroup).toEqual([]);
    tour.group_id = 'homework';
    expect(tour.othersInGroup.length).toBeGreaterThan(2);
  });

  it ('replays itself and others in group', () => {
    const tour = Tour.forIdentifier('homework-assignment-editor');
    tour.play();
    expect(tour.isEnabled).toBeTruthy();
    expect(Tour.forIdentifier('add-homework-select-exercises').isEnabled).toBeTruthy();
  });

  it ('marks itself viewed', () => {
    const tour = Tour.forIdentifier('homework-assignment-editor');
    tour.markViewed({ exitedEarly: false });
    expect(User.viewedTour).toHaveBeenCalledWith(tour, { exitedEarly: false });
    expect(tour.isEnabled).toBeFalsy();
  });

  it ('marks others in group as viewed when canceled early', () => {
    const tour = Tour.forIdentifier('homework-assignment-editor');
    tour.markViewed({ exitedEarly: true });
    expect(tour.isEnabled).toBeFalsy();
    expect(Tour.forIdentifier('add-homework-select-exercises').isEnabled).toBeFalsy();
  });

  it('calculates when an autoplay tour is viewable', () => {
    User.viewed_tour_stats = [];
    const tour = Tour.forIdentifier('question-library-super');
    expect(tour.autoplay).toBe(true);
    expect(tour.isViewed).toBe(false);
    expect(tour.standalone).toBe(true);
    expect(tour.isViewable).toBe(true);

    User.viewed_tour_stats = [{ identifier: 'question-library-super', view_count: 1 }];
    expect(tour.isViewable).toBe(false);
  });

});
<|endoftext|>