forked from medplum/medplum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.setup.ts
229 lines (207 loc) · 6.27 KB
/
test.setup.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
import { createReference, getReferenceString, ProfileResource, sleep } from '@medplum/core';
import {
AccessPolicy,
AsyncJob,
Bundle,
ClientApplication,
Login,
Project,
ProjectMembership,
Resource,
User,
} from '@medplum/fhirtypes';
import { randomUUID } from 'crypto';
import { Express } from 'express';
import request from 'supertest';
import { inviteUser } from './admin/invite';
import { AuthenticatedRequestContext, requestContextStore } from './context';
import { getSystemRepo } from './fhir/repo';
import { generateAccessToken } from './oauth/keys';
import { tryLogin } from './oauth/utils';
export async function createTestProject(
projectOptions?: Partial<Project>,
membershipOptions?: Partial<ProjectMembership>
): Promise<{
project: Project;
client: ClientApplication;
membership: ProjectMembership;
login: Login;
accessToken: string;
}> {
requestContextStore.enterWith(AuthenticatedRequestContext.system());
const systemRepo = getSystemRepo();
const project = await systemRepo.createResource<Project>({
resourceType: 'Project',
name: 'Test Project',
owner: {
reference: 'User/' + randomUUID(),
},
strictMode: true,
features: ['bots', 'email', 'graphql-introspection', 'cron'],
secret: [
{
name: 'foo',
valueString: 'bar',
},
],
...projectOptions,
});
const client = await systemRepo.createResource<ClientApplication>({
resourceType: 'ClientApplication',
secret: randomUUID(),
redirectUri: 'https://example.com/',
meta: {
project: project.id as string,
},
name: 'Test Client Application',
});
const membership = await systemRepo.createResource<ProjectMembership>({
resourceType: 'ProjectMembership',
user: createReference(client),
profile: createReference(client),
project: createReference(project),
...membershipOptions,
});
const scope = 'openid';
const login = await systemRepo.createResource<Login>({
resourceType: 'Login',
authMethod: 'client',
user: createReference(client),
client: createReference(client),
membership: createReference(membership),
authTime: new Date().toISOString(),
superAdmin: projectOptions?.superAdmin,
scope,
});
const accessToken = await generateAccessToken({
login_id: login.id as string,
sub: client.id as string,
username: client.id as string,
client_id: client.id as string,
profile: client.resourceType + '/' + client.id,
scope,
});
return {
project,
client,
membership,
login,
accessToken,
};
}
export async function createTestClient(
projectOptions?: Partial<Project>,
membershipOptions?: Partial<ProjectMembership>
): Promise<ClientApplication> {
return (await createTestProject(projectOptions, membershipOptions)).client;
}
export async function initTestAuth(
projectOptions?: Partial<Project>,
membershipOptions?: Partial<ProjectMembership>
): Promise<string> {
return (await createTestProject(projectOptions, membershipOptions)).accessToken;
}
export async function addTestUser(
project: Project,
accessPolicy?: AccessPolicy
): Promise<{ user: User; profile: ProfileResource; accessToken: string }> {
requestContextStore.enterWith(AuthenticatedRequestContext.system());
if (accessPolicy) {
const systemRepo = getSystemRepo();
accessPolicy = await systemRepo.createResource<AccessPolicy>({
...accessPolicy,
meta: { project: project.id },
});
}
const email = randomUUID() + '@example.com';
const password = randomUUID();
const { user, profile } = await inviteUser({
project,
email,
password,
resourceType: 'Practitioner',
firstName: 'Bob',
lastName: 'Jones',
sendEmail: false,
membership: {
accessPolicy: accessPolicy && createReference(accessPolicy),
},
});
const login = await tryLogin({
authMethod: 'password',
email,
password,
scope: 'openid',
nonce: 'nonce',
});
const accessToken = await generateAccessToken({
login_id: login.id as string,
sub: user.id,
username: user.id as string,
scope: login.scope as string,
profile: getReferenceString(profile),
});
return { user, profile, accessToken };
}
/**
* Sets up the pwnedPassword mock to handle "Have I Been Pwned" requests.
* @param pwnedPassword - The pwnedPassword mock.
* @param numPwns - The mock value to return. Zero is a safe password.
*/
export function setupPwnedPasswordMock(pwnedPassword: jest.Mock, numPwns: number): void {
pwnedPassword.mockImplementation(async () => numPwns);
}
/**
* Sets up the fetch mock to handle Recaptcha requests.
* @param fetch - The fetch mock.
* @param success - Whether the mock should return a successful response.
*/
export function setupRecaptchaMock(fetch: jest.Mock, success: boolean): void {
fetch.mockImplementation(() => ({
status: 200,
json: () => ({ success }),
}));
}
/**
* Returns true if the resource is in an entry in the bundle.
* @param bundle - A bundle of resources.
* @param resource - The resource to search for.
* @returns True if the resource is in the bundle.
*/
export function bundleContains(bundle: Bundle, resource: Resource): boolean {
return !!bundle.entry?.some((entry) => entry.resource?.id === resource.id);
}
/**
* Waits for a function to evaluate successfully.
* Use this to wait for async behaviors without a handle.
* @param fn - Function to call.
*/
export function waitFor(fn: () => Promise<void>): Promise<void> {
return new Promise((resolve) => {
const timer = setInterval(() => {
fn()
.then(() => {
clearTimeout(timer);
resolve();
})
.catch(() => {
// ignore
});
}, 100);
});
}
export async function waitForAsyncJob(contentLocation: string, app: Express, accessToken: string): Promise<AsyncJob> {
for (let i = 0; i < 10; i++) {
const res = await request(app)
.get(new URL(contentLocation).pathname)
.set('Authorization', 'Bearer ' + accessToken);
if (res.status !== 202) {
return res.body as AsyncJob;
}
await sleep(1000);
}
throw new Error('Async Job did not complete');
}
export function withTestContext<T>(fn: () => T, ctx?: { requestId?: string; traceId?: string }): T {
return requestContextStore.run(AuthenticatedRequestContext.system(ctx), fn);
}