Skip to content

Commit

Permalink
Add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
adamjmcgrath committed Nov 8, 2023
1 parent 1e88154 commit c2a4292
Show file tree
Hide file tree
Showing 5 changed files with 403 additions and 1,527 deletions.
34 changes: 32 additions & 2 deletions playground/handlers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { program } from 'commander';
import fetch from 'node-fetch';
import {
Connection,
GetOrganizationMemberRoles200ResponseOneOfInner,
Expand All @@ -16,7 +17,10 @@ import fs from 'fs';
import { fileURLToPath } from 'url';
import nock from 'nock';

process.env.RECORD && nock.recorder.rec({ output_objects: true });
if (process.env.RECORD) {
(globalThis as any).fetch = fetch;
nock.recorder.rec({ output_objects: true });
}

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
Expand Down Expand Up @@ -151,6 +155,7 @@ export async function attackProtection() {
revertedSuspiciousIpThrottlingConfig.enabled
);
}

export async function anomaly() {
const mgmntClient = new ManagementClient(program.opts());
try {
Expand Down Expand Up @@ -296,6 +301,7 @@ export async function clientGrants() {
const { data: clientGrant } = await mgmntClient.clientGrants.create({
client_id: program.opts().clientId,
audience: api?.identifier as string,
organization_usage: 'allow',
scope: ['openid'],
});
console.log(`Created client grant ${clientGrant.id}`);
Expand All @@ -310,11 +316,35 @@ export async function clientGrants() {
{ id: clientGrant.id as string },
{ scope: ['openid', 'profile'] }
);

console.log(`Updated client grant to use scopes '${updatedClientGrant.scope?.join(', ')}'`);

const { data: organization } = await mgmntClient.organizations.create({
name: 'test-org',
});

await mgmntClient.organizations.addClientGrant(
{ id: organization.id },
{ grant_id: clientGrant.id }
);

const { data: orgsByClientGrant } = await mgmntClient.clientGrants.getOrganizations({
id: clientGrant.id,
});
console.log(`got orgs by ${clientGrant.id} ${orgsByClientGrant.map((org) => org.name)}`);
const { data: clientGrantsByOrg } = await mgmntClient.organizations.getClientGrants({
id: organization.id,
});
console.log(`got client grants by ${organization.name} ${clientGrantsByOrg.map((cg) => cg.id)}`);

await mgmntClient.organizations.deleteClientGrant({
id: organization.id,
grant_id: clientGrant.id,
});
console.log(`Removed ${clientGrant.id} from ${organization.id}`);

// Delete API for testing
await mgmntClient.resourceServers.delete({ id: api?.id as string });
await mgmntClient.organizations.delete({ id: organization.id });

await mgmntClient.clientGrants.delete({ id: clientGrant.id as string });
console.log('Removed the client grant: ' + clientGrant.id);
Expand Down
256 changes: 47 additions & 209 deletions test/management/client-grants.test.ts
Original file line number Diff line number Diff line change
@@ -1,237 +1,75 @@
import nock from 'nock';
import { afterAll, beforeAll } from '@jest/globals';
import { ClientGrantsManager, ManagementClient } from '../../src/index.js';

const API_URL = 'https://tenant.auth0.com/api/v2';

import { ClientGrant, ClientGrantsManager, ManagementClient } from '../../src/index.js';
const { back: nockBack } = nock;

describe('ClientGrantsManager', () => {
let grants: ClientGrantsManager;
const token = 'TOKEN';
beforeAll(() => {
const client = new ManagementClient({
domain: 'tenant.auth0.com',
token: token,
});
grants = client.clientGrants;
});
let clientGrantsManager: ClientGrantsManager;

afterEach(() => {
nock.cleanAll();
});
let nockDone: () => void;

describe('instance', () => {
const methods = ['getAll', 'create', 'update', 'delete'];
beforeAll(async () => {
({ nockDone } = await nockBack('management/fixtures/client-grants.json'));

methods.forEach((method) => {
it(`should have a ${method} method`, () => {
expect((grants as any)[method]).toBeInstanceOf(Function);
});
const client = new ManagementClient({
domain: 'test-domain.auth0.com',
token: 'TOKEN',
});
clientGrantsManager = client.clientGrants;
});

describe('#constructor', () => {
it('should throw an error when no base URL is provided', () => {
expect(() => {
new ClientGrantsManager({} as any);
}).toThrowError(Error);
});

it('should throw an error when the base URL is invalid', () => {
expect(() => {
new ClientGrantsManager({
baseUrl: '',
} as any);
}).toThrowError(Error);
});
afterAll(() => {
nockDone();
});

describe('#getAll', () => {
const data = [{ id: '1', client_id: '123', audience: 'abc', scope: ['openid'] }];
let request: nock.Scope;

beforeEach(() => {
request = nock(API_URL).get('/client-grants').reply(200, data);
});

it('should return a promise if no callback is given', (done) => {
grants.getAll().then(done.bind(null, null)).catch(done.bind(null, null));
});

it('should pass any errors to the promise catch handler', (done) => {
nock.cleanAll();

nock(API_URL).get('/client-grants').reply(500, {});

grants.getAll().catch((err) => {
expect(err).toBeDefined();
done();
});
});

it('should pass the body of the response to the "then" handler', (done) => {
nock.cleanAll();

nock(API_URL).get('/client-grants').reply(200, data);

grants.getAll().then((grants) => {
expect(grants.data).toBeInstanceOf(Array);

expect((grants.data as Array<ClientGrant>).length).toBe(data.length);
expect((grants.data as Array<ClientGrant>)[0].id).toBe(data[0].id);
expect((grants.data as Array<ClientGrant>)[0].client_id).toBe(data[0].client_id);
expect((grants.data as Array<ClientGrant>)[0].audience).toBe(data[0].audience);
expect((grants.data as Array<ClientGrant>)[0].scope?.[0]).toBe(data[0].scope[0]);

done();
});
});

it('should perform a GET request to /api/v2/client-grants', (done) => {
grants.getAll().then(() => {
expect(request.isDone()).toBe(true);
done();
});
});

it('should include the token in the Authorization header', (done) => {
nock.cleanAll();

const request = nock(API_URL)
.get('/client-grants')
.matchHeader('Authorization', `Bearer ${token}`)
.reply(200, data);

grants.getAll().then(() => {
expect(request.isDone()).toBe(true);
done();
});
});

it('should pass the parameters in the query-string', (done) => {
nock.cleanAll();

const request = nock(API_URL)
.get('/client-grants')
.query({
page: 1,
per_page: 2,
})
.reply(200, data);

grants.getAll({ page: 1, per_page: 2 }).then(() => {
expect(request.isDone()).toBe(true);
done();
});
it('should create a client grant', async () => {
await expect(
clientGrantsManager.create({
client_id: 'test-client-id',
audience: 'test-aud',
scope: ['read:foo', 'write:foo'],
})
).resolves.toMatchObject({
status: 201,
});
});

describe('#create', () => {
const data = {
client_id: 'CLIENT_ID',
audience: 'AUDIENCE',
scope: ['user'],
};
let request: nock.Scope;

beforeEach(() => {
request = nock(API_URL).post('/client-grants').reply(201, data);
});

it('should return a promise if no callback is given', (done) => {
grants.create(data).then(done.bind(null, null)).catch(done.bind(null, null));
});

it('should perform a POST request to /api/v2/client-grants', (done) => {
grants.create(data).then(() => {
expect(request.isDone()).toBe(true);

done();
});
});

it('should include the token in the Authorization header', (done) => {
nock.cleanAll();

const request = nock(API_URL)
.post('/client-grants')
.matchHeader('Authorization', `Bearer ${token}`)
.reply(201, data);

grants.create(data).then(() => {
expect(request.isDone()).toBe(true);

done();
});
});

it('should include the new client grant data in the request body', (done) => {
nock.cleanAll();

const request = nock(API_URL).post('/client-grants', data).reply(201, data);

grants.create(data).then(() => {
expect(request.isDone()).toBe(true);

done();
});
it('should get client grants by client id', async () => {
await expect(
clientGrantsManager.getAll({ client_id: 'test-client-id' })
).resolves.toMatchObject({
status: 200,
});
});

describe('#update', () => {
const data = {
client_id: 'CLIENT_ID',
audience: 'AUDIENCE',
scope: ['user'],
};
let request: nock.Scope;

beforeEach(() => {
request = nock(API_URL).patch(`/client-grants/5`).reply(200, data);
});

it('should return a promise if no callback is given', (done) => {
grants.update({ id: '5' }, {}).then(done.bind(null, null)).catch(done.bind(null, null));
});

it('should perform a PATCH request to /api/v2/client-grants/5', (done) => {
grants.update({ id: '5' }, {}).then(() => {
expect(request.isDone()).toBe(true);

done();
});
});

it('should include the new data in the body of the request', (done) => {
nock.cleanAll();

const request = nock(API_URL).patch(`/client-grants/5`, data).reply(200, data);

grants.update({ id: '5' }, data).then(() => {
expect(request.isDone()).toBe(true);

done();
});
it('should get client grants by client id and allow_any_organization', async () => {
await expect(
clientGrantsManager.getAll({ client_id: 'test-client-id', allow_any_organization: true })
).resolves.toMatchObject({
status: 200,
});
});

describe('#delete', () => {
const id = '5';
let request: nock.Scope;

beforeEach(() => {
request = nock(API_URL).delete(`/client-grants/${id}`).reply(200, {});
it('should update a client grant', async () => {
await expect(
clientGrantsManager.update({ id: 'test-client-grant' }, { scope: ['read:foo', 'read:bar'] })
).resolves.toMatchObject({
status: 200,
});
});

it('should return a promise when no callback is given', (done) => {
grants.delete({ id }).then(done.bind(null, null));
it('should delete a client grant', async () => {
await expect(clientGrantsManager.delete({ id: 'test-client-grant' })).resolves.toMatchObject({
status: 204,
});
});

it(`should perform a DELETE request to /client-grants/${id}`, (done) => {
grants.delete({ id }).then(() => {
expect(request.isDone()).toBe(true);

done();
});
it('should get an organization by client grant', async () => {
await expect(
clientGrantsManager.getOrganizations({ id: 'test-client-grant' })
).resolves.toMatchObject({
status: 200,
});
});
});
Loading

0 comments on commit c2a4292

Please sign in to comment.