|
| 1 | +import type { IIoHost, IoMessage, IoMessageLevel, IoRequest } from '../../lib/api/io'; |
| 2 | +import { asIoHelper, isMessageRelevantForLevel, type IoHelper } from '../../lib/api/shared-private'; |
| 3 | +import { RequireApproval } from '../../lib/toolkit'; |
| 4 | + |
| 5 | +/** |
| 6 | + * A test implementation of IIoHost that does nothing but can be spied on. |
| 7 | + * |
| 8 | + * Includes a level to filter out irrelevant messages, defaults to `info`. |
| 9 | + * |
| 10 | + * Optionally set an approval level for code `CDK_TOOLKIT_I5060`. |
| 11 | + * |
| 12 | + * # How to use |
| 13 | + * |
| 14 | + * Configure and reset the `notifySpy` and `requestSpy` members as you would any |
| 15 | + * mock function. |
| 16 | + */ |
| 17 | +export class TestIoHost implements IIoHost { |
| 18 | + public readonly notifySpy: jest.Mock<any, any, any>; |
| 19 | + public readonly requestSpy: jest.Mock<any, any, any>; |
| 20 | + |
| 21 | + public requireDeployApproval = RequireApproval.NEVER; |
| 22 | + |
| 23 | + constructor(public level: IoMessageLevel = 'info') { |
| 24 | + this.notifySpy = jest.fn(); |
| 25 | + this.requestSpy = jest.fn(); |
| 26 | + } |
| 27 | + |
| 28 | + public asHelper(action = 'synth'): IoHelper { |
| 29 | + return asIoHelper(this, action as any); |
| 30 | + } |
| 31 | + |
| 32 | + public async notify(msg: IoMessage<unknown>): Promise<void> { |
| 33 | + if (isMessageRelevantForLevel(msg, this.level)) { |
| 34 | + this.notifySpy(msg); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + public async requestResponse<T, U>(msg: IoRequest<T, U>): Promise<U> { |
| 39 | + if (isMessageRelevantForLevel(msg, this.level) && this.needsApproval(msg)) { |
| 40 | + this.requestSpy(msg); |
| 41 | + } |
| 42 | + return msg.defaultResponse; |
| 43 | + } |
| 44 | + |
| 45 | + private needsApproval(msg: IoRequest<any, any>): boolean { |
| 46 | + // Return true if the code is unrelated to approval |
| 47 | + if (!['CDK_TOOLKIT_I5060'].includes(msg.code)) { |
| 48 | + return true; |
| 49 | + } |
| 50 | + |
| 51 | + switch (this.requireDeployApproval) { |
| 52 | + case RequireApproval.NEVER: |
| 53 | + return false; |
| 54 | + case RequireApproval.ANY_CHANGE: |
| 55 | + return true; |
| 56 | + case RequireApproval.BROADENING: |
| 57 | + return msg.data?.permissionChangeType === 'broadening'; |
| 58 | + default: |
| 59 | + return true; |
| 60 | + } |
| 61 | + } |
| 62 | +} |
0 commit comments