it('should fail if the artifact is too large', async () => {
   const artifactRequest = nock(BASE_URL).get(ARTIFACT_PATH).reply(200, ARTIFACT_CONTENTS);
   retriever = new BuildRetriever(api, 10, DOWNLOAD_DIR);
   try {
     await retriever.downloadBuildArtifact(12345, 777, 'COMMIT', ARTIFACT_PATH);
     throw new Error('Exception Expected');
   } catch (error) {
     expect(error.status).toEqual(413);
   }
   artifactRequest.done();
 });
 it('should fail if the URL fetch 404s',  async () => {
   // create a new handler that errors
   const artifactRequest = nock(BASE_URL).get(ARTIFACT_PATH).reply(404, 'No such artifact');
   try {
     await retriever.downloadBuildArtifact(12345, 777, 'COMMIT', ARTIFACT_PATH);
     throw new Error('Exception Expected');
   } catch (error) {
     expect(error.message).toEqual('CircleCI artifact download failed (Error 404 - Not Found)');
   }
   artifactRequest.done();
 });
  it("should add required Vary headers to the response", async () => {
    nock(cloudRunApiOrigin)
      .get("/v1alpha1/projects/project-foo/locations/us-central1/services/helloworld")
      .reply(200, { status: { address: { hostname: cloudRunServiceOrigin } } });
    nock(cloudRunServiceOrigin)
      .get("/vary")
      .reply(200, "live vary version", { vary: "Other, Authorization" });

    const mwGenerator = await cloudRunProxy(fakeOptions);
    const mw = await mwGenerator(fakeRewrite);
    const spyMw = sinon.spy(mw);

    return supertest(spyMw)
      .get("/vary")
      .expect(200, "live vary version")
      .then((res) => {
        expect(spyMw.calledOnce).to.be.true;
        expect(res.header.vary).to.equal("Other, Authorization, Accept-Encoding, Cookie");
      });
  });
 it('should return a single response object for single requests', async () => {
   nock(Utils.baseUrl, {allowUnmocked: true})
       .post('/urlshortener/v1/url')
       .times(2)
       .replyWithFile(
           200,
           path.join(
               __dirname, '../../test/fixtures/urlshort-insert-res.json'));
   await testInsert(localUrlshortener);
   await testInsert(remoteUrlshortener);
 });
 it('should allow overriding validateStatus', async () => {
   const scope = nock(Utils.baseUrl).get('/drive/v2/files').reply(500);
   const google = new GoogleApis();
   const drive = google.drive('v2');
   const res = await drive.files.list({}, {
     validateStatus: (status: number) => {
       return true;
     }
   });
   assert.equal(res.status, 500);
 });
 it('should upload a video', async () => {
   const scope =
       nock(Utils.baseUrl)
           .post(
               `/upload/youtube/v3/videos?part=id%2Csnippet%2Cstatus&notifySubscribers=false&uploadType=multipart`)
           .reply(200, {kind: 'youtube#video'});
   const data = await samples.upload.runSample(someFile);
   assert(data);
   assert.strictEqual(data.kind, 'youtube#video');
   scope.done();
 });
util.setupExpectedWSTrustRequestCommon = function () {
  var RSTRDoc = fs.readFileSync(parameters.RSTRFile, 'utf8');
  var wstrustRequest = nock(parameters.adfsUrlNoPath)
    .filteringRequestBody(function () { return '*'; })
    .post(parameters.adfsWsTrustPath, '*')
    .reply(200, RSTRDoc);

  util.matchStandardRequestHeaders(wstrustRequest);

  return wstrustRequest;
};
Example #8
0
 it('sould call callback with value', done => {
   const endpoint = 'tag/sunset';
   nock('https://api.instagram.com')
     .get(`/v1/${endpoint}`)
     .query({ access_token: 'toto' })
     .reply(200, { message: 'success' });
   (instagram as any).request('GET', endpoint, (_, result) => {
     expect(result).toMatchSnapshot();
     done();
   });
 });
 async () => {
   nock(Utils.baseUrl)
       .post('/upload/drive/v2/files?uploadType=multipart')
       .times(2)
       .reply(201, (uri: string, reqBody: {}) => {
         return reqBody;  // return request body as response
                          // for testing purposes
       });
   await testMultpart(localDrive);
   await testMultpart(remoteDrive);
 });
    it('should set loading status as expected', function () {
      const scope = nock(BASE_URL).get('/api/settings').reply(200);
      const promise = store.load()
        .then(() => {
          scope.done();
          expect(store.loading).to.be.false;
        });

      expect(store.loading).to.be.true;
      return promise;
    });
 it('should revoke credentials if access token present', async () => {
   const scope = nock('https://accounts.google.com')
                     .get('/o/oauth2/revoke?token=abc')
                     .reply(200, {success: true});
   const oauth2client =
       new googleapis.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);
   oauth2client.credentials = {access_token: 'abc', refresh_token: 'abc'};
   const res = await oauth2client.revokeCredentials();
   assert.equal(res.data.success, true);
   assert.equal(JSON.stringify(oauth2client.credentials), '{}');
 });
        it("writes the consumer and provider details into the pact", () => {
          nock(mock.baseUrl)
            .post(/pact$/, {
              consumer: { name: "aconsumer" },
              pactfile_write_mode: "overwrite",
              provider: { name: "aprovider" },
            })
            .reply(200)

          return expect(mock.writePact()).to.eventually.be.fulfilled
        })
 it('should generate valid multipart upload if media and metadata are both set', async () => {
   nock(Utils.baseUrl)
     .post('/upload/drive/v2/files?uploadType=multipart')
     .times(2)
     .reply(201, (uri: string, reqBody: {}) => {
       return reqBody; // return request body as response
       // for testing purposes
     });
   await testMultpart(localDrive);
   await testMultpart(remoteDrive);
 });
