describe('#submitSettings', () => {
     var data = testUtils.makeFakeData();
     data.urls.view = faker.internet.ip();
     var configUrl = faker.internet.ip();
     var endpoints = [{
         method: 'PUT',
         url: configUrl,
         response: {
             result: data
         }
     }];
     var server;
     var spy;
     before(() => {
         server = utils.createServer(sinon, endpoints);
         spy = sinon.spy($osf, 'putJSON');
     });
     after(() => {
         server.restore();
         $osf.putJSON.restore();
     });
     data.urls.config = configUrl;
     it('serializes the VM state and sends a PUT request to the \'config\' url passed in settings', (done) => {
         hardReset();
         vm.updateFromData(data)
             .always(function() {
                 vm.submitSettings()
                     .always(function() {
                         assert.calledWith(spy, data.urls.config, vm.folder().name.toUpperCase());
                         done();
                     });
             });
     });
 });
export function fake_cp() {
  var dummy_event =
    [
      '2014-07-14T21:38:52+0000 6Mar2014 14:07:24 redirect ' + faker.internet.ip() + ' <eth1 alert web_client_type: Microsoft IE 8.0;',
      'resource: ' + faker.internet.url() + ';',
      'src: ' + faker.internet.ip() + ';',
      'dst: ' + faker.internet.ip() + ';',
      'proto: ' + fake_proto() + ';',
      'session_id: [' + fake_session_id() + '];',
      'Protection name: Check Point - Testing Bot;',
      'malware_family: Check Point;',
      'Source OS: ' + fake_os() + ';',
      'Confidence Level: ' + faker.random.number({ min: 0, max: 5}) + ';',
      'severity: ' + faker.random.number({ min: 0, max: 5}) + ';',
      'malware_action: Communication with C&C site;',
      'rule_uid: {' + faker.random.uuid() + '};',
      'Protection Type: URL reputation;',
      'malware_rule_id: {' + fake_malware_rule_id() + '};',
      'protection_id: 00233CFEE;',
      'refid: ' + faker.random.number({ min: 0, max: 5}) + ';',
      'log_id: ' + faker.random.number({ min: 0, max: 5}) + ';',
      'proxy_src_ip: ' + faker.internet.ip() + ';',
      'scope: ' + faker.internet.ip() + ';',
      'user: ' + fake_user_name() + ';',
      'src_user_name: ' + fake_user_name() + ';',
      'src_machine_name: ' + faker.internet.email() + ';',
      'snid: ' + fake_snid() + ';',
      'product: Anti Malware;',
      'service: ' + faker.internet.protocol() + ';',
      's_port: ' + faker.random.number({ min: 22, max: 8080}) + ';',
      'device_version: This is Check Points software version R77.10 - Build 243;'
    ];

  return dummy_event.join(' ');
}
 describe('#fetchAccounts', () => {
     var accountsUrl = faker.internet.ip();
     var accounts = makeAccountList();
     var endpoints = [{
         url: accountsUrl,
         method: 'GET',
         response: {
             accounts: accounts
         }
     }];
     var server;
     before(() => {
         server = utils.createServer(sinon, endpoints);
     });
     after(() => {
         server.restore();
     });
     it('makes a GET request to the "accounts" url passed in settings, and returns a promise that resolves to that value', (done) => {
         var data = testUtils.makeFakeData();
         data.urls.accounts = accountsUrl;
         vm.updateFromData(data)
             .always(function() {
                 vm.fetchAccounts()
                     .done(function(fetched) {
                         assert.deepEqual(fetched, endpoints[0].response.accounts);
                         done();
                     });
             });
     });
 });
  lazy.lines.map(String).forEach(function (line) {
    nbRead++;

    line = line.toString().replace(/\r$/, '');
    if (!line) {
      console.error('line %d: removed (line is empty)', nbRead);
      nbEmpty++;
      return;
    }

    var ec = logParser.parse(line);
    if (!ec) {
      console.error('line %d: removed (wrong format)', nbRead);
      nbWrong++;
      return;
    }

    if (ec.host) {
      var fakeHost = hosts[ec.host];
      if (!fakeHost) {
        fakeHost = faker.internet.ip();
        while (fakeHostsList[fakeHost]) {
          fakeHost = faker.internet.ip();
        }
        fakeHostsList[fakeHost] = ec.host;
        hosts[ec.host]          = fakeHost;
      }
      line = line.replace(ec.host, fakeHost);
    }

    if (ec.login) {
      var fakeLogin = logins[ec.login];
      if (!fakeLogin) {
        fakeLogin = faker.internet.userName().replace('\'', '').toUpperCase();
        while (fakeLoginsList[fakeLogin]) {
          fakeLogin = faker.internet.userName().replace('\'', '').toUpperCase();
        }
        fakeLoginsList[fakeLogin] = ec.login;
        logins[ec.login]          = fakeLogin;
      }
      line = line.replace(ec.login, fakeLogin);
    }

    resultStream.write(line + '\n');
  });
 it('opens a new window (tab) pointed at the "auth" url passed in settings', (done) => {
     var data = testUtils.makeFakeData();
     var authUrl = faker.internet.ip();
     data.urls.auth = authUrl;
     vm.updateFromData(data)
         .always(function() {
             vm.connectAccount();
             assert.calledWith(stub, authUrl);
             done();
         });
 });
 before(() => {
     importAuthUrl = faker.internet.ip();
     data = testUtils.makeFakeData();
     data.urls.importAuth = importAuthUrl;
     stub = sinon.stub($osf, 'putJSON', function() {
         var ret = $.Deferred();
         ret.resolve({
             result: data
         });
         return ret.promise();
     });
 });
            it('instantiates a new folderPicker instance if folders have not been loaded', () => {
                var urls = vm.urls();
                urls.folders = faker.internet.ip();
                vm.urls(urls);
                var opts = $.extend({}, {
                    initialFolderPath: vm.folder().path || '',
                    filesData: vm.urls().folders
                }, vm.treebeardOptions);

                vm.loadedFolders(false);
                vm.activatePicker();
                assert.calledOnce(doActivatePickerStub);
            });
