it('allows for id to be provided', () => {
      const attributes = { foo: 'Foo', bar: 'Bar' };
      const url = `${basePath}/api/saved_objects/index-pattern/myId`;
      $http.withArgs({
        method: 'POST',
        url,
        data: sinon.match.any
      }).returns(Promise.resolve({ data: 'api-response' }));

      savedObjectsClient.create('index-pattern', attributes, { id: 'myId' });

      sinon.assert.calledOnce($http);
      sinon.assert.calledWithExactly($http, sinon.match({
        url
      }));
    });
Example #2
0
			it('should throw an error', () => {
				const readStream = stream.Readable()
				sandbox.stub(cache, 'read').returns(readStream)
				const expectedError = new Error()

				const next = sandbox.stub()
				const error = sandbox.stub()
				const complete = sandbox.stub()

				cache.extract().subscribe(next, error, complete)
				readStream.emit('error', expectedError)

				sinon.assert.notCalled(next)
				sinon.assert.notCalled(complete)
				sinon.assert.calledOnce(error)
				sinon.assert.calledWithExactly(error, expectedError)
			})
	it('the context1 should be isolated inside server', function(){
			sinon.assert.calledOnce(fn1);
			expect(fn1.getCall(0).args[1]).to.have.property('outerContext', true);
			expect(fn1.getCall(0).args[1]).to.not.have.property('innerContext');
			sinon.assert.calledOnce(fn2);
			expect(fn2.getCall(0).args[1]).to.have.property('outerContext', true);
			expect(fn2.getCall(0).args[1]).to.have.property('innerContext', true);
			sinon.assert.calledOnce(fn3);
			sinon.assert.calledOnce(fn4);
			expect(fn4.getCall(0).args[1]).to.have.property('outerContext', true);
			expect(fn4.getCall(0).args[1]).to.have.property('innerContext', true);
			sinon.assert.calledOnce(fn5);
			expect(fn5.getCall(0).args[1]).to.have.property('outerContext', true);
			expect(fn5.getCall(0).args[1]).to.not.have.property('innerContext');

			sinon.assert.calledWithExactly(finish, data1);
	})
Example #4
0
    it('passes the parameters to callAdminCluster', async () => {
      callAdminCluster.returns({
        result: 'deleted'
      });
      await savedObjectsRepository.delete('index-pattern', 'logstash-*');

      sinon.assert.calledOnce(callAdminCluster);
      sinon.assert.calledWithExactly(callAdminCluster, 'delete', {
        type: 'doc',
        id: 'index-pattern:logstash-*',
        refresh: 'wait_for',
        index: '.kibana-test',
        ignore: [404],
      });

      sinon.assert.calledOnce(onBeforeWrite);
    });
Example #5
0
  it('returns wrapped original error when `authenticate` fails to authenticate user', async () => {
    const esError = Boom.badRequest('some message');
    server.plugins.security.authenticate.withArgs(request).returns(
      Promise.resolve(AuthenticationResult.failed(esError))
    );

    const response = await authenticate(request, h);

    sinon.assert.calledWithExactly(
      server.log,
      ['info', 'authentication'],
      'Authentication attempt failed: some message'
    );
    expect(response).to.eql(esError);
    sinon.assert.notCalled(h.redirect);
    sinon.assert.notCalled(h.authenticated);
  });
        it('should send BAD_MESSAGE on validation error', () => {
            let invalidMessage = {
                    type: MessageType.JOIN_BOT.name,
                    data: {}
                },
                webSocketStub = {
                    on: (type, givenMessageHandler) => {
                        givenMessageHandler(JSON.stringify(invalidMessage));
                    }
                },
                messageHandlerSpy = sinon.spy();

            ClientCommunication.on(webSocketStub, MessageType.JOIN_BOT, messageHandlerSpy);

            sinon.assert.notCalled(messageHandlerSpy);
            sinon.assert.calledWithExactly(sendSpy, webSocketStub, MessageType.BAD_MESSAGE.name, sinon.match.object);
        });
    it('should log a message for upgrades', async () => {
      const { getUpgradeableConfig, logWithMetadata, run } = setup();

      getUpgradeableConfig
        .returns({ id: prevVersion, attributes: { buildNum: buildNum - 100 } });

      await run();
      sinon.assert.calledOnce(logWithMetadata);
      sinon.assert.calledWithExactly(logWithMetadata,
        ['plugin', 'elasticsearch'],
        sinon.match('Upgrade'),
        sinon.match({
          prevVersion,
          newVersion: version,
        })
      );
    });
    it("should call provided submit handler with form state", () => {
      const schema = {
        type: "object",
        properties: {
          foo: {type: "string"},
        }
      };
      const formData = {
        foo: "bar"
      };
      const onSubmit = sandbox.spy();
      const {comp, node} = createComponent({schema, formData, onSubmit});

      Simulate.submit(node);

      sinon.assert.calledWithExactly(onSubmit, comp.state);
    });
