Example #1
0
function generateGenericDevice (options) {
  options = options || {}
  const templateName = options.templateName
  const idx = options.idx
  const orgIdx = options.orgIdx
  const organization = options.organization || {}
  const namePostfix = _.isNumber(idx) ? idx + 1 : ''
  const name = options.name || `${(NAMES[templateName] || '').replace(/\s/g, '-')}-${namePostfix}`
  const serialNumberPostfix = _.isNumber(orgIdx) && _.isNumber(idx) ? _.padStart(DEVICES_PER_ORGANIZATION[templateName] * orgIdx + idx + 1, 6, '0') : ''
  const serialNumber = options.serialNumber || `${(NAMES[templateName] || '').replace(/\s/g, '-')}-${serialNumberPostfix}`
  const deviceTemplateId = options.deviceTemplateId

  const location = getLocation()
  return {
    name,
    serialNumber,
    deviceTemplateId,
    deviceTemplate: NAMES[templateName],
    organization: organization.name,
    organizationId: organization.id,
    color: faker.commerce.color(),
    productionRun: 'DEC2016',
    hardwareVersion: faker.system.semver(),
    firmwareVersion: faker.system.semver(),
    longitude: location[0],
    latitude: location[1]
  }
}
Example #2
0
function fakeItem(){
  // trying to get a more realistic distribution here
  const priceMax = faker.random.number(10) > 8 ? 5000 : 100
  const random = (odds, value) => faker.random.number(10) < odds ? value : ""
  const times = (n, func) => {
    let i = 0
    let results = ""
    while(n > i){
      results += func()
      i = i + 1
    }
    return results
  }
  return {
    id: faker.random.uuid(),
    sku: times(16, faker.random.alphaNumeric),
    title: faker.commerce.product(),
    brand: random(8, faker.company.companyName()),
    color: random(8, faker.commerce.color()),
    size: random(8, times(2, faker.random.alphaNumeric)),
    description: random(8, faker.commerce.productName()),
    percSplit: faker.random.number(100),
    price: faker.commerce.price(0, priceMax),
    printed: faker.random.boolean()
  }
}
var createProduct = () => {
  return {
    name: faker.commerce.productName(),
    price: parseFloat(faker.commerce.price()),
    department: faker.commerce.department(),
    color: faker.commerce.color(),
    sales: faker.random.number({ min: 0, max: 100 }),
    stock: faker.random.number({ min: 0, max: 100 })
  };
};
app.get('/api/fake/commerce', function(req, res) {
	res.json([
		{
			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()
		}
	])
});
Example #5
0
 handler: function (request, reply) {
     const 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()
     };
     
     reply(commerce);
 }
  /**
   * Generate 10 products using faker >:)
   * @param  {[type]} req [description]
   * @param  {[type]} res [description]
   * @return {[type]}     [description]
   */
  generate(req, res) {
    const product = new Product();
    const products = [];

    for (let i = 0; i < 10; i++) {
      products.push({
        name: faker.commerce.productName(),
        color: faker.commerce.color(),
        price: faker.commerce.price(),
        qty: Math.floor(Math.random() * 100 + 1),
        createdAt: new Date(),
      });
    }

    product.collection.insert(products, (err, raw) => {
      if (err) res.status(400).send(err.stack);

      res.json({ status: 200, message: raw.ops });
    });
  }
Example #7
0
const genCaseData = () =>
  ({
    app: coinFlip(),
    area: faker.address.city(),
    contacts: genContacts().join('\n'),
    db: coinFlip(),
    email: coinFlip(),
    caseRef: faker.random.uuid(),
    info: coinFlip(),
    nc: coinFlip(),
    notes: [],
    tasks: [],
    operation: faker.commerce.color(),
    pc: coinFlip(),
    police: coinFlip(),
    referral: 'referral',
    sp: coinFlip(),
    sms: coinFlip(),
    web: coinFlip(),
  });