Example #8
0
function writeLine() {

	var httpLine = faker.internet.ip();
	httpLine 	+= ' - - [';
	httpLine	+= strftime("%d/%b/%Y:%H:%M:%S %z");
	httpLine	+= '] \"GET ';
	httpLine	+= '/' + faker.system.commonFileName(faker.random.arrayElement(fileExts));
	httpLine	+= ' HTTP/1.1\" ';
	httpLine	+= faker.random.arrayElement(respCodes) + " ";
	httpLine	+= faker.random.number(8192) + 128;
	httpLine	+= ' \"-\" \"';
	httpLine	+= faker.internet.userAgent() + '\"';
	
	console.log(httpLine);

	// add a random factor to the interval
	setTimeout(writeLine, (Math.random() + 1) * 1000 / speed);
}
app.get('/api/fake/internet', function(req, res) {
	res.json([
		{
			avatar: faker.internet.avatar(),
			email: faker.internet.email(),
			exampleEmail: faker.internet.exampleEmail(),
			userName: faker.internet.userName(),
			protocol: faker.internet.protocol(),
			url: faker.internet.url(),
			domainName: faker.internet.domainName(),
			domainSuffix: faker.internet.domainSuffix(),
			domainWord: faker.internet.domainWord(),
			ip: faker.internet.ip(),
			userAgent: faker.internet.userAgent(),
			color: faker.internet.color(),
			mac: faker.internet.mac(),
			password: faker.internet.password()
		}
	])
});
 describe('#_deauthorizeConfirm', () => {
     var deleteUrl = faker.internet.ip();
     var endpoints = [{
         url: deleteUrl,
         method: 'DELETE',
         response: {}
     }];
     var server;
     var spy;
     var destroyPickerStub;
     before(() => {
         hardReset();
         server = utils.createServer(sinon, endpoints);
         spy = sinon.spy($, 'ajax');
         destroyPickerStub = sinon.stub(vm, 'destroyPicker');
     });
     after(() => {
         server.restore();
         $.ajax.restore();
         vm.destroyPicker.restore();
     });
     var data = testUtils.makeFakeData();
     data.urls.deauthorize = deleteUrl;
     it('sends a DELETE request to the \'deauthorize\' url passed in settings', (done) => {
         vm.updateFromData(data)
             .always(function() {
                 vm._deauthorizeConfirm()
                     .always(function() {
                         assert.calledWith(
                             spy,
                             {
                                 url: deleteUrl,
                                 type: 'DELETE'
                             }
                         );
                         done();
                     });
             });
     });
 });
 describe('#_importAuthConfirm', () => {
     var importAuthUrl = faker.internet.ip();
     var endpoints = [{
         method: 'PUT',
         url: importAuthUrl,
         response: {}
     }];
     var server;
     var putJSONSpy;
     var activatePickerSpy;
     before(() => {
         hardReset();
         server = utils.createServer(sinon, endpoints);
         putJSONSpy = sinon.spy($osf, 'putJSON');
         activatePickerSpy = sinon.spy(vm, 'activatePicker');
     });
     after(() => {
         server.restore();
         $osf.putJSON.restore();
         activatePickerSpy.restore();
     });
     var data = testUtils.makeFakeData();
     data.urls.importAuth = importAuthUrl;
     it('sends a PUT request to the \'importAuth\' url passed in settings, calls updateFromData with the response, and calls activatePicker', (done) => {
         vm.updateFromData(data)
             .always(function() {
                 vm._importAuthConfirm()
                     .always(function() {
                         assert.calledWith(
                             putJSONSpy, 
                             importAuthUrl, 
                             {}
                         );
                         assert.calledOnce(activatePickerSpy);
                         done();
                     });
             });
     });
 });