Example #9
0
    it('reads the mapping for the indexName', async () => {
      const indexName = chance.word();
      const mappings = createRandomMappings();
      const callCluster = createCallCluster(createIndex(indexName, mappings));
      await patchKibanaIndex({
        callCluster,
        indexName,
        kibanaIndexMappingsDsl: mappings,
        log: sinon.stub()
      });

      sinon.assert.calledOnce(callCluster);
      sinon.assert.calledWithExactly(callCluster, 'indices.getMapping', sinon.match({
        ignore: [404],
        index: indexName,
      }));
    });
 browserStackTunnel.start(function (error) {
   if (error) {
     expect().fail(function () { return error; });
   } else if (browserStackTunnel.state === 'started') {
     sinon.assert.calledOnce(spawnSpy);
     sinon.assert.calledWithExactly(
       spawnSpy,
       WIN32_BINARY_FILE, [
         KEY,
         HOST_NAME + ',' + PORT + ',' + SSL_FLAG,
         '-tunnelIdentifier',
         'my_tunnel'
       ]
     );
     done();
   }
 });
Example #11
0
    it('returns 400 for AJAX requests that can not handle redirect.', async () => {
      const request = requestFixture({ headers: { 'kbn-xsrf': 'xsrf' } });

      await logoutRoute.handler(request, replyStub);

      sinon.assert.calledOnce(replyStub);
      sinon.assert.calledWithExactly(
        replyStub,
        sinon.match({
          isBoom: true,
          message: 'Client should be able to process redirect response.',
          output: { statusCode: 400 }
        })
      );
      sinon.assert.notCalled(replyStub.continue);
      sinon.assert.notCalled(replyStub.redirect);
    });
 browserStackTunnel.start(function (error) {
   if (error) {
     expect().fail(function () { return error; });
   } else if (browserStackTunnel.state === 'started') {
     sinon.assert.calledOnce(spawnSpy);
     sinon.assert.calledWithExactly(
       spawnSpy,
       WIN32_BINARY_FILE, [
         KEY,
         '--only',
         HOST_NAME + ',' + PORT + ',' + SSL_FLAG,
         '--enable-logging-for-api'
       ]
     );
     done();
   }
 });
    it('calls limit and returns a query object', function () {
      var queryOptions = {
        limit: '1'
      }

      var result = buildQuery({})(query, queryOptions)

      sinon.assert.calledOnce(query.limit)
      sinon.assert.calledWithExactly(query.limit, queryOptions.limit)
      sinon.assert.notCalled(query.where)
      sinon.assert.notCalled(query.skip)
      sinon.assert.notCalled(query.sort)
      sinon.assert.notCalled(query.select)
      sinon.assert.notCalled(query.populate)
      sinon.assert.notCalled(query.distinct)
      assert.equal(result, query)
    })
    it('calls skip and returns a query object', () => {
      let queryOptions = {
        skip: '1'
      }

      let result = buildQuery({})(query, queryOptions)

      sinon.assert.calledOnce(query.skip)
      sinon.assert.calledWithExactly(query.skip, queryOptions.skip)
      sinon.assert.notCalled(query.where)
      sinon.assert.notCalled(query.limit)
      sinon.assert.notCalled(query.sort)
      sinon.assert.notCalled(query.select)
      sinon.assert.notCalled(query.populate)
      sinon.assert.notCalled(query.distinct)
      assert.equal(result, query)
    })