Example #14
0
 it("resolves when request succeeds with response body", () => {
   const body = "body"
   nock(url)
     .get("/")
     .reply(200, body)
   const p = request.send(HTTPMethod.GET, url)
   return Promise.all([
     expect(p).to.be.fulfilled,
     expect(p).to.eventually.be.equal(body),
   ])
 })
Example #15
0
    it('should parse the response body into an object using \'JSON.parse\'', done => {
      const requestHandler = nock('https://api.github.com')
        .intercept('/path', 'method')
        .reply(300, '{"foo": "bar"}');

      (api as any).request('method', '/path').then((data: any) => {
        expect(data).toEqual({foo: 'bar'});
        done();
      });
      requestHandler.done();
    });
Example #16
0
 it('sould overwrite access_token in query', async () => {
   const endpoint = 'tag/sunset';
   nock('https://api.instagram.com')
     .get(`/v1/${endpoint}`)
     .query({ access_token: 'titi' })
     .reply(200, { message: 'success' });
   const result = await (instagram as any).request('GET', endpoint, {
     accessToken: 'titi',
   });
   expect(result).toMatchSnapshot();
 });
Example #17
0
    it('should reject if the response text is malformed JSON', done => {
      const requestHandler = nock('https://api.github.com')
        .intercept('/path', 'method')
        .reply(300, '}');

      (api as any).request('method', '/path').catch((err: any) => {
        expect(err).toEqual(jasmine.any(SyntaxError));
        done();
      });
      requestHandler.done();
    });
Example #18
0
 it('sould call callback with error', done => {
   const endpoint = 'tag/sunset';
   nock('https://api.instagram.com')
     .get(`/v1/${endpoint}`)
     .query({ access_token: 'toto' })
     .reply(400, { message: 'error' });
   (instagram as any).request('GET', endpoint, err => {
     expect(err).toMatchSnapshot();
     done();
   });
 });
export function oauth2(validator?: Validator): nock.Scope {
  validator = validator || accept;
  return nock('https://oauth2.googleapis.com')
    .post('/token', validator)
    .once()
    .reply(200, {
      refresh_token: 'hello',
      access_token: 'goodbye',
      expiry_date: new Date(9999, 1, 1),
    });
}
 it('should append values', async () => {
   const range = 'A1:A10';
   const scope = nock(baseUrl)
                     .post(`/v4/spreadsheets/aSheetId/values/${
                         encodeURIComponent(
                             range)}:append?valueInputOption=USER_ENTERED`)
                     .reply(200, {});
   const data = await samples.append.runSample('aSheetId', 'A1:A10');
   assert(data);
   scope.done();
 });
async function testKeyParam(drive: APIEndpoint) {
  nock(Utils.baseUrl)
    .get('/drive/v2/files/123?key=abc123')
    .reply(200);
  const res = await drive.files.get({
    fileId: '123',
    auth: 'API KEY',
    key: 'abc123',
  });
  assert.strictEqual(Utils.getQs(res), 'key=abc123');
}
  it("should remove cookies on non-private cached responses", async () => {
    nock(cloudRunApiOrigin)
      .get("/v1alpha1/projects/project-foo/locations/us-central1/services/helloworld")
      .reply(200, { status: { address: { hostname: cloudRunServiceOrigin } } });
    nock(cloudRunServiceOrigin)
      .get("/cached")
      .reply(200, "cached page", { "cache-control": "custom", "set-cookie": "nom" });

    const mwGenerator = await cloudRunProxy(fakeOptions);
    const mw = await mwGenerator(fakeRewrite);
    const spyMw = sinon.spy(mw);

    return supertest(spyMw)
      .get("/cached")
      .expect(200, "cached page")
      .then((res) => {
        expect(spyMw.calledOnce).to.be.true;
        expect(res.header["set-cookie"]).to.be.undefined;
      });
  });
