Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HTTP unit tests part 2 #55

Merged
merged 3 commits into from
Nov 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion config/__tests__/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -241,7 +241,8 @@ describe('lib/config', () => {
).toEqual(env);
});

it('overwrites the existing env in the config if specified', () => {
it('overwrites the existing env in the config if specified as environment', () => {
// NOTE: the config now uses "env", but this is to support legacy behavior
const previousEnv = ENVIRONMENTS.PROD;
const newEnv = ENVIRONMENTS.QA;
setConfig({
Expand All @@ -262,6 +263,27 @@ describe('lib/config', () => {
).toEqual(newEnv);
});

it('overwrites the existing env in the config if specified as env', () => {
const previousEnv = ENVIRONMENTS.PROD;
const newEnv = ENVIRONMENTS.QA;
setConfig({
defaultPortal: PERSONAL_ACCESS_KEY_CONFIG.name,
portals: [{ ...PERSONAL_ACCESS_KEY_CONFIG, env: previousEnv }],
});
const modifiedPersonalAccessKeyConfig = {
...PERSONAL_ACCESS_KEY_CONFIG,
env: newEnv,
};
updateAccountConfig(modifiedPersonalAccessKeyConfig);

expect(
getAccountByAuthType(
getConfig(),
modifiedPersonalAccessKeyConfig.authType
).env
).toEqual(newEnv);
});

it('sets the name in the config if specified', () => {
const name = 'MYNAME';
const modifiedPersonalAccessKeyConfig = {
Expand Down
5 changes: 3 additions & 2 deletions config/config_DEPRECATED.ts
Original file line number Diff line number Diff line change
Expand Up @@ -479,8 +479,9 @@ export function updateAccountConfig(
}

const env = getValidEnv(
environment || (accountConfig && accountConfig.env),
undefined
environment ||
(configOptions && configOptions.env) ||
(accountConfig && accountConfig.env)
);
const mode: Mode | undefined =
defaultMode && (defaultMode.toLowerCase() as Mode);
Expand Down
40 changes: 40 additions & 0 deletions http/__tests__/getAxiosConfig.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { getAndLoadConfigIfNeeded as __getAndLoadConfigIfNeeded } from '../../config';
import { ENVIRONMENTS } from '../../constants/environments';
import { getAxiosConfig } from '../getAxiosConfig';

jest.mock('../../config');

const getAndLoadConfigIfNeeded =
__getAndLoadConfigIfNeeded as jest.MockedFunction<
typeof __getAndLoadConfigIfNeeded
>;

const url = 'https://app.hubspot.com';

describe('getAxiosConfig', () => {
it('constructs baseURL as expected based on environment', () => {
getAndLoadConfigIfNeeded.mockReturnValue({
accounts: [],
});

expect(getAxiosConfig({ url })).toMatchObject({
baseURL: 'https://api.hubapi.com',
});
expect(getAxiosConfig({ url, env: ENVIRONMENTS.QA })).toMatchObject({
baseURL: 'https://api.hubapiqa.com',
});
});
it('supports httpUseLocalhost config option to construct baseURL for local HTTP services', () => {
getAndLoadConfigIfNeeded.mockReturnValue({
httpUseLocalhost: true,
accounts: [],
});

expect(getAxiosConfig({ url })).toMatchObject({
baseURL: 'https://local.hubapi.com',
});
expect(getAxiosConfig({ url, env: ENVIRONMENTS.QA })).toMatchObject({
baseURL: 'https://local.hubapiqa.com',
});
});
});
121 changes: 115 additions & 6 deletions http/__tests__/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import axios from 'axios';
import fs from 'fs-extra';
import moment from 'moment';
import {
getAndLoadConfigIfNeeded as __getAndLoadConfigIfNeeded,
getAccountConfig as __getAccountConfig,
} from '../../config';
import { ENVIRONMENTS } from '../../constants/environments';
import http from '../';
import { version } from '../../package.json';
import { StatusCodeError } from '../../types/Error';
import { AuthType } from '../../types/Accounts';

jest.mock('fs-extra');
jest.mock('axios');
Expand Down Expand Up @@ -37,20 +40,20 @@ describe('http', () => {
getAccountConfig.mockReset();
});

describe('getOctetStream()', () => {
describe('http.getOctetStream()', () => {
beforeEach(() => {
getAndLoadConfigIfNeeded.mockReturnValue({
httpTimeout: 1000,
portals: [
accounts: [
{
portalId: 123,
accountId: 123,
apiKey: 'abc',
env: ENVIRONMENTS.QA,
},
],
});
getAccountConfig.mockReturnValue({
portalId: 123,
accountId: 123,
apiKey: 'abc',
env: ENVIRONMENTS.QA,
});
Expand All @@ -77,7 +80,7 @@ describe('http', () => {
url: 'some/endpoint/path',
})
);
expect(fs.createWriteStream).toBeCalledWith('path/to/local/file', {
expect(fs.createWriteStream).toHaveBeenCalledWith('path/to/local/file', {
encoding: 'binary',
});
});
Expand Down Expand Up @@ -109,5 +112,111 @@ describe('http', () => {
}
});
});
// NOTE: there are more tests to add, but I'm stopping here to keep the PR smaller

describe('http.get()', () => {
it('adds authorization header when using OAuth2 with valid access token', async () => {
const accessToken = 'let-me-in';
const account = {
accountId: 123,
env: ENVIRONMENTS.PROD,
authType: 'oauth2' as AuthType,
auth: {
clientId: 'd996372f-2b53-30d3-9c3b-4fdde4bce3a2',
clientSecret: 'f90a6248-fbc0-3b03-b0db-ec58c95e791',
scopes: ['content'],
tokenInfo: {
expiresAt: moment().add(2, 'hours').toISOString(),
refreshToken: '84d22710-4cb7-5581-ba05-35f9945e5e8e',
accessToken,
},
},
};
getAndLoadConfigIfNeeded.mockReturnValue({
accounts: [account],
});
getAccountConfig.mockReturnValue(account);

await http.get(123, { url: 'some/endpoint/path' });

expect(mockedAxios).toHaveBeenCalledWith({
baseURL: `https://api.hubapi.com`,
url: 'some/endpoint/path',
headers: {
'User-Agent': `HubSpot Local Dev Lib/${version}`,
Authorization: `Bearer ${accessToken}`,
},
timeout: 15000,
params: {
portalId: 123,
},
});
});
it('adds authorization header when using a user token', async () => {
const accessToken = 'let-me-in';
const account = {
accountId: 123,
env: ENVIRONMENTS.PROD,
authType: 'personalaccesskey' as AuthType,
personalAccessKey: 'some-secret',
auth: {
tokenInfo: {
expiresAt: moment().add(2, 'hours').toISOString(),
accessToken,
},
},
};
getAndLoadConfigIfNeeded.mockReturnValue({
accounts: [account],
});
getAccountConfig.mockReturnValue(account);

await http.get(123, { url: 'some/endpoint/path' });

expect(mockedAxios).toHaveBeenCalledWith({
baseURL: `https://api.hubapi.com`,
url: 'some/endpoint/path',
headers: {
'User-Agent': `HubSpot Local Dev Lib/${version}`,
Authorization: `Bearer ${accessToken}`,
},
timeout: 15000,
params: {
portalId: 123,
},
});
});

it('supports setting a custom timeout', async () => {
getAndLoadConfigIfNeeded.mockReturnValue({
httpTimeout: 1000,
accounts: [
{
accountId: 123,
apiKey: 'abc',
env: ENVIRONMENTS.PROD,
},
],
});
getAccountConfig.mockReturnValue({
accountId: 123,
apiKey: 'abc',
env: ENVIRONMENTS.PROD,
});

await http.get(123, { url: 'some/endpoint/path' });

expect(mockedAxios).toHaveBeenCalledWith({
baseURL: `https://api.hubapi.com`,
url: 'some/endpoint/path',
headers: {
'User-Agent': `HubSpot Local Dev Lib/${version}`,
},
timeout: 1000,
params: {
portalId: 123,
hapikey: 'abc',
},
});
});
});
});
2 changes: 1 addition & 1 deletion lib/__tests__/uploadFolder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ const filesProto = [
'folder/sample.module/module.html',
'folder/templates/page.html',
];
describe('uploadFolder', () => {
describe('cms/uploadFolder', () => {
beforeAll(() => {
createIgnoreFilter.mockImplementation(() => () => true);
});
Expand Down
6 changes: 3 additions & 3 deletions models/OAuth2Manager.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import axios from 'axios';
import moment from 'moment';

import { ENVIRONMENTS } from '../constants/environments';
import { getHubSpotApiOrigin } from '../lib/urls';
import { getValidEnv } from '../lib/environment';
import { FlatAccountFields, OAuthAccount, TokenInfo } from '../types/Accounts';
Expand Down Expand Up @@ -38,9 +37,10 @@ class OAuth2Manager {
refreshTokenRequest: Promise<RefreshTokenResponse> | null;

constructor(account: OAuthAccount, writeTokenInfo: WriteTokenInfoFunction) {
this.account = account;
this.writeTokenInfo = writeTokenInfo;
this.refreshTokenRequest = null;
this.account = account;
// NOTE: Potential issues by not using maskProductionValue = '' for env like in cli-lib
}

async accessToken(): Promise<string | undefined> {
Expand Down Expand Up @@ -142,7 +142,7 @@ class OAuth2Manager {

toObj() {
return {
environment: this.account.env ? ENVIRONMENTS.QA : ENVIRONMENTS.PROD,
env: this.account.env,
clientSecret: this.account.auth.clientSecret,
clientId: this.account.auth.clientId,
scopes: this.account.auth.scopes,
Expand Down
Loading