Example #8
0
function generateProduct() {
    var product = {
        name: faker.commerce.productName(),
        producer: faker.company.companyName(),
        price: Number(faker.commerce.price())
    };
    var properties = {
        size: faker.random.number(),
        weight: faker.random.number(),
        material: faker.commerce.productMaterial(),
        color: faker.commerce.color(),
        department: faker.commerce.department()
    };
    Object.keys(properties).forEach(function (key) {
        if (Math.random() > 1 - PRODUCTS_SIMILARITY) {
            product[key] =  properties[key];
        }
    })
    return product;
}
  describe('2 files', function () {
    let lower = {
      path: '',
      name: faker.commerce.color().toLowerCase(),
      lastModification: '2015-10-12T01:02:03Z'
    }
    let upper = {
      path: lower.path,
      name: lower.name.toUpperCase(),
      lastModification: '2015-11-13T02:03:05Z'
    }
    let expectedSizes = []

    before(Files.deleteAll)
    before(Cozy.registerDevice)

    before('force case insensitive for local', function () {
      this.app.instanciate()
      this.app.prep.buildId = this.app.prep.buildIdHFS
    })

    before('Create the lower file', function (done) {
      let fixturePath = path.join(Cozy.fixturesDir, 'chat-mignon-mod.jpg')
      return Files.uploadFile(lower, fixturePath, function (_, created) {
        lower.remote = {
          id: created.id,
          size: fs.statSync(fixturePath).size
        }
        done()
      })
    })

    before(Cozy.fetchRemoteMetadata)

    before('Create the upper file', function (done) {
      let fixturePath = path.join(Cozy.fixturesDir, 'chat-mignon.jpg')
      return Files.uploadFile(upper, fixturePath, function (_, created) {
        upper.remote = {
          id: created.id,
          size: fs.statSync(fixturePath).size
        }
        done()
      })
    })

    before(Cozy.sync)

    after(Cozy.clean)

    it('waits a bit to resolve the conflict', function (done) {
      expectedSizes = [upper.remote.size, lower.remote.size]
      return setTimeout(done, 3500)
    })

    it('has the two files on local', function () {
      let f
      let files = fs.readdirSync(this.syncPath)
      files = ((() => {
        let result = []
        for (f of Array.from(files)) {
          if (f !== '.cozy-desktop') {
            result.push(f)
          }
        }
        return result
      })())
      files.length.should.equal(2)
      let sizes = (() => {
        let result1 = []
        for (f of Array.from(files)) {
          result1.push(fs.statSync(path.join(this.syncPath, f)).size)
        }
        return result1
      })()
      sizes.should.eql(expectedSizes)
      let names = files.sort()
      let parts = names[0].split('-conflict-')
      parts.length.should.equal(2)
      parts[0].should.equal(upper.name)
      names[1].should.equal(lower.name)
    })

    it('has the files on remote', done =>
      Files.getAllFiles(function (_, files) {
        let f
        files.length.should.equal(2)
        let sizes = ((() => {
          let result = []
          for (f of Array.from(files)) {
            result.push(f.size)
          }
          return result
        })())
        sizes.sort().should.eql(expectedSizes.sort())
        let names = ((() => {
          let result1 = []
          for (f of Array.from(files)) {
            result1.push(f.name)
          }
          return result1
        })()).sort()
        let parts = names[0].split('-conflict-')
        parts.length.should.equal(2)
        parts[0].should.equal(upper.name)
        names[1].should.equal(lower.name)
        done()
      })
    )
  })
  describe('a folder and a file', function () {
    let lower = {
      path: '',
      name: faker.commerce.product().toLowerCase()
    }
    let upper = {
      path: lower.path,
      name: lower.name.toUpperCase(),
      lastModification: '2015-11-13T02:03:05Z'
    }
    let child = {
      path: path.join(lower.path, lower.name),
      name: faker.commerce.color(),
      lastModification: '2015-10-12T01:02:03Z'
    }

    before(Files.deleteAll)
    before(Cozy.registerDevice)

    before('force case insensitive for local', function () {
      this.app.instanciate()
      this.app.prep.buildId = this.app.prep.buildIdHFS
    })

    before('Create the lower folder', done =>
      Files.createFolder(lower, function (_, created) {
        let fixturePath = path.join(Cozy.fixturesDir, 'chat-mignon-mod.jpg')
        return Files.uploadFile(child, fixturePath, function (_, created) {
          child.remote = {
            id: created.id,
            size: fs.statSync(fixturePath).size
          }
          done()
        })
      })
    )

    before(Cozy.fetchRemoteMetadata)

    before('Create the upper file', function (done) {
      let fixturePath = path.join(Cozy.fixturesDir, 'chat-mignon.jpg')
      return Files.uploadFile(upper, fixturePath, function (_, created) {
        upper.remote = {
          id: created.id,
          size: fs.statSync(fixturePath).size
        }
        done()
      })
    })

    before(Cozy.sync)

    after(Cozy.clean)

    it('waits a bit to resolve the conflict', done => setTimeout(done, 3500))

    it('has the two files on local', function () {
      let paths = fs.readdirSync(this.syncPath)
      paths = (Array.from(paths).filter((f) => f !== '.cozy-desktop').map((f) => f))
      paths.length.should.equal(2)
      let [file, folder] = paths
      let { size } = fs.statSync(path.join(this.syncPath, file))
      size.should.eql(upper.remote.size)
      let parts = file.split('-conflict-')
      parts.length.should.equal(2)
      parts[0].should.equal(upper.name)
      folder.should.equal(lower.name)
      let children = fs.readdirSync(path.join(this.syncPath, folder))
      children.length.should.equal(1)
      children[0].should.equal(child.name)
    })

    it('has the files on remote', done =>
      Files.getAllFolders(function (_, folders) {
        folders.length.should.equal(1)
        folders[0].should.have.properties(lower)
        return Files.getAllFiles(function (_, files) {
          files.length.should.equal(2)
          files[0]._id.should.equal(child.remote.id)
          files[0].path.should.equal(`/${child.path}`)
          files[0].name.should.equal(child.name)
          files[0].size.should.equal(child.remote.size)
          let parts = files[1].name.split('-conflict-')
          parts.length.should.equal(2)
          parts[0].should.equal(upper.name)
          files[1].path.should.equal(upper.path)
          files[1].size.should.equal(upper.remote.size)
          done()
        })
      })
    )
  })