Example #15
0
 it("should split the auth if it's openID", () => {
   const setupClient = sandbox.spy(clientUtils, "setupClient");
   const authData = {
     server: "http://server.test/v1",
     authType: "openid-google",
     credentials: { token: "the token" },
   };
   action = actions.getServerInfo(authData);
   getServerInfo = saga.getServerInfo(getState, action);
   getServerInfo.next();
   sinon.assert.calledWithExactly(setupClient, {
     authType: "openid",
     provider: "google",
     server: "http://server.test/v1",
     credentials: { token: "the token" },
   });
 });
    it('parses a string to exclude fields', () => {
      let req = {
        query: {
          select: '-foo'
        }
      }

      prepareQuery(options)(req, {}, next)

      assert.deepEqual(req._ermQueryOptions, {
        select: {
          foo: 0
        }
      })
      sinon.assert.calledOnce(next)
      sinon.assert.calledWithExactly(next)
      sinon.assert.notCalled(options.onError)
    })
Example #17
0
            function(err, bs) {
                var emitterStub = sinon.spy(bs.emitter, "emit");

                browserSync.reload("*.css");

                scheduler.advanceTo(500);

                sinon.assert.calledWithExactly(emitterStub, "file:changed", {
                    path: "*.css",
                    basename: "*.css",
                    log: true,
                    namespace: "core",
                    event: "change",
                    ext: "css"
                });

                bs.cleanup(done);
            }
Example #18
0
    it('should transform settings when determining what is unused', async function () {
      sandbox.spy(transformDeprecationsNS, 'transformDeprecations');

      const settings = {
        foo: 1
      };

      const { callCompleteMixin } = setup({
        settings,
        configValues: {
          ...settings
        }
      });

      await callCompleteMixin();
      sinon.assert.calledOnce(transformDeprecations);
      sinon.assert.calledWithExactly(transformDeprecations, settings);
    });
Example #19
0
    it('returns 401 if authentication fails.', async () => {
      const failureReason = new Error('Something went wrong.');
      authenticateStub.returns(Promise.resolve(AuthenticationResult.failed(failureReason)));

      await loginRoute.handler(request, replyStub);

      sinon.assert.notCalled(replyStub.continue);
      sinon.assert.calledOnce(replyStub);

      sinon.assert.calledWithExactly(
        replyStub,
        sinon.match({
          isBoom: true,
          message: failureReason.toString(),
          output: { statusCode: 401 },
        })
      );
    });
  it('calls outputFn with default options and no post* middleware', () => {
    let req = {
      method: 'GET',
      erm: {}
    }

    let options = {
      onError: onError,
      outputFn: outputFn
    }

    prepareOutput(options)(req, {}, next)

    sinon.assert.calledOnce(outputFn)
    sinon.assert.calledWithExactly(outputFn, req, {})
    sinon.assert.notCalled(onError)
    sinon.assert.notCalled(next)
  })
    it('parses a string to populate a path', () => {
      let req = {
        query: {
          populate: 'foo'
        }
      }

      prepareQuery(options)(req, {}, next)

      assert.deepEqual(req._ermQueryOptions, {
        populate: [{
          path: 'foo'
        }]
      })
      sinon.assert.calledOnce(next)
      sinon.assert.calledWithExactly(next)
      sinon.assert.notCalled(options.onError)
    })
Example #22
0
    it('passes the parameters to callAdminCluster', async () => {
      await savedObjectsRepository.update('index-pattern', 'logstash-*', { title: 'Testing' });

      sinon.assert.calledOnce(callAdminCluster);
      sinon.assert.calledWithExactly(callAdminCluster, 'update', {
        type: 'doc',
        id: 'index-pattern:logstash-*',
        version: undefined,
        body: {
          doc: { updated_at: mockTimestamp, 'index-pattern': { title: 'Testing' } }
        },
        ignore: [404],
        refresh: 'wait_for',
        index: '.kibana-test'
      });

      sinon.assert.calledOnce(onBeforeWrite);
    });
