http-status-codes#StatusCodes TypeScript Examples

The following examples show how to use http-status-codes#StatusCodes. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HttpResponseError.test.ts    From abacus with GNU General Public License v2.0 6 votes vote down vote up
describe('HttpResponseError.ts module', () => {
  describe('wretcherErrorToHttpResponseError', () => {
    it('should return a correct HttpResponseError', () => {
      const error: WretcherError = new Error() as WretcherError
      error.status = StatusCodes.NOT_FOUND
      ;(error.response as unknown) = { statusText: 'Not Found' }
      error.message = 'Not Found'
      error.json = { foo: 'bar' }
      const httpResponseError = wretcherErrorToHttpResponseError(error)
      expect(httpResponseError).toBeInstanceOf(HttpResponseError)
      expect(httpResponseError).toMatchInlineSnapshot(`[HttpResponseError: 404 Not Found]`)
    })
  })

  describe('serverErrorMessage', () => {
    it('should return an empty message for an unknown error', () => {
      const error = new Error()
      expect(serverErrorMessage(error)).toBe('')
    })

    it('should return a correct error message', () => {
      const error = new HttpResponseError(StatusCodes.BAD_REQUEST)
      expect(serverErrorMessage(error)).toMatchInlineSnapshot(`"Response Error [400]: No server message"`)
      error.json = { code: 'invalid_name', message: 'The experiment name is already taken', data: { status: 400 } }
      expect(serverErrorMessage(error)).toMatchInlineSnapshot(
        `"Response Error [400]: The experiment name is already taken"`,
      )
    })
  })
})
Example #2
Source File: api-key.ts    From integration-services with Apache License 2.0 6 votes vote down vote up
hasValidApiKey = (serverApiKey: string) => (req: Request, res: Response, next: NextFunction) => {
	const decodeParam = (param: string): string | undefined => (param ? decodeURI(param) : undefined);
	const apiKey = req.query && decodeParam(<string>req.query['api-key']);

	if (serverApiKey && apiKey !== serverApiKey) {
		return res.status(StatusCodes.UNAUTHORIZED).send({ error: 'no valid api key provided!' });
	}

	next();
}
Example #3
Source File: response-handler.ts    From node-boilerplate with Apache License 2.0 6 votes vote down vote up
function send(res: Response): void {
    let obj = {};
    obj = res.locals.data;
    if(environment.isProductionEnvironment()) {
        logger.info(JSON.stringify(obj, null, 2));
    }
    if(environment.applyEncryption) {
        obj = encrypt(JSON.stringify(obj), environment.secretKey);
    }
    res.status(StatusCodes.OK).send(obj);
}
Example #4
Source File: review.ts    From approveman with MIT License 6 votes vote down vote up
approveChange = async (context: Context<"pull_request.opened" | "pull_request.reopened" | "pull_request.synchronize">): Promise<void> => {
  const req = context.repo({
    "event": "APPROVE" as ReviewEvent,
    "pull_number": context.payload.pull_request.number,
  });
  context.log.trace(`Reviewing PR with request ${JSON.stringify(req)}`);
  try {
    const res = await context.octokit.pulls.createReview(req);
    if (res.status === StatusCodes.OK) {
      context.log.trace("Approve changes succeeded.");
    } else {
      context.log.error(
        `Approve change rejected with: ${JSON.stringify(res.data)}`,
      );
    }
  } catch (err) {
    context.log.error(`Approve change failed with: ${JSON.stringify(err)}`);
  }
}
Example #5
Source File: AutocompleteApi.test.ts    From abacus with GNU General Public License v2.0 5 votes vote down vote up
test('a nonexistent event name returns a useful error message', async () => {
  mockedUtils.fetchApi.mockImplementation(async () => {
    throw new HttpResponseError(StatusCodes.NOT_FOUND)
  })
  expect(await getPropNameCompletions('no_exist')).toMatchInlineSnapshot(`null`)
})
Example #6
Source File: api-error-factory.ts    From selling-partner-api-sdk with MIT License 5 votes vote down vote up
export function apiErrorFactory(error: AxiosError): ExtendableError {
  const { response, code, message } = error

  if (response) {
    const { headers, data, status } = response

    if (isAPIModelError(data)) {
      const modelError = data.errors.shift()
      if (modelError === undefined) {
        return new SellingPartnerUnknownError(
          {
            code: code || 'UnknownError',
            message,
          },
          headers,
        )
      }

      switch (status) {
        case StatusCodes.BAD_REQUEST:
          return new SellingPartnerBadRequestError(modelError, headers)
        case StatusCodes.FORBIDDEN:
          return new SellingPartnerForbiddenError(modelError, headers)
        case StatusCodes.NOT_FOUND:
          return new SellingPartnerNotFoundError(modelError, headers)
        case StatusCodes.REQUEST_TOO_LONG:
          return new SellingPartnerRequestTooLongError(modelError, headers)
        case StatusCodes.UNSUPPORTED_MEDIA_TYPE:
          return new SellingPartnerUnsupportedMediaTypeError(modelError, headers)
        case StatusCodes.TOO_MANY_REQUESTS:
          return new SellingPartnerTooManyRequestsError(modelError, headers)
        case StatusCodes.INTERNAL_SERVER_ERROR:
          return new SellingPartnerInternalServerError(modelError, headers)
        case StatusCodes.SERVICE_UNAVAILABLE:
          return new SellingPartnerServiceUnavailableError(modelError, headers)
        default:
          return new SellingPartnerGenericError(modelError, headers)
      }
    }
  }

  return error
}
Example #7
Source File: error.ts    From dendron with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
   * Optional HTTP status code for error
   */
  public code?: StatusCodes;
Example #8
Source File: NetworkUtils.ts    From legend-studio with Apache License 2.0 5 votes vote down vote up
HttpStatus = StatusCodes
Example #9
Source File: api-key.test.ts    From integration-services with Apache License 2.0 5 votes vote down vote up
describe('test api-key middleware', () => {
	let nextMock: any, res: any, sendMock: any, sendStatusMock: any;
	beforeEach(() => {
		sendMock = jest.fn();
		sendStatusMock = jest.fn();
		nextMock = jest.fn();
		res = {
			send: sendMock,
			sendStatus: sendStatusMock,
			status: jest.fn(() => res)
		};
		nextMock = jest.fn();
	});

	it('request has not the valid api key!', async () => {
		const req: any = {
			query: {
				'api-key': 'wrong-api-key'
			}
		};

		hasValidApiKey('valid-api-key')(req, res, nextMock);

		expect(res.status).toHaveBeenCalledWith(StatusCodes.UNAUTHORIZED);
		expect(res.send).toHaveBeenCalledWith({ error: 'no valid api key provided!' });
		expect(nextMock).not.toHaveBeenCalledWith();
	});

	it('no api key was set by the server so everything is valid', async () => {
		const req: any = {
			query: {
				'api-key': 'any-value-is-ok'
			}
		};

		hasValidApiKey('')(req, res, nextMock);
		expect(nextMock).toHaveBeenCalledWith();
	});

	it('request has no valid query', async () => {
		const req: any = {
			query: undefined
		};

		hasValidApiKey('valid-api-key')(req, res, nextMock);

		expect(res.status).toHaveBeenCalledWith(StatusCodes.UNAUTHORIZED);
		expect(res.send).toHaveBeenCalledWith({ error: 'no valid api key provided!' });
		expect(nextMock).not.toHaveBeenCalledWith();
	});

	it('request has a valid api key!', async () => {
		const req: any = {
			query: {
				'api-key': 'valid-api-key'
			}
		};

		hasValidApiKey('valid-api-key')(req, res, nextMock);
		expect(nextMock).toHaveBeenCalledWith();
	});
});
Example #10
Source File: system-status.controller.ts    From node-boilerplate with Apache License 2.0 5 votes vote down vote up
public getError(req: Request, res: Response, next: NextFunction): void {
        try {
            throw new ApiError(ReasonPhrases.BAD_REQUEST, StatusCodes.BAD_REQUEST);
        } catch (error) {
            next(error);
        }
    }
