|
| 1 | +import { |
| 2 | + trackUsage, |
| 3 | + TestLimitReachedError, |
| 4 | +} from '../../../../src/cli/commands/test/iac-local-execution/usage-tracking'; |
| 5 | +import { mocked } from 'ts-jest/utils'; |
| 6 | +import { NeedleResponse } from 'needle'; |
| 7 | +import makeRequest = require('../../../../src/lib/request/request'); |
| 8 | +import { CustomError } from '../../../../src/lib/errors'; |
| 9 | + |
| 10 | +jest.mock('../../../../src/lib/request/request'); |
| 11 | +const mockedMakeRequest = mocked(makeRequest); |
| 12 | + |
| 13 | +const results = [ |
| 14 | + { |
| 15 | + meta: { |
| 16 | + isPrivate: true, |
| 17 | + }, |
| 18 | + result: { |
| 19 | + cloudConfigResults: ['an issue'], |
| 20 | + }, |
| 21 | + }, |
| 22 | + { |
| 23 | + meta: { |
| 24 | + isPrivate: false, |
| 25 | + }, |
| 26 | + result: { |
| 27 | + cloudConfigResults: [], |
| 28 | + }, |
| 29 | + }, |
| 30 | +]; |
| 31 | + |
| 32 | +describe('tracking IaC test usage', () => { |
| 33 | + afterEach(() => { |
| 34 | + jest.clearAllMocks(); |
| 35 | + }); |
| 36 | + |
| 37 | + it('does not throw an error when backend returns HTTP 200', async () => { |
| 38 | + mockedMakeRequest.mockImplementationOnce(() => { |
| 39 | + return Promise.resolve({ |
| 40 | + res: { statusCode: 200 } as NeedleResponse, |
| 41 | + body: { |
| 42 | + foo: 'bar', |
| 43 | + }, |
| 44 | + }); |
| 45 | + }); |
| 46 | + |
| 47 | + await trackUsage(results); |
| 48 | + |
| 49 | + expect(mockedMakeRequest.mock.calls.length).toEqual(1); |
| 50 | + expect(mockedMakeRequest.mock.calls[0][0].body).toEqual({ |
| 51 | + results: [ |
| 52 | + { |
| 53 | + isPrivate: true, |
| 54 | + issuesPrevented: 1, |
| 55 | + }, |
| 56 | + { |
| 57 | + isPrivate: false, |
| 58 | + issuesPrevented: 0, |
| 59 | + }, |
| 60 | + ], |
| 61 | + }); |
| 62 | + }); |
| 63 | + |
| 64 | + it('throws TestLimitReachedError when backend returns HTTP 429', async () => { |
| 65 | + mockedMakeRequest.mockImplementationOnce(() => { |
| 66 | + return Promise.resolve({ |
| 67 | + res: { statusCode: 429 } as NeedleResponse, |
| 68 | + body: { |
| 69 | + foo: 'bar', |
| 70 | + }, |
| 71 | + }); |
| 72 | + }); |
| 73 | + |
| 74 | + await expect(trackUsage(results)).rejects.toThrow( |
| 75 | + new TestLimitReachedError(), |
| 76 | + ); |
| 77 | + }); |
| 78 | + |
| 79 | + it('throws CustomError when backend returns HTTP 500', async () => { |
| 80 | + mockedMakeRequest.mockImplementationOnce(() => { |
| 81 | + return Promise.resolve({ |
| 82 | + res: { statusCode: 500, body: { foo: 'bar' } } as NeedleResponse, |
| 83 | + body: { |
| 84 | + foo: 'bar', |
| 85 | + }, |
| 86 | + }); |
| 87 | + }); |
| 88 | + |
| 89 | + await expect(trackUsage(results)).rejects.toThrow( |
| 90 | + new CustomError( |
| 91 | + 'An error occurred while attempting to track test usage: {"foo":"bar"}', |
| 92 | + ), |
| 93 | + ); |
| 94 | + }); |
| 95 | +}); |
0 commit comments