async function testGzip(drive: APIEndpoint) {
  nock(Utils.baseUrl)
    .get('/drive/v2/files', undefined, {
      reqheaders: {'Accept-Encoding': 'gzip'},
    })
    .reply(200, {});
  const res = await drive.files.list();
  assert.deepStrictEqual(res.data, {});
  // note: axios strips the `content-encoding` header from the response,
  // so that cannot be checked here.
}
  it("should resolve to a live version in another region", async () => {
    const cloudRunServiceOriginAsia = "https://helloworld-hash-as.a.run.app";
    nock(cloudRunApiOrigin)
      .get("/v1alpha1/projects/project-foo/locations/asia-southeast1/services/helloworld")
      .reply(200, { status: { address: { hostname: cloudRunServiceOriginAsia } } });
    nock(cloudRunServiceOriginAsia)
      .get("/")
      .reply(200, "live version");

    const mwGenerator = await cloudRunProxy(fakeOptions);
    const mw = await mwGenerator({ run: { serviceId: "helloworld", region: "asia-southeast1" } });
    const spyMw = sinon.spy(mw);

    return supertest(spyMw)
      .get("/")
      .expect(200, "live version")
      .then(() => {
        expect(spyMw.calledOnce).to.be.true;
      });
  });
Example #25
0
 it('should fail if file write fails',  async () => {
   const artifactRequest = nock(BASE_URL).get(ARTIFACT_PATH).reply(200, ARTIFACT_CONTENTS);
   try {
     WRITEFILE_RESULT = 'Test Error';
     await retriever.downloadBuildArtifact(12345, 777, 'COMMIT', ARTIFACT_PATH);
     throw new Error('Exception Expected');
   } catch (error) {
     expect(error.message).toEqual('CircleCI artifact download failed (Test Error)');
   }
   artifactRequest.done();
 });
 it("should return subpaths from shallow get request", async () => {
   nock(serverUrl)
     .get("/.json")
     .query({ shallow: true, limitToFirst: "1234" })
     .reply(200, {
       a: true,
       x: true,
       f: true,
     });
   await expect(remote.listPath("/", 1234)).to.eventually.eql(["a", "x", "f"]);
 });
async function testNoAccessToken(
    drive: APIEndpoint, oauth2client: OAuth2Client, now: number) {
  nock(Utils.baseUrl).get('/drive/v2/files/wat').reply(200);
  await drive.files.get({fileId: 'wat', auth: oauth2client});
  const expiryDate = oauth2client.credentials.expiry_date;
  assert.notEqual(expiryDate, undefined);
  assert(expiryDate! > now);
  assert(expiryDate! < now + 4000);
  assert.strictEqual(oauth2client.credentials.refresh_token, 'abc');
  assert.strictEqual(oauth2client.credentials.access_token, 'abc123');
}
  it('should set text/plain when passed a string as media body', async () => {
    nock(Utils.baseUrl)
        .post('/upload/drive/v2/files?uploadType=multipart')
        .times(2)
        .reply(201, (uri: string, reqBody: {}) => {
          return reqBody;  // return request body as response for
                           // testing purposes
        });

    await testMediaBody(localDrive);
    await testMediaBody(remoteDrive);
  });
 async () => {
   nock(Utils.baseUrl)
       .post('/upload/drive/v2/files?uploadType=media')
       .times(2)
       .reply(200, {fileId: 'abc123'});
   const res = await localDrive.files.insert({media: {body: 'hello'}});
   assert.strictEqual(
       JSON.stringify(res.data), JSON.stringify({fileId: 'abc123'}));
   const res2 = await remoteDrive.files.insert({media: {body: 'hello'}});
   assert.strictEqual(
       JSON.stringify(res2.data), JSON.stringify({fileId: 'abc123'}));
 });
  it('should set access token type to Bearer if none is set', async () => {
    const oauth2client =
        new googleapis.auth.OAuth2(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI);
    oauth2client.credentials = {access_token: 'foo', refresh_token: ''};
    const scope = nock(Utils.baseUrl)
                      .get('/urlshortener/v1/url/history')
                      .times(2)
                      .reply(200);

    await testNoBearer(localUrlshortener, oauth2client);
    await testNoBearer(remoteUrlshortener, oauth2client);
  });