How to use this.verifyExistence method in Cypress

Best JavaScript code snippet using cypress

project_spec.js

Source:project_spec.js Github

copy

Full Screen

1require('../spec_helper')2const mockedEnv = require('mocked-env')3const path = require('path')4const commitInfo = require('@cypress/commit-info')5const Fixtures = require('../support/helpers/fixtures')6const api = require(`${root}lib/api`)7const user = require(`${root}lib/user`)8const cache = require(`${root}lib/cache`)9const config = require(`${root}lib/config`)10const scaffold = require(`${root}lib/scaffold`)11const { ServerE2E } = require(`${root}lib/server-e2e`)12const { ProjectE2E } = require(`${root}lib/project-e2e`)13const Automation = require(`${root}lib/automation`)14const savedState = require(`${root}lib/saved_state`)15const preprocessor = require(`${root}lib/plugins/preprocessor`)16const plugins = require(`${root}lib/plugins`)17const { fs } = require(`${root}lib/util/fs`)18const settings = require(`${root}lib/util/settings`)19const Watchers = require(`${root}lib/watchers`)20const { SocketE2E } = require(`${root}lib/socket-e2e`)21xdescribe('lib/project-e2e', () => {22 beforeEach(function () {23 Fixtures.scaffold()24 this.todosPath = Fixtures.projectPath('todos')25 this.idsPath = Fixtures.projectPath('ids')26 this.pristinePath = Fixtures.projectPath('pristine')27 return settings.read(this.todosPath).then((obj = {}) => {28 ({ projectId: this.projectId } = obj)29 return config.set({ projectName: 'project', projectRoot: '/foo/bar' })30 .then((config1) => {31 this.config = config132 this.project = new ProjectE2E(this.todosPath)33 })34 })35 })36 afterEach(function () {37 Fixtures.remove()38 if (this.project) {39 this.project.close()40 }41 })42 it('requires a projectRoot', () => {43 const fn = () => new ProjectE2E()44 expect(fn).to.throw('Instantiating lib/project requires a projectRoot!')45 })46 it('always resolves the projectRoot to be absolute', () => {47 const p = new ProjectE2E('../foo/bar')48 expect(p.projectRoot).not.to.eq('../foo/bar')49 expect(p.projectRoot).to.eq(path.resolve('../foo/bar'))50 })51 context('#saveState', () => {52 beforeEach(function () {53 const integrationFolder = 'the/save/state/test'54 sinon.stub(config, 'get').withArgs(this.todosPath).resolves({ integrationFolder })55 sinon.stub(this.project, 'determineIsNewProject').withArgs(integrationFolder).resolves(false)56 this.project.cfg = { integrationFolder }57 return savedState.create(this.project.projectRoot)58 .then((state) => state.remove())59 })60 afterEach(function () {61 return savedState.create(this.project.projectRoot)62 .then((state) => state.remove())63 })64 it('saves state without modification', function () {65 return this.project.saveState()66 .then((state) => expect(state).to.deep.eq({}))67 })68 it('adds property', function () {69 return this.project.saveState()70 .then(() => this.project.saveState({ foo: 42 }))71 .then((state) => expect(state).to.deep.eq({ foo: 42 }))72 })73 it('adds second property', function () {74 return this.project.saveState()75 .then(() => this.project.saveState({ foo: 42 }))76 .then(() => this.project.saveState({ bar: true }))77 .then((state) => expect(state).to.deep.eq({ foo: 42, bar: true }))78 })79 it('modifes property', function () {80 return this.project.saveState()81 .then(() => this.project.saveState({ foo: 42 }))82 .then(() => this.project.saveState({ foo: 'modified' }))83 .then((state) => expect(state).to.deep.eq({ foo: 'modified' }))84 })85 })86 context('#getConfig', () => {87 const integrationFolder = 'foo/bar/baz'88 beforeEach(function () {89 sinon.stub(config, 'get').withArgs(this.todosPath, { foo: 'bar' }).resolves({ baz: 'quux', integrationFolder })90 sinon.stub(this.project, 'determineIsNewProject').withArgs(integrationFolder).resolves(false)91 })92 it('calls config.get with projectRoot + options + saved state', function () {93 return savedState.create(this.todosPath)94 .then((state) => {95 sinon.stub(state, 'get').resolves({ reporterWidth: 225 })96 this.project.getConfig({ foo: 'bar' })97 .then((cfg) => {98 expect(cfg).to.deep.eq({99 integrationFolder,100 isNewProject: false,101 baz: 'quux',102 state: {103 reporterWidth: 225,104 },105 })106 })107 })108 })109 it('resolves if cfg is already set', function () {110 this.project.cfg = {111 integrationFolder,112 foo: 'bar',113 }114 return this.project.getConfig()115 .then((cfg) => {116 expect(cfg).to.deep.eq({117 integrationFolder,118 foo: 'bar',119 })120 })121 })122 it('sets cfg.isNewProject to false when state.showedOnBoardingModal is true', function () {123 return savedState.create(this.todosPath)124 .then((state) => {125 sinon.stub(state, 'get').resolves({ showedOnBoardingModal: true })126 this.project.getConfig({ foo: 'bar' })127 .then((cfg) => {128 expect(cfg).to.deep.eq({129 integrationFolder,130 isNewProject: false,131 baz: 'quux',132 state: {133 showedOnBoardingModal: true,134 },135 })136 })137 })138 })139 it('does not set cfg.isNewProject when cfg.isTextTerminal', function () {140 const cfg = { isTextTerminal: true }141 config.get.resolves(cfg)142 sinon.stub(this.project, '_setSavedState').resolves(cfg)143 return this.project.getConfig({ foo: 'bar' })144 .then((cfg) => {145 expect(cfg).not.to.have.property('isNewProject')146 })147 })148 })149 context('#open', () => {150 beforeEach(function () {151 sinon.stub(this.project, 'watchSettingsAndStartWebsockets').resolves()152 sinon.stub(this.project, 'checkSupportFile').resolves()153 sinon.stub(this.project, 'scaffold').resolves()154 sinon.stub(this.project, 'getConfig').resolves(this.config)155 sinon.stub(ServerE2E.prototype, 'open').resolves([])156 sinon.stub(ServerE2E.prototype, 'reset')157 sinon.stub(config, 'updateWithPluginValues').returns(this.config)158 sinon.stub(scaffold, 'plugins').resolves()159 sinon.stub(plugins, 'init').resolves()160 })161 it('calls #watchSettingsAndStartWebsockets with options + config', function () {162 const opts = { changeEvents: false, onAutomationRequest () {} }163 this.project.cfg = {}164 return this.project.open(opts).then(() => {165 expect(this.project.watchSettingsAndStartWebsockets).to.be.calledWith(opts, this.project.cfg)166 })167 })168 it('calls #scaffold with server config promise', function () {169 return this.project.open().then(() => {170 expect(this.project.scaffold).to.be.calledWith(this.config)171 })172 })173 it('calls #checkSupportFile with server config when scaffolding is finished', function () {174 return this.project.open().then(() => {175 expect(this.project.checkSupportFile).to.be.calledWith(this.config)176 })177 })178 it('calls #getConfig options', function () {179 const opts = {}180 return this.project.open(opts).then(() => {181 expect(this.project.getConfig).to.be.calledWith(opts)182 })183 })184 it('initializes the plugins', function () {185 return this.project.open({}).then(() => {186 expect(plugins.init).to.be.called187 })188 })189 it('calls support.plugins with pluginsFile directory', function () {190 return this.project.open({}).then(() => {191 expect(scaffold.plugins).to.be.calledWith(path.dirname(this.config.pluginsFile))192 })193 })194 it('calls options.onError with plugins error when there is a plugins error', function () {195 const onError = sinon.spy()196 const err = {197 name: 'plugin error name',198 message: 'plugin error message',199 }200 return this.project.open({ onError }).then(() => {201 const pluginsOnError = plugins.init.lastCall.args[1].onError202 expect(pluginsOnError).to.be.a('function')203 pluginsOnError(err)204 expect(onError).to.be.calledWith(err)205 })206 })207 it('updates config.state when saved state changes', function () {208 sinon.spy(this.project, 'saveState')209 const options = {}210 return this.project.open(options)211 .then(() => options.onSavedStateChanged({ autoScrollingEnabled: false }))212 .then(() => this.project.getConfig())213 .then((config) => {214 expect(this.project.saveState).to.be.calledWith({ autoScrollingEnabled: false })215 expect(config.state).to.eql({ autoScrollingEnabled: false })216 })217 })218 // TODO: skip this for now219 it.skip('watches cypress.json', function () {220 return this.server.open().bind(this).then(() => {221 expect(Watchers.prototype.watch).to.be.calledWith('/Users/brian/app/cypress.json')222 })223 })224 // TODO: skip this for now225 it.skip('passes watchers to Socket.startListening', function () {226 const options = {}227 return this.server.open(options).then(() => {228 const { startListening } = SocketE2E.prototype229 expect(startListening.getCall(0).args[0]).to.be.instanceof(Watchers)230 expect(startListening.getCall(0).args[1]).to.eq(options)231 })232 })233 it('attaches warning to non-chrome browsers when chromeWebSecurity:false', function () {234 Object.assign(this.config, {235 browsers: [{ family: 'chromium', name: 'Canary' }, { family: 'some-other-family', name: 'some-other-name' }],236 chromeWebSecurity: false,237 })238 return this.project.open()239 .then(() => this.project.getConfig())240 .then((config) => {241 expect(config.chromeWebSecurity).eq(false)242 expect(config.browsers).deep.eq([243 {244 family: 'chromium',245 name: 'Canary',246 },247 {248 family: 'some-other-family',249 name: 'some-other-name',250 warning: `\251Your project has set the configuration option: \`chromeWebSecurity: false\`252This option will not have an effect in Some-other-name. Tests that rely on web security being disabled will not run as expected.\253`,254 },255 ])256 expect(config).ok257 })258 })259 })260 context('#close', () => {261 beforeEach(function () {262 this.project = new ProjectE2E('/_test-output/path/to/project-e2e')263 sinon.stub(this.project, 'getConfig').resolves(this.config)264 sinon.stub(user, 'ensureAuthToken').resolves('auth-token-123')265 })266 it('closes server', function () {267 this.project.server = sinon.stub({ close () {} })268 return this.project.close().then(() => {269 expect(this.project.server.close).to.be.calledOnce270 })271 })272 it('closes watchers', function () {273 this.project.watchers = sinon.stub({ close () {} })274 return this.project.close().then(() => {275 expect(this.project.watchers.close).to.be.calledOnce276 })277 })278 it('can close when server + watchers arent open', function () {279 return this.project.close()280 })281 })282 context('#reset', () => {283 beforeEach(function () {284 this.project = new ProjectE2E(this.pristinePath)285 this.project.automation = { reset: sinon.stub() }286 this.project.server = { reset: sinon.stub() }287 })288 it('resets server + automation', function () {289 return this.project.reset()290 .then(() => {291 expect(this.project.automation.reset).to.be.calledOnce292 expect(this.project.server.reset).to.be.calledOnce293 })294 })295 })296 context('#getRuns', () => {297 beforeEach(function () {298 this.project = new ProjectE2E(this.todosPath)299 sinon.stub(settings, 'read').resolves({ projectId: 'id-123' })300 sinon.stub(api, 'getProjectRuns').resolves('runs')301 sinon.stub(user, 'ensureAuthToken').resolves('auth-token-123')302 })303 it('calls api.getProjectRuns with project id + session', function () {304 return this.project.getRuns().then((runs) => {305 expect(api.getProjectRuns).to.be.calledWith('id-123', 'auth-token-123')306 expect(runs).to.equal('runs')307 })308 })309 })310 context('#scaffold', () => {311 beforeEach(function () {312 this.project = new ProjectE2E('/_test-output/path/to/project-e2e')313 sinon.stub(scaffold, 'integration').resolves()314 sinon.stub(scaffold, 'fixture').resolves()315 sinon.stub(scaffold, 'support').resolves()316 sinon.stub(scaffold, 'plugins').resolves()317 this.obj = { projectRoot: 'pr', fixturesFolder: 'ff', integrationFolder: 'if', supportFolder: 'sf', pluginsFile: 'pf/index.js' }318 })319 it('calls scaffold.integration with integrationFolder', function () {320 return this.project.scaffold(this.obj).then(() => {321 expect(scaffold.integration).to.be.calledWith(this.obj.integrationFolder)322 })323 })324 it('calls fixture.scaffold with fixturesFolder', function () {325 return this.project.scaffold(this.obj).then(() => {326 expect(scaffold.fixture).to.be.calledWith(this.obj.fixturesFolder)327 })328 })329 it('calls support.scaffold with supportFolder', function () {330 return this.project.scaffold(this.obj).then(() => {331 expect(scaffold.support).to.be.calledWith(this.obj.supportFolder)332 })333 })334 it('does not call support.plugins if config.pluginsFile is falsey', function () {335 this.obj.pluginsFile = false336 return this.project.scaffold(this.obj).then(() => {337 expect(scaffold.plugins).not.to.be.called338 })339 })340 describe('forced', () => {341 let resetEnv342 beforeEach(function () {343 this.obj.isTextTerminal = true344 resetEnv = mockedEnv({345 CYPRESS_INTERNAL_FORCE_SCAFFOLD: '1',346 })347 })348 afterEach(() => {349 resetEnv()350 })351 it('calls scaffold when forced by environment variable', function () {352 return this.project.scaffold(this.obj).then(() => {353 expect(scaffold.integration).to.be.calledWith(this.obj.integrationFolder)354 expect(scaffold.fixture).to.be.calledWith(this.obj.fixturesFolder)355 expect(scaffold.support).to.be.calledWith(this.obj.supportFolder)356 })357 })358 })359 describe('not forced', () => {360 let resetEnv361 beforeEach(function () {362 this.obj.isTextTerminal = true363 resetEnv = mockedEnv({364 CYPRESS_INTERNAL_FORCE_SCAFFOLD: undefined,365 })366 })367 afterEach(() => {368 resetEnv()369 })370 it('does not scaffold integration folder', function () {371 return this.project.scaffold(this.obj).then(() => {372 expect(scaffold.integration).to.not.be.calledWith(this.obj.integrationFolder)373 expect(scaffold.fixture).to.not.be.calledWith(this.obj.fixturesFolder)374 // still scaffolds support folder due to old logic375 expect(scaffold.support).to.be.calledWith(this.obj.supportFolder)376 })377 })378 })379 })380 context('#watchSettings', () => {381 beforeEach(function () {382 this.project = new ProjectE2E('/_test-output/path/to/project-e2e')383 this.project.server = { startWebsockets () {} }384 sinon.stub(settings, 'pathToConfigFile').returns('/path/to/cypress.json')385 sinon.stub(settings, 'pathToCypressEnvJson').returns('/path/to/cypress.env.json')386 this.watch = sinon.stub(this.project.watchers, 'watch')387 })388 it('watches cypress.json and cypress.env.json', function () {389 this.project.watchSettingsAndStartWebsockets({ onSettingsChanged () {} })390 expect(this.watch).to.be.calledTwice391 expect(this.watch).to.be.calledWith('/path/to/cypress.json')392 expect(this.watch).to.be.calledWith('/path/to/cypress.env.json')393 })394 it('sets onChange event when {changeEvents: true}', function (done) {395 this.project.watchSettingsAndStartWebsockets({ onSettingsChanged: () => done() })396 // get the object passed to watchers.watch397 const obj = this.watch.getCall(0).args[1]398 expect(obj.onChange).to.be.a('function')399 obj.onChange()400 })401 it('does not call watch when {changeEvents: false}', function () {402 this.project.watchSettingsAndStartWebsockets({ onSettingsChanged: undefined })403 expect(this.watch).not.to.be.called404 })405 it('does not call onSettingsChanged when generatedProjectIdTimestamp is less than 1 second', function () {406 let timestamp = new Date()407 this.project.generatedProjectIdTimestamp = timestamp408 const stub = sinon.stub()409 this.project.watchSettingsAndStartWebsockets({ onSettingsChanged: stub })410 // get the object passed to watchers.watch411 const obj = this.watch.getCall(0).args[1]412 obj.onChange()413 expect(stub).not.to.be.called414 // subtract 1 second from our timestamp415 timestamp.setSeconds(timestamp.getSeconds() - 1)416 obj.onChange()417 expect(stub).to.be.calledOnce418 })419 })420 context('#checkSupportFile', () => {421 beforeEach(function () {422 sinon.stub(fs, 'pathExists').resolves(true)423 this.project = new ProjectE2E('/_test-output/path/to/project-e2e')424 this.project.server = { onTestFileChange: sinon.spy() }425 sinon.stub(preprocessor, 'getFile').resolves()426 this.config = {427 projectRoot: '/path/to/root/',428 supportFile: '/path/to/root/foo/bar.js',429 }430 })431 it('does nothing when {supportFile: false}', function () {432 const ret = this.project.checkSupportFile({ supportFile: false })433 expect(ret).to.be.undefined434 })435 it('throws when support file does not exist', function () {436 fs.pathExists.resolves(false)437 return this.project.checkSupportFile(this.config)438 .catch((e) => {439 expect(e.message).to.include('The support file is missing or invalid.')440 })441 })442 })443 context('#watchPluginsFile', () => {444 beforeEach(function () {445 sinon.stub(fs, 'pathExists').resolves(true)446 this.project = new ProjectE2E('/_test-output/path/to/project-e2e')447 this.project.watchers = { watchTree: sinon.spy() }448 sinon.stub(plugins, 'init').resolves()449 this.config = {450 pluginsFile: '/path/to/plugins-file',451 }452 })453 it('does nothing when {pluginsFile: false}', function () {454 this.config.pluginsFile = false455 return this.project.watchPluginsFile(this.config, {}).then(() => {456 expect(this.project.watchers.watchTree).not.to.be.called457 })458 })459 it('does nothing if pluginsFile does not exist', function () {460 fs.pathExists.resolves(false)461 return this.project.watchPluginsFile(this.config, {}).then(() => {462 expect(this.project.watchers.watchTree).not.to.be.called463 })464 })465 it('does nothing if in run mode', function () {466 return this.project.watchPluginsFile(this.config, {467 isTextTerminal: true,468 }).then(() => {469 expect(this.project.watchers.watchTree).not.to.be.called470 })471 })472 it('watches the pluginsFile', function () {473 return this.project.watchPluginsFile(this.config, {}).then(() => {474 expect(this.project.watchers.watchTree).to.be.calledWith(this.config.pluginsFile)475 expect(this.project.watchers.watchTree.lastCall.args[1]).to.be.an('object')476 expect(this.project.watchers.watchTree.lastCall.args[1].onChange).to.be.a('function')477 })478 })479 it('calls plugins.init when file changes', function () {480 return this.project.watchPluginsFile(this.config, {}).then(() => {481 this.project.watchers.watchTree.firstCall.args[1].onChange()482 expect(plugins.init).to.be.calledWith(this.config)483 })484 })485 it('handles errors from calling plugins.init', function (done) {486 const error = { name: 'foo', message: 'foo' }487 plugins.init.rejects(error)488 this.project.watchPluginsFile(this.config, {489 onError (err) {490 expect(err).to.eql(error)491 done()492 },493 })494 .then(() => {495 this.project.watchers.watchTree.firstCall.args[1].onChange()496 })497 })498 })499 context('#watchSettingsAndStartWebsockets', () => {500 beforeEach(function () {501 this.project = new ProjectE2E('/_test-output/path/to/project-e2e')502 this.project.watchers = {}503 this.project.server = sinon.stub({ startWebsockets () {} })504 sinon.stub(this.project, 'watchSettings')505 sinon.stub(Automation, 'create').returns('automation')506 })507 it('calls server.startWebsockets with automation + config', function () {508 const c = {}509 this.project.watchSettingsAndStartWebsockets({}, c)510 expect(this.project.server.startWebsockets).to.be.calledWith('automation', c)511 })512 it('passes onReloadBrowser callback', function () {513 const fn = sinon.stub()514 this.project.server.startWebsockets.yieldsTo('onReloadBrowser')515 this.project.watchSettingsAndStartWebsockets({ onReloadBrowser: fn }, {})516 expect(fn).to.be.calledOnce517 })518 })519 context('#getProjectId', () => {520 beforeEach(function () {521 this.project = new ProjectE2E('/_test-output/path/to/project-e2e')522 this.verifyExistence = sinon.stub(ProjectE2E.prototype, 'verifyExistence').resolves()523 })524 it('calls verifyExistence', function () {525 sinon.stub(settings, 'read').resolves({ projectId: 'id-123' })526 return this.project.getProjectId()527 .then(() => expect(this.verifyExistence).to.be.calledOnce)528 })529 it('returns the project id from settings', function () {530 sinon.stub(settings, 'read').resolves({ projectId: 'id-123' })531 return this.project.getProjectId()532 .then((id) => expect(id).to.eq('id-123'))533 })534 it('throws NO_PROJECT_ID with the projectRoot when no projectId was found', function () {535 sinon.stub(settings, 'read').resolves({})536 return this.project.getProjectId()537 .then((id) => {538 throw new Error('expected to fail, but did not')539 }).catch((err) => {540 expect(err.type).to.eq('NO_PROJECT_ID')541 expect(err.message).to.include('/_test-output/path/to/project-e2e')542 })543 })544 it('bubbles up Settings.read errors', function () {545 const err = new Error()546 err.code = 'EACCES'547 sinon.stub(settings, 'read').rejects(err)548 return this.project.getProjectId()549 .then((id) => {550 throw new Error('expected to fail, but did not')551 }).catch((err) => {552 expect(err.code).to.eq('EACCES')553 })554 })555 })556 context('#writeProjectId', () => {557 beforeEach(function () {558 this.project = new ProjectE2E('/_test-output/path/to/project-e2e')559 sinon.stub(settings, 'write')560 .withArgs(this.project.projectRoot, { projectId: 'id-123' })561 .resolves({ projectId: 'id-123' })562 })563 it('calls Settings.write with projectRoot and attrs', function () {564 return this.project.writeProjectId('id-123').then((id) => {565 expect(id).to.eq('id-123')566 })567 })568 it('sets generatedProjectIdTimestamp', function () {569 return this.project.writeProjectId('id-123').then(() => {570 expect(this.project.generatedProjectIdTimestamp).to.be.a('date')571 })572 })573 })574 context('#getSpecUrl', () => {575 beforeEach(function () {576 this.project2 = new ProjectE2E(this.idsPath)577 return settings.write(this.idsPath, { port: 2020 })578 })579 it('returns fully qualified url when spec exists', function () {580 return this.project2.getSpecUrl('cypress/integration/bar.js')581 .then((str) => {582 expect(str).to.eq('http://localhost:2020/__/#/tests/integration/bar.js')583 })584 })585 it('returns fully qualified url on absolute path to spec', function () {586 const todosSpec = path.join(this.todosPath, 'tests/sub/sub_test.coffee')587 return this.project.getSpecUrl(todosSpec)588 .then((str) => {589 expect(str).to.eq('http://localhost:8888/__/#/tests/integration/sub/sub_test.coffee')590 })591 })592 it('escapses %, &', function () {593 const todosSpec = path.join(this.todosPath, 'tests/sub/a&b%c.js')594 return this.project.getSpecUrl(todosSpec)595 .then((str) => {596 expect(str).to.eq('http://localhost:8888/__/#/tests/integration/sub/a%26b%25c.js')597 })598 })599 // ? is invalid in Windows, but it can be tested here600 // because it's a unit test and doesn't check the existence of files601 it('escapes ?', function () {602 const todosSpec = path.join(this.todosPath, 'tests/sub/a?.spec.js')603 return this.project.getSpecUrl(todosSpec)604 .then((str) => {605 expect(str).to.eq('http://localhost:8888/__/#/tests/integration/sub/a%3F.spec.js')606 })607 })608 it('escapes %, &, ? in the url dir', function () {609 const todosSpec = path.join(this.todosPath, 'tests/s%&?ub/a.spec.js')610 return this.project.getSpecUrl(todosSpec)611 .then((str) => {612 expect(str).to.eq('http://localhost:8888/__/#/tests/integration/s%25%26%3Fub/a.spec.js')613 })614 })615 it('returns __all spec url', function () {616 return this.project.getSpecUrl()617 .then((str) => {618 expect(str).to.eq('http://localhost:8888/__/#/tests/__all')619 })620 })621 it('returns __all spec url with spec is __all', function () {622 return this.project.getSpecUrl('__all')623 .then((str) => {624 expect(str).to.eq('http://localhost:8888/__/#/tests/__all')625 })626 })627 })628 context('.add', () => {629 beforeEach(function () {630 this.pristinePath = Fixtures.projectPath('pristine')631 })632 it('inserts path into cache', function () {633 return ProjectE2E.add(this.pristinePath, {})634 .then(() => cache.read()).then((json) => {635 expect(json.PROJECTS).to.deep.eq([this.pristinePath])636 })637 })638 describe('if project at path has id', () => {639 it('returns object containing path and id', function () {640 sinon.stub(settings, 'read').resolves({ projectId: 'id-123' })641 return ProjectE2E.add(this.pristinePath, {})642 .then((project) => {643 expect(project.id).to.equal('id-123')644 expect(project.path).to.equal(this.pristinePath)645 })646 })647 })648 describe('if project at path does not have id', () => {649 it('returns object containing just the path', function () {650 sinon.stub(settings, 'read').rejects()651 return ProjectE2E.add(this.pristinePath, {})652 .then((project) => {653 expect(project.id).to.be.undefined654 expect(project.path).to.equal(this.pristinePath)655 })656 })657 })658 describe('if configFile is non-default', () => {659 it('doesn\'t cache anything and returns object containing just the path', function () {660 return ProjectE2E.add(this.pristinePath, { configFile: false })661 .then((project) => {662 expect(project.id).to.be.undefined663 expect(project.path).to.equal(this.pristinePath)664 return cache.read()665 }).then((json) => {666 expect(json.PROJECTS).to.deep.eq([])667 })668 })669 })670 })671 context('#createCiProject', () => {672 beforeEach(function () {673 this.project = new ProjectE2E('/_test-output/path/to/project-e2e')674 this.newProject = { id: 'project-id-123' }675 sinon.stub(this.project, 'writeProjectId').resolves('project-id-123')676 sinon.stub(user, 'ensureAuthToken').resolves('auth-token-123')677 sinon.stub(commitInfo, 'getRemoteOrigin').resolves('remoteOrigin')678 sinon.stub(api, 'createProject')679 .withArgs({ foo: 'bar' }, 'remoteOrigin', 'auth-token-123')680 .resolves(this.newProject)681 })682 it('calls api.createProject with user session', function () {683 return this.project.createCiProject({ foo: 'bar' }).then(() => {684 expect(api.createProject).to.be.calledWith({ foo: 'bar' }, 'remoteOrigin', 'auth-token-123')685 })686 })687 it('calls writeProjectId with id', function () {688 return this.project.createCiProject({ foo: 'bar' }).then(() => {689 expect(this.project.writeProjectId).to.be.calledWith('project-id-123')690 })691 })692 it('returns project id', function () {693 return this.project.createCiProject({ foo: 'bar' }).then((projectId) => {694 expect(projectId).to.eql(this.newProject)695 })696 })697 })698 context('#getRecordKeys', () => {699 beforeEach(function () {700 this.recordKeys = []701 this.project = new ProjectE2E(this.pristinePath)702 sinon.stub(settings, 'read').resolves({ projectId: 'id-123' })703 sinon.stub(user, 'ensureAuthToken').resolves('auth-token-123')704 sinon.stub(api, 'getProjectRecordKeys').resolves(this.recordKeys)705 })706 it('calls api.getProjectRecordKeys with project id + session', function () {707 return this.project.getRecordKeys().then(() => {708 expect(api.getProjectRecordKeys).to.be.calledWith('id-123', 'auth-token-123')709 })710 })711 it('returns ci keys', function () {712 return this.project.getRecordKeys().then((recordKeys) => {713 expect(recordKeys).to.equal(this.recordKeys)714 })715 })716 })717 context('#requestAccess', () => {718 beforeEach(function () {719 this.project = new ProjectE2E(this.pristinePath)720 sinon.stub(user, 'ensureAuthToken').resolves('auth-token-123')721 sinon.stub(api, 'requestAccess').resolves('response')722 })723 it('calls api.requestAccess with project id + auth token', function () {724 return this.project.requestAccess('project-id-123').then(() => {725 expect(api.requestAccess).to.be.calledWith('project-id-123', 'auth-token-123')726 })727 })728 it('returns response', function () {729 return this.project.requestAccess('project-id-123').then((response) => {730 expect(response).to.equal('response')731 })732 })733 })734 context('.remove', () => {735 beforeEach(() => {736 sinon.stub(cache, 'removeProject').resolves()737 })738 it('calls cache.removeProject with path', () => {739 return ProjectE2E.remove('/_test-output/path/to/project-e2e').then(() => {740 expect(cache.removeProject).to.be.calledWith('/_test-output/path/to/project-e2e')741 })742 })743 })744 context('.id', () => {745 it('returns project id', function () {746 return ProjectE2E.id(this.todosPath).then((id) => {747 expect(id).to.eq(this.projectId)748 })749 })750 })751 context('.getOrgs', () => {752 beforeEach(() => {753 sinon.stub(user, 'ensureAuthToken').resolves('auth-token-123')754 sinon.stub(api, 'getOrgs').resolves([])755 })756 it('calls api.getOrgs', () => {757 return ProjectE2E.getOrgs().then((orgs) => {758 expect(orgs).to.deep.eq([])759 expect(api.getOrgs).to.be.calledOnce760 expect(api.getOrgs).to.be.calledWith('auth-token-123')761 })762 })763 })764 context('.paths', () => {765 beforeEach(() => {766 sinon.stub(cache, 'getProjectRoots').resolves([])767 })768 it('calls cache.getProjectRoots', () => {769 return ProjectE2E.paths().then((ret) => {770 expect(ret).to.deep.eq([])771 expect(cache.getProjectRoots).to.be.calledOnce772 })773 })774 })775 context('.getPathsAndIds', () => {776 beforeEach(() => {777 sinon.stub(cache, 'getProjectRoots').resolves([778 '/path/to/first',779 '/path/to/second',780 ])781 sinon.stub(settings, 'id').resolves('id-123')782 })783 it('returns array of objects with paths and ids', () => {784 return ProjectE2E.getPathsAndIds().then((pathsAndIds) => {785 expect(pathsAndIds).to.eql([786 {787 path: '/path/to/first',788 id: 'id-123',789 },790 {791 path: '/path/to/second',792 id: 'id-123',793 },794 ])795 })796 })797 })798 context('.getProjectStatuses', () => {799 beforeEach(() => {800 sinon.stub(user, 'ensureAuthToken').resolves('auth-token-123')801 })802 it('gets projects from api', () => {803 sinon.stub(api, 'getProjects').resolves([])804 return ProjectE2E.getProjectStatuses([])805 .then(() => {806 expect(api.getProjects).to.have.been.calledWith('auth-token-123')807 })808 })809 it('returns array of projects', () => {810 sinon.stub(api, 'getProjects').resolves([])811 return ProjectE2E.getProjectStatuses([])812 .then((projectsWithStatuses) => {813 expect(projectsWithStatuses).to.eql([])814 })815 })816 it('returns same number as client projects, even if there are less api projects', () => {817 sinon.stub(api, 'getProjects').resolves([])818 return ProjectE2E.getProjectStatuses([{}])819 .then((projectsWithStatuses) => {820 expect(projectsWithStatuses.length).to.eql(1)821 })822 })823 it('returns same number as client projects, even if there are more api projects', () => {824 sinon.stub(api, 'getProjects').resolves([{}, {}])825 return ProjectE2E.getProjectStatuses([{}])826 .then((projectsWithStatuses) => {827 expect(projectsWithStatuses.length).to.eql(1)828 })829 })830 it('merges in details of matching projects', () => {831 sinon.stub(api, 'getProjects').resolves([832 { id: 'id-123', lastBuildStatus: 'passing' },833 ])834 return ProjectE2E.getProjectStatuses([{ id: 'id-123', path: '/_test-output/path/to/project' }])835 .then((projectsWithStatuses) => {836 expect(projectsWithStatuses[0]).to.eql({837 id: 'id-123',838 path: '/_test-output/path/to/project',839 lastBuildStatus: 'passing',840 state: 'VALID',841 })842 })843 })844 it('returns client project when it has no id', () => {845 sinon.stub(api, 'getProjects').resolves([])846 return ProjectE2E.getProjectStatuses([{ path: '/_test-output/path/to/project' }])847 .then((projectsWithStatuses) => {848 expect(projectsWithStatuses[0]).to.eql({849 path: '/_test-output/path/to/project',850 state: 'VALID',851 })852 })853 })854 describe('when client project has id and there is no matching user project', () => {855 beforeEach(() => {856 sinon.stub(api, 'getProjects').resolves([])857 })858 it('marks project as invalid if api 404s', () => {859 sinon.stub(api, 'getProject').rejects({ name: '', message: '', statusCode: 404 })860 return ProjectE2E.getProjectStatuses([{ id: 'id-123', path: '/_test-output/path/to/project' }])861 .then((projectsWithStatuses) => {862 expect(projectsWithStatuses[0]).to.eql({863 id: 'id-123',864 path: '/_test-output/path/to/project',865 state: 'INVALID',866 })867 })868 })869 it('marks project as unauthorized if api 403s', () => {870 sinon.stub(api, 'getProject').rejects({ name: '', message: '', statusCode: 403 })871 return ProjectE2E.getProjectStatuses([{ id: 'id-123', path: '/_test-output/path/to/project' }])872 .then((projectsWithStatuses) => {873 expect(projectsWithStatuses[0]).to.eql({874 id: 'id-123',875 path: '/_test-output/path/to/project',876 state: 'UNAUTHORIZED',877 })878 })879 })880 it('merges in project details and marks valid if somehow project exists and is authorized', () => {881 sinon.stub(api, 'getProject').resolves({ id: 'id-123', lastBuildStatus: 'passing' })882 return ProjectE2E.getProjectStatuses([{ id: 'id-123', path: '/_test-output/path/to/project' }])883 .then((projectsWithStatuses) => {884 expect(projectsWithStatuses[0]).to.eql({885 id: 'id-123',886 path: '/_test-output/path/to/project',887 lastBuildStatus: 'passing',888 state: 'VALID',889 })890 })891 })892 it('throws error if not accounted for', () => {893 const error = { name: '', message: '' }894 sinon.stub(api, 'getProject').rejects(error)895 return ProjectE2E.getProjectStatuses([{ id: 'id-123', path: '/_test-output/path/to/project' }])896 .then(() => {897 throw new Error('should have caught error but did not')898 }).catch((err) => {899 expect(err).to.equal(error)900 })901 })902 })903 })904 context('.getProjectStatus', () => {905 beforeEach(function () {906 this.clientProject = {907 id: 'id-123',908 path: '/_test-output/path/to/project',909 }910 sinon.stub(user, 'ensureAuthToken').resolves('auth-token-123')911 })912 it('gets project from api', function () {913 sinon.stub(api, 'getProject').resolves([])914 return ProjectE2E.getProjectStatus(this.clientProject)915 .then(() => {916 expect(api.getProject).to.have.been.calledWith('id-123', 'auth-token-123')917 })918 })919 it('returns project merged with details', function () {920 sinon.stub(api, 'getProject').resolves({921 lastBuildStatus: 'passing',922 })923 return ProjectE2E.getProjectStatus(this.clientProject)924 .then((project) => {925 expect(project).to.eql({926 id: 'id-123',927 path: '/_test-output/path/to/project',928 lastBuildStatus: 'passing',929 state: 'VALID',930 })931 })932 })933 it('returns project, marked as valid, if it does not have an id, without querying api', function () {934 sinon.stub(api, 'getProject')935 this.clientProject.id = undefined936 return ProjectE2E.getProjectStatus(this.clientProject)937 .then((project) => {938 expect(project).to.eql({939 id: undefined,940 path: '/_test-output/path/to/project',941 state: 'VALID',942 })943 expect(api.getProject).not.to.be.called944 })945 })946 it('marks project as invalid if api 404s', function () {947 sinon.stub(api, 'getProject').rejects({ name: '', message: '', statusCode: 404 })948 return ProjectE2E.getProjectStatus(this.clientProject)949 .then((project) => {950 expect(project).to.eql({951 id: 'id-123',952 path: '/_test-output/path/to/project',953 state: 'INVALID',954 })955 })956 })957 it('marks project as unauthorized if api 403s', function () {958 sinon.stub(api, 'getProject').rejects({ name: '', message: '', statusCode: 403 })959 return ProjectE2E.getProjectStatus(this.clientProject)960 .then((project) => {961 expect(project).to.eql({962 id: 'id-123',963 path: '/_test-output/path/to/project',964 state: 'UNAUTHORIZED',965 })966 })967 })968 it('throws error if not accounted for', function () {969 const error = { name: '', message: '' }970 sinon.stub(api, 'getProject').rejects(error)971 return ProjectE2E.getProjectStatus(this.clientProject)972 .then(() => {973 throw new Error('should have caught error but did not')974 }).catch((err) => {975 expect(err).to.equal(error)976 })977 })978 })979 context('.getSecretKeyByPath', () => {980 beforeEach(() => {981 sinon.stub(user, 'ensureAuthToken').resolves('auth-token-123')982 })983 it('calls api.getProjectToken with id + session', function () {984 sinon.stub(api, 'getProjectToken')985 .withArgs(this.projectId, 'auth-token-123')986 .resolves('key-123')987 return ProjectE2E.getSecretKeyByPath(this.todosPath).then((key) => {988 expect(key).to.eq('key-123')989 })990 })991 it('throws CANNOT_FETCH_PROJECT_TOKEN on error', function () {992 sinon.stub(api, 'getProjectToken')993 .withArgs(this.projectId, 'auth-token-123')994 .rejects(new Error())995 return ProjectE2E.getSecretKeyByPath(this.todosPath)996 .then(() => {997 throw new Error('should have caught error but did not')998 }).catch((err) => {999 expect(err.type).to.eq('CANNOT_FETCH_PROJECT_TOKEN')1000 })1001 })1002 })1003 context('.generateSecretKeyByPath', () => {1004 beforeEach(() => {1005 sinon.stub(user, 'ensureAuthToken').resolves('auth-token-123')1006 })1007 it('calls api.updateProjectToken with id + session', function () {1008 sinon.stub(api, 'updateProjectToken')1009 .withArgs(this.projectId, 'auth-token-123')1010 .resolves('new-key-123')1011 return ProjectE2E.generateSecretKeyByPath(this.todosPath).then((key) => {1012 expect(key).to.eq('new-key-123')1013 })1014 })1015 it('throws CANNOT_CREATE_PROJECT_TOKEN on error', function () {1016 sinon.stub(api, 'updateProjectToken')1017 .withArgs(this.projectId, 'auth-token-123')1018 .rejects(new Error())1019 return ProjectE2E.generateSecretKeyByPath(this.todosPath)1020 .then(() => {1021 throw new Error('should have caught error but did not')1022 }).catch((err) => {1023 expect(err.type).to.eq('CANNOT_CREATE_PROJECT_TOKEN')1024 })1025 })1026 })...

Full Screen

Full Screen

project-base.js

Source:project-base.js Github

copy

Full Screen

...608 }609 // These methods are not related to start server/sockets/runners610 getProjectId() {611 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {612 yield this.verifyExistence();613 const readSettings = yield settings.read(this.projectRoot, this.options);614 if (readSettings && readSettings.projectId) {615 return readSettings.projectId;616 }617 errors_1.default.throw('NO_PROJECT_ID', settings.configFile(this.options), this.projectRoot);618 });619 }620 verifyExistence() {621 return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {622 try {623 yield fs_1.fs.statAsync(this.projectRoot);624 }625 catch (err) {626 errors_1.default.throw('NO_PROJECT_FOUND_AT_PROJECT_ROOT', this.projectRoot);...

Full Screen

Full Screen

project.js

Source:project.js Github

copy

Full Screen

...397 this.generatedProjectIdTimestamp = new Date;398 return settings.write(this.projectRoot, attrs)["return"](id);399 };400 Project.prototype.getProjectId = function() {401 return this.verifyExistence().then((function(_this) {402 return function() {403 return settings.read(_this.projectRoot);404 };405 })(this)).then((function(_this) {406 return function(settings) {407 var id;408 if (settings && (id = settings.projectId)) {409 return id;410 }411 return errors["throw"]("NO_PROJECT_ID", _this.projectRoot);412 };413 })(this));414 };415 Project.prototype.verifyExistence = function() {...

Full Screen

Full Screen

EventUtil.js

Source:EventUtil.js Github

copy

Full Screen

1var EventUtil = new function() {2 var DEFAULT_TIMEOUT = 15000;3 var DEFAULT_TIMEOUT_STEP = 1000;4 this.click = function(elementId, ignoreError) {5 return new Promise(function executor(resolve, reject) {6 try {7 var element = EventUtil.getElement(elementId, ignoreError, resolve);8 element.focus();9 element.trigger('click');10 resolve();11 } catch(error) {12 reject(error);13 }14 });15 };16 this.change = function(elementId, value, ignoreError) {17 return new Promise(function executor(resolve, reject) {18 try {19 var element = EventUtil.getElement(elementId, ignoreError, resolve);20 element.focus();21 element.val(value).change();22 resolve();23 } catch(error) {24 reject(error);25 }26 });27 };28 this.changeSelect2 = function(elementId, value, ignoreError) {29 return new Promise(function executor(resolve, reject) {30 try {31 var element = EventUtil.getElement(elementId, ignoreError, resolve);32 element.select2();33 element.focus();34 element.val(value);35 element.select2().trigger('change');36 resolve();37 } catch(error) {38 reject(error);39 }40 });41 };42 this.triggerSelectSelect2 = function(elementId, value, ignoreError) {43 return new Promise(function executor(resolve, reject) {44 try {45 var element = EventUtil.getElement(elementId, ignoreError, resolve);46 element.focus();47 element.val(value);48 element.select2().trigger('select2:select');49 resolve();50 } catch(error) {51 reject(error);52 }53 });54 };55 this.checked = function(elementId, value, ignoreError) {56 return new Promise(function executor(resolve, reject) {57 try {58 var element = EventUtil.getElement(elementId, ignoreError, resolve);59 element.focus();60 element.prop('checked', value);61 resolve();62 } catch(error) {63 reject(error);64 }65 });66 };67 this.equalTo = function(elementId, value, isEqual, ignoreError) {68 return new Promise(function executor(resolve, reject) {69 try {70 var element = EventUtil.getElement(elementId, ignoreError, resolve);71 if (isEqual && (element.html() === value || element.val() === value) ||72 !isEqual && (element.html() != value && element.val() != value)) {73 resolve();74 } else {75 throw "Element #" + elementId + " should" + (isEqual ? "" : " not") + " be equal " + value;76 }77 } catch(error) {78 reject(error);79 }80 });81 };82 this.write = function(elementId, text, ignoreError) {83 return new Promise(function executor(resolve, reject) {84 try {85 var element = EventUtil.getElement(elementId, ignoreError, resolve);86 element.focus();87 $(element).val(text);88 for (var i = 0; i < text.length; i++) {89 $(element).trigger('keydown', {which: text.charCodeAt(i)});90 $(element).trigger('keyup', {which: text.charCodeAt(i)});91 }92 resolve();93 } catch(error) {94 reject(error);95 }96 });97 };98 this.keypress = function(elementId, key, ignoreError) {99 return new Promise(function executor(resolve, reject) {100 try {101 var element = EventUtil.getElement(elementId, ignoreError, resolve);102 element.focus();103 var e = $.Event('keypress');104 e.which = key;105 $(element).trigger(e);106 resolve();107 } catch(error) {108 reject(error);109 }110 });111 }112 this.verifyExistence = function(elementId, isExist, ignoreError) {113 return new Promise(function executor(resolve, reject) {114 var elementExistence = $("#" + elementId).length > 0;115 if (elementExistence == isExist) {116 resolve();117 } else {118 if (ignoreError) {119 resolve();120 } else {121 throw "Element " + (isExist ? "not" : "") + " found: #" + elementId;122 }123 }124 });125 }126 this.waitForId = function(elementId, ignoreError, timeout) {127 return new Promise(function executor(resolve, reject) {128 timeout = EventUtil.checkTimeout(elementId, timeout, ignoreError, resolve, reject);129 if($("#" + elementId).length <= 0) {130 setTimeout(executor.bind(null, resolve, reject), DEFAULT_TIMEOUT_STEP);131 } else {132 resolve();133 }134 });135 };136 this.waitForClass = function(className, ignoreError, timeout) {137 return new Promise(function executor(resolve, reject) {138 timeout = EventUtil.checkTimeout(className, timeout, ignoreError, resolve, reject);139 if($("." + className).length <= 0) {140 setTimeout(executor.bind(null, resolve, reject), DEFAULT_TIMEOUT_STEP);141 } else {142 resolve();143 }144 });145 };146 this.waitForStyle = function(elementId, styleName, styleValue, ignoreError, timeout) {147 return new Promise(function executor(resolve, reject) {148 try {149 timeout = EventUtil.checkTimeout(elementId, timeout, ignoreError, resolve, reject);150 var element = EventUtil.getElement(elementId, ignoreError, resolve);151 if (element[0].style[styleName] === styleValue) {152 resolve();153 } else {154 setTimeout(executor.bind(null, resolve, reject), DEFAULT_TIMEOUT_STEP);155 }156 } catch(error) {157 reject(error);158 }159 });160 }161 this.waitForFill = function(elementId, ignoreError, timeout) {162 return new Promise(function executor(resolve, reject) {163 timeout = EventUtil.checkTimeout(elementId, timeout, ignoreError, resolve, reject);164 var element = EventUtil.getElement(elementId, ignoreError, resolve);165 if(element.html().length <= 0 && element.val().length <= 0) {166 setTimeout(executor.bind(null, resolve, reject), DEFAULT_TIMEOUT_STEP);167 } else {168 resolve();169 }170 });171 };172 this.waitForCkeditor = function(elementId, data, timeout) {173 return new Promise(function executor(resolve, reject) {174 timeout = EventUtil.checkTimeout(elementId, timeout, false, resolve, reject);175 editor = CKEditorManager.getEditorById(elementId);176 if(editor === undefined) {177 setTimeout(executor.bind(null, resolve, reject), DEFAULT_TIMEOUT_STEP);178 } else {179 resolve();180 }181 });182 }183 this.checkTimeout = function(elementId, timeout, ignoreError, resolve, reject) {184 if (!timeout) {185 timeout = DEFAULT_TIMEOUT;186 }187 timeout -= DEFAULT_TIMEOUT_STEP;188 if (timeout <= 0) {189 if(ignoreError) {190 resolve();191 } else {192 reject(new Error("Element '" + elementId + "' is not exist."));193 }194 }195 return timeout;196 }197 this.sleep = function(ms) {198 return new Promise(resolve => setTimeout(resolve, ms));199 }200 this.dragAndDrop = function(dragId, dropId, ignoreError) {201 return new Promise(function executor(resolve, reject) {202 try {203 var dragElement = EventUtil.getElement(dragId, ignoreError, resolve).draggable();204 var dropElement = EventUtil.getElement(dropId, ignoreError, resolve).droppable();205 var dt = new DataTransfer();206 var dragStartEvent = jQuery.Event("dragstart");207 dragStartEvent.originalEvent = jQuery.Event("mousedown");208 dragStartEvent.originalEvent.dataTransfer = dt;209 dropEvent = jQuery.Event("drop");210 dropEvent.originalEvent = jQuery.Event("DragEvent");211 dropEvent.originalEvent.dataTransfer = dt;212 dragElement.trigger(dragStartEvent);213 dropElement.trigger(dropEvent);214 resolve();215 } catch(error) {216 reject(error);217 }218 });219 };220 this.dropFile = function(fileName, url, dropId, ignoreError) {221 return new Promise(function executor(resolve, reject) {222 try {223 var dropElement = EventUtil.getElement(dropId, ignoreError, resolve).droppable();224 TestUtil.fetchBytes(url, function(file) {225 file.name = fileName;226 var dt = { files: [file] };227 dropEvent = jQuery.Event("drop");228 dropEvent.originalEvent = jQuery.Event("DragEvent");229 dropEvent.originalEvent.dataTransfer = dt;230 dropElement.trigger(dropEvent);231 resolve();232 });233 } catch(error) {234 reject(error);235 }236 });237 };238 this.getElement = function(elementId, ignoreError, resolve) {239 var element = $( "#" + elementId );240 if(!element) {241 if(ignoreError) {242 resolve();243 } else {244 throw "Element not found: #" + elementId;245 }246 }247 return element;248 }...

Full Screen

Full Screen

bucket.js

Source:bucket.js Github

copy

Full Screen

1/*!2 * bucket.js3 * 4 * Copyright (c) 20145 */6// core7var path = require('path');8var fs = require('fs');9// 3rd party10var _ = require('underscore');11var async = require('async');12var mime = require('mime');13var AWS = require('aws-sdk');14// lib15var policy = require('./policy.json');16/* -----------------------------------------------------------------------------17 * Bucket18 * ---------------------------------------------------------------------------*/19/**20 * Interface to manipulate an s3 bucket.21 *22 * @constructor23 * @public24 *25 * @param {object} s3config - s3config (http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#constructor-property)26 * @param {string} name - site options.27 */28var Bucket = function (options, s3config) {29 // store all options on instance30 this.options = options;31 this.s3 = new AWS.S3(s3config || {});32 this.bucketName = this._createBucketName(options);33 34 // Make sure all methods are called with bucket as content. Necessary35 // due to using async for flow management.36 _.bindAll(this, 'deploy', 'destroy', 'verifyExistence', 'listContents',37 'removeContents', 'removeBucket', 'create', 'createBucket',38 'makeWebsite', 'makePublic', 'upload', 'uploadDirectory',39 'uploadFile', 'uploadContent', '_createBucketName', '_params');40};41/* -----------------------------------------------------------------------------42 * deploy43 * ---------------------------------------------------------------------------*/44/**45 * Upload a local folder to a bucket in s3. If a46 * bucket by the specified name already exists, first47 * remove the bucket and all of its contents.48 *49 * @public50 *51 * @parma {object} options - Deploy options.52 */53Bucket.prototype.deploy = function (callback) {54 async.series([this.destroy, this.create, this.upload], callback);55},56/* -----------------------------------------------------------------------------57 * destroy58 * ---------------------------------------------------------------------------*/59/**60 * Remove bucket and all of its contents.61 *62 * @public63 *64 * @param {function} callback - Function executed after removing65 * bucket.66 */67Bucket.prototype.destroy = function (callback) {68 async.waterfall([69 this.verifyExistence,70 this.listContents,71 this.removeContents,72 this.removeBucket73 ], function (err) {74 return !err || err === 'Does not exist'75 ? callback()76 : callback(err);77 });78};79/**80 * Check for existence of bucket.81 *82 * @public83 *84 * @param {function} callback - Function executed after checking85 * aws for resource.86 */87Bucket.prototype.verifyExistence = function (callback) {88 this.s3.headBucket(this._params(), function (err, data) {89 return err && err.statusCode == 40490 ? callback('Does not exist')91 : callback(err);92 });93};94/**95 * List contents of bucket.96 *97 * @public98 *99 * @param {function} callback - Function executed after listing100 * bucket contents.101 */102Bucket.prototype.listContents = function (callback) {103 this.s3.listObjects(this._params(), function (err, res) {104 return callback(err, res ? res['Contents'] : null);105 });106};107/**108 * Remove contents from bucket.109 *110 * @public111 *112 * @param {object} contents - Contents to remove from bucket.113 * @param {function} callback - Function executed after removing114 * bucket contents.115 */116Bucket.prototype.removeContents = function (contents, callback) {117 // no contents to remove from bucket118 if (!contents[0]) {119 return callback();120 }121 var Objects = _.map(contents, function (content) {122 return _.pick(content, 'Key');123 });124 this.s3.deleteObjects(this._params({125 Delete: { Objects: Objects }126 }), function (err) {127 callback(err);128 });129};130/**131 * Remove bucket from s3. Contents must first be empty.132 *133 * @public134 *135 * @param {function} callback - Function executed after removing136 * bucket.137 */138Bucket.prototype.removeBucket = function (callback) {139 this.s3.deleteBucket(this._params(), callback);140};141/* -----------------------------------------------------------------------------142 * create143 * ---------------------------------------------------------------------------*/144/**145 * Create bucket suitable to host a static website.146 *147 * @private148 *149 * @param {function} callback - Function executed after creating150 * bucket.151 */152Bucket.prototype.create = function (callback) {153 async.series([154 this.createBucket,155 this.makeWebsite,156 this.makePublic157 ], callback);158};159/**160 * Create bucket on s3.161 *162 * @public163 *164 * @param {function} callback - Function executed after creating165 * bucket.166 */167Bucket.prototype.createBucket = function (callback) {168 this.s3.createBucket(this._params(), callback);169};170/**171 * Configure bucket for website hosting.172 *173 * @public174 *175 * @param {function} callback - Function executed after configuring176 * bucket.177 */178Bucket.prototype.makeWebsite = function (callback) {179 var WebsiteConfiguration = {180 IndexDocument: { Suffix: 'index.html' }181 };182 this.s3.putBucketWebsite(this._params({183 WebsiteConfiguration: WebsiteConfiguration184 }), callback);185};186/**187 * Add bucket policy which makes all bucket contents publicly188 * accessible.189 *190 * @public191 *192 * @param {function} callback - Function executed after setting193 * bucket policy.194 */195Bucket.prototype.makePublic = function (callback) {196 var bucketPolicy = _.clone(policy);197 bucketPolicy.Statement[0].Resource += this.bucketName + '/*';198 this.s3.putBucketPolicy(this._params({199 Policy: JSON.stringify(bucketPolicy)200 }), callback);201};202/* -----------------------------------------------------------------------------203 * upload204 * ---------------------------------------------------------------------------*/205/**206 * Upload src directory to bucket.207 *208 * @public209 *210 * @param {function} callback - Function executed after uploading211 * directory.212 */213Bucket.prototype.upload = function (callback) {214 this.uploadDirectory(this.options.srcPath, callback);215};216/**217 * Upload a directory to s3.218 *219 * @public220 *221 * @param {string} directoryPath - Absolute path of directory to upload.222 * @param {function} callback - Function executed after uploading223 * directory.224 */225Bucket.prototype.uploadDirectory = function (directoryPath, callback) { 226 var readDirectory = _.partial(fs.readdir, directoryPath);227 var uploadContent = _.partial(this.uploadContent);228 async.waterfall([readDirectory, function (files, callback) {229 files = _.map(files, function(file) {230 return path.join(directoryPath, file);231 });232 async.each(files, uploadContent, callback);233 }], callback);234};235/**236 * Upload a file to s3 bucket.237 *238 * @public239 *240 * @param {string} filePath - Absolute path of file to upload.241 * @param {function} callback - Function executed after uploding242 * file.243 */244Bucket.prototype.uploadFile = function (filePath, callback) {245 var fileKey = filePath.replace(this.options.srcPath, '').substr(1);246 fs.readFile(filePath, _.bind(function (err, fileBuffer) {247 var params = this._params({248 Key: fileKey,249 Body: fileBuffer,250 ContentType: mime.lookup(filePath)251 });252 // Remove all browser caching on specified253 // resources254 if (_.contains(this.options.noCache, fileKey)) {255 _.extend(params, {256 CacheControl: 'no-cache, no-store, must-revalidate',257 Expires: (new Date()).toISOString()258 });259 }260 this.s3.putObject(params, callback);261 }, this));262};263/**264 * Wrapper that checks if path represents a file or a265 * directory, and calls an upload method accordingly.266 *267 * @public268 *269 * @param {string} path - Absolute path of content on file system.270 * @param {function} callback - Function passed as callback to271 * corresponding upload method.272 */273Bucket.prototype.uploadContent = function (path, callback) {274 fs.stat(path, _.bind(function (err, stats) {275 if (err) {276 return callback(err);277 }278 return stats.isDirectory()279 ? this.uploadDirectory(path, callback)280 : this.uploadFile(path, callback);281 }, this));282};283/* -----------------------------------------------------------------------------284 * utils285 * ---------------------------------------------------------------------------*/286/**287 * Create bucket name by concatenating specified288 * options (name, env, prefix).289 *290 * @private291 *292 * @parma {object} options - Deploy options.293 */294Bucket.prototype._createBucketName = function (options) {295 var parts = [options.name];296 if (options.env) {297 parts.unshift(options.env);298 }299 if (options.prefix) {300 parts.unshift(options.prefix);301 }302 return parts.join('-');303};304/**305 * Create params for s3 calls. By mixing in required306 * Bucket key with any passed options.307 *308 * @private309 *310 * @param {object} options - Additional params to send to s3.311 */312Bucket.prototype._params = function (options) {313 return _.extend({314 Bucket: this.bucketName315 }, options || {});316};317/* -----------------------------------------------------------------------------318 * export319 * ---------------------------------------------------------------------------*/...

Full Screen

Full Screen

user.js

Source:user.js Github

copy

Full Screen

1/* globals angular, blockchain, lightwallet, web3, _, CryptoJS, openpgp, HookedWeb3Provider, nacl */2angular.module('app').service('user', function userService($q, $rootScope, words, pgp, Key, modals, growl, Affiliate, utils) {3 const user = this4 let keystore5 this.getSeed = function getSeed() {6 if (blockchain.env === 'development') {7 this.data.seed = 'gasp quote useless purity isolate truly scout baby rule nest bridge february'8 }9 return this.data.seed10 }11 this.getKeystore = function getKeystore() {12 if (keystore) {13 return keystore14 }15 const seed = this.getSeed()16 const password = this.password17 if (!seed) {18 throw new Error('Seed not set')19 }20 if (!password) {21 throw new Error('Password not set')22 }23 keystore = new lightwallet.keystore(seed, password)24 keystore.passwordProvider = function passwordProvider(callback) {25 callback(null, password)26 }27 keystore.generateNewAddress(password, 20)28 return keystore29 }30 this.getAccounts = function getAccounts() {31 return this.getKeystore().getAddresses().map((addr) => {32 return utils.hexify(addr)33 })34 }35 this.getData = function getData() {36 if (!this.data) {37 this.data = {}38 }39 return this.data40 }41 this.getAccount = function getAccount() {42 if (!this.getData().account) {43 this.getData().account = this.getAccounts()[0]44 }45 return this.getData().account46 }47 this.setAccount = function setAccount(account) {48 web3.eth.defaultAccount = $rootScope.account = this.getData().account = account49 }50 this.getCurrency = function getCurrency() {51 if (!this.getData().currency) {52 this.getData().currency = 'USD'53 }54 return this.getData().currency55 }56 this.setCurrency = function setCurrency(currency) {57 this.getData().currency = currency58 this.setDisplayCurrencies()59 }60 this.getHiddenCommentIds = function getHiddenCommentIds() {61 if (!this.getData().hiddenCommentIds) {62 this.getData().hiddenCommentIds = []63 }64 return this.getData().hiddenCommentIds65 }66 this.setHiddenCommentIds = function setHiddenCommentIds(hiddenCommentIds) {67 this.getData().hiddenCommentIds = hiddenCommentIds68 }69 this.getBalance = function getBalance() {70 return web3.eth.getBalance(this.getAccount())71 }72 this.getAccountsData = function getAccountsData() {73 if (!this.getData().accounts) {74 this.getData().accounts = {}75 }76 return this.getData().accounts77 }78 this.getAccountData = function getAccountsData() {79 const account = this.getAccount()80 if (!this.getAccountsData()[account]) {81 this.getAccountsData()[account] = {}82 }83 return this.getAccountsData()[account]84 }85 this.getAffiliateCodes = function getAffiliateCodes() {86 if (!this.getAccountData().affiliateCodes) {87 this.getAccountData().affiliateCodes = []88 }89 return this.getAccountData().affiliateCodes90 }91 this.getAffiliates = function getAffiliates() {92 return _.unique(this.getAffiliateCodes()).map((code) => {93 return new Affiliate(code)94 }).filter((affiliate) => {95 return !affiliate.isDeleted && user.getAccount() === affiliate.owner96 })97 }98 this.getOrderAddrs = function getOrderAddrs() {99 if (!this.getAccountData().orderAddrs) {100 this.getAccountData().orderAddrs = []101 }102 return this.getAccountData().orderAddrs103 }104 this.getStoreAddrs = function getStoreAddrs() {105 if (!this.getAccountData().storeAddrs) {106 this.getAccountData().storeAddrs = []107 }108 return this.getAccountData().storeAddrs109 }110 this.getSubmarketAddrs = function getSubmarketAddrs() {111 if (!this.getAccountData().submarketAddrs) {112 this.getAccountData().submarketAddrs = []113 }114 return this.getAccountData().submarketAddrs115 }116 this.getKeypairs = function getKeypairs() {117 if (!this.getAccountData().keypairs) {118 this.getAccountData().keypairs = []119 }120 return this.getAccountData().keypairs121 }122 this.getKeypair = function getKeypair() {123 const account = this.getAccount()124 const keypairs = this.getKeypairs()125 const key = new Key(account)126 return _.find(keypairs, (keypair) => {127 return _.isEqual(keypair.pk, key.pk)128 })129 }130 this.getStorage = function getStorage() {131 return localStorage.getItem('user')132 }133 this.setStorage = function setStorage(string) {134 localStorage.setItem('user', string)135 }136 this.logout = function logout() {137 this.password = null138 keystore = null139 $rootScope.isLoggedIn = false140 window.location.hash = '/login'141 }142 this.register = function register(password) {143 this.password = password144 this.getData().seed = lightwallet.keystore.generateRandomSeed()145 this.save()146 this.init()147 window.location.hash = '/'148 }149 this.setDisplayCurrencies = function setDisplayCurrencies() {150 $rootScope.userCurrency = this.getCurrency()151 $rootScope.displayCurrencies = _.uniq([this.getCurrency(), 'ETH'])152 }153 this.login = function login(password) {154 try {155 this.data = JSON.parse(CryptoJS.AES.decrypt(this.getStorage(), password).toString(CryptoJS.enc.Utf8))156 } catch (e) {157 return false158 }159 this.password = password160 this.init()161 return true162 }163 this.verifyExistence = function verifyExistence() {164 return !! this.getStorage()165 }166 this.reset = function reset() {167 this.data = null168 this.setStorage('')169 $rootScope.userExists = false170 this.logout()171 }172 this.save = function save() {173 this.setStorage(CryptoJS.AES.encrypt(JSON.stringify(this.getData()), this.password))174 }175 this.addKeypair = function addKeypair() {176 const boxKeypair = nacl.box.keyPair()177 const keypair = {178 label: words.generateWordPair(),179 pk: Array.from(boxKeypair.publicKey),180 sk: Array.from(boxKeypair.secretKey),181 timestamp: utils.getTimestamp()182 }183 user.getKeypairs().push(keypair)184 user.save()185 return keypair186 }187 this.addAffiliate = function addAffiliate(code) {188 this.getAffiliateCodes().push(code)189 this.save()190 }191 this.addOrder = function addOrder(addr) {192 this.getOrderAddrs().push(addr)193 $rootScope.orderAddrs = this.getOrderAddrs()194 this.save()195 }196 this.addStore = function addStore(addr) {197 this.getStoreAddrs().push(addr)198 $rootScope.storeAddrs = this.getStoreAddrs()199 this.save()200 }201 this.addSubmarket = function addSubmarket(addr) {202 this.getSubmarketAddrs().push(addr)203 $rootScope.submarketAddrs = this.getSubmarketAddrs()204 this.save()205 }206 this.setRootScopeVars = function setRootScopeVars() {207 $rootScope.orderAddrs = this.getOrderAddrs()208 $rootScope.storeAddrs = this.getStoreAddrs()209 $rootScope.submarketAddrs = this.getSubmarketAddrs()210 this.save()211 }212 this.deleteKeypair = function deleteKeypair(index) {213 user.setKeypairs(this.getKeypairs().splice(index, 1))214 }215 this.verifyKeypair = function verifyKeypair() {216 const currentKey = this.getKeypair()217 if (!currentKey) {218 growl.addErrorMessage('You need to set a primary keypair in the settings menu')219 throw new Error('Primary keypair not set')220 }221 222 }223 this.setProvider = function setProvider() {224 web3.setProvider(new HookedWeb3Provider({225 host: `http://127.0.0.1:${blockchain.rpcport}`,226 transaction_signer: this.getKeystore()227 }))228 }229 this.init = function init() {230 $rootScope.isLoggedIn = true231 this.setAccount(this.getAccount())232 this.setDisplayCurrencies()233 this.setProvider()234 this.setRootScopeVars()235 }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.contains('type').click()4 cy.url().should('include', '/commands/actions')5 cy.get('.action-email')6 .type('

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('My First Test', function() {2 it('Does not do much!', function() {3 cy.contains('type').click()4 cy.get('.action-email').verifyExistence()5 })6})7Cypress.Commands.add('verifyExistence', { prevSubject: true }, (subject) => {8 expect(subject).to.exist9})10import './commands'11module.exports = (on, config) => {12}13describe('My First Test', function() {14 it('Does not do much!', function() {15 cy.contains('type').click()16 cy.get('.action-email').verifyExistence()17 })18})19Cypress.Commands.add('verify

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Verify that the element exists', () => {2 it('Verify that the element exists', () => {3 cy.get('.home-list > :nth-child(1) > .home-list-item').verifyExistence()4 })5})6Cypress.Commands.add('verifyExistence', { prevSubject: true }, (subject) => {7 cy.wrap(subject).should('exist')8})9describe('Verify that the element does not exist', () => {10 it('Verify that the element does not exist', () => {11 cy.get('.home-list > :nth-child(1) > .home-list-item').verifyNonExistence()12 })13})14Cypress.Commands.add('verifyNonExistence', { prevSubject: true }, (subject) => {15 cy.wrap(subject).should('not.exist')16})

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Verify Existence', () => {2 it('Verify Existence', () => {3 cy.get('input[name="q"]').type('Cypress').should('have.value', 'Cypress')4 cy.get('input[name="btnK"]').click()5 .should('be.visible')6 .and('have.attr', 'href')7 .and('include', 'cypress')8 })9})10Cypress.Commands.add('verifyExistence', (selector, text) => {11 cy.get(selector).should('be.visible').and('have.text', text)12})13describe('Verify Existence', () => {14 it('Verify Existence', () => {15 cy.get('input[name="q"]').type('Cypress').should('have.value', 'Cypress')16 cy.get('input[name="btnK"]').click()17 .should('be.visible')18 .and('have.attr', 'href')19 .and('include', 'cypress')20 })21})22Cypress.Commands.add('verifyExistence', (selector, text) => {23 cy.get(selector).should('be.visible').and('have.text', text)24})25describe('Verify Existence', () => {26 it('Verify Existence', () => {27 cy.get('input[name="q"]').type('Cypress').should('have.value', 'Cypress')28 cy.get('input[name="btnK"]').click()29 .should('be.visible')30 .and('have.attr', 'href')

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test', () => {2 it('test', () => {3 cy.get('input[name="q"]').type('Hello World{enter}')4 cy.get('input[name="q"]').verifyExistence()5 })6})7Cypress.Commands.add('verifyExistence', { prevSubject: true }, (subject) => {8 cy.wrap(subject).should('exist')9})10TypeError: (0 , _cypress2.add) is not a function11 at Object.<anonymous> (cypress/support/commands.js:3:19)12 at Object.<anonymous> (cypress/support/index.js:1:1)13 at Object.<anonymous> (cypress/integration/test.js:1:1)14 at Object.<anonymous> (cypress/integration/index.js:1:1)15 at Object.<anonymous> (cypress/plugins/index.js:1:1)16 at Object.<anonymous> (cypress/plugins/index.js:1:1)17 at Object.<anonymous> (cypress/support/index.js:1:1)18 at Object.<anonymous> (cypress/support/index.js:1:1)19 at Object.<anonymous> (cypress/integration/test.js:1:1)20 at Object.<anonymous> (cypress/integration/test.js:1:1)21 at Object.<anonymous> (cypress/integration/index.js:1:1)22 at Object.<anonymous> (cypress/integration/index.js:1:1)23 at Object.<anonymous> (cypress/plugins/index.js:1:1)24 at Object.<anonymous> (cypress/plugins/index.js:1:1)25 at Object.<anonymous> (cypress/support/index.js:1:1)26 at Object.<anonymous> (cypress/support/index.js:1:1)27 at Object.<anonymous> (cypress/integration/test.js:1:1)28 at Object.<anonymous> (cypress/integration/test.js:1:1)29 at Object.<anonymous> (cypress/integration/index.js:1:1)30 at Object.<anonymous> (cypress/integration/index.js:1:1)31 at Object.<anonymous> (cypress/plugins/index.js:1:1)

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Test Case 1', function() {2 it('Test Case 1.1', function() {3 cy.get('#hplogo').should('be.visible');4 cy.get('#hplogo').verifyExistence();5 });6});7Cypress.Commands.add('verifyExistence', { prevSubject: 'element' }, (subject) => {8 cy.log('Verify existence of element');9 cy.wrap(subject).should('be.visible');10});11{12 "env": {13 },14}

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('test', () => {2 it('test', () => {3 cy.get('#hplogo').verifyExistence()4 })5})6Cypress.Commands.add('verifyExistence', function () {7 cy.get(this).should('exist')8})9declare namespace Cypress {10 interface Chainable<Subject> {11 verifyExistence(): Chainable<Subject>12 }13}14"compilerOptions": {15}16{17}18{19}20{21}22{23}24{25}26{27}28{29}30{

Full Screen

Cypress Tutorial

Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful