@aloma.io/integration-sdk 3.8.66 → 3.8.68

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.
Files changed (42) hide show
  1. package/README.md +60 -0
  2. package/build/builder/runtime-context.mjs +2 -2
  3. package/build/cli.mjs +0 -0
  4. package/build/controller/index.d.mts +3 -2
  5. package/build/controller/index.mjs +4 -3
  6. package/build/internal/dispatcher/index.d.mts +1 -4
  7. package/build/internal/dispatcher/index.mjs +3 -2
  8. package/build/testing/fake-aloma.d.mts +87 -0
  9. package/build/testing/fake-aloma.mjs +248 -0
  10. package/build/testing/harness.d.mts +51 -0
  11. package/build/testing/harness.mjs +139 -0
  12. package/build/testing/index.d.mts +15 -0
  13. package/build/testing/index.mjs +13 -0
  14. package/build/testing/keys.d.mts +9 -0
  15. package/build/testing/keys.mjs +15 -0
  16. package/build/testing/network-guard.d.mts +3 -0
  17. package/build/testing/network-guard.mjs +49 -0
  18. package/build/testing/runtime-connector.d.mts +11 -0
  19. package/build/testing/runtime-connector.mjs +38 -0
  20. package/build/testing/vendor-mock.d.mts +59 -0
  21. package/build/testing/vendor-mock.mjs +121 -0
  22. package/package.json +8 -4
  23. package/src/builder/runtime-context.mts +2 -2
  24. package/src/controller/index.mts +4 -3
  25. package/src/internal/dispatcher/index.mts +3 -2
  26. package/src/testing/fake-aloma.mts +306 -0
  27. package/src/testing/harness.mts +172 -0
  28. package/src/testing/index.mts +15 -0
  29. package/src/testing/keys.mts +19 -0
  30. package/src/testing/network-guard.mts +57 -0
  31. package/src/testing/runtime-connector.mts +50 -0
  32. package/src/testing/vendor-mock.mts +166 -0
  33. package/test/MUTATION-entry.md +21 -0
  34. package/test/MUTATION.md +43 -0
  35. package/test/dispatcher-ctx-forwarding.test.mjs +161 -0
  36. package/test/harness-connector-smoke.test.mjs +72 -0
  37. package/test/harness.test.mjs +375 -0
  38. package/test/openapi-to-connector.test.mts +25 -7
  39. package/test/scenarios.test.mts +15 -7
  40. package/tools/mutation-run-entry.mjs +52 -0
  41. package/tools/mutation-run.mjs +120 -0
  42. package/tools/run-tests.mjs +64 -0
@@ -0,0 +1,166 @@
1
+ import {installNetworkGuard, uninstallNetworkGuard} from './network-guard.mjs';
2
+
3
+ export type VendorRequest = {
4
+ method: string;
5
+ url: string;
6
+ /** the url exactly as the connector passed it to fetch */
7
+ rawUrl: string;
8
+ headers: Record<string, string>;
9
+ body?: string;
10
+ };
11
+
12
+ export type VendorResponse = {
13
+ status?: number;
14
+ headers?: Record<string, string>;
15
+ /** sent as JSON with a json content-type */
16
+ json?: unknown;
17
+ /** sent as is */
18
+ text?: string;
19
+ };
20
+
21
+ export type VendorResponder = VendorResponse | ((request: VendorRequest) => VendorResponse | Promise<VendorResponse>);
22
+ export type UrlMatcher = string | RegExp | ((url: string) => boolean);
23
+
24
+ type Route = {
25
+ method: string;
26
+ matcher: UrlMatcher;
27
+ respond: VendorResponder;
28
+ times: number;
29
+ used: number;
30
+ };
31
+
32
+ // "https:/host/x" (one slash, which the SDK Fetcher produces) and "https://host/x" are the same URL to fetch
33
+ const canonical = (url: string): string => {
34
+ try {
35
+ return new URL(url).href;
36
+ } catch (e) {
37
+ return url;
38
+ }
39
+ };
40
+
41
+ const matches = (matcher: UrlMatcher, url: string): boolean => {
42
+ if (typeof matcher === 'string') return canonical(matcher) === url;
43
+ if (matcher instanceof RegExp) return matcher.test(url);
44
+ return matcher(url);
45
+ };
46
+
47
+ /**
48
+ * Mock for the HTTP calls a connector makes to its vendor API.
49
+ *
50
+ * - intercepts global fetch (what the SDK Fetcher and OAuth code use)
51
+ * - answers from routes you register with on()/get()/post()...
52
+ * - any request without a route is recorded in `unmocked` and rejected,
53
+ * verify() then fails the test even if the connector swallowed the error
54
+ * - also installs the network guard, so nothing can reach a non-loopback host
55
+ */
56
+ export class VendorMock {
57
+ readonly requests: VendorRequest[] = [];
58
+ readonly unmocked: VendorRequest[] = [];
59
+ private routes: Route[] = [];
60
+ private originalFetch?: typeof fetch;
61
+ private passthrough: (url: URL) => boolean = () => false;
62
+
63
+ /** urls for which the real fetch is used (the fake ALOMA endpoint); everything else is mocked */
64
+ allowPassthrough(fn: (url: URL) => boolean) {
65
+ this.passthrough = fn;
66
+ return this;
67
+ }
68
+
69
+ on(method: string, matcher: UrlMatcher, respond: VendorResponder, options: {times?: number} = {}) {
70
+ this.routes.push({method: method.toUpperCase(), matcher, respond, times: options.times ?? Infinity, used: 0});
71
+ return this;
72
+ }
73
+
74
+ get(matcher: UrlMatcher, respond: VendorResponder, options?: {times?: number}) {
75
+ return this.on('GET', matcher, respond, options);
76
+ }
77
+ post(matcher: UrlMatcher, respond: VendorResponder, options?: {times?: number}) {
78
+ return this.on('POST', matcher, respond, options);
79
+ }
80
+ put(matcher: UrlMatcher, respond: VendorResponder, options?: {times?: number}) {
81
+ return this.on('PUT', matcher, respond, options);
82
+ }
83
+ delete(matcher: UrlMatcher, respond: VendorResponder, options?: {times?: number}) {
84
+ return this.on('DELETE', matcher, respond, options);
85
+ }
86
+
87
+ install() {
88
+ if (this.originalFetch) return this;
89
+
90
+ installNetworkGuard();
91
+ this.originalFetch = globalThis.fetch;
92
+ globalThis.fetch = ((input: any, init?: any) => this.handle(input, init)) as typeof fetch;
93
+
94
+ return this;
95
+ }
96
+
97
+ uninstall() {
98
+ if (!this.originalFetch) return;
99
+
100
+ globalThis.fetch = this.originalFetch;
101
+ this.originalFetch = undefined;
102
+ uninstallNetworkGuard();
103
+ }
104
+
105
+ /** throws if the connector made a request that had no mock, even if it caught the error */
106
+ verify() {
107
+ if (this.unmocked.length) {
108
+ const list = this.unmocked.map((r) => `${r.method} ${r.url}`).join('\n ');
109
+ throw new Error(`UNMOCKED vendor requests were made (no network is allowed in tests):\n ${list}`);
110
+ }
111
+ }
112
+
113
+ /** throws if a registered route was never used */
114
+ verifyAllRoutesUsed() {
115
+ const unused = this.routes.filter((r) => r.used === 0);
116
+ if (unused.length) {
117
+ throw new Error(`mocked routes never called: ${unused.map((r) => `${r.method} ${String(r.matcher)}`).join(', ')}`);
118
+ }
119
+ }
120
+
121
+ private async handle(input: any, init: any = {}): Promise<Response> {
122
+ const rawUrl: string = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
123
+ const url = canonical(rawUrl);
124
+ const method = String(init.method || (typeof input === 'object' && input.method) || 'GET').toUpperCase();
125
+
126
+ const headers: Record<string, string> = {};
127
+ new Headers(init.headers || (typeof input === 'object' && (input as any).headers) || {}).forEach((value, key) => {
128
+ headers[key] = value;
129
+ });
130
+
131
+ const request: VendorRequest = {method, url, rawUrl, headers};
132
+ if (init.body != null) request.body = typeof init.body === 'string' ? init.body : String(init.body);
133
+
134
+ const route = this.routes.find((r) => r.method === method && r.used < r.times && matches(r.matcher, url));
135
+
136
+ if (route) {
137
+ route.used++;
138
+ this.requests.push(request);
139
+ const spec = typeof route.respond === 'function' ? await route.respond(request) : route.respond;
140
+
141
+ const responseHeaders = {...spec.headers};
142
+ let body: string | null = null;
143
+ if (spec.json !== undefined) {
144
+ body = JSON.stringify(spec.json);
145
+ responseHeaders['content-type'] ||= 'application/json';
146
+ } else if (spec.text !== undefined) {
147
+ body = spec.text;
148
+ }
149
+
150
+ const status = spec.status ?? 200;
151
+ return new Response([204, 205, 304].includes(status) ? null : body, {status, headers: responseHeaders});
152
+ }
153
+
154
+ if (this.originalFetch && this.passthrough(new URL(url))) {
155
+ return this.originalFetch(input, init);
156
+ }
157
+
158
+ this.unmocked.push(request);
159
+
160
+ // status 400 makes the SDK Fetcher give up at once instead of retrying for seconds
161
+ const error: any = new Error(`UNMOCKED vendor request: ${method} ${url} (add a route with vendor.on(...))`);
162
+ error.status = 400;
163
+ error.alomaHarnessUnmocked = true;
164
+ throw error;
165
+ }
166
+ }
@@ -0,0 +1,21 @@
1
+ # Mutation check for the SDK tests that `yarn test` now runs
2
+
3
+ Result: **8/8 mutants killed** (24 Oct). Run with `yarn build && node tools/mutation-run-entry.mjs`.
4
+
5
+ Each row is one deliberate single-point bug in `src/openapi-to-connector.mts` (the OpenAPI to connector generator). The
6
+ script applies it alone, rebuilds, runs the full `yarn test`, expects a failure, and restores the file.
7
+
8
+ | # | Bug | Result |
9
+ |---|-----|--------|
10
+ | E01 | the HTTP verb is taken in lower case | killed |
11
+ | E02 | path parameter substitution is guarded by the wrong condition | killed |
12
+ | E03 | fallback method name drops the separator | killed |
13
+ | E04 | body properties are documented with the wrong required flag | killed |
14
+ | E05 | headers are dropped from the generated options type | killed |
15
+ | E06 | options is not defaulted in generated methods | killed |
16
+ | E07 | invalid specs are no longer rejected | killed |
17
+ | E08 | a property is required only if both the schema and the body say so | killed |
18
+
19
+ A first run left two survivors: E02 (nothing asserted the path parameter substitution) and a draft E03 aimed at
20
+ `disambiguateMethodName` (no test reaches it, so a different mutant on the fallback name was used). A test for E02 was
21
+ added to `test/openapi-to-connector.test.mts`; `disambiguateMethodName` remains without direct coverage.
@@ -0,0 +1,43 @@
1
+ # Mutation check for the connector test harness
2
+
3
+ Result: **32/32 mutants killed**.
4
+
5
+ Each row is one deliberate single-point bug in the SDK code paths the harness exercises (handshake, transport,
6
+ dispatch, result return, config) or in the harness itself. `tools/mutation-run.mjs` applies it to `src/`, rebuilds,
7
+ runs `test/harness.test.mjs` with `--bail`, expects a failure, and restores the file. Re-run with
8
+ `yarn build && yarn test:mutation` after changing the harness or those SDK paths.
9
+
10
+ | # | Area | File | Bug | Result |
11
+ |---|------|------|-----|--------|
12
+ | M01 | sdk handshake | `src/internal/websocket/connection/index.mjs` | a 401 from /connect no longer triggers registration | killed |
13
+ | M02 | sdk handshake | `src/internal/websocket/connection/index.mjs` | the token from registration is not stored | killed |
14
+ | M03 | sdk handshake | `src/internal/websocket/connection/registration.mjs` | registration reads the wrong field of the answer | killed |
15
+ | M04 | sdk handshake | `src/internal/websocket/connection/registration.mjs` | registration sends the name as the connector id | killed |
16
+ | M05 | sdk handshake | `src/internal/websocket/connection/registration.mjs` | registration omits the public key | killed |
17
+ | M06 | sdk handshake | `src/internal/websocket/connection/constants.mjs` | authenticated requests drop the version from the User-Agent | killed |
18
+ | M07 | sdk handshake | `src/internal/websocket/connection/constants.mjs` | wrong authorization scheme for the session token | killed |
19
+ | M08 | sdk handshake | `src/internal/websocket/transport/index.mjs` | websocket opened without the "connector" subprotocol | killed |
20
+ | M09 | sdk transport | `src/internal/websocket/transport/index.mjs` | the first packet of every incoming frame is dropped | killed |
21
+ | M10 | sdk transport | `src/internal/websocket/transport/index.mjs` | outgoing frames use the wrong envelope | killed |
22
+ | M11 | sdk transport | `src/internal/websocket/transport/index.mjs` | answers to connector-initiated requests are never routed to their callback | killed |
23
+ | M12 | sdk dispatch | `src/internal/dispatcher/index.mts` | configuration secrets are dropped before onConfig | killed |
24
+ | M13 | sdk dispatch | `src/internal/dispatcher/index.mts` | sticky is not forwarded to the method | killed |
25
+ | M14 | sdk dispatch | `src/internal/dispatcher/index.mts` | unknown methods are no longer reported as "not found" | killed |
26
+ | M15 | sdk result return | `src/internal/dispatcher/index.mts` | scalar results are wrapped under the wrong key | killed |
27
+ | M16 | sdk result return | `src/internal/util/index.mts` | successful results are replied empty | killed |
28
+ | M17 | sdk result return | `src/internal/util/index.mts` | errors lose their message | killed |
29
+ | M18 | sdk result return | `src/internal/connector/server/on-message.mts` | results are never sent back | killed |
30
+ | M19 | sdk config | `src/internal/connector/server/on-connect/decrypt-config.mts` | config is decrypted for the wrong audience | killed |
31
+ | M20 | sdk config | `src/internal/connector/server/on-connect/decrypt-config.mts` | plain fields are decrypted like secrets | killed |
32
+ | M21 | sdk config | `src/internal/connector/server/on-connect/index.mts` | main() receives an empty config | killed |
33
+ | M22 | harness vendor mock | `src/testing/vendor-mock.mts` | an unmocked request is answered instead of rejected | killed |
34
+ | M23 | harness vendor mock | `src/testing/vendor-mock.mts` | verify() never fails | killed |
35
+ | M24 | harness vendor mock | `src/testing/vendor-mock.mts` | mocked status codes are ignored | killed |
36
+ | M25 | harness vendor mock | `src/testing/vendor-mock.mts` | the times limit on a route is ignored | killed |
37
+ | M26 | harness network guard | `src/testing/network-guard.mts` | the network guard lets everything through (the mutant may try one TCP connect to the TEST-NET-3 documentation address 203.0.113.9) | killed |
38
+ | M27 | harness fake ALOMA | `src/testing/fake-aloma.mts` | the fake accepts a connect without registration | killed |
39
+ | M28 | harness fake ALOMA | `src/testing/fake-aloma.mts` | the fake encrypts config for the wrong audience | killed |
40
+ | M29 | harness fake ALOMA | `src/testing/fake-aloma.mts` | the fake drops the connector's answer | killed |
41
+ | M30 | harness fake ALOMA | `src/testing/fake-aloma.mts` | call() drops the ctx fields | killed |
42
+ | M31 | harness | `src/testing/harness.mts` | stop() no longer fails on unmocked requests | killed |
43
+ | M32 | harness | `src/testing/harness.mts` | the harness never sends configuration | killed |
@@ -0,0 +1,161 @@
1
+ import { Dispatcher } from '../build/internal/dispatcher/index.mjs';
2
+ import { buildResolvers } from '../build/builder/runtime-context.mjs';
3
+
4
+ // Simple test framework matching project convention
5
+ const colors = {
6
+ green: '\x1b[32m',
7
+ red: '\x1b[31m',
8
+ yellow: '\x1b[33m',
9
+ reset: '\x1b[0m',
10
+ cyan: '\x1b[36m'
11
+ };
12
+
13
+ let passed = 0;
14
+ let failed = 0;
15
+
16
+ async function test(name, fn) {
17
+ try {
18
+ console.log(`${colors.cyan}Running: ${name}${colors.reset}`);
19
+ await fn();
20
+ console.log(`${colors.green}✓ PASS: ${name}${colors.reset}\n`);
21
+ passed++;
22
+ } catch (error) {
23
+ console.log(`${colors.red}✗ FAIL: ${name}${colors.reset}`);
24
+ console.log(`${colors.red} Error: ${error.message}${colors.reset}\n`);
25
+ failed++;
26
+ }
27
+ }
28
+
29
+ function assert(condition, message) {
30
+ if (!condition) throw new Error(message || 'Assertion failed');
31
+ }
32
+
33
+ function assertEqual(actual, expected, message) {
34
+ if (JSON.stringify(actual) !== JSON.stringify(expected)) {
35
+ throw new Error(message || `Expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`);
36
+ }
37
+ }
38
+
39
+ // Helper: build a dispatcher with given resolvers and execute a query+envelope.
40
+ // IMPORTANT: this test passes taskId/namespace/sticky in the envelope to verify the
41
+ // dispatcher destructures them and forwards them as a ctx object to handlers.
42
+ async function buildAndExecute(resolvers, envelope) {
43
+ const dispatcher = new Dispatcher();
44
+ dispatcher.types({ fields: {} });
45
+ dispatcher.resolvers(resolvers);
46
+ dispatcher.main(async () => {});
47
+ const built = dispatcher.build();
48
+ return built.execute(envelope);
49
+ }
50
+
51
+ // --- RED TESTS for ctx forwarding (SDK v3.8.67 additive change) ---
52
+
53
+ // Test 1: dispatcher.execute forwards ctx (taskId, namespace, sticky) to a NAMED METHOD handler
54
+ // as the second argument. Currently the dispatcher only passes `variables` — so the second
55
+ // arg is undefined and this test must FAIL (red) until the SDK is patched.
56
+ await test('dispatcher forwards ctx as second arg to named-method handler', async () => {
57
+ let receivedArgs;
58
+ let receivedCtx;
59
+
60
+ // Use buildResolvers so the wrapper is exercised exactly as it is in production.
61
+ const mockController = {
62
+ myMethod: async (args, ctx) => {
63
+ receivedArgs = args;
64
+ receivedCtx = ctx;
65
+ return { ok: true };
66
+ },
67
+ '__autocomplete': async () => ({}),
68
+ '__endpoint': async () => ({}),
69
+ '__default': async () => ({}),
70
+ };
71
+ const methods = ['myMethod', '__autocomplete', '__endpoint', '__default'];
72
+ const resolvers = buildResolvers(methods, mockController);
73
+
74
+ await buildAndExecute(resolvers, {
75
+ query: ['myMethod'],
76
+ variables: { foo: 'bar' },
77
+ taskId: 'task-123',
78
+ namespace: 'testing',
79
+ sticky: 'sticky-abc',
80
+ });
81
+
82
+ assertEqual(receivedArgs, { foo: 'bar' }, 'args should be forwarded unchanged');
83
+ assert(receivedCtx !== undefined, 'ctx should be defined as second argument');
84
+ assertEqual(receivedCtx.taskId, 'task-123', `ctx.taskId should be "task-123", got ${JSON.stringify(receivedCtx)}`);
85
+ assertEqual(receivedCtx.namespace, 'testing', `ctx.namespace should be "testing", got ${JSON.stringify(receivedCtx)}`);
86
+ assertEqual(receivedCtx.sticky, 'sticky-abc', `ctx.sticky should be "sticky-abc", got ${JSON.stringify(receivedCtx)}`);
87
+ });
88
+
89
+ // Test 2: dispatcher.execute forwards ctx to the __default (fallback) handler as second arg
90
+ // when the named method is not found. Currently the __default invocation only receives the
91
+ // merged variables — so ctx is undefined and this test must FAIL (red) until patched.
92
+ await test('dispatcher forwards ctx as second arg to __default fallback handler', async () => {
93
+ let receivedArg;
94
+ let receivedCtx;
95
+
96
+ // Resolvers map with ONLY __default — no named methods, so dispatcher falls back.
97
+ const resolvers = {
98
+ __default: async (arg, ctx) => {
99
+ receivedArg = arg;
100
+ receivedCtx = ctx;
101
+ return { fallback: true };
102
+ },
103
+ };
104
+
105
+ await buildAndExecute(resolvers, {
106
+ query: ['someUnknownMethod'],
107
+ variables: { hello: 'world' },
108
+ taskId: 'task-456',
109
+ namespace: 'testing',
110
+ sticky: 'sticky-def',
111
+ });
112
+
113
+ assert(receivedArg !== undefined, '__default should receive arg');
114
+ assertEqual(receivedArg.hello, 'world', 'variables should be merged into arg');
115
+ assertEqual(receivedArg.__method, ['someUnknownMethod'], '__method should be in arg');
116
+ assert(receivedCtx !== undefined, 'ctx should be defined as second argument to __default');
117
+ assertEqual(receivedCtx.taskId, 'task-456', `ctx.taskId should be "task-456", got ${JSON.stringify(receivedCtx)}`);
118
+ assertEqual(receivedCtx.namespace, 'testing', `ctx.namespace should be "testing"`);
119
+ assertEqual(receivedCtx.sticky, 'sticky-def', `ctx.sticky should be "sticky-def"`);
120
+ });
121
+
122
+ // Test 3: BACKWARD COMPATIBILITY. A controller method with the old 1-arg signature
123
+ // `async myMethod(args)` continues to work when called via the new dispatcher path.
124
+ // The second argument exists but is ignored. This test MUST PASS even in the red phase —
125
+ // if it fails red, the test setup is broken (not the implementation).
126
+ await test('one-arg handler still works (backward compatibility)', async () => {
127
+ let receivedArgs;
128
+
129
+ const mockController = {
130
+ // Note: only one parameter. Second arg, if any, must be silently ignored.
131
+ legacyMethod: async (args) => {
132
+ receivedArgs = args;
133
+ return { legacy: true, ...args };
134
+ },
135
+ '__autocomplete': async () => ({}),
136
+ '__endpoint': async () => ({}),
137
+ '__default': async () => ({}),
138
+ };
139
+ const methods = ['legacyMethod', '__autocomplete', '__endpoint', '__default'];
140
+ const resolvers = buildResolvers(methods, mockController);
141
+
142
+ const result = await buildAndExecute(resolvers, {
143
+ query: ['legacyMethod'],
144
+ variables: { id: 7 },
145
+ taskId: 'task-789',
146
+ namespace: 'testing',
147
+ sticky: 'sticky-ghi',
148
+ });
149
+
150
+ assertEqual(receivedArgs, { id: 7 }, 'legacy handler should receive args unchanged');
151
+ assertEqual(result, { legacy: true, id: 7 }, 'legacy handler should return correct result');
152
+ });
153
+
154
+ // --- Results ---
155
+ console.log(`\n${colors.yellow}--- Dispatcher ctx forwarding test results ---${colors.reset}`);
156
+ console.log(`${colors.green}Passed: ${passed}${colors.reset}`);
157
+ console.log(`${colors.red}Failed: ${failed}${colors.reset}`);
158
+
159
+ if (failed > 0) {
160
+ process.exit(1);
161
+ }
@@ -0,0 +1,72 @@
1
+ // Handshake smoke test: the one file a connector repo adds (see "Testing a connector" in the SDK README).
2
+ //
3
+ // In a connector repo the RuntimeContext comes from the repo's own builder after `yarn build`:
4
+ // const context = await new Builder().config({...}).build();
5
+ // Here the controller is defined inline so this file also tests the harness path used by connector repos.
6
+ import {describe, it, afterEach} from 'mocha';
7
+ import {expect} from 'chai';
8
+ import {AbstractController} from '../build/index.mjs';
9
+ import RuntimeContext from '../build/builder/runtime-context.mjs';
10
+ import {ConnectorHarness, connectorFromRuntimeContext} from '../build/testing/index.mjs';
11
+
12
+ const VENDOR = 'https://api.crm.example.test';
13
+
14
+ class Controller extends AbstractController {
15
+ async getContact({id}) {
16
+ return this.getClient({baseUrl: VENDOR, retry: 1, customize: (r) => {
17
+ r.headers = {...r.headers, Authorization: `Bearer ${this.config.apiKey}`};
18
+ }}).fetch(`/contacts/${id}`, {method: 'GET'});
19
+ }
20
+ }
21
+
22
+ const context = () =>
23
+ new RuntimeContext(new Controller(), {
24
+ id: 'crm-connector',
25
+ version: '0.0.1',
26
+ methods: ['getContact'],
27
+ types: 'type Query { getContact(id: String): String }',
28
+ config: {fields: {apiKey: {name: 'API Key', type: 'line'}}},
29
+ });
30
+
31
+ describe('crm-connector handshake smoke test', function () {
32
+ this.timeout(15000);
33
+ let harness;
34
+
35
+ afterEach(async () => {
36
+ // stop() also fails the test when the connector made a request that was not mocked
37
+ if (harness) await harness.stop();
38
+ harness = undefined;
39
+ });
40
+
41
+ it('registers, connects, starts and reports healthy', async () => {
42
+ harness = await ConnectorHarness.start({
43
+ connector: connectorFromRuntimeContext(context()),
44
+ config: {apiKey: 'fake-api-key-not-real'},
45
+ });
46
+
47
+ expect(harness.aloma.registration.id).to.equal('crm-connector');
48
+ expect(harness.aloma.registration.schema.configSchema.fields).to.have.property('apiKey');
49
+
50
+ const health = await harness.aloma.waitForPacket('connector.health.check');
51
+ expect(health.a).to.deep.equal({ok: true, error: null});
52
+ });
53
+
54
+ it('answers a method call from a recorded vendor response', async () => {
55
+ harness = await ConnectorHarness.start({
56
+ connector: connectorFromRuntimeContext(context()),
57
+ config: {apiKey: 'fake-api-key-not-real'},
58
+ });
59
+ harness.vendor.get(`${VENDOR}/contacts/42`, {json: {id: 42, email: 'jane@example.test'}});
60
+
61
+ expect(await harness.callOk('getContact', {id: 42})).to.deep.equal({id: 42, email: 'jane@example.test'});
62
+ expect(harness.vendor.requests[0].headers.authorization).to.equal('Bearer fake-api-key-not-real');
63
+ });
64
+
65
+ it('reports a missing configuration value as unhealthy', async () => {
66
+ harness = await ConnectorHarness.start({connector: connectorFromRuntimeContext(context()), config: {}});
67
+
68
+ const health = await harness.aloma.waitForPacket('connector.health.check');
69
+ expect(health.a.ok).to.equal(false);
70
+ expect(health.a.error).to.match(/API Key is required/);
71
+ });
72
+ });