Example #11
0
exports.product = function(app, count, update) {
  if(update !== false)
  console.info('RUN FAKER PRODUCT');
  var helper = faker.helpers;
  var products = [];
  for(var i = count; i >= 0; i--){

      var name = faker.commerce.productName();
      var price = parseFloat(faker.commerce.price());
      var price_euro = faker.commerce.price(10.9, 17.9, 2, '') * 1;
      var price_dollar = faker.commerce.price(2.9, 7.9, 2, '') * 1;

      var prod = {
        _id: (i+1).toString(),
        active: faker.random.boolean(),
        sku: faker.finance.mask(),
        name: name,
        description: faker.lorem.sentences(),
        url: faker.internet.url() + '/' + faker.helpers.slugify(name),
        price_euro: price_euro,
        price_dollar: price_dollar,
        image: faker.image.fashion(),
        locales: [
          {lang:'EN', title:name, description: faker.lorem.sentences()},
          {lang:'ES', title:faker.commerce.productName(), description: faker.lorem.sentences()},
          {lang:'FR', title:faker.commerce.productName(), description: faker.lorem.sentences()},
          {lang:'IT', title:faker.commerce.productName(), description: faker.lorem.sentences()}
        ],
        images: [
          {
            href: 'https://www.medic-world.com/skin/frontend/ultimo/mw/images/flags/mwd.png',
            // href: faker.image.fashion(),
            title: faker.random.words(),
            description: faker.random.words(),
            mediaType: 'jpg',
          }
        ],
        attributes: {
          color: faker.commerce.color(),
          material: faker.commerce.productMaterial(),
          adjective: faker.commerce.productAdjective(),
        },
        base_color: '#'+(function lol(m,s,c){return s[m.floor(m.random() * s.length)] +
  (c && lol(m,s,c-1));})(Math,'0123456789ABCDEF',4),
        createdAt:'2016-12-18',
        updatedAt:'2016-12-18',
    };

    if(update !== false)
    app.service('products').create(prod, {}).then(function(data) {
      // console.log('Created product data', 'data');
    });

    products.push(prod);
    if(i==1 && update !== false)
    console.log('FAKER product',prod);
    // post('http://localhost:3030/cms', prod);

  };
  return products;
}
var faker = require('faker');
var fs = require('fs');
var path = require('path');

var itemList = [];
var id;

for (var i = 0; i < 50; i++) {
  id = faker.random.uuid();
  itemList.push({
    id: id,
    color: faker.commerce.color(),
    department: faker.commerce.department(),
    productName: faker.commerce.productName(),
    price: faker.commerce.price(),
    image: faker.image.technics() + '/' + id
  });
}

