@juit/lib-aws-mock 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,211 @@
1
+ # Apache License
2
+
3
+ Version 2.0, January 2004
4
+
5
+ [http://www.apache.org/licenses/](http://www.apache.org/licenses/)
6
+
7
+ ##### TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ ### 1. Definitions.
10
+
11
+ "**License**" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "**Licensor**" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "**Legal Entity**" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "**control**" means **(i)** the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, _or_ **(ii)** ownership of fifty percent (50%) or more of
23
+ the outstanding shares, _or_ **(iii)** beneficial ownership of such
24
+ entity.
25
+
26
+ "**You**" (or "**Your**") shall mean an individual or Legal Entity
27
+ exercising permissions granted by this License.
28
+
29
+ "**Source**" form shall mean the preferred form for making
30
+ modifications, including but not limited to software source code,
31
+ documentation source, and configuration files.
32
+
33
+ "**Object**" form shall mean any form resulting from mechanical
34
+ transformation or translation of a Source form, including but not
35
+ limited to compiled object code, generated documentation, and
36
+ conversions to other media types.
37
+
38
+ "**Work**" shall mean the work of authorship, whether in Source or
39
+ Object form, made available under the License, as indicated by a
40
+ copyright notice that is included in or attached to the work (an example
41
+ is provided in the Appendix below).
42
+
43
+ "**Derivative Works**" shall mean any work, whether in Source or Object
44
+ form, that is based on (or derived from) the Work and for which the
45
+ editorial revisions, annotations, elaborations, or other modifications
46
+ represent, as a whole, an original work of authorship. For the purposes
47
+ of this License, Derivative Works shall not include works that remain
48
+ separable from, or merely link (or bind by name) to the interfaces of,
49
+ the Work and Derivative Works thereof.
50
+
51
+ "**Contribution**" shall mean any work of authorship, including the
52
+ original version of the Work and any modifications or additions to that
53
+ Work or Derivative Works thereof, that is intentionally submitted to
54
+ Licensor for inclusion in the Work by the copyright owner or by an
55
+ individual or Legal Entity authorized to submit on behalf of the
56
+ copyright owner. For the purposes of this definition, "**submitted**"
57
+ means any form of electronic, verbal, or written communication sent to
58
+ the Licensor or its representatives, including but not limited to
59
+ communication on electronic mailing lists, source code control systems,
60
+ and issue tracking systems that are managed by, or on behalf of, the
61
+ Licensor for the purpose of discussing and improving the Work, but
62
+ excluding communication that is conspicuously marked or otherwise
63
+ designated in writing by the copyright owner as "**Not a
64
+ Contribution**".
65
+
66
+ "**Contributor**" shall mean Licensor and any individual or Legal Entity
67
+ on behalf of whom a Contribution has been received by Licensor and
68
+ subsequently incorporated within the Work.
69
+
70
+ ### 2. Grant of Copyright License.
71
+
72
+ Subject to the terms and conditions of this License, each Contributor
73
+ hereby grants to You a perpetual, worldwide, non-exclusive, no-charge,
74
+ royalty-free, irrevocable copyright license to reproduce, prepare
75
+ Derivative Works of, publicly display, publicly perform, sublicense,
76
+ and distribute the Work and such Derivative Works in Source or Object
77
+ form.
78
+
79
+ ### 3. Grant of Patent License.
80
+
81
+ Subject to the terms and conditions of this License, each Contributor
82
+ hereby grants to You a perpetual, worldwide, non-exclusive, no-charge,
83
+ royalty-free, irrevocable (except as stated in this section) patent
84
+ license to make, have made, use, offer to sell, sell, import, and
85
+ otherwise transfer the Work, where such license applies only to those
86
+ patent claims licensable by such Contributor that are necessarily
87
+ infringed by their Contribution(s) alone or by combination of their
88
+ Contribution(s) with the Work to which such Contribution(s) was
89
+ submitted. If You institute patent litigation against any entity
90
+ (including a cross-claim or counterclaim in a lawsuit) alleging that
91
+ the Work or a Contribution incorporated within the Work constitutes
92
+ direct or contributory patent infringement, then any patent licenses
93
+ granted to You under this License for that Work shall terminate as of
94
+ the date such litigation is filed.
95
+
96
+ ### 4. Redistribution.
97
+
98
+ You may reproduce and distribute copies of the Work or Derivative Works
99
+ thereof in any medium, with or without modifications, and in Source or
100
+ Object form, provided that You meet the following conditions:
101
+
102
+ <ol type="a">
103
+ <li>You must give any other recipients of the Work or Derivative Works
104
+ a copy of this License; and
105
+ <li>You must cause any modified files to carry prominent notices
106
+ stating that You changed the files; and
107
+ <li>You must retain, in the Source form of any Derivative Works that
108
+ You distribute, all copyright, patent, trademark, and attribution
109
+ notices from the Source form of the Work, excluding those notices
110
+ that do not pertain to any part of the Derivative Works; and
111
+ <li>If the Work includes a "NOTICE" text file as part of its
112
+ distribution, then any Derivative Works that You distribute must
113
+ include a readable copy of the attribution notices contained within
114
+ such NOTICE file, excluding those notices that do not pertain to any
115
+ part of the Derivative Works, in at least one of the following
116
+ places: within a NOTICE text file distributed as part of the
117
+ Derivative Works; within the Source form or documentation, if
118
+ provided along with the Derivative Works; or, within a display
119
+ generated by the Derivative Works, if and wherever such third-party
120
+ notices normally appear. The contents of the NOTICE file are for
121
+ informational purposes only and do not modify the License. You may
122
+ add Your own attribution notices within Derivative Works that You
123
+ distribute, alongside or as an addendum to the NOTICE text from the
124
+ Work, provided that such additional attribution notices cannot be
125
+ construed as modifying the License.
126
+ </ol>
127
+
128
+ You may add Your own copyright statement to Your modifications and may
129
+ provide additional or different license terms and conditions for use,
130
+ reproduction, or distribution of Your modifications, or for any such
131
+ Derivative Works as a whole, provided Your use, reproduction, and
132
+ distribution of the Work otherwise complies with the conditions stated
133
+ in this License.
134
+
135
+ ### 5. Submission of Contributions.
136
+
137
+ Unless You explicitly state otherwise, any Contribution intentionally
138
+ submitted for inclusion in the Work by You to the Licensor shall be
139
+ under the terms and conditions of this License, without any additional
140
+ terms or conditions. Notwithstanding the above, nothing herein shall
141
+ supersede or modify the terms of any separate license agreement you may
142
+ have executed with Licensor regarding such Contributions.
143
+
144
+ ### 6. Trademarks.
145
+
146
+ This License does not grant permission to use the trade names,
147
+ trademarks, service marks, or product names of the Licensor, except as
148
+ required for reasonable and customary use in describing the origin of
149
+ the Work and reproducing the content of the NOTICE file.
150
+
151
+ ### 7. Disclaimer of Warranty.
152
+
153
+ Unless required by applicable law or agreed to in writing, Licensor
154
+ provides the Work (and each Contributor provides its Contributions) on
155
+ an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
156
+ express or implied, including, without limitation, any warranties or
157
+ conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR
158
+ A PARTICULAR PURPOSE. You are solely responsible for determining the
159
+ appropriateness of using or redistributing the Work and assume any risks
160
+ associated with Your exercise of permissions under this License.
161
+
162
+ ### 8. Limitation of Liability.
163
+
164
+ In no event and under no legal theory, whether in tort (including
165
+ negligence), contract, or otherwise, unless required by applicable law
166
+ (such as deliberate and grossly negligent acts) or agreed to in writing,
167
+ shall any Contributor be liable to You for damages, including any
168
+ direct, indirect, special, incidental, or consequential damages of any
169
+ character arising as a result of this License or out of the use or
170
+ inability to use the Work (including but not limited to damages for loss
171
+ of goodwill, work stoppage, computer failure or malfunction, or any and
172
+ all other commercial damages or losses), even if such Contributor has
173
+ been advised of the possibility of such damages.
174
+
175
+ ### 9. Accepting Warranty or Additional Liability.
176
+
177
+ While redistributing the Work or Derivative Works thereof, You may
178
+ choose to offer, and charge a fee for, acceptance of support, warranty,
179
+ indemnity, or other liability obligations and/or rights consistent with
180
+ this License. However, in accepting such obligations, You may act only
181
+ on Your own behalf and on Your sole responsibility, not on behalf of any
182
+ other Contributor, and only if You agree to indemnify, defend, and hold
183
+ each Contributor harmless for any liability incurred by, or claims
184
+ asserted against, such Contributor by reason of your accepting any
185
+ such warranty or additional liability.
186
+
187
+ ##### END OF TERMS AND CONDITIONS
188
+
189
+ ## APPENDIX: How to apply the Apache License to your work.
190
+
191
+ To apply the Apache License to your work, attach the following
192
+ boilerplate notice, with the fields enclosed by brackets "[]"
193
+ replaced with your own identifying information. (Don't include the
194
+ brackets!) The text should be enclosed in the appropriate comment
195
+ syntax for the file format. We also recommend that a file or class name
196
+ and description of purpose be included on the same "printed page" as the
197
+ copyright notice for easier identification within third-party archives.
198
+
199
+ > #### Copyright [yyyy] [name of copyright owner]
200
+ >
201
+ > Licensed under the Apache License, Version 2.0 (the "License");
202
+ > you may not use this file except in compliance with the License.
203
+ > You may obtain a copy of the License at
204
+ >
205
+ > [http://www.apache.org/licenses/](http://www.apache.org/licenses/)
206
+ >
207
+ > Unless required by applicable law or agreed to in writing, software
208
+ > distributed under the License is distributed on an "AS IS" BASIS,
209
+ > WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
210
+ > See the License for the specific language governing permissions and
211
+ > limitations under the License.
package/NOTICE.md ADDED
@@ -0,0 +1,13 @@
1
+ # Copyright 2021-2023 Juit GmbH
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License");
4
+ you may not use this file except in compliance with the License.
5
+ You may obtain a copy of the License at
6
+
7
+ [http://www.apache.org/licenses/](http://www.apache.org/licenses/)
8
+
9
+ Unless required by applicable law or agreed to in writing, software
10
+ distributed under the License is distributed on an "AS IS" BASIS,
11
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ See the License for the specific language governing permissions and
13
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,126 @@
1
+ # Easy Mocking for AWS SDK v3
2
+
3
+ A simple way to create mocks for the AWS SDK v3 library.
4
+
5
+ * [Mocking commands](#mocking-commands)
6
+ * [Call Tracing](#call-tracing)
7
+ * [State for Handlers](#state-for-handlers)
8
+ * [Resetting](#resetting)
9
+ * [Destroying](#destroying)
10
+ * [Typical Test Scenario](#typical-test-scenario)
11
+ * [License](LICENSE.md)
12
+ * [Copyright Notice](NOTICE.md)
13
+
14
+
15
+ ## Mocking commands
16
+
17
+ Mocking commands for an AWS client is quite easy. For example:
18
+
19
+ ```typescript
20
+ import { AWSMock } from '@juit/lib-aws-mock'
21
+ import {
22
+ AssumeRoleCommand,
23
+ GetCallerIdentityCommand,
24
+ STS,
25
+ } from '@aws-sdk/client-sts'
26
+
27
+ const mock = new AWSMock(STS)
28
+ .on(GetCallerIdentityCommand, (input, state) => {
29
+ // here `input` will be the parameter passed to `getCallerIdentity(...)`
30
+ // and `state` will be whatever was passed to `mock.setState(...)`
31
+ return { Account: 'the account' }
32
+ })
33
+ .on(AssumeRoleCommand, (input, state) => {
34
+ // ... mocked implementation lives here...
35
+ })
36
+
37
+ const sts = new STS({})
38
+ const identity = await sts.getCallerIdentity({})
39
+ // here `identity` will be `{ Account: 'the account' }`
40
+ // as returned by our handler configured in the mock
41
+ ```
42
+
43
+
44
+ ## Call Tracing
45
+
46
+ Instances of `AWSMock` provide a `getCalls()` function returning
47
+ all calls invoked on the mock. Calls will contain the following:
48
+
49
+ * `command`: The _string_ name of the command invoked
50
+ * `input`: The input given to the call
51
+ * `success`: A _boolean_ indicating whether the call succeeded or not
52
+
53
+ ```typescript
54
+ const identity = await sts.getCallerIdentity({})
55
+
56
+ const calls = mock.calls()
57
+ // here `calls` will be:
58
+ // {
59
+ // command: 'GetCallerIdentityCommand',
60
+ // input: '',
61
+ // success: true,
62
+ // }
63
+ ```
64
+
65
+
66
+ ## State for Handlers
67
+
68
+ Instances of `AWSMock` provide a `setState(...)` function which can be used
69
+ to pass extra data to handlers:
70
+
71
+ ```typescript
72
+ const mock = new AWSMock<string>(STS)
73
+ .on(GetCallerIdentityCommand, (input, state) => {
74
+ // state will have a `string` type
75
+ return { Account: state || 'the account' }
76
+ })
77
+
78
+ const sts = new STS({})
79
+
80
+ const identity1 = await sts.getCallerIdentity({})
81
+ // here identity1 will be `{ Account: 'the account' }`
82
+
83
+ mock.setState('another account') // set the stae
84
+ const identity2 = await sts.getCallerIdentity({})
85
+ // here identity2 will be `{ Account: 'another account' }`
86
+ ```
87
+
88
+
89
+ ## Resetting
90
+
91
+ Reseting [calls](#call-tracing) and [state](#state-for-handlers) is as easy as
92
+ calling the `reset()` function on the mock instance.
93
+
94
+
95
+ ## Destroying
96
+
97
+ Destroying the mock instance and un-hooking it from the client can be done
98
+ calling the `destroy()` function on the mock instance.
99
+
100
+
101
+ ## Typical Test Scenario
102
+
103
+ A typical test scenario can look somehow like this:
104
+
105
+ ```typescript
106
+ describe('My Suite', () => {
107
+ let mock: AWSMock
108
+
109
+ beforeAll(() => {
110
+ mock = new AWSMock(STS)
111
+ .on(GetCallerIdentityCommand, (input, state) => {
112
+ // ... mocked implementation lives here...
113
+ })
114
+ .on(AssumeRoleCommand, (input, state) => {
115
+ // ... mocked implementation lives here...
116
+ })
117
+ })
118
+
119
+ afterAll(() => mock.destroy())
120
+ afterEach(() => mock.reset())
121
+
122
+ it('should run this spec', async () => {
123
+ // ... here's your spec...
124
+ })
125
+ })
126
+ ```
package/dist/index.cjs ADDED
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // index.ts
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ AWSMock: () => AWSMock
24
+ });
25
+ module.exports = __toCommonJS(src_exports);
26
+ var import_node_crypto = require("node:crypto");
27
+ var AWSMock = class {
28
+ // Overload to hide private parameter
29
+ constructor(_client) {
30
+ this._client = _client;
31
+ this._send = _client.prototype.send;
32
+ const clientName = _client.name || /* coverage ignore next */
33
+ "[Unknown Client]";
34
+ _client.prototype.send = (_command, ..._args) => {
35
+ const commandProto = Object.getPrototypeOf(_command);
36
+ const commandConstuctor = commandProto.constructor;
37
+ const commandName = commandConstuctor?.name || /* coverage ignore next */
38
+ "[Unknown Command]";
39
+ const lastArgument = _args.pop();
40
+ const cb = typeof lastArgument === "function" ? lastArgument : void 0;
41
+ const promise = Promise.resolve().then(async () => {
42
+ const handler = this._handlers.get(commandConstuctor);
43
+ if (!handler)
44
+ throw new Error(`No mock for "${clientName}.${commandName}"`);
45
+ const result = await handler(_command.input, this._state);
46
+ if (!result)
47
+ throw new Error(`Mock for "${clientName}.${commandName}" returned no result`);
48
+ if (!result.$metadata)
49
+ result.$metadata = { httpStatusCode: 200 };
50
+ if (!result.$metadata.requestId)
51
+ result.$metadata.requestId = (0, import_node_crypto.randomUUID)();
52
+ return result;
53
+ }).then((result) => {
54
+ this._calls.push({ command: commandName, input: _command.input, success: true });
55
+ return result;
56
+ }, (error) => {
57
+ this._calls.push({ command: commandName, input: _command.input, success: false });
58
+ throw error;
59
+ });
60
+ if (cb)
61
+ promise.then((result) => cb(null, result), (error) => cb(error));
62
+ return promise;
63
+ };
64
+ }
65
+ /** All configured command handlers */
66
+ _handlers = /* @__PURE__ */ new Map();
67
+ /** The _original_ (unmocked) `send(...)` method from the client prototype */
68
+ _send;
69
+ /** Current record of all calls handled by this instance */
70
+ _calls = [];
71
+ /** Current state to be passed to handlers */
72
+ _state = void 0;
73
+ /** Associate a _state_ with this instance, to be passed to handlers */
74
+ setState(state) {
75
+ this._state = state;
76
+ }
77
+ /** Return the list of calls executed by this instance */
78
+ getCalls() {
79
+ return this._calls;
80
+ }
81
+ /**
82
+ * Reset this instance by zeroing the {@link AWSMock.calls calls} and wiping
83
+ * the {@link AWSMock.state state}.
84
+ *
85
+ * @returns The list of calls executed by this instance before reset.
86
+ */
87
+ reset() {
88
+ const calls = this._calls;
89
+ delete this._state;
90
+ this._calls = [];
91
+ return calls;
92
+ }
93
+ /** Destroy this instance, restoring the mocked methods */
94
+ destroy() {
95
+ this._client.prototype.send = this._send;
96
+ }
97
+ /** Setup a _handler_ for a specific {@link Command} */
98
+ on(command, handler) {
99
+ this._handlers.set(command, handler);
100
+ return this;
101
+ }
102
+ };
103
+ // Annotate the CommonJS export names for ESM import in node:
104
+ 0 && (module.exports = {
105
+ AWSMock
106
+ });
107
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts"],
4
+ "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,yBAA2B;AAmCpB,IAAM,UAAN,MAA2B;AAAA;AAAA,EAahC,YAAoB,SAAiC;AAAjC;AAElB,SAAK,QAAQ,QAAQ,UAAU;AAG/B,UAAM,aAAa,QAAQ;AAAA,IAAmC;AAG9D,YAAQ,UAAU,OAAO,CAAC,aAAyB,UAA+B;AAChF,YAAM,eAAe,OAAO,eAAe,QAAQ;AACnD,YAAM,oBAAoB,aAAa;AACvC,YAAM,cAAc,mBAAmB;AAAA,MAAmC;AAG1E,YAAM,eAAe,MAAM,IAAI;AAC/B,YAAM,KACJ,OAAO,iBAAiB,aAAa,eAAe;AAGtD,YAAM,UAAU,QAAQ,QAAQ,EAAE,KAAK,YAAY;AAEjD,cAAM,UAAU,KAAK,UAAU,IAAI,iBAAiB;AACpD,YAAI,CAAE;AAAS,gBAAM,IAAI,MAAM,gBAAgB,cAAc,cAAc;AAG3E,cAAM,SAAyB,MAAM,QAAQ,SAAS,OAAO,KAAK,MAAM;AAGxE,YAAI,CAAE;AAAQ,gBAAM,IAAI,MAAM,aAAa,cAAc,iCAAiC;AAG1F,YAAI,CAAE,OAAO;AAAW,iBAAO,YAAY,EAAE,gBAAgB,IAAI;AACjE,YAAI,CAAE,OAAO,UAAU;AAAW,iBAAO,UAAU,gBAAY,+BAAW;AAG1E,eAAO;AAAA,MACT,CAAC,EAAE,KAAK,CAAC,WAAW;AAElB,aAAK,OAAO,KAAK,EAAE,SAAS,aAAa,OAAO,SAAS,OAAO,SAAS,KAAK,CAAC;AAC/E,eAAO;AAAA,MACT,GAAG,CAAC,UAAU;AAEZ,aAAK,OAAO,KAAK,EAAE,SAAS,aAAa,OAAO,SAAS,OAAO,SAAS,MAAM,CAAC;AAChF,cAAM;AAAA,MACR,CAAC;AAGD,UAAI;AAAI,gBAAQ,KAAK,CAAC,WAAW,GAAG,MAAM,MAAM,GAAG,CAAC,UAAU,GAAG,KAAK,CAAC;AACvE,aAAO;AAAA,IACT;AAAA,EACF;AAAA;AAAA,EA7DQ,YAAY,oBAAI,IAAuD;AAAA;AAAA,EAEvE;AAAA;AAAA,EAEA,SAAwB,CAAC;AAAA;AAAA,EAEzB,SAA4B;AAAA;AAAA,EA0DpC,SAAS,OAAgC;AACvC,SAAK,SAAS;AAAA,EAChB;AAAA;AAAA,EAGA,WAAmC;AACjC,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,QAAuB;AACrB,UAAM,QAAQ,KAAK;AACnB,WAAO,KAAK;AACZ,SAAK,SAAS,CAAC;AACf,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,UAAgB;AACd,SAAK,QAAQ,UAAU,OAAO,KAAK;AAAA,EACrC;AAAA;AAAA,EAGA,GACI,SACA,SACI;AACN,SAAK,UAAU,IAAI,SAAS,OAAO;AACnC,WAAO;AAAA,EACT;AACF;",
5
+ "names": []
6
+ }
@@ -0,0 +1,49 @@
1
+ import type { Client, Command, MetadataBearer } from '@aws-sdk/types';
2
+ /** A type identifying _any_ AWS {@link Client} */
3
+ type AnyClient = Client<any, any, any>;
4
+ /** A type identifying _any_ AWS {@link Command} */
5
+ type AnyCommand = Command<any, any, any, any, any>;
6
+ /** Infer the _input type_ of an AWS {@link Command} */
7
+ type CommandInput<T> = T extends Command<any, infer Input, any, any, any> ? Input : never;
8
+ /** Infer the _output type_ of an AWS {@link Command} */
9
+ type CommandOutput<T> = T extends Command<any, any, any, infer Output, any> ? Omit<Output, '$metadata'> & Partial<MetadataBearer> : never;
10
+ /** A type identifying a _constructor_ for an instance */
11
+ type Constructor<T> = new (...args: any) => T;
12
+ /** An interface defining a _call record_ in a {@link AWSMock} */
13
+ export interface AWSMockCall {
14
+ command: string;
15
+ input: any;
16
+ success: boolean;
17
+ }
18
+ /** A _handler_ for intercepting commands in {@link AWSMock} */
19
+ export type AWSMockHandler<Input, Output, State = any> = (input: Input, state: State | undefined) => Output | Promise<Output>;
20
+ /** The {@link AWSMock} class allows easy mocking of AWS clients */
21
+ export declare class AWSMock<State = any> {
22
+ private _client;
23
+ /** All configured command handlers */
24
+ private _handlers;
25
+ /** The _original_ (unmocked) `send(...)` method from the client prototype */
26
+ private _send;
27
+ /** Current record of all calls handled by this instance */
28
+ private _calls;
29
+ /** Current state to be passed to handlers */
30
+ private _state;
31
+ /** Create a new {@link AWSMock} instance mocking the specified {@link Client} */
32
+ constructor(client: Constructor<AnyClient>);
33
+ /** Associate a _state_ with this instance, to be passed to handlers */
34
+ setState(state: State | undefined): void;
35
+ /** Return the list of calls executed by this instance */
36
+ getCalls(): readonly AWSMockCall[];
37
+ /**
38
+ * Reset this instance by zeroing the {@link AWSMock.calls calls} and wiping
39
+ * the {@link AWSMock.state state}.
40
+ *
41
+ * @returns The list of calls executed by this instance before reset.
42
+ */
43
+ reset(): AWSMockCall[];
44
+ /** Destroy this instance, restoring the mocked methods */
45
+ destroy(): void;
46
+ /** Setup a _handler_ for a specific {@link Command} */
47
+ on<AWSCommand extends AnyCommand>(command: new (...args: any) => AWSCommand, handler: AWSMockHandler<CommandInput<AWSCommand>, CommandOutput<AWSCommand>, State>): this;
48
+ }
49
+ export {};
package/dist/index.mjs ADDED
@@ -0,0 +1,82 @@
1
+ // index.ts
2
+ import { randomUUID } from "node:crypto";
3
+ var AWSMock = class {
4
+ // Overload to hide private parameter
5
+ constructor(_client) {
6
+ this._client = _client;
7
+ this._send = _client.prototype.send;
8
+ const clientName = _client.name || /* coverage ignore next */
9
+ "[Unknown Client]";
10
+ _client.prototype.send = (_command, ..._args) => {
11
+ const commandProto = Object.getPrototypeOf(_command);
12
+ const commandConstuctor = commandProto.constructor;
13
+ const commandName = commandConstuctor?.name || /* coverage ignore next */
14
+ "[Unknown Command]";
15
+ const lastArgument = _args.pop();
16
+ const cb = typeof lastArgument === "function" ? lastArgument : void 0;
17
+ const promise = Promise.resolve().then(async () => {
18
+ const handler = this._handlers.get(commandConstuctor);
19
+ if (!handler)
20
+ throw new Error(`No mock for "${clientName}.${commandName}"`);
21
+ const result = await handler(_command.input, this._state);
22
+ if (!result)
23
+ throw new Error(`Mock for "${clientName}.${commandName}" returned no result`);
24
+ if (!result.$metadata)
25
+ result.$metadata = { httpStatusCode: 200 };
26
+ if (!result.$metadata.requestId)
27
+ result.$metadata.requestId = randomUUID();
28
+ return result;
29
+ }).then((result) => {
30
+ this._calls.push({ command: commandName, input: _command.input, success: true });
31
+ return result;
32
+ }, (error) => {
33
+ this._calls.push({ command: commandName, input: _command.input, success: false });
34
+ throw error;
35
+ });
36
+ if (cb)
37
+ promise.then((result) => cb(null, result), (error) => cb(error));
38
+ return promise;
39
+ };
40
+ }
41
+ /** All configured command handlers */
42
+ _handlers = /* @__PURE__ */ new Map();
43
+ /** The _original_ (unmocked) `send(...)` method from the client prototype */
44
+ _send;
45
+ /** Current record of all calls handled by this instance */
46
+ _calls = [];
47
+ /** Current state to be passed to handlers */
48
+ _state = void 0;
49
+ /** Associate a _state_ with this instance, to be passed to handlers */
50
+ setState(state) {
51
+ this._state = state;
52
+ }
53
+ /** Return the list of calls executed by this instance */
54
+ getCalls() {
55
+ return this._calls;
56
+ }
57
+ /**
58
+ * Reset this instance by zeroing the {@link AWSMock.calls calls} and wiping
59
+ * the {@link AWSMock.state state}.
60
+ *
61
+ * @returns The list of calls executed by this instance before reset.
62
+ */
63
+ reset() {
64
+ const calls = this._calls;
65
+ delete this._state;
66
+ this._calls = [];
67
+ return calls;
68
+ }
69
+ /** Destroy this instance, restoring the mocked methods */
70
+ destroy() {
71
+ this._client.prototype.send = this._send;
72
+ }
73
+ /** Setup a _handler_ for a specific {@link Command} */
74
+ on(command, handler) {
75
+ this._handlers.set(command, handler);
76
+ return this;
77
+ }
78
+ };
79
+ export {
80
+ AWSMock
81
+ };
82
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1,6 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts"],
4
+ "mappings": ";AAAA,SAAS,kBAAkB;AAmCpB,IAAM,UAAN,MAA2B;AAAA;AAAA,EAahC,YAAoB,SAAiC;AAAjC;AAElB,SAAK,QAAQ,QAAQ,UAAU;AAG/B,UAAM,aAAa,QAAQ;AAAA,IAAmC;AAG9D,YAAQ,UAAU,OAAO,CAAC,aAAyB,UAA+B;AAChF,YAAM,eAAe,OAAO,eAAe,QAAQ;AACnD,YAAM,oBAAoB,aAAa;AACvC,YAAM,cAAc,mBAAmB;AAAA,MAAmC;AAG1E,YAAM,eAAe,MAAM,IAAI;AAC/B,YAAM,KACJ,OAAO,iBAAiB,aAAa,eAAe;AAGtD,YAAM,UAAU,QAAQ,QAAQ,EAAE,KAAK,YAAY;AAEjD,cAAM,UAAU,KAAK,UAAU,IAAI,iBAAiB;AACpD,YAAI,CAAE;AAAS,gBAAM,IAAI,MAAM,gBAAgB,cAAc,cAAc;AAG3E,cAAM,SAAyB,MAAM,QAAQ,SAAS,OAAO,KAAK,MAAM;AAGxE,YAAI,CAAE;AAAQ,gBAAM,IAAI,MAAM,aAAa,cAAc,iCAAiC;AAG1F,YAAI,CAAE,OAAO;AAAW,iBAAO,YAAY,EAAE,gBAAgB,IAAI;AACjE,YAAI,CAAE,OAAO,UAAU;AAAW,iBAAO,UAAU,YAAY,WAAW;AAG1E,eAAO;AAAA,MACT,CAAC,EAAE,KAAK,CAAC,WAAW;AAElB,aAAK,OAAO,KAAK,EAAE,SAAS,aAAa,OAAO,SAAS,OAAO,SAAS,KAAK,CAAC;AAC/E,eAAO;AAAA,MACT,GAAG,CAAC,UAAU;AAEZ,aAAK,OAAO,KAAK,EAAE,SAAS,aAAa,OAAO,SAAS,OAAO,SAAS,MAAM,CAAC;AAChF,cAAM;AAAA,MACR,CAAC;AAGD,UAAI;AAAI,gBAAQ,KAAK,CAAC,WAAW,GAAG,MAAM,MAAM,GAAG,CAAC,UAAU,GAAG,KAAK,CAAC;AACvE,aAAO;AAAA,IACT;AAAA,EACF;AAAA;AAAA,EA7DQ,YAAY,oBAAI,IAAuD;AAAA;AAAA,EAEvE;AAAA;AAAA,EAEA,SAAwB,CAAC;AAAA;AAAA,EAEzB,SAA4B;AAAA;AAAA,EA0DpC,SAAS,OAAgC;AACvC,SAAK,SAAS;AAAA,EAChB;AAAA;AAAA,EAGA,WAAmC;AACjC,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,QAAuB;AACrB,UAAM,QAAQ,KAAK;AACnB,WAAO,KAAK;AACZ,SAAK,SAAS,CAAC;AACf,WAAO;AAAA,EACT;AAAA;AAAA,EAGA,UAAgB;AACd,SAAK,QAAQ,UAAU,OAAO,KAAK;AAAA,EACrC;AAAA;AAAA,EAGA,GACI,SACA,SACI;AACN,SAAK,UAAU,IAAI,SAAS,OAAO;AACnC,WAAO;AAAA,EACT;AACF;",
5
+ "names": []
6
+ }
package/package.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@juit/lib-aws-mock",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "description": "Easy Mocking for AWS SDK v3",
6
+ "main": "index.js",
7
+ "scripts": {
8
+ "build": "plug",
9
+ "coverage": "plug coverage",
10
+ "dev": "plug coverage -w src -w test",
11
+ "lint": "plug lint",
12
+ "test": "echo \"Error: no test specified\" && exit 1",
13
+ "transpile": "plug transpile"
14
+ },
15
+ "dependencies": {
16
+ "@aws-sdk/types": "^3.296.0"
17
+ },
18
+ "devDependencies": {
19
+ "@aws-sdk/client-sts": "^3.297.0",
20
+ "@plugjs/build": "^0.3.0"
21
+ },
22
+ "author": "Juit Developers <developers@juit.com>",
23
+ "license": "Apache-2.0",
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "https://github.com/juitnow/juit-lib-aws-mock.git"
27
+ },
28
+ "keywords": [
29
+ "aws",
30
+ "aws-sdk",
31
+ "mock",
32
+ "testing"
33
+ ],
34
+ "bugs": {
35
+ "url": "https://github.com/juitnow/juit-lib-aws-mock/issues"
36
+ },
37
+ "homepage": "https://github.com/juitnow/juit-lib-aws-mock#readme",
38
+ "files": [
39
+ "*.md",
40
+ "dist/",
41
+ "src/"
42
+ ],
43
+ "directories": {
44
+ "test": "test"
45
+ }
46
+ }
package/src/index.ts ADDED
@@ -0,0 +1,137 @@
1
+ import { randomUUID } from 'node:crypto'
2
+
3
+ import type { Client, Command, MetadataBearer } from '@aws-sdk/types'
4
+
5
+ /** A type identifying _any_ AWS {@link Client} */
6
+ type AnyClient = Client<any, any, any>
7
+
8
+ /** A type identifying _any_ AWS {@link Command} */
9
+ type AnyCommand = Command<any, any, any, any, any>
10
+
11
+ /** Infer the _input type_ of an AWS {@link Command} */
12
+ type CommandInput<T> =
13
+ T extends Command<any, infer Input, any, any, any> ? Input : never
14
+
15
+ /** Infer the _output type_ of an AWS {@link Command} */
16
+ type CommandOutput<T> =
17
+ T extends Command<any, any, any, infer Output, any> ?
18
+ Omit<Output, '$metadata'> & Partial<MetadataBearer> :
19
+ never
20
+
21
+ /** A type identifying a _constructor_ for an instance */
22
+ type Constructor<T> = new (...args: any) => T
23
+
24
+ /** An interface defining a _call record_ in a {@link AWSMock} */
25
+ export interface AWSMockCall {
26
+ command: string,
27
+ input: any,
28
+ success: boolean,
29
+ }
30
+
31
+ /** A _handler_ for intercepting commands in {@link AWSMock} */
32
+ export type AWSMockHandler<Input, Output, State = any> =
33
+ (input: Input, state: State | undefined) => Output | Promise<Output>
34
+
35
+ /** The {@link AWSMock} class allows easy mocking of AWS clients */
36
+ export class AWSMock<State = any> {
37
+ /** All configured command handlers */
38
+ private _handlers = new Map<Constructor<AnyCommand>, AWSMockHandler<any, any>>()
39
+ /** The _original_ (unmocked) `send(...)` method from the client prototype */
40
+ private _send: AnyClient['send']
41
+ /** Current record of all calls handled by this instance */
42
+ private _calls: AWSMockCall[] = []
43
+ /** Current state to be passed to handlers */
44
+ private _state: State | undefined = undefined
45
+
46
+ /** Create a new {@link AWSMock} instance mocking the specified {@link Client} */
47
+ constructor(client: Constructor<AnyClient>)
48
+ // Overload to hide private parameter
49
+ constructor(private _client: Constructor<AnyClient>) {
50
+ // Remember the original `send` method
51
+ this._send = _client.prototype.send
52
+
53
+ // Figure out the name of the client
54
+ const clientName = _client.name || /* coverage ignore next */ '[Unknown Client]'
55
+
56
+ // Inject our `send` method in the client's prototype
57
+ _client.prototype.send = (_command: AnyCommand, ..._args: any[]): Promise<any> => {
58
+ const commandProto = Object.getPrototypeOf(_command)
59
+ const commandConstuctor = commandProto.constructor
60
+ const commandName = commandConstuctor?.name || /* coverage ignore next */ '[Unknown Command]'
61
+
62
+ // Figure out if we have a callback
63
+ const lastArgument = _args.pop()
64
+ const cb: ((err: any, data?: any) => void) | undefined =
65
+ typeof lastArgument === 'function' ? lastArgument : undefined
66
+
67
+ // Always work with promises
68
+ const promise = Promise.resolve().then(async () => {
69
+ // Get the handler for the method and verify it
70
+ const handler = this._handlers.get(commandConstuctor)
71
+ if (! handler) throw new Error(`No mock for "${clientName}.${commandName}"`)
72
+
73
+ // Call the handler and get the result
74
+ const result: MetadataBearer = await handler(_command.input, this._state)
75
+
76
+ // If no result (null loose check) then simply return a 404
77
+ if (! result) throw new Error(`Mock for "${clientName}.${commandName}" returned no result`)
78
+
79
+ // If we don't have some metadata, inject some fake stuff
80
+ if (! result.$metadata) result.$metadata = { httpStatusCode: 200 }
81
+ if (! result.$metadata.requestId) result.$metadata.requestId = randomUUID()
82
+
83
+ // All done!
84
+ return result
85
+ }).then((result) => {
86
+ // On success, record the call and return the result
87
+ this._calls.push({ command: commandName, input: _command.input, success: true })
88
+ return result
89
+ }, (error) => {
90
+ // On failure, record the call and throw the error
91
+ this._calls.push({ command: commandName, input: _command.input, success: false })
92
+ throw error
93
+ })
94
+
95
+ // Invoke our callback (if any) and always return the promise
96
+ if (cb) promise.then((result) => cb(null, result), (error) => cb(error))
97
+ return promise
98
+ }
99
+ }
100
+
101
+ /** Associate a _state_ with this instance, to be passed to handlers */
102
+ setState(state: State | undefined): void {
103
+ this._state = state
104
+ }
105
+
106
+ /** Return the list of calls executed by this instance */
107
+ getCalls(): readonly AWSMockCall[] {
108
+ return this._calls
109
+ }
110
+
111
+ /**
112
+ * Reset this instance by zeroing the {@link AWSMock.calls calls} and wiping
113
+ * the {@link AWSMock.state state}.
114
+ *
115
+ * @returns The list of calls executed by this instance before reset.
116
+ */
117
+ reset(): AWSMockCall[] {
118
+ const calls = this._calls
119
+ delete this._state
120
+ this._calls = []
121
+ return calls
122
+ }
123
+
124
+ /** Destroy this instance, restoring the mocked methods */
125
+ destroy(): void {
126
+ this._client.prototype.send = this._send
127
+ }
128
+
129
+ /** Setup a _handler_ for a specific {@link Command} */
130
+ on<AWSCommand extends AnyCommand>(
131
+ command: new (...args: any) => AWSCommand,
132
+ handler: AWSMockHandler<CommandInput<AWSCommand>, CommandOutput<AWSCommand>, State>,
133
+ ): this {
134
+ this._handlers.set(command, handler)
135
+ return this
136
+ }
137
+ }