-
Notifications
You must be signed in to change notification settings - Fork 547
/
test-http-handler.ts
209 lines (188 loc) · 5.94 KB
/
test-http-handler.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
import { HttpHandler, HttpRequest, HttpResponse } from "@aws-sdk/protocol-http";
import { Client, HttpHandlerOptions, RequestHandler, RequestHandlerOutput } from "@aws-sdk/types";
/**
* Instructs {@link TestHttpHandler} how to match the handled request and the expected request.
* @internal
*/
export type Matcher = string | number | boolean | RegExp | null | undefined | ((value: any) => void);
/**
* @internal
*/
export type HttpRequestMatcher = {
// endpoint
protocol?: Matcher;
hostname?: Matcher;
port?: Matcher;
path?: Matcher;
query?: Record<string, Matcher> | Map<RegExp | string, Matcher>;
// message
headers?: Record<string, Matcher> | Map<RegExp | string, Matcher>;
body?: Matcher;
method?: Matcher;
// debug option
log?: boolean;
};
/**
* @internal
*/
const MOCK_CREDENTIALS = {
accessKeyId: "MOCK_ACCESS_KEY_ID",
secretAccessKey: "MOCK_SECRET_ACCESS_KEY_ID",
};
/**
* Supplied to test clients to assert correct requests.
* @internal
*/
export class TestHttpHandler implements HttpHandler {
private static WATCHER = Symbol("TestHttpHandler_WATCHER");
private originalSend?: Function;
private originalRequestHandler?: RequestHandler<any, any, any>;
private client?: Client<any, any, any>;
private assertions = 0;
public constructor(public readonly matcher: HttpRequestMatcher) {}
/**
* @param client - to watch for requests.
* @param matcher - optional override of this instance's matchers.
*
* Temporarily hooks the client.send call to check the outgoing request.
*/
public watch(client: Client<any, any, any>, matcher: HttpRequestMatcher = this.matcher) {
this.client = client;
this.originalRequestHandler = client.config.originalRequestHandler;
// mock credentials to avoid default chain lookup.
client.config.credentials = async () => MOCK_CREDENTIALS;
client.config.credentialDefaultProvider = () => {
return async () => {
return MOCK_CREDENTIALS;
};
};
const signerProvider = client.config.signer;
if (typeof signerProvider === "function") {
client.config.signer = async () => {
const _signer = await signerProvider();
if (typeof _signer.credentialProvider === "function") {
// signer is instance of SignatureV4
_signer.credentialProvider = async () => {
return MOCK_CREDENTIALS;
};
}
return _signer;
};
}
client.config.requestHandler = new TestHttpHandler(matcher);
if (!(client as any)[TestHttpHandler.WATCHER]) {
(client as any)[TestHttpHandler.WATCHER] = true;
const originalSend = (this.originalSend = client.send as any);
client.send = async function (...args: any[]) {
return originalSend.apply(client, args).catch((e: unknown) => {
if ((e as any).id === TestHttpHandlerSuccess.ID) {
} else {
throw e;
}
});
};
}
}
/**
* @throws TestHttpHandlerSuccess to indicate success (only way to control it).
* @throws Error any other exception to indicate failure.
*/
public async handle(
request: HttpRequest,
handlerOptions?: HttpHandlerOptions
): Promise<RequestHandlerOutput<HttpResponse>> {
const m = this.matcher;
if (m.log) {
console.log(request);
}
this.check(m.protocol, request.protocol);
this.check(m.hostname, request.hostname);
this.check(m.port, request.port);
this.check(m.path, request.path);
this.checkAll(m.query, request.query);
this.checkAll(m.headers, request.headers);
this.check(m.body, request.body);
this.check(m.method, request.method);
if (this.assertions === 0) {
throw new Error("Request handled with no assertions, empty matcher?");
}
throw new TestHttpHandlerSuccess();
}
public async destroy(): Promise<void> {
(this.client as any).config.requestHandler = this.originalRequestHandler;
(this.client as any).send = this.originalSend as any;
}
private check(matcher?: Matcher, observed?: any) {
if (matcher === undefined) {
return;
}
switch (typeof matcher) {
case "string":
if (matcher.startsWith("/") && matcher.endsWith("/")) {
expect(String(observed)).toMatch(new RegExp(matcher));
} else {
expect(observed).toEqual(matcher);
}
break;
case "number":
case "bigint":
case "boolean":
expect(observed).toEqual(matcher);
break;
case "object":
if (matcher instanceof RegExp) {
expect(String(observed)).toMatch(matcher);
}
break;
case "function":
matcher(observed);
break;
default:
throw new Error("Matcher did not create assertion");
}
this.assertions++;
}
private checkAll(matchers?: Record<string, Matcher> | Map<RegExp | string, Matcher>, observed?: any) {
if (matchers == null) {
return;
}
let key: string | RegExp;
for (const [_key, matcher] of matchers instanceof Map ? matchers : Object.entries(matchers)) {
key = _key;
if (typeof key === "string") {
if (key.startsWith("/") && key.endsWith("/")) {
key = new RegExp(key);
} else {
this.check(matcher, observed[key]);
}
}
if (key instanceof RegExp) {
for (const [observedKey, observedValue] of Object.entries(observed)) {
if (key.test(observedKey)) {
this.check(matcher, observedValue);
}
}
}
}
}
}
/**
* This is used as an interrupt signal for success.
* It does not indicate a true error.
*
* @internal
*/
export class TestHttpHandlerSuccess extends Error {
public static readonly ID = Symbol("TestHttpHandlerSuccess");
public readonly id = TestHttpHandlerSuccess.ID;
}
/**
* @internal
*/
export const requireRequestsFrom = (client: Client<any, any, any>) => {
return {
toMatch(matcher: HttpRequestMatcher) {
return new TestHttpHandler(matcher).watch(client);
},
};
};