fs.writeFile(path.join(__dirname, '../mock/items.json'), JSON.stringify(itemList));
  describe('with local first', function () {
    let file = {
      path: '',
      name: faker.commerce.color(),
      lastModification: '2015-10-12T01:02:03Z'
    }
    let expectedSizes = []

    before(Files.deleteAll)
    before(Cozy.registerDevice)

    before('Create the remote tree', function (done) {
      let fixturePath = path.join(Cozy.fixturesDir, 'chat-mignon-mod.jpg')
      return Files.uploadFile(file, fixturePath, function (_, created) {
        file.remote = {
          id: created.id,
          size: fs.statSync(fixturePath).size
        }
        done()
      })
    })

    before('Create the local tree', function () {
      let fixturePath = path.join(Cozy.fixturesDir, 'chat-mignon.jpg')
      let filePath = path.join(this.syncPath, file.path, file.name)
      file.local = {size: fs.statSync(fixturePath).size}
      return fs.copySync(fixturePath, filePath)
    })

    before(Cozy.sync)

    after(Cozy.clean)

    it('waits a bit to resolve the conflict', function (done) {
      expectedSizes = [file.local.size, file.remote.size].sort()
      return setTimeout(done, 3000)
    })

    it('has the two files on local', function () {
      let f
      let files = fs.readdirSync(this.syncPath)
      files = ((() => {
        let result = []
        for (f of Array.from(files)) {
          if (f !== '.cozy-desktop') {
            result.push(f)
          }
        }
        return result
      })())
      files.length.should.equal(2)
      let sizes = (() => {
        let result1 = []
        for (f of Array.from(files)) {
          result1.push(fs.statSync(path.join(this.syncPath, f)).size)
        }
        return result1
      })()
      sizes.sort().should.eql(expectedSizes)
      let names = files.sort()
      names[0].should.equal(file.name)
      let parts = names[1].split('-conflict-')
      parts.length.should.equal(2)
      parts[0].should.equal(file.name)
    })

    it('has the files on remote', done =>
      Files.getAllFiles(function (_, files) {
        let f
        files.length.should.equal(2)
        let sizes = ((() => {
          let result = []
          for (f of Array.from(files)) {
            result.push(f.size)
          }
          return result
        })())
        sizes.sort().should.eql(expectedSizes)
        let names = ((() => {
          let result1 = []
          for (f of Array.from(files)) {
            result1.push(f.name)
          }
          return result1
        })()).sort()
        names[0].should.equal(file.name)
        let parts = names[1].split('-conflict-')
        parts.length.should.equal(2)
        parts[0].should.equal(file.name)
        done()
      })
    )
  })
Example #14
0
describe('Image from mobile', function () {
  this.slow(1000)
  this.timeout(10000)

  before(Cozy.ensurePreConditions)
  before(Files.deleteAll)
  before(Cozy.registerDevice)

  let file = {
    path: '',
    name: faker.commerce.color(),
    lastModification: '2015-10-12T01:02:03Z',
    checksum: 'fc7e0b72b8e64eb05e05aef652d6bbed950f85df'
  }
  let localPath = '/storage/emulated/0/DCIM/Camera/IMG_20160411_172611324.jpg'

  before('Create the remote file', function (done) {
    let fixturePath = path.join(Cozy.fixturesDir, 'chat-mignon-mod.jpg')
    return Files.uploadFile(file, fixturePath, function (_, created) {
      file.remote = {id: created.id}
      file.size = fs.statSync(fixturePath).size
      done()
    })
  })

  before('Remove the checksum and add tags + localPath', function () {
    this.app.instanciate()
    let client = this.app.remote.couch
    return client.get(file.remote.id, function (err, doc) {
      should.not.exist(err)
      delete doc.checksum
      doc.tags = ['foo', 'bar']
      doc.localPath = localPath
      client.put(doc, (err, updated) => should.not.exist(err))
    })
  })

  before(Cozy.sync)
  after(Cozy.clean)

  it('waits a bit to do the synchronization', done => setTimeout(done, 5000))

  it('has the file on local', function () {
    let files = fs.readdirSync(this.syncPath)
    files = (Array.from(files).filter((f) => f !== '.cozy-desktop').map((f) => f))
    files.length.should.equal(1)
    let local = files[0]
    local.should.equal(file.name)
    let { size } = fs.statSync(path.join(this.syncPath, local))
    size.should.equal(file.size)
  })

  it('has the file on remote', done =>
    Files.getAllFiles(function (_, files) {
      files.length.should.equal(1)
      let remote = files[0]
      remote.name.should.equal(file.name)
      remote.size.should.equal(file.size)
      remote.checksum.should.equal(file.checksum)
      remote.tags.should.eql(['foo', 'bar'])
      done()
    })
  )

  it('has kept the localPath on the remote file', function (done) {
    let client = request.newClient('http://localhost:5984/')
    return client.get(`cozy/${file.remote.id}`, function (err, res, body) {
      should.not.exist(err)
      body.localPath.should.equal(localPath)
      done()
    })
  })
})
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()
		}
	})
});