Example #23
0
test('start should start daemon', (t) => {
  const node = process.execPath
  const daemonFile = path.join(__dirname, '../../src/daemon')
  const daemonLog = path.resolve(untildify('~/.hotel/daemon.log'))

  cli(['', '', 'start'])

  sinon.assert.calledWithExactly(
    userStartup.create,
    'hotel', node, [daemonFile], daemonLog
  )

  t.is(
    fs.readFileSync(common.startupFile, 'utf-8'),
    userStartup.getFile('hotel'),
    'startupFile should point to startup file path'
  )
})
    it('converts > to $gt', () => {
      let req = {
        query: {
          query: '{"foo":">bar"}'
        }
      }

      prepareQuery(options)(req, {}, next)

      assert.deepEqual(req._ermQueryOptions, {
        query: {
          foo: { $gt: 'bar' }
        }
      })
      sinon.assert.calledOnce(next)
      sinon.assert.calledWithExactly(next)
      sinon.assert.notCalled(options.onError)
    })
Example #25
0
      it('iterates all values from the generator, even if one is already "resolved"', () => {
        let yieldCount = 0;
        function *gen() {
          yieldCount += 1;
          yield 1;
          yieldCount += 1;
          yield new Promise(resolve => setTimeout(resolve, 200, 2));
        }

        const onResolve = sinon.stub();
        Promise.race(gen()).then(onResolve);

        tick(200);

        sinon.assert.calledOnce(onResolve);
        sinon.assert.calledWithExactly(onResolve, 1);
        expect(yieldCount).to.be(2);
      });
    it('converts ~ to undefined', () => {
      let req = {
        query: {
          query: '{"foo":"~bar"}'
        }
      }

      options.allowRegex = false

      prepareQuery(options)(req, {}, next)

      assert.deepEqual(req._ermQueryOptions, {
        query: {}
      })
      sinon.assert.calledOnce(next)
      sinon.assert.calledWithExactly(next)
      sinon.assert.notCalled(options.onError)
    })
Example #27
0
    it('correctly setups Hapi plugin.', async () => {
      config.get.withArgs('xpack.security.cookieName').returns('cookie-name');
      config.get.withArgs('xpack.security.encryptionKey').returns('encryption-key');
      config.get.withArgs('xpack.security.secureCookies').returns('secure-cookies');
      config.get.withArgs('server.basePath').returns('base/path');

      await Session.create(server);

      sinon.assert.calledOnce(server.auth.strategy);
      sinon.assert.calledWithExactly(server.auth.strategy, 'security-cookie', 'cookie', false, {
        cookie: 'cookie-name',
        password: '******',
        clearInvalid: true,
        validateFunc: sinon.match.func,
        isSecure: 'secure-cookies',
        path: 'base/path/'
      });
    });
    it('converts ~ to a case insensitive regex', () => {
      let req = {
        query: {
          query: '{"foo":"~bar"}'
        }
      }

      prepareQuery(options)(req, {}, next)

      assert.deepEqual(req._ermQueryOptions, {
        query: {
          foo: new RegExp('bar', 'i')
        }
      })
      sinon.assert.calledOnce(next)
      sinon.assert.calledWithExactly(next)
      sinon.assert.notCalled(options.onError)
    })
    it('passes `server` and `options` argument to factory', () => {
      const { decorations, server } = setup();
      expect(decorations.server).to.have.property('uiSettingsServiceFactory').a('function');

      sandbox.stub(uiSettingsServiceFactoryNS, 'uiSettingsServiceFactory');
      sinon.assert.notCalled(uiSettingsServiceFactory);
      decorations.server.uiSettingsServiceFactory({
        foo: 'bar'
      });
      sinon.assert.calledOnce(uiSettingsServiceFactory);
      sinon.assert.calledWithExactly(uiSettingsServiceFactory, server, {
        foo: 'bar',
        overrides: {
          foo: 'bar'
        },
        getDefaults: sinon.match.func,
      });
    });
Example #30
0
  it('returns `unauthorized` when authentication can not be handled', async () => {
    server.plugins.security.authenticate.withArgs(request).returns(
      Promise.resolve(AuthenticationResult.notHandled())
    );

    await authenticate(request, reply);

    sinon.assert.calledWithExactly(
      reply,
      sinon.match({
        isBoom: true,
        message: 'Unauthorized',
        output: { statusCode: 401 },
      })
    );
    sinon.assert.notCalled(reply.redirect);
    sinon.assert.notCalled(reply.continue);
  });