Example #11
Source File: check_status.ts    From approveman with MIT License 5 votes vote down vote up
createStatus = async (
  context: Context<"pull_request.opened" | "pull_request.reopened" | "pull_request.synchronize">,
  conclusion:
    | "success"
    | "failure"
    | "neutral"
    | "cancelled"
    | "timed_out"
    | "action_required"
    | undefined,
  status: "in_progress" | "completed" | "queued",
  title: string,
  summary: string,
  details: string,
  startTime: string,
): Promise<void> => {
  context.log.trace(`Create ${status} status with conclusion ${conclusion}.`);
  context.log.trace(
    `title: ${title}, summary: ${summary}, details: ${details}`,
  );
  /* eslint-disable */
  const completedAt: string | undefined = conclusion
    ? new Date().toISOString()
    : undefined;
  const startedAt: string | undefined =
    status === "in_progress" ? startTime : undefined;
  /* eslint-enable */
  const statusOptions = context.repo({
    "completed_at": completedAt,
    conclusion,
    "head_sha": context.payload.pull_request.head.sha,
    "name": APP_CHECK_NAME,
    "output": {
      summary,
      "text": details,
      title,
    },
    "request": {
      "retries": 3,
      "retryAfter": 3,
    },
    "started_at": startedAt,
    status,
  });
  const response = await context.octokit.checks.create(statusOptions);
  context.log.trace(`Posting status finished with status ${response.status}`);
  if (response.status !== StatusCodes.CREATED) {
    context.log.error(
      `Create passing status failed with status ${
        response.status
      } and error: ${JSON.stringify(response.data)}`,
    );
  }
}
Example #12
Source File: ExperimentForm.test.tsx    From abacus with GNU General Public License v2.0 4 votes vote down vote up
test('form submits with valid fields', async () => {
  MockDate.set('2020-08-13')

  let submittedData: unknown = null
  const onSubmit = async (formData: unknown): Promise<undefined> => {
    // We need to add a timeout here so the loading indicator renders
    await new Promise((resolve) => setTimeout(resolve, StatusCodes.OK))
    submittedData = formData
    return
  }

  render(
    <ExperimentForm
      indexedMetrics={Normalizers.indexMetrics(Fixtures.createMetrics(20))}
      indexedSegments={Normalizers.indexSegments(Fixtures.createSegments(20))}
      initialExperiment={experimentToFormData({})}
      onSubmit={onSubmit}
      completionBag={completionBag}
    />,
  )

  // ### Start
  screen.getByText(/Design and Document Your Experiment/)
  await changeFieldByRole('textbox', /Your Post's URL/, 'http://example.com/')
  await act(async () => {
    fireEvent.click(screen.getByRole('button', { name: /Begin/ }))
  })

  // ### Basic Info
  screen.getAllByText(/Basic Info/)
  await changeFieldByRole('textbox', /Experiment name/, 'test_experiment_name')
  await changeFieldByRole('textbox', /Experiment description/, 'experiment description')
  // We need to make some dates relative to today since mocking the schema to work with MockDate is a pain!
  const now = new Date()
  now.setDate(now.getDate() + 1)
  const nextWeek = new Date()
  nextWeek.setDate(now.getDate() + 7)
  await act(async () => {
    fireEvent.change(screen.getByLabelText(/Start date/), { target: { value: formatIsoDate(now) } })
  })
  await act(async () => {
    fireEvent.change(screen.getByLabelText(/End date/), { target: { value: formatIsoDate(nextWeek) } })
  })
  // search for the user
  await act(async () => {
    await changeFieldByRole('textbox', /Owner/, 'testing')
  })
  // click the selected user
  await act(async () => {
    fireEvent.click(screen.getByText('testing (owner-nickname)'))
  })
  await act(async () => {
    fireEvent.click(screen.getByRole('button', { name: /Next/ }))
  })

  // ### Audience
  screen.getByText(/Define Your Audience/)

  const platformField = screen.getByRole('button', { name: /Select a Platform/ })
  await act(async () => {
    fireEvent.focus(platformField)
  })
  await act(async () => {
    fireEvent.keyDown(platformField, { key: 'Enter' })
  })
  const platformOption = await screen.findByRole('option', { name: /wpcom/ })
  await act(async () => {
    fireEvent.click(platformOption)
  })

  const targetingField = screen.getByRole('textbox', { name: /Targeting/ })
  fireEvent.change(targetingField, { target: { value: 'segment_3' } })
  const targetingOption = await screen.findByRole('option', { name: /Locale: segment_3/ })
  await act(async () => {
    fireEvent.click(targetingOption)
  })

  const addVariationButton = screen.getByRole('button', { name: /Add variation/i })
  fireEvent.click(addVariationButton)

  const variationNames = screen.getAllByRole('textbox', { name: /Variation name/i })
  fireEvent.change(variationNames[1], { target: { value: 'treatment_2' } })

  const allocatedPercentages = screen.getAllByRole('spinbutton', { name: /Allocated percentage/i })
  await act(async () => {
    fireEvent.change(allocatedPercentages[0], { target: { value: '33' } })
    fireEvent.change(allocatedPercentages[1], { target: { value: '33' } })
    fireEvent.change(allocatedPercentages[2], { target: { value: '33' } })
  })

  await act(async () => {
    fireEvent.click(screen.getByRole('button', { name: /Next/ }))
  })

  // ### Metrics
  screen.getByText(/Assign Metrics/)
  const metricSearchField = screen.getByRole('combobox', { name: /Select a metric/ })
  const metricSearchFieldMoreButton = getByRole(metricSearchField, 'button', { name: 'Open' })
  const metricAddButton = screen.getByRole('button', { name: 'Add metric' })

  fireEvent.click(metricSearchFieldMoreButton)
  const metricOption = await screen.findByRole('option', { name: /metric_10/ })
  await act(async () => {
    fireEvent.click(metricOption)
  })
  await act(async () => {
    fireEvent.click(metricAddButton)
  })

  const attributionWindowField = await screen.findByLabelText('Attribution Window')
  await act(async () => {
    fireEvent.focus(attributionWindowField)
  })
  await act(async () => {
    fireEvent.keyDown(attributionWindowField, { key: 'Enter' })
  })
  const attributionWindowFieldOption = await screen.findByRole('option', { name: /24 hours/ })
  await act(async () => {
    fireEvent.click(attributionWindowFieldOption)
  })

  await changeFieldByRole('spinbutton', /Minimum Difference/, '0.01')

  // #### Exposure Events
  await act(async () => {
    fireEvent.click(screen.getByRole('button', { name: /Add exposure event/ }))
  })
  await act(async () => {
    fireEvent.click(await screen.findByRole('button', { name: /Add Property/ }))
  })
  await act(async () => {
    fireEvent.click(await screen.findByRole('button', { name: /Remove exposure event property/ }))
  })
  await act(async () => {
    fireEvent.click(await screen.findByRole('button', { name: /Remove exposure event/ }))
  })
  await act(async () => {
    fireEvent.click(screen.getByRole('button', { name: /Add exposure event/ }))
  })
  await act(async () => {
    fireEvent.click(await screen.findByRole('button', { name: /Add Property/ }))
  })
  // search for the event
  await act(async () => {
    await changeFieldByRole('textbox', /Event Name/, 'event_name')
  })
  // click the selected event
  await act(async () => {
    fireEvent.click(screen.getByText('event_name'))
  })
  // enter the prop value
  await act(async () => {
    await changeFieldByRole('textbox', /Key/, 'prop_key_value')
  })
  await changeFieldByRole('textbox', /Property Value/, 'value')

  await act(async () => {
    fireEvent.click(screen.getByRole('button', { name: /Next/ }))
  })

  // ### Submit
  screen.getByText(/Confirm and Submit Your Experiment/)
  await act(async () => {
    screen.getAllByRole('button', { name: /Submit/ })
    const submit = screen
      .getAllByRole('button', { name: /Submit/ })
      .find((submit) => submit.getAttribute('type') === 'submit')
    if (!submit) {
      throw new Error(`Can't find submit button.`)
    }
    fireEvent.click(submit)
  })

  await waitFor(() => expect(submittedData).not.toBeNull())

  expect(submittedData).toEqual({
    experiment: {
      p2Url: 'http://example.com/',
      name: 'test_experiment_name',
      description: 'experiment description',
      startDatetime: formatIsoDate(now),
      endDatetime: formatIsoDate(nextWeek),
      exclusionGroupTagIds: [],
      ownerLogin: 'owner-nickname',
      platform: 'wpcom',
      existingUsersAllowed: 'true',
      exposureEvents: [
        {
          event: 'event_name',
          props: [
            {
              key: 'prop_key_value',
              value: 'value',
            },
          ],
        },
      ],
      segmentAssignments: [
        {
          isExcluded: false,
          segmentId: 3,
        },
      ],
      variations: [
        {
          allocatedPercentage: 33,
          isDefault: true,
          name: 'control',
        },
        {
          allocatedPercentage: 33,
          isDefault: false,
          name: 'treatment',
        },
        {
          allocatedPercentage: 33,
          isDefault: false,
          name: 'treatment_2',
        },
      ],
      metricAssignments: [
        {
          attributionWindowSeconds: '86400',
          changeExpected: true,
          isPrimary: true,
          metricId: 10,
          minDifference: 0.01,
        },
      ],
    },
  })
})
Example #13
Source File: berry.spec.ts    From pokenode-ts with MIT License 4 votes vote down vote up
describe('test Berry Client', () => {
  let client: BerryClient;
  beforeAll(() => {
    client = new BerryClient();
  });

  // Berry

  it('check if it returns a berry passig a name', async () => {
    const data = await client.getBerryByName('cheri').then((response: Berry) => response);

    expect(data.id).toBe(Berries.CHERI);
  });

  it('check if it returns a berry passing an ID', async () => {
    const data = await client.getBerryById(Berries.CHERI).then((response: Berry) => response);

    expect(data.name).toBe('cheri');
  });

  it('check if getBerryByName returns NOT FOUND', async () => {
    const data = await client
      .getBerryByName('it will not pass')
      .catch((error: AxiosError<string>) => error.response?.status);

    expect(data).toBe(StatusCodes.NOT_FOUND);
  });

  it('check if getBerryById returns NOT FOUND', async () => {
    const data = await client
      .getBerryById(aHugeNumber)
      .catch((error: AxiosError<string>) => error.response?.status);

    expect(data).toBe(StatusCodes.NOT_FOUND);
  });

  it('check if it returns a list of berries', async () => {
    const data = await client.listBerries().then((response: NamedAPIResourceList) => response);

    expect(data.results.length).toBeGreaterThan(0);
  });

  // Berry Firmness

  it('check if it returns a berry firmness passig a name', async () => {
    const data = await client
      .getBerryFirmnessByName('very-soft')
      .then((response: BerryFirmness) => response);

    expect(data.name).toBe('very-soft');
  });

  it('check if it returns a berry firmness passing an ID', async () => {
    const data = await client
      .getBerryFirmnessById(BerryFirmnesses.VERY_SOFT)
      .then((response: BerryFirmness) => response);

    expect(data.name).toBe('very-soft');
  });

  it('check if getBerryFirmnessByName returns NOT FOUND', async () => {
    const data = await client
      .getBerryFirmnessByName('it will not pass')
      .catch((error: AxiosError<string>) => error.response?.status);

    expect(data).toBe(StatusCodes.NOT_FOUND);
  });

  it('check if getBerryFirmnessById returns NOT FOUND', async () => {
    const data = await client
      .getBerryFirmnessById(aHugeNumber)
      .catch((error: AxiosError<string>) => error.response?.status);

    expect(data).toBe(StatusCodes.NOT_FOUND);
  });

  it('check if it returns a list of berry firmnesses', async () => {
    const data = await client
      .listBerryFirmnesses()
      .then((response: NamedAPIResourceList) => response);

    expect(data.results.length).toBeGreaterThan(0);
  });

  // Berry Flavor

  it('check if it returns a berry flavor passig a name', async () => {
    const data = await client
      .getBerryFlavorByName('spicy')
      .then((response: BerryFlavor) => response);

    expect(data.id).toBe(BerryFlavors.SPICY);
  });

  it('check if it returns a berry flavor passing an ID', async () => {
    const data = await client
      .getBerryFlavorById(BerryFlavors.SPICY)
      .then((response: BerryFlavor) => response);

    expect(data.name).toBe('spicy');
  });

  it('check if getBerryFlavorByName returns NOT FOUND', async () => {
    const data = await client
      .getBerryFlavorByName('it will not pass')
      .catch((error: AxiosError<string>) => error.response?.status);

    expect(data).toBe(StatusCodes.NOT_FOUND);
  });

  it('check if getBerryFlavorById returns NOT FOUND', async () => {
    const data = await client
      .getBerryFlavorById(aHugeNumber)
      .catch((error: AxiosError<string>) => error.response?.status);

    expect(data).toBe(404);
  });

  it('check if it returns a list of berry flavors', async () => {
    const data = await client.listBerryFlavors().then((response: NamedAPIResourceList) => response);

    expect(data.results.length).toBeGreaterThan(0);
  });
});
Example #14
Source File: errors.test.ts    From selling-partner-api-sdk with MIT License 4 votes vote down vote up
describe(`client`, () => {
  it(`should throw ${SellingPartnerForbiddenError.name} when pass invalid token`, async () => {
    expect.assertions(2)

    const { CA } = amazonMarketplaces
    assertMarketplaceHasSellingPartner(CA)
    const requestId = 'ABC'

    const configuration: APIConfigurationParameters = {
      accessToken: 'Atza|...',
      region: CA.sellingPartner.region.awsRegion,
    }

    jestPollyContext.polly.server
      .any(`${CA.sellingPartner.region.endpoint}/sellers/v1/marketplaceParticipations`)
      .intercept((request, response) => {
        response.setHeader('x-amzn-requestid', requestId).sendStatus(StatusCodes.FORBIDDEN)
        response.send({
          errors: [
            {
              code: 'Forbidden',
              message: 'Forbidden',
            },
          ],
        })
      })

    const client = new SellersApiClient(configuration)

    await expect(client.getMarketplaceParticipations()).rejects.toBeInstanceOf(
      SellingPartnerForbiddenError,
    )
    await expect(client.getMarketplaceParticipations()).rejects.toHaveProperty(
      'requestId',
      requestId,
    )
  })

  it(`should throw ${SellingPartnerNotFoundRegionError.name} if cannot extract region from base path`, async () => {
    expect.assertions(2)

    const basePath = 'example.com'
    const { CA } = amazonMarketplaces

    const client = new Promise(() => {
      assertMarketplaceHasSellingPartner(CA)

      const configuration: APIConfigurationParameters = {
        accessToken: 'Atza|...',
        basePath,
      }
      return new SellersApiClient(configuration)
    })

    await expect(client).rejects.toBeInstanceOf(SellingPartnerNotFoundRegionError)
    await expect(client).rejects.toHaveProperty('basePath', basePath)
  })

  it(`should throw ${SellingPartnerMismatchRegionError.name} if mismatch between region in default base path and region parameter`, async () => {
    expect.assertions(3)

    const region = 'us'
    const { CA } = amazonMarketplaces

    const client = new Promise(() => {
      assertMarketplaceHasSellingPartner(CA)

      const configuration: APIConfigurationParameters = {
        accessToken: 'Atza|...',
        region,
      }

      return new SellersApiClient(configuration)
    })

    await expect(client).rejects.toBeInstanceOf(SellingPartnerMismatchRegionError)
    await expect(client).rejects.toHaveProperty('defaultRegion', 'us-east-1')
    await expect(client).rejects.toHaveProperty('region', region)
  })

  it(`should throw ${SellingPartnerTooManyRequestsError.name} if reach api limit`, async () => {
    expect.assertions(2)

    const { CA } = amazonMarketplaces
    assertMarketplaceHasSellingPartner(CA)
    const defaultRateLimit = '0.1'

    jestPollyContext.polly.server
      .any(`${CA.sellingPartner.region.endpoint}/sellers/v1/marketplaceParticipations`)
      .intercept((request, response) => {
        response
          .setHeader('x-amzn-RateLimit-Limit', defaultRateLimit)
          .sendStatus(StatusCodes.TOO_MANY_REQUESTS)
        response.send({
          errors: [
            {
              code: 'TooManyRequests',
              message: 'Too many requests',
            },
          ],
        })
      })

    const configuration: APIConfigurationParameters = {
      accessToken: 'Atza|...',
      region: CA.sellingPartner.region.awsRegion,
    }
    const client = new SellersApiClient(configuration)

    await expect(client.getMarketplaceParticipations()).rejects.toBeInstanceOf(
      SellingPartnerTooManyRequestsError,
    )
    await expect(client.getMarketplaceParticipations()).rejects.toHaveProperty(
      'rateLimit',
      toNumber(defaultRateLimit),
    )
  })

  it(`should handle unknown error`, async () => {
    expect.assertions(3)

    const { CA } = amazonMarketplaces
    assertMarketplaceHasSellingPartner(CA)

    const configuration: APIConfigurationParameters = {
      accessToken: 'Atza|...',
      region: CA.sellingPartner.region.awsRegion,
    }

    jestPollyContext.polly.server
      .any(`${CA.sellingPartner.region.endpoint}/sellers/v1/marketplaceParticipations`)
      .intercept((request, response) => {
        response.sendStatus(StatusCodes.INTERNAL_SERVER_ERROR)
        response.send({
          errors: [],
        })
      })

    const client = new SellersApiClient(configuration)

    await expect(client.getMarketplaceParticipations()).rejects.toThrow(SellingPartnerUnknownError)

    await expect(client.getMarketplaceParticipations()).rejects.toHaveProperty(
      'message',
      'Request failed with status code 500',
    )
    await expect(client.getMarketplaceParticipations()).rejects.toHaveProperty(
      'code',
      'ERR_BAD_RESPONSE',
    )
  })

  it(`should throw original error if cannot handle`, async () => {
    expect.assertions(3)

    const { CA } = amazonMarketplaces
    assertMarketplaceHasSellingPartner(CA)

    const configuration: APIConfigurationParameters = {
      accessToken: 'Atza|...',
      region: CA.sellingPartner.region.awsRegion,
    }

    jestPollyContext.polly.server
      .any(`${CA.sellingPartner.region.endpoint}/sellers/v1/marketplaceParticipations`)
      .intercept((request, response) => {
        response.sendStatus(StatusCodes.INTERNAL_SERVER_ERROR)
      })

    const client = new SellersApiClient(configuration)

    await expect(client.getMarketplaceParticipations()).rejects.toThrow(AxiosError)

    await expect(client.getMarketplaceParticipations()).rejects.toHaveProperty(
      'message',
      'Request failed with status code 500',
    )
    await expect(client.getMarketplaceParticipations()).rejects.toHaveProperty(
      'code',
      'ERR_BAD_RESPONSE',
    )
  })
})
Example #15
Source File: authentication.test.ts    From integration-services with Apache License 2.0 4 votes vote down vote up
describe('test authentication middleware', () => {
	const jwtSecret = 'very-secret-secret';
	let nextMock: any, res: any, sendMock: any, sendStatusMock: any;
	beforeEach(() => {
		sendMock = jest.fn();
		sendStatusMock = jest.fn();
		nextMock = jest.fn();
		res = {
			send: sendMock,
			sendStatus: sendStatusMock,
			status: jest.fn(() => res)
		};
		nextMock = jest.fn();
	});

	it('request is not authenticated since no authorization header provided!', async () => {
		const req: any = {
			headers: {
				authorization: ''
			}
		};

		isAuth(jwtSecret)(req, res, nextMock);

		expect(res.status).toHaveBeenCalledWith(StatusCodes.UNAUTHORIZED);
		expect(res.send).toHaveBeenCalledWith({ error: 'not authenticated!' });
	});

	it('request is not authenticated since no valid splittable authorization header provided!', async () => {
		const req: any = {
			headers: {
				authorization: 'Bearer'
			}
		};

		isAuth(jwtSecret)(req, res, nextMock);

		expect(res.status).toHaveBeenCalledWith(StatusCodes.UNAUTHORIZED);
		expect(res.send).toHaveBeenCalledWith({ error: 'not authenticated!' });
	});

	it('throws error since jwt signed with wrong key!', async () => {
		const req: any = {
			headers: {
				authorization:
					'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7InVzZXJJZCI6ImRpZDppb3RhOjZoeWFIZ3J2RWVYRDh6NnFxZDFReVlOUTFRRDU0ZlhmTHM2dUdldzNEZU51IiwicHVibGljS2V5IjoiRERCSmdFVU5tV2lzR2Y0Wmg2TWF6QXRlZjdWNUJqVkpkRVlLbzJ5UkxZVnAiLCJ1c2VybmFtZSI6InRlc3QtZGV2aWNlIiwiY2xhc3NpZmljYXRpb24iOiJkZXZpY2UiLCJzdWJzY3JpYmVkQ2hhbm5lbElkcyI6WyJ0ZXN0LWFkZHJlc3MtYzIiLCJ0ZXN0LWFkZHJlc3MiXSwiZmlyc3ROYW1lIjpudWxsLCJsYXN0TmFtZSI6bnVsbCwiZGVzY3JpcHRpb24iOiJEZXZpY2Ugd2hpY2ggbWVhc3VyZXMgdGVtcGVyYXR1cmUgaW4gdGhlIGtpdGNoZW4uIiwicmVnaXN0cmF0aW9uRGF0ZSI6IjIwMjEtMDMtMjRUMTY6NTQ6MzgrMDE6MDAiLCJ2ZXJpZmljYXRpb24iOnsidmVyaWZpZWQiOnRydWUsInZlcmlmaWNhdGlvbkRhdGUiOiIyMDIxLTAzLTI0VDE2OjU5OjAwKzAxOjAwIiwibGFzdFRpbWVDaGVja2VkIjoiMjAyMS0wMy0yNFQxNjo1OTowMCswMTowMCIsInZlcmlmaWNhdGlvbklzc3VlcklkIjoiZGlkOmlvdGE6NUVzZms5WUhwcVpBR0ZCQ2g0RXpiblZIMmtRaGlybXhRQXBjMWdoQ25jR1EifSwib3JnYW5pemF0aW9uIjoiSU9UQSIsIm9yZ2FuaXphdGlvblVybCI6bnVsbCwibG9jYXRpb24iOm51bGwsInZlcmlmaWFibGVDcmVkZW50aWFscyI6W3siQGNvbnRleHQiOiJodHRwczovL3d3dy53My5vcmcvMjAxOC9jcmVkZW50aWFscy92MSIsImlkIjoiZGlkOmlvdGE6Nmh5YUhncnZFZVhEOHo2cXFkMVF5WU5RMVFENTRmWGZMczZ1R2V3M0RlTnUiLCJ0eXBlIjpbIlZlcmlmaWFibGVDcmVkZW50aWFsIiwiVXNlckNyZWRlbnRpYWwiXSwiY3JlZGVudGlhbFN1YmplY3QiOnsiaWQiOiJkaWQ6aW90YTo2aHlhSGdydkVlWEQ4ejZxcWQxUXlZTlExUUQ1NGZYZkxzNnVHZXczRGVOdSIsImNsYXNzaWZpY2F0aW9uIjoiZGV2aWNlIiwib3JnYW5pemF0aW9uIjoiSU9UQSIsInJlZ2lzdHJhdGlvbkRhdGUiOiIyMDIxLTAzLTI0VDE2OjU0OjM4KzAxOjAwIiwidXNlcm5hbWUiOiJ0ZXN0LWRldmljZSJ9LCJpc3N1ZXIiOiJkaWQ6aW90YTo1RXNmazlZSHBxWkFHRkJDaDRFemJuVkgya1FoaXJteFFBcGMxZ2hDbmNHUSIsImlzc3VhbmNlRGF0ZSI6IjIwMjEtMDMtMjRUMTU6NTg6NTlaIiwicHJvb2YiOnsidHlwZSI6Ik1lcmtsZUtleVNpZ25hdHVyZTIwMjEiLCJ2ZXJpZmljYXRpb25NZXRob2QiOiIja2V5LWNvbGxlY3Rpb24iLCJzaWduYXR1cmVWYWx1ZSI6IjlmTnFnWmZGWlRudDZIcHlSRDJ5WFJvdmlqamV3VlRwR1N6d05YNFl2UGIxLjExMTd1OWliUHp1OGl0ekhBV2pMZG82ajd2VFdkV0N1dkFEWTFvVXFySkx4VW1Ra0NuaEVnSldCb0FTd2VMWG9KQVBZdVVlOGl5eVlFZ29hUUREVEhoYUw1eFpROGZLNm5idzY3cUxvNUJ1VGJRSGlxcG5pbnRacGg5VGpLRmVwN3BrNnpvTE1HZEQuM3hoNHIzOGlpTGhYeWpCd2RKUE1xelN5ckpBdFNwM3UzcEpVR1RHeWR5TjQ1clRFV1hmcVBFREx3OHV4OXR0WGlqQURUSDVTQXdyOTI0QWduazJWbTN3QSJ9fV19LCJpYXQiOjE2MTY2MDUxMjgsImV4cCI6MTYxODMzMzEyOH0.ocjuG9oObwbURS0qO6FreSJUzRie_thYkEENE5d16ok'
			}
		};
		const t = () => {
			isAuth(jwtSecret)(req, res, nextMock);
		};

		expect(t).toThrowError();
	});

	it('throws error since jwt signed does not contain signed user object!', async () => {
		const wrongUserJwt =
			'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJkaWZmZXJlbnQtdXNlci1vYmplY3QiOnt9LCJpYXQiOjE2MTU5ODY3ODV9.VgXT7GIj5R4P1vjcoAFNZ5N-u8oRj90wRUyX5UgjV2Q';
		const req: any = {
			headers: {
				authorization: 'Bearer ' + wrongUserJwt
			}
		};
		// jwt from: { user: { id: 'NEEDS TO BE CALLED id' }
		isAuth(jwtSecret)(req, res, nextMock);

		expect(res.status).toHaveBeenCalledWith(StatusCodes.UNAUTHORIZED);
		expect(res.send).toHaveBeenCalledWith({ error: 'not authenticated!' });
	});

	// TODO fix test
	xit('should add user to request and call nextMock!', async () => {
		const validJwt =
			'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyIjp7InVzZXJJZCI6ImRpZDppb3RhOjEyMzQ1NiJ9LCJpYXQiOjE2MTU5ODY4ODR9.YH6kjYlMDG3MnhvB5q1AUR3ntiEj_m7dpSAMfNUJFx0';
		const req: any = {
			headers: {
				authorization: 'Bearer ' + validJwt
			}
		};
		// jwt from: { user: { id: 'did:iota:123456' } }
		expect(req.user).toBeUndefined();

		isAuth(jwtSecret)(req, res, nextMock);

		expect(req.user).toEqual({ id: 'did:iota:123456' });
		expect(nextMock).toHaveBeenCalledWith();
	});
});