Example #12
0
var makeFakeData = function(overrides) {
    var nodeHasAuth = faker.random.number() ? true : false;
    var userHasAuth = faker.random.number() ? true : false;
    var userIsOwner = faker.random.number() ? true : false;
    var ownerName = faker.name.findName();
    var folder = {
        name: faker.hacker.noun(),
        id: faker.finance.account(),
        path: faker.hacker.noun()
    };
    var urlPath = faker.internet.domainWord();
    var url = faker.internet.ip();
    var urls = {};
    urls[urlPath] = url;
    var data = {
        nodeHasAuth: nodeHasAuth,
        userHasAuth: userHasAuth,
        userIsOwner: userIsOwner,
        folder: folder,
        ownerName: ownerName,
        urls: urls
    };
    return $.extend({}, data, overrides);
};
var utils = require('tests/utils');
var faker = require('faker');

var $ = require('jquery');
require('jquery-qrcode');

var osfHelpers = require('js/osfHelpers');

var ViewModel = require('../twoFactorUserConfig')._ViewModel;

var DISABLED = {
    is_enabled: false,
    is_confirmed: false,
    secret: '',
    urls: {
        enable: faker.internet.ip()
    }
};
var ENABLED_AND_UNCONFIRMED = {
    is_enabled: true,
    is_confirmed: false,
    secret: '',
    urls: {
        otpauth: faker.internet.ip(),
        disable: faker.internet.ip()
    }
};
var ENABLED_AND_CONFIRMED = {

};
var SELECTOR = '#myQRCode';
Example #14
0
describe('NodeCategorySettings', () => {
    var category = faker.internet.domainWord();
    var categories = [];
    for (var i = 0; i < 10; i++) {
        categories.push(faker.internet.domainWord());
    }
    var updateUrl = faker.internet.ip();
    var vm = new NodeCategorySettings(category, categories, updateUrl);
    describe('#constructor', function() {
        it('throws an error if no updateUrl is passed', () => {
            var broken = function() {
                new NodeCategorySettings(category, categories);
            };
            assert.throws(broken , vm.INSTANTIATION_ERROR_MESSAGE);
        });
        it('implements the changeMessage interface', () => {
            assert.isTrue(vm.hasOwnProperty('message'));
            assert.isTrue(vm.hasOwnProperty('messageClass'));
            assert.isTrue(Boolean(vm.changeMessage) || false);
            assert.isTrue(Boolean(vm.resetMessage) || false);
        });
    });
    describe('#updateSuccess', () => {
        var changeMessageSpy;
        before(() => {
            changeMessageSpy = sinon.spy(vm, 'changeMessage');
        });
        after(() => {
            vm.changeMessage.restore();
        });
        it('updates the message, updates the category, and sets the dirty state to false', () => {
            var newcategory = categories[0];
            vm.updateSuccess(newcategory);
            assert.calledWith(changeMessageSpy, vm.UPDATE_SUCCESS_MESSAGE, vm.MESSAGE_SUCCESS_CLASS);
            assert.equal(newcategory, vm.category());
            assert.isFalse(vm.dirty());
        });
    });
    describe('#updateError', () => {
        var changeMessageSpy;
        var ravenStub;
        before(() => {
            changeMessageSpy = sinon.spy(vm, 'changeMessage');
            ravenStub = sinon.stub(Raven, 'captureMessage');
        });
        after(() => {
            vm.changeMessage.restore();
            Raven.captureMessage.restore();
        });
        it('updates the message, and captures the error with Raven', () => {
            var error = faker.lorem.sentence();
            vm.updateError({}, error, {});
            assert.calledWith(changeMessageSpy, vm.UPDATE_ERROR_MESSAGE, vm.MESSAGE_ERROR_CLASS);
            assert.calledWith(ravenStub, vm.UPDATE_ERROR_MESSAGE_RAVEN, {
                url: updateUrl,
                textStatus: error,
                err: {}
            });
        });
    });
    describe('#updateCategory', () => {
        var server;
        var serverSpy = sinon.spy();
        var updateSuccessSpy = sinon.spy(vm, 'updateSuccess');
        before(() => {
            server = sinon.fakeServer.create();
            server.respondWith(
                'PUT',
                updateUrl,
                function(xhr) {
                    serverSpy();
                    var response = {
                        'updated_fields': JSON.parse(xhr.requestBody)
                    };
                    xhr.respond(
                        200,
                        {'Content-Type': 'application/json'},
                        JSON.stringify(response)
                    );
                }
            );
        });
        after(() => {
            server.restore();
        });
        it('sends a put to the updateUrl with the selected category, and updates the category on success', (done) => {
            var newcategory = categories[0];
            vm.selectedCategory(newcategory);
            vm.updateCategory()
                .always(function() {
                    assert.called(serverSpy);
                    assert.calledWith(updateSuccessSpy, newcategory);
                    done();
                });
            server.respond();
        });
    });
    describe('#cancelUpdateCategory', () => {
        var resetMessageSpy;
        before(() => {
            resetMessageSpy = sinon.spy(vm, 'resetMessage');
        });
        after(() => {
            vm.resetMessage.restore();
        });
        it('restores the selectedCategory to the VM\'s category, sets the dirty state to false, and resets the message', () => {
            vm.selectedCategory(categories[0]);
            vm.dirty(true);
            vm.changeMessage('Some message', 'some-class');
            vm.cancelUpdateCategory();
            assert.equal(vm.selectedCategory(), vm.category());
            assert.isFalse(vm.dirty());
            assert.called(resetMessageSpy);
        });
    });
});
Example #15
0
var $osf = require('js/osfHelpers');
var Raven = require('raven-js');

/*
 * Dear sloria,
 *
 * I'm sorry for injecting globals. Please forgive me.
 *
 * Yours truly,
 * samchrisinger
 */
window.contextVars = {
    node: {
        urls: {
            api: faker.internet.ip()
        }
    }
};

var ProjectSettings = require('js/projectSettings.js');

var NodeCategorySettings = ProjectSettings.NodeCategorySettings;

describe('NodeCategorySettings', () => {
    var category = faker.internet.domainWord();
    var categories = [];
    for (var i = 0; i < 10; i++) {
        categories.push(faker.internet.domainWord());
    }
    var updateUrl = faker.internet.ip();
Example #16
0
	},
];

var additionalDataValidCases = [
	{
		input: faker.internet.email(),
		description: 'email',
		expectation: 'string',
	},
	{
		input: faker.internet.url(),
		description: 'URL',
		expectation: 'string',
	},
	{
		input: faker.internet.ip(),
		description: 'IP',
		expectation: 'string',
	},
	{
		input: faker.internet.mac(),
		description: 'MAC',
		expectation: 'string',
	},
	{
		input: faker.random.image(),
		description: 'image',
		expectation: 'string',
	},
	{
		input: faker.random.uuid(),
app.get('/api/fake', function(req, res) {
	res.json({
		"address": {
			zipCode: faker.address.zipCode(),
			city: faker.address.city(),
			cityPrefix: faker.address.cityPrefix(),
			citySuffix: faker.address.citySuffix(),
			streetName: faker.address.streetName(),
			streetAddress: faker.address.streetAddress(),
			streetSuffix: faker.address.streetSuffix(),
			streetPrefix: faker.address.streetPrefix(),
			secondaryAddress: faker.address.secondaryAddress(),
			county: faker.address.county(),
			country: faker.address.country(),
			countryCode: faker.address.countryCode(),
			state: faker.address.state(),
			stateAbbr: faker.address.stateAbbr(),
			latitude: faker.address.latitude(),
			longitude: faker.address.longitude()
		},
		"commerce": {
			color: faker.commerce.color(),
			department: faker.commerce.department(),
			productName: faker.commerce.productName(),
			price: faker.commerce.price(),
			productAdjective: faker.commerce.productAdjective(),
			productMaterial: faker.commerce.productMaterial(),
			product: faker.commerce.product()
		},
		"company": {
			suffixes: faker.company.suffixes(),
			companyName: faker.company.companyName(),
			companySuffix: faker.company.companySuffix(),
			catchPhrase: faker.company.catchPhrase(),
			bs: faker.company.bs(),
			catchPhraseAdjective: faker.company.catchPhraseAdjective(),
			catchPhraseDescriptor: faker.company.catchPhraseDescriptor(),
			catchPhraseNoun: faker.company.catchPhraseNoun(),
			bsAdjective: faker.company.bsAdjective(),
			bsBuzz: faker.company.bsBuzz(),
			bsNoun: faker.company.bsNoun()
		},
		"date": {
			past: faker.date.past(),
			future: faker.date.future(),
			between: faker.date.between(),
			recent: faker.date.recent(),
			month: faker.date.month(),
			weekday: faker.date.weekday()
		},
		"finance": {
			account: faker.finance.account(),
			accountName: faker.finance.accountName(),
			mask: faker.finance.mask(),
			amount: faker.finance.amount(),
			transactionType: faker.finance.transactionType(),
			currencyCode: faker.finance.currencyCode(),
			currencyName: faker.finance.currencyName(),
			currencySymbol: faker.finance.currencySymbol(),
			bitcoinAddress: faker.finance.bitcoinAddress()
		},
		"hacker": {
			abbreviation: faker.hacker.abbreviation(),
			adjective: faker.hacker.adjective(),
			noun: faker.hacker.noun(),
			verb: faker.hacker.verb(),
			ingverb: faker.hacker.ingverb(),
			phrase: faker.hacker.phrase()
		},
		"helpers": {
			randomize: faker.helpers.randomize(),
			slugify: faker.helpers.slugify(),
			replaceSymbolWithNumber: faker.helpers.replaceSymbolWithNumber(),
			replaceSymbols: faker.helpers.replaceSymbols(),
			shuffle: faker.helpers.shuffle(),
			mustache: faker.helpers.mustache(),
			createCard: faker.helpers.createCard(),
			contextualCard: faker.helpers.contextualCard(),
			userCard: faker.helpers.userCard(),
			createTransaction: faker.helpers.createTransaction()
		},
		"image": {
			image: faker.image.image(),
			avatar: faker.image.avatar(),
			imageUrl: faker.image.imageUrl(),
			abstract: faker.image.abstract(),
			animals: faker.image.animals(),
			business: faker.image.business(),
			cats: faker.image.cats(),
			city: faker.image.city(),
			food: faker.image.food(),
			nightlife: faker.image.nightlife(),
			fashion: faker.image.fashion(),
			people: faker.image.people(),
			nature: faker.image.nature(),
			sports: faker.image.sports(),
			technics: faker.image.technics(),
			transport: faker.image.transport()
		},
		"internet": {
			avatar: faker.internet.avatar(),
			email: faker.internet.email(),
			exampleEmail: faker.internet.exampleEmail(),
			userName: faker.internet.userName(),
			protocol: faker.internet.protocol(),
			url: faker.internet.url(),
			domainName: faker.internet.domainName(),
			domainSuffix: faker.internet.domainSuffix(),
			domainWord: faker.internet.domainWord(),
			ip: faker.internet.ip(),
			userAgent: faker.internet.userAgent(),
			color: faker.internet.color(),
			mac: faker.internet.mac(),
			password: faker.internet.password()
		},
		"lorem": {
			word: faker.lorem.word(),
			words: faker.lorem.words(),
			sentence: faker.lorem.sentence(),
			sentences: faker.lorem.sentences(),
			paragraph: faker.lorem.paragraph(),
			paragraphs: faker.lorem.paragraphs(),
			text: faker.lorem.text(),
			lines: faker.lorem.lines()
		},
		"name": {
			firstName: faker.name.firstName(),
			lastName: faker.name.lastName(),
			findName: faker.name.findName(),
			jobTitle: faker.name.jobTitle(),
			prefix: faker.name.prefix(),
			suffix: faker.name.suffix(),
			title: faker.name.title(),
			jobDescriptor: faker.name.jobDescriptor(),
			jobArea: faker.name.jobArea(),
			jobType: faker.name.jobType()
		},
		"phone": {
			phoneNumber: faker.phone.phoneNumber(),
			phoneNumberFormat: faker.phone.phoneNumberFormat(),
			phoneFormats: faker.phone.phoneFormats()
		},
		"random": {
			number: faker.random.number(),
			arrayElement: faker.random.arrayElement(),
			objectElement: faker.random.objectElement(),
			uuid: faker.random.uuid(),
			boolean: faker.random.boolean(),
			word: faker.random.word(),
			words: faker.random.words(),
			image: faker.random.image(),
			locale: faker.random.locale(),
			alphaNumeric: faker.random.alphaNumeric()
		},
		"system": {
			fileName: faker.system.fileName(),
			commonFileName: faker.system.commonFileName(),
			mimeType: faker.system.mimeType(),
			commonFileType: faker.system.commonFileType(),
			commonFileExt: faker.system.commonFileExt(),
			fileType: faker.system.fileType(),
			fileExt: faker.system.fileExt(),
			directoryPath: faker.system.directoryPath(),
			filePath: faker.system.filePath(),
			semver: faker.system.semver()
		}
	})
});
describe('ProjectSettings', () => {
    var category = faker.internet.domainWord();
    var categoryOptions = [];
    for (var i = 0; i < 10; i++) {
        categoryOptions.push(faker.internet.domainWord());
    }
    var updateUrl = faker.internet.ip();
    var vm = new ProjectSettings({category: category, categoryOptions: categoryOptions, updateUrl: updateUrl, node_id: 'nodeID'});
    describe('#constructor', function() {
        it('throws an error if no updateUrl is passed', () => {
            var broken = function() {
                new ProjectSettings({category: category, categoryOptions: categoryOptions});
            };
            assert.throws(broken , language.instantiationErrorMessage);
        });
        it('implements the changeMessage interface', () => {
            assert.isTrue(vm.hasOwnProperty('message'));
            assert.isTrue(vm.hasOwnProperty('messageClass'));
            assert.isTrue(Boolean(vm.changeMessage) || false);
            assert.isTrue(Boolean(vm.resetMessage) || false);
        });
    });
    describe('#updateError', () => {
        var changeMessageSpy;
        var ravenStub;
        before(() => {
            changeMessageSpy = sinon.spy(vm, 'changeMessage');
            ravenStub = sinon.stub(Raven, 'captureMessage');
        });
        after(() => {
            vm.changeMessage.restore();
            Raven.captureMessage.restore();
        });
        it('updates the message, and captures the error with Raven', () => {
            var error = faker.lorem.sentence();
            vm.updateError({}, error, {});
            assert.calledWith(changeMessageSpy, language.updateErrorMessage);
            assert.calledWith(ravenStub, language.updateErrorMessage, {
                url: updateUrl,
                textStatus: error,
                err: {},
            });
        });
    });
    describe('#updateAll', () => {
        var server;
        var serverSpy = sinon.spy();
        before(() => {
            server = sinon.fakeServer.create();
            server.respondWith(
                'PATCH',
                updateUrl,
                function(xhr) {
                    serverSpy();
                    xhr.respond(
                        200,
                        {'Content-Type': 'application/json'}
                    );
                }
            );
        });
        after(() => {
            server.restore();
        });
        it('sends a PATCH to the updateUrl with the settings inputs and updates them on success', (done) => {
            var newcategory = categoryOptions[0];
            vm.selectedCategory(newcategory);
            vm.title('New title');
            vm.description('New description');
            vm.requestPayload = vm.serialize();
            vm.updateAll()
                .always(function() {
                    assert.called(serverSpy);
                    done();
                });
            server.respond();
        });
    });
    describe('#cancelAll', () => {
        var resetMessageSpy;
        before(() => {
            resetMessageSpy = sinon.spy(vm, 'resetMessage');
        });
        after(() => {
            vm.resetMessage.restore();
        });
        it('restores the category, title, and description to those of the VM, and resets the message', () => {
            vm.selectedCategory(categoryOptions[0]);
            vm.changeMessage('Some message', 'some-class');
            vm.cancelAll();
            assert.equal(vm.selectedCategory(), vm.categoryPlaceholder);
            assert.equal(vm.title(), vm.titlePlaceholder);
            assert.equal(vm.description(), vm.descriptionPlaceholder);
            assert.called(resetMessageSpy);
        });
    });
});
/*global describe, it, expect, example, before, after, beforeEach, afterEach, mocha, sinon*/
'use strict';
var assert = require('chai').assert;
var utils = require('tests/utils');
var faker = require('faker');

var licenses = require('json-loader!@centerforopenscience/list-of-licenses');
var $ = require('jquery');

var LicensePicker = require('js/licensePicker');

var saveUrl = faker.internet.ip();
var saveMethod = 'POST';
var saveLicenseKey = 'node_license';
var license = licenses.MIT;
// proxy attribute to match server data
license.copyright_holders = [];

describe.skip('LicensePicker', () => {

    before(() => {
        window.contextVars = $.extend({}, window.contextVars || {}, {
            currentUser: {
                isAdmin: true
            }
        });
    });
    var lp;
    beforeEach(() => {
        lp = new LicensePicker(saveUrl, saveMethod, saveLicenseKey, license);
    });
 beforeEach(function (done) {
     ip = faker.internet.ip();
     srvOut = [];
     srvErr = [];
     done();
 });
Example #21
0
	props: {
		broadhash: '',
		dappid: null,
		height: null,
		ip: '40.40.40.40',
		os: 'unknown',
		wsPort: null,
		httpPort: null,
		state: null,
		nonce: '',
		version: '',
	},
	init({ broadhash, nonce, state }) {
		this.dappid = null;
		this.height = parseInt(_.sample([50, 70, 90, 110]));
		this.ip = faker.internet.ip();
		this.os = faker.lorem.slug();
		this.wsPort = `5${faker.random.number({ max: 999, min: 100 })}`;
		this.httpPort = `4${faker.random.number({ max: 999, min: 100 })}`;
		this.version = faker.system.semver();

		this.broadhash =
			broadhash ||
			randomstring.generate({
				charset: 'hex',
				length: 64,
				capitalization: 'lowercase',
			});
		this.state = state || 2; // Connected Peer
		this.nonce = nonce || randomstring.generate(16);
	},
Example #22
0
var expect = require('chai').expect;
var faker = require('faker');
var async = require('async');

var previousIp = faker.internet.ip();
var currentIp = faker.internet.ip();
var email = faker.internet.email();

describe('Trackable', function() {

    it('should have trackable attributes', function(done) {
        expect(User._attributes.signInCount).to.exist;
        expect(User._attributes.currentSignInAt).to.exist;
        expect(User._attributes.currentSignInIpAddress).to.exist;
        expect(User._attributes.lastSignInAt).to.exist;
        expect(User._attributes.lastSignInIpAddress).to.exist;
        done();
    });

    it('should be able to set trackable details', function(done) {

        var trackable = User.new({
            email: email,
            username: faker.internet.userName(),
            password: faker.internet.password()
        });

        expect(trackable.track).to.exist;
        expect(trackable).to.respondTo('track');

        trackable
Example #23
0
  router.get('/perform-signup', (req, res) => {
    const subscriptionId = faker.random.uuid()
    const subscriptionRenewalDate = faker.date.future()
    const creditCardExpirationDate = faker.date.future()
    const subscription = {
      customer: {
        your_customer_id: req.query.user_id,
        default_currency_iso_code: 'EUR',
        default_contact: {
          locale: req.query.locale,
          first_name: faker.name.firstName(),
          last_name: faker.name.lastName(),
          company: faker.company.companyName(),
          street: faker.address.streetName(),
          zip_code: faker.address.zipCode(),
          city: faker.address.city(),
          country_iso_code: 'US',
          email: faker.internet.email(),
        },
        payment_information: {
          payment_method: 'visa',
          card_last_four_digits: `${faker.random.number({ min: 1000, max: 9999 })}`,
          card_expiration_date: `${creditCardExpirationDate.getMonth()}/${creditCardExpirationDate.getFullYear()}`,
        },
        remote_ip: faker.internet.ip(),
      },
      id: subscriptionId, // for mock retrieval
      billing_cycle_frequency: '6m',
      currency_iso_code: 'EUR',
      next_billing_at: subscriptionRenewalDate,
      next_renewal_at: subscriptionRenewalDate,
      plans: [
        {
          plan_id: req.query.plan_id,
          plan_version: 0,
          quantity: 1,
        },
      ],
      renewal_type: 'auto',
      started_at: new Date().toISOString(),
      status: 'active',
      subscription_id: subscriptionId,
    }
    const invoiceId = `${faker.random.number({ min: 100000000, max: 999999999 })}`
    const invoice = {
      currency_iso_code: 'EUR',
      customer_id: subscription.customer.your_customer_id,
      created_at: subscription.started_at,
      document_url: `/v1/customers/${subscription.customer.your_customer_id}/invoices/${invoiceId}`,
      gross: faker.finance.amount(),
      id: invoiceId,
      payment_provider_invoice_id: invoiceId,
      type: 'charge',
    }
    const notification = {
      notification_id: `notification_${subscriptionId}_created`,
      client_id: '',
      event: {
        type: 'subscription.created',
        id: `event_${subscriptionId}_created`,
        occurred_at: subscription.started_at,
      },
      resource: {
        type: 'subscription',
        id: subscriptionId,
        current_state: subscription,
      },
    }
    const mvtCampaign = req.query.mvt_campaign

    db('subscriptions').push(subscription)
    db('invoices').push(invoice)

    utils.createNotificationRequest(env, notification)
      .end((err) => {
        if (err) {
          res
            .status(500)
            .send(`An error occured while sending the notification: ${err}`)

          return
        }

        res
          .status(200)
          .send(`The following subscription has been created:
            subscription_id: ${subscription.subscription_id}
            plan_id: ${subscription.plans[0].plan_id}
            user_id: ${subscription.customer.your_customer_id}
            locale: ${subscription.customer.default_contact.locale}
            mvt_campaign: ${mvtCampaign}
            `)
      })
  })
    describe('ViewModel', () => {
        var settingsUrl = faker.internet.ip();
        var vm = new ViewModel(settingsUrl, SELECTOR);

        describe('#initialize', () => {
            var fetchFromServerStub;
            var updateFromDataSpy;
            before(() => {
                fetchFromServerStub = new sinon.stub(vm, 'fetchFromServer', function() {
                    var ret = $.Deferred();
                    ret.resolve(DISABLED);
                    return ret.promise();
                });
                updateFromDataSpy = sinon.spy(vm, 'updateFromData');
            });
            after(() => {
                vm.fetchFromServer.restore();
                vm.updateFromData.restore();
            });
            it('makes a call to fetchFromServer, and updates the VM state with the result', (done) => {
                vm.initialize()
                    .always(function() {
                        assert.calledOnce(fetchFromServerStub);
                        assert.calledWith(updateFromDataSpy, DISABLED);
                        done();
                    });
            });
        });
        describe('#updateFromData', () => {
            it('updates the VM state with the passed data', () => {
                vm.isEnabled(true);
                vm.isConfirmed(true);
                vm.secret('SUPER SECRET');
                vm.urls = 'SOME URLS';
                vm.updateFromData(DISABLED);
                assert.isFalse(vm.isEnabled());
                assert.isFalse(vm.isConfirmed());
                assert.equal(DISABLED.secret, vm.secret());
                assert.deepEqual(DISABLED.urls, vm.urls);
            });
           
            /*
             TODO: it would be nice to have a sinon.spy on the $() method here, 
             but this is proving problematc in practice. 
             */
            var qrcodeStub;
            before(() => {
                qrcodeStub = new sinon.stub($.prototype, 'qrcode');
            });
            after(() => {
                $.prototype.qrcode.restore();
            });
            it('calls jQuery(selector).qrcode(url) on the passed selector with the fetched otpauth url if enabled', () => {
                // set VM state to DISBALED
                vm.updateFromData(DISABLED);
                vm.updateFromData(ENABLED_AND_UNCONFIRMED);
                assert.calledWith(qrcodeStub, ENABLED_AND_UNCONFIRMED.urls.otpauth);
            });            
        });
        describe('#fetchFromServer', () => {
            var endpoints = [
                {
                    url: settingsUrl,
                    method: 'GET',
                    response: {
                        result: DISABLED
                    }
                }
            ];
            var server;
            var callback;
            before(() => {
                callback = sinon.spy();
                server = utils.createServer(sinon, endpoints);
            });
            after(() => {
                server.restore();
            });
            it("makes a get request to the settingsUrl and resolves its promised with the unwrapped 'result'", (done) => {
                vm.fetchFromServer()
                    .done(callback)
                    .always(function() {
                        assert.calledWith(callback, DISABLED);
                        done();
                    });
            });
        });
        describe('#changeMessage', () => {
            it('updates the VM\'s message and message CSS class', () => {
                vm.message('');
                vm.messageClass('some-class');
                var msg = 'Such success!';
                var cls = 'text-success';
                vm.changeMessage(msg, cls);
                assert.equal(vm.message(), msg);
                assert.equal(vm.messageClass(), cls);
                msg = 'Much fail!';
                cls = 'text-error';
                vm.changeMessage(msg, cls);
                assert.equal(vm.message(), msg);
                assert.equal(vm.messageClass(), cls);
            });
            var timer;
            before(() => {
                timer = sinon.useFakeTimers();
            });
            after(() => {
                timer.restore();
            });
            it('... and removes the message after a timeout if supplied', () => {
                vm.message('');
                vm.messageClass('text-info');
                var oldMsg = vm.message();
                var oldCls = vm.messageClass();
                var msg = 'Such success!';
                var cls = 'text-success';
                vm.changeMessage(msg, cls, 200);
                timer.tick(201);
                assert.equal(vm.message(), oldMsg);
                assert.equal(vm.messageClass(), oldCls);
            });
        });
        describe('#submitSettings', () => {
            var server;
            var callback;
            before(() => {
                server = sinon.fakeServer.create();                    
                server.respondWith('PUT', settingsUrl, function(xhr) { 
                    // An echo endpoint
                    xhr.respond(200, {'Content-Type': 'application/json'}, xhr.requestBody);
                });
                callback = sinon.spy();
            });
            after(() => {
                server.restore();
            });
            it("makes a PUT request contianing the VM's tfaCode to the settingsUrl passed on instantiation", (done) => {
                var code = faker.finance.account();
                vm.tfaCode(code);
                vm.submitSettings()
                    .done(callback)
                    .always(function() {
                        assert.calledWith(callback, {
                            code: code
                        });
                        done();
                    });
                server.respond();
            });               
        });
        describe('#disableTwofactorConfirm', () => {
            var server;
            var serverSpy;
            before(() => {
                serverSpy = sinon.spy();
                server = sinon.fakeServer.create();
                server.respondWith('DELETE', 
                                   ENABLED_AND_UNCONFIRMED.urls.disable, 
                                   function(xhr) {
                                       serverSpy();
                                       xhr.respond(200, {'Content-Type': 'application/json'}, '{}');
                                   });                
            });
            after(() => {
                server.restore();
            });
            it('sends a DELETE request to the disable url, sets isEnabled to false, sets isConfirmed to false', (done) => {
                vm.updateFromData(ENABLED_AND_UNCONFIRMED);
                vm.disableTwofactorConfirm()
                    .always(function() {
                        assert.calledOnce(serverSpy);
                        assert.isFalse(vm.isEnabled());
                        assert.isFalse(vm.isConfirmed());
                        done();
                    });
                server.respond();
            });
        });
        describe('#enableTwofactorConfirm', () => {
            var server;
            var serverSpy;
            var updateFromDataStub;
            before(() => {
                vm.updateFromData(DISABLED);
                serverSpy = sinon.spy();
                server = sinon.fakeServer.create();                
                server.respondWith('POST', DISABLED.urls.enable, function(xhr) {
                    serverSpy();
                    xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify({result: ENABLED_AND_UNCONFIRMED}));
                });
                updateFromDataStub = sinon.stub(vm, 'updateFromData');
            });
            after(() => {
                server.restore();
                vm.updateFromData.restore();
            });
            it('sends a POST request to the enable url and calls updateFromData with the response', (done) => {
                vm.enableTwofactorConfirm()
                    .always(function() {
                        assert.called(serverSpy);
                        assert.calledWith(updateFromDataStub, ENABLED_AND_UNCONFIRMED);
                        done();
                    });
                server.respond();
            });
        });
    });
Example #25
0
var faker = require('faker');

var data = [];

// generate 30 random books
for (var i = 0; i < 30; i++) {
    var book = {
        title: faker.lorem.words().join(' '),
        author: faker.name.findName(),
        author_image: faker.image.avatar(),
        release_date: faker.date.recent(),
        image: faker.image.abstract() + '?_r=' + Math.floor(((new Date()).getTime() * Math.random()) + i),
        price: faker.internet.ip().replace(/\./g, '').substring(0, 3),
        short_description: faker.lorem.sentence(),
        rating: (Math.floor(Math.random() * (5 - 2 + 1)) + 2), // Generate a random number between 2 & 5
        long_description: faker.lorem.paragraph()
    }

    data.push(book);
};

module.exports = data;