-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathconnections.test.ts
More file actions
787 lines (675 loc) · 27.2 KB
/
connections.test.ts
File metadata and controls
787 lines (675 loc) · 27.2 KB
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
import { describe, expect, test, beforeEach, afterEach, beforeAll, afterAll } from "bun:test"
import * as Dispatcher from "../../src/altimate/native/dispatcher"
// Disable telemetry via env var instead of mock.module
beforeAll(() => { process.env.ALTIMATE_TELEMETRY_DISABLED = "true" })
afterAll(() => { delete process.env.ALTIMATE_TELEMETRY_DISABLED })
// ---------------------------------------------------------------------------
// Import modules under test
// ---------------------------------------------------------------------------
import * as Registry from "../../src/altimate/native/connections/registry"
import { detectAuthMethod } from "../../src/altimate/native/connections/registry"
import * as CredentialStore from "../../src/altimate/native/connections/credential-store"
import { parseDbtProfiles } from "../../src/altimate/native/connections/dbt-profiles"
import { discoverContainers, containerToConfig } from "../../src/altimate/native/connections/docker-discovery"
import { registerAll } from "../../src/altimate/native/connections/register"
// ---------------------------------------------------------------------------
// ConnectionRegistry
// ---------------------------------------------------------------------------
describe("ConnectionRegistry", () => {
beforeEach(() => {
Registry.reset()
})
test("list returns empty when no configs loaded", () => {
Registry.setConfigs({})
const result = Registry.list()
expect(result.warehouses).toEqual([])
})
test("list returns configured warehouses", () => {
Registry.setConfigs({
mydb: { type: "postgres", host: "localhost", port: 5432, database: "test" },
snowprod: { type: "snowflake", account: "abc123" },
})
const result = Registry.list()
expect(result.warehouses).toHaveLength(2)
expect(result.warehouses[0].name).toBe("mydb")
expect(result.warehouses[0].type).toBe("postgres")
expect(result.warehouses[1].name).toBe("snowprod")
expect(result.warehouses[1].type).toBe("snowflake")
})
test("get throws for unknown connection", async () => {
Registry.setConfigs({})
await expect(Registry.get("nonexistent")).rejects.toThrow(
'Connection "nonexistent" not found',
)
})
test("getConfig returns config for known connection", () => {
Registry.setConfigs({
mydb: { type: "postgres", host: "localhost" },
})
const config = Registry.getConfig("mydb")
expect(config).toBeDefined()
expect(config?.type).toBe("postgres")
})
test("getConfig returns undefined for unknown connection", () => {
Registry.setConfigs({})
expect(Registry.getConfig("nope")).toBeUndefined()
})
test("setConfigs overrides existing state", () => {
Registry.setConfigs({ a: { type: "postgres" } })
expect(Registry.list().warehouses).toHaveLength(1)
Registry.setConfigs({ b: { type: "mysql" }, c: { type: "duckdb" } })
expect(Registry.list().warehouses).toHaveLength(2)
expect(Registry.getConfig("a")).toBeUndefined()
})
})
// ---------------------------------------------------------------------------
// loadFromEnv — env-var-based connection config loading
// ---------------------------------------------------------------------------
describe("loadFromEnv via Registry.load()", () => {
const saved: Record<string, string | undefined> = {}
function setEnv(key: string, value: string) {
saved[key] = process.env[key]
process.env[key] = value
}
beforeEach(() => {
Registry.reset()
})
afterEach(() => {
for (const [key, orig] of Object.entries(saved)) {
if (orig === undefined) delete process.env[key]
else process.env[key] = orig
}
for (const key of Object.keys(saved)) delete saved[key]
})
test("parses valid JSON from ALTIMATE_CODE_CONN_* env vars", () => {
setEnv("ALTIMATE_CODE_CONN_MYDB", JSON.stringify({ type: "postgres", host: "localhost", port: 5432 }))
Registry.load()
const config = Registry.getConfig("mydb")
expect(config).toBeDefined()
expect(config?.type).toBe("postgres")
expect(config?.host).toBe("localhost")
})
test("lowercases connection name from env var suffix", () => {
setEnv("ALTIMATE_CODE_CONN_PROD_DB", JSON.stringify({ type: "snowflake", account: "abc" }))
Registry.load()
expect(Registry.getConfig("prod_db")).toBeDefined()
expect(Registry.getConfig("PROD_DB")).toBeUndefined()
})
test("ignores env var with invalid JSON", () => {
setEnv("ALTIMATE_CODE_CONN_BAD", "not-valid-json{")
Registry.load()
expect(Registry.getConfig("bad")).toBeUndefined()
})
test("ignores env var config without type field", () => {
setEnv("ALTIMATE_CODE_CONN_NOTYPE", JSON.stringify({ host: "localhost", port: 5432 }))
Registry.load()
expect(Registry.getConfig("notype")).toBeUndefined()
})
test("ignores non-object JSON values (string, number, array)", () => {
setEnv("ALTIMATE_CODE_CONN_STR", JSON.stringify("just a string"))
setEnv("ALTIMATE_CODE_CONN_NUM", JSON.stringify(42))
setEnv("ALTIMATE_CODE_CONN_ARR", JSON.stringify([1, 2, 3]))
Registry.load()
expect(Registry.getConfig("str")).toBeUndefined()
expect(Registry.getConfig("num")).toBeUndefined()
expect(Registry.getConfig("arr")).toBeUndefined()
})
})
// ---------------------------------------------------------------------------
// detectAuthMethod
// ---------------------------------------------------------------------------
describe("detectAuthMethod", () => {
test("returns 'connection_string' for config with connection_string", () => {
expect(detectAuthMethod({ type: "postgres", connection_string: "postgresql://..." } as any)).toBe("connection_string")
})
test("returns 'key_pair' for Snowflake private_key_path", () => {
expect(detectAuthMethod({ type: "snowflake", private_key_path: "/path/to/key.p8" } as any)).toBe("key_pair")
})
test("returns 'key_pair' for camelCase privateKeyPath", () => {
expect(detectAuthMethod({ type: "snowflake", privateKeyPath: "/path/to/key.p8" } as any)).toBe("key_pair")
})
test("returns 'sso' for Snowflake externalbrowser", () => {
expect(detectAuthMethod({ type: "snowflake", authenticator: "EXTERNALBROWSER" } as any)).toBe("sso")
})
test("returns 'sso' for Okta URL authenticator", () => {
expect(detectAuthMethod({ type: "snowflake", authenticator: "https://myorg.okta.com" } as any)).toBe("sso")
})
test("returns 'oauth' for OAuth authenticator", () => {
expect(detectAuthMethod({ type: "snowflake", authenticator: "OAUTH" } as any)).toBe("oauth")
})
test("returns 'token' for access_token", () => {
expect(detectAuthMethod({ type: "databricks", access_token: "dapi..." } as any)).toBe("token")
})
test("returns 'password' for config with password", () => {
expect(detectAuthMethod({ type: "postgres", password: "secret" } as any)).toBe("password")
})
test("returns 'file' for duckdb", () => {
expect(detectAuthMethod({ type: "duckdb", path: "/data/my.db" } as any)).toBe("file")
})
test("returns 'file' for sqlite", () => {
expect(detectAuthMethod({ type: "sqlite", path: "/data/my.sqlite" } as any)).toBe("file")
})
test("returns 'connection_string' for mongodb without password", () => {
expect(detectAuthMethod({ type: "mongodb" } as any)).toBe("connection_string")
})
test("returns 'password' for mongo with password", () => {
expect(detectAuthMethod({ type: "mongo", password: "secret" } as any)).toBe("password")
})
test("returns 'unknown' for null/undefined", () => {
expect(detectAuthMethod(null)).toBe("unknown")
expect(detectAuthMethod(undefined)).toBe("unknown")
})
test("returns 'unknown' for empty config with no identifiable auth", () => {
expect(detectAuthMethod({ type: "postgres" } as any)).toBe("unknown")
})
})
// ---------------------------------------------------------------------------
// CredentialStore (keytar not available in test environment)
// ---------------------------------------------------------------------------
describe("CredentialStore", () => {
test("storeCredential returns false when keytar unavailable", async () => {
const result = await CredentialStore.storeCredential("mydb", "password", "secret")
expect(result).toBe(false)
})
test("getCredential returns null when keytar unavailable", async () => {
const result = await CredentialStore.getCredential("mydb", "password")
expect(result).toBeNull()
})
test("resolveConfig returns config as-is when keytar unavailable", async () => {
const config = { type: "postgres", host: "localhost" } as any
const resolved = await CredentialStore.resolveConfig("mydb", config)
expect(resolved).toEqual(config)
})
test("saveConnection returns config with warnings when keytar unavailable", async () => {
const config = { type: "postgres", password: "secret123" } as any
const { sanitized, warnings } = await CredentialStore.saveConnection("mydb", config)
// Password stripped from config since keytar can't store it, warning emitted
expect(sanitized.password).toBeUndefined()
expect(warnings.length).toBeGreaterThan(0)
})
test("isSensitiveField identifies sensitive fields", () => {
expect(CredentialStore.isSensitiveField("password")).toBe(true)
expect(CredentialStore.isSensitiveField("private_key")).toBe(true)
expect(CredentialStore.isSensitiveField("privateKey")).toBe(true)
expect(CredentialStore.isSensitiveField("private_key_passphrase")).toBe(true)
expect(CredentialStore.isSensitiveField("privateKeyPassphrase")).toBe(true)
expect(CredentialStore.isSensitiveField("privateKeyPass")).toBe(true)
expect(CredentialStore.isSensitiveField("access_token")).toBe(true)
expect(CredentialStore.isSensitiveField("token")).toBe(true)
expect(CredentialStore.isSensitiveField("oauth_client_secret")).toBe(true)
expect(CredentialStore.isSensitiveField("oauthClientSecret")).toBe(true)
expect(CredentialStore.isSensitiveField("passcode")).toBe(true)
expect(CredentialStore.isSensitiveField("connection_string")).toBe(true)
expect(CredentialStore.isSensitiveField("host")).toBe(false)
expect(CredentialStore.isSensitiveField("port")).toBe(false)
expect(CredentialStore.isSensitiveField("authenticator")).toBe(false)
})
test("saveConnection strips inline private_key as sensitive", async () => {
const config = { type: "snowflake", private_key: "-----BEGIN PRIVATE KEY-----\nMIIE..." } as any
const { sanitized, warnings } = await CredentialStore.saveConnection("sf_keypair", config)
expect(sanitized.private_key).toBeUndefined()
expect(warnings.length).toBeGreaterThan(0)
})
test("saveConnection strips OAuth credentials as sensitive", async () => {
const config = { type: "snowflake", authenticator: "oauth", token: "access-token-123", oauth_client_secret: "secret" } as any
const { sanitized } = await CredentialStore.saveConnection("sf_oauth", config)
expect(sanitized.token).toBeUndefined()
expect(sanitized.oauth_client_secret).toBeUndefined()
expect(sanitized.authenticator).toBe("oauth")
})
test("saveConnection strips all sensitive fields from complex config", async () => {
const config = {
type: "snowflake",
account: "abc123",
user: "svc_user",
password: "pw123",
private_key: "-----BEGIN PRIVATE KEY-----",
private_key_passphrase: "passphrase",
token: "oauth-token",
oauth_client_secret: "client-secret",
ssh_password: "ssh-pw",
connection_string: "mongodb://...",
} as any
const { sanitized, warnings } = await CredentialStore.saveConnection("complex", config)
expect(sanitized.password).toBeUndefined()
expect(sanitized.private_key).toBeUndefined()
expect(sanitized.private_key_passphrase).toBeUndefined()
expect(sanitized.token).toBeUndefined()
expect(sanitized.oauth_client_secret).toBeUndefined()
expect(sanitized.ssh_password).toBeUndefined()
expect(sanitized.connection_string).toBeUndefined()
expect(sanitized.type).toBe("snowflake")
expect(sanitized.account).toBe("abc123")
expect(sanitized.user).toBe("svc_user")
expect(warnings).toHaveLength(7)
})
})
// ---------------------------------------------------------------------------
// dbt profiles parser
// ---------------------------------------------------------------------------
describe("dbt profiles parser", () => {
test("returns empty array for non-existent file", async () => {
const connections = await parseDbtProfiles("/nonexistent/profiles.yml")
expect(connections).toEqual([])
})
// For a real profiles.yml parse test, we would need to write a temp file.
// Keeping it simple for now — the parser is mostly about YAML parsing + mapping.
test("handles env_var resolution in profiles", async () => {
// Set env var for test
process.env.TEST_DBT_PASSWORD = "my_secret"
const fs = await import("fs")
const os = await import("os")
const path = await import("path")
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "dbt-test-"))
const profilesPath = path.join(tmpDir, "profiles.yml")
fs.writeFileSync(
profilesPath,
`
myproject:
target: dev
outputs:
dev:
type: postgres
host: localhost
port: 5432
user: testuser
password: "{{ env_var('TEST_DBT_PASSWORD') }}"
dbname: mydb
schema: public
`,
)
try {
const connections = await parseDbtProfiles(profilesPath)
expect(connections).toHaveLength(1)
expect(connections[0].name).toBe("myproject_dev")
expect(connections[0].type).toBe("postgres")
expect(connections[0].config.password).toBe("my_secret")
expect(connections[0].config.database).toBe("mydb")
} finally {
fs.rmSync(tmpDir, { recursive: true })
delete process.env.TEST_DBT_PASSWORD
}
})
test("parses Snowflake private_key from dbt profile", async () => {
const fs = await import("fs")
const os = await import("os")
const path = await import("path")
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "dbt-test-"))
const profilesPath = path.join(tmpDir, "profiles.yml")
fs.writeFileSync(
profilesPath,
`
snowflake_keypair:
outputs:
prod:
type: snowflake
account: abc123
user: svc_user
private_key: "-----BEGIN PRIVATE KEY-----\\nMIIEvQ..."
private_key_passphrase: "my-passphrase"
database: ANALYTICS
warehouse: COMPUTE_WH
schema: PUBLIC
role: TRANSFORMER
`,
)
try {
const connections = await parseDbtProfiles(profilesPath)
expect(connections).toHaveLength(1)
expect(connections[0].type).toBe("snowflake")
expect(connections[0].config.private_key).toBe("-----BEGIN PRIVATE KEY-----\nMIIEvQ...")
expect(connections[0].config.private_key_passphrase).toBe("my-passphrase")
expect(connections[0].config.password).toBeUndefined()
} finally {
fs.rmSync(tmpDir, { recursive: true })
}
})
test("maps dbt adapter types correctly", async () => {
const fs = await import("fs")
const os = await import("os")
const path = await import("path")
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "dbt-test-"))
const profilesPath = path.join(tmpDir, "profiles.yml")
fs.writeFileSync(
profilesPath,
`
snow:
outputs:
prod:
type: snowflake
account: abc123
user: admin
password: pw
database: ANALYTICS
warehouse: COMPUTE_WH
schema: PUBLIC
`,
)
try {
const connections = await parseDbtProfiles(profilesPath)
expect(connections).toHaveLength(1)
expect(connections[0].type).toBe("snowflake")
expect(connections[0].config.account).toBe("abc123")
} finally {
fs.rmSync(tmpDir, { recursive: true })
}
})
// altimate_change start — tests for untested dbt profiles parser edge cases
test("resolves env_var with default fallback when env var is missing", async () => {
const fs = await import("fs")
const os = await import("os")
const path = await import("path")
delete process.env.__TEST_DBT_MISSING_VAR_12345
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "dbt-test-"))
const profilesPath = path.join(tmpDir, "profiles.yml")
fs.writeFileSync(
profilesPath,
`
myproject:
outputs:
dev:
type: postgres
host: "{{ env_var('__TEST_DBT_MISSING_VAR_12345', 'localhost') }}"
port: 5432
user: "{{ env_var('__TEST_DBT_MISSING_USER_12345', 'default_user') }}"
password: secret
dbname: mydb
`,
)
try {
const connections = await parseDbtProfiles(profilesPath)
expect(connections).toHaveLength(1)
expect(connections[0].config.host).toBe("localhost")
expect(connections[0].config.user).toBe("default_user")
} finally {
fs.rmSync(tmpDir, { recursive: true })
}
})
test("skips 'config' top-level key (dbt global settings)", async () => {
const fs = await import("fs")
const os = await import("os")
const path = await import("path")
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "dbt-test-"))
const profilesPath = path.join(tmpDir, "profiles.yml")
fs.writeFileSync(
profilesPath,
`
config:
send_anonymous_usage_stats: false
use_colors: true
real_project:
outputs:
dev:
type: postgres
host: localhost
dbname: analytics
`,
)
try {
const connections = await parseDbtProfiles(profilesPath)
expect(connections).toHaveLength(1)
expect(connections[0].name).toBe("real_project_dev")
expect(connections.find((c) => c.name.startsWith("config"))).toBeUndefined()
} finally {
fs.rmSync(tmpDir, { recursive: true })
}
})
test("handles multiple profiles with multiple outputs", async () => {
const fs = await import("fs")
const os = await import("os")
const path = await import("path")
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "dbt-test-"))
const profilesPath = path.join(tmpDir, "profiles.yml")
fs.writeFileSync(
profilesPath,
`
warehouse_a:
outputs:
dev:
type: postgres
host: localhost
dbname: dev_db
prod:
type: postgres
host: prod.example.com
dbname: prod_db
warehouse_b:
outputs:
staging:
type: snowflake
account: abc123
user: admin
password: pw
database: STAGING
warehouse: COMPUTE_WH
schema: PUBLIC
`,
)
try {
const connections = await parseDbtProfiles(profilesPath)
expect(connections).toHaveLength(3)
const names = connections.map((c) => c.name).sort()
expect(names).toEqual(["warehouse_a_dev", "warehouse_a_prod", "warehouse_b_staging"])
} finally {
fs.rmSync(tmpDir, { recursive: true })
}
})
// altimate_change end
})
// ---------------------------------------------------------------------------
// Docker discovery (dockerode not available)
// ---------------------------------------------------------------------------
describe("Docker discovery", () => {
test("returns empty array when dockerode not installed", async () => {
const containers = await discoverContainers()
expect(containers).toEqual([])
})
test("containerToConfig omits undefined optional fields", () => {
const container = {
container_id: "def456",
name: "mysql_dev",
image: "mysql:8",
db_type: "mysql",
host: "127.0.0.1",
port: 3306,
user: undefined as string | undefined,
password: undefined as string | undefined,
database: undefined as string | undefined,
status: "running",
}
const config = containerToConfig(container as any)
expect(config.type).toBe("mysql")
expect(config.host).toBe("127.0.0.1")
expect(config.port).toBe(3306)
expect(config.user).toBeUndefined()
expect(config.password).toBeUndefined()
expect(config.database).toBeUndefined()
})
})
// ---------------------------------------------------------------------------
// Dispatcher registration
// ---------------------------------------------------------------------------
describe("Connection dispatcher registration", () => {
beforeEach(() => {
Dispatcher.reset()
Registry.reset()
registerAll()
})
test("registers sql.execute handler", () => {
expect(Dispatcher.hasNativeHandler("sql.execute")).toBe(true)
})
test("registers sql.explain handler", () => {
expect(Dispatcher.hasNativeHandler("sql.explain")).toBe(true)
})
test("registers warehouse.list handler", () => {
expect(Dispatcher.hasNativeHandler("warehouse.list")).toBe(true)
})
test("registers warehouse.test handler", () => {
expect(Dispatcher.hasNativeHandler("warehouse.test")).toBe(true)
})
test("registers warehouse.add handler", () => {
expect(Dispatcher.hasNativeHandler("warehouse.add")).toBe(true)
})
test("registers warehouse.remove handler", () => {
expect(Dispatcher.hasNativeHandler("warehouse.remove")).toBe(true)
})
test("registers warehouse.discover handler", () => {
expect(Dispatcher.hasNativeHandler("warehouse.discover")).toBe(true)
})
test("registers schema.inspect handler", () => {
expect(Dispatcher.hasNativeHandler("schema.inspect")).toBe(true)
})
test("registers dbt.profiles handler", () => {
expect(Dispatcher.hasNativeHandler("dbt.profiles")).toBe(true)
})
test("does NOT register sql.autocomplete (deferred to bridge)", () => {
expect(Dispatcher.hasNativeHandler("sql.autocomplete")).toBe(false)
})
test("warehouse.list returns empty when no configs", async () => {
Registry.setConfigs({})
const result = await Dispatcher.call("warehouse.list", {})
expect(result.warehouses).toEqual([])
})
test("warehouse.list returns configured warehouses", async () => {
Registry.setConfigs({
pg_local: { type: "postgres", host: "localhost", database: "testdb" },
})
const result = await Dispatcher.call("warehouse.list", {})
expect(result.warehouses).toHaveLength(1)
expect(result.warehouses[0].name).toBe("pg_local")
expect(result.warehouses[0].type).toBe("postgres")
expect(result.warehouses[0].database).toBe("testdb")
})
test("warehouse.test returns error for unknown connection", async () => {
Registry.setConfigs({})
const result = await Dispatcher.call("warehouse.test", { name: "nope" })
expect(result.connected).toBe(false)
expect(result.error).toContain("not found")
})
test("warehouse.add rejects config without type", async () => {
const result = await Dispatcher.call("warehouse.add", {
name: "bad",
config: { host: "localhost" },
})
expect(result.success).toBe(false)
expect(result.error).toContain("type")
})
test("warehouse.discover returns containers (empty when docker unavailable)", async () => {
const result = await Dispatcher.call("warehouse.discover", {})
expect(result.containers).toEqual([])
expect(result.container_count).toBe(0)
})
test("sql.execute returns error when no warehouse configured", async () => {
Registry.setConfigs({})
const result = await Dispatcher.call("sql.execute", { sql: "SELECT 1" }) as any
expect(result.error).toContain("No warehouse configured")
expect(result.columns).toEqual([])
expect(result.rows).toEqual([])
})
test("dbt.profiles returns empty for non-existent path", async () => {
const result = await Dispatcher.call("dbt.profiles", {
path: "/nonexistent/profiles.yml",
})
expect(result.success).toBe(true)
expect(result.connections).toEqual([])
expect(result.connection_count).toBe(0)
})
})
// ---------------------------------------------------------------------------
// DuckDB driver (in-memory, actual queries)
// ---------------------------------------------------------------------------
// altimate_change start - check DuckDB availability by actually connecting to guard
// against environments where require.resolve succeeds but the native binding is broken
// (e.g. worktrees where node-pre-gyp hasn't built the .node file).
let duckdbAvailable = false
try {
require.resolve("duckdb")
duckdbAvailable = true
} catch {
// DuckDB native driver not installed — skip all tests in this block
}
describe.skipIf(!duckdbAvailable)("DuckDB driver (in-memory)", () => {
let connector: any
// duckdbReady is set only when the driver successfully connects.
// duckdbAvailable may be true even when the native binding is broken.
let duckdbReady = false
// altimate_change start — use beforeAll/afterAll to share one connection per
// describe block, avoiding native-binding contention when the full suite runs
// in parallel. A single connection is created once and reused across all tests.
beforeAll(async () => {
duckdbReady = false
const maxAttempts = 3
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
const { connect } = await import("@altimateai/drivers/duckdb")
connector = await connect({ type: "duckdb", path: ":memory:" })
await connector.connect()
// Verify connector has the full API (guards against test-suite mock leakage)
if (
typeof connector.listSchemas === "function" &&
typeof connector.listTables === "function" &&
typeof connector.describeTable === "function"
) {
duckdbReady = true
break
}
} catch {
if (attempt < maxAttempts) {
// Brief delay before retry to let concurrent native-binding loads settle
await new Promise((r) => setTimeout(r, 100 * attempt))
}
// Native binding unavailable — tests will skip via duckdbReady guard
}
}
})
afterAll(async () => {
if (connector) {
await connector.close()
connector = undefined
}
})
// altimate_change end
test("execute SELECT 1", async () => {
if (!duckdbReady) return
const result = await connector.execute("SELECT 1 AS num")
expect(result.columns).toEqual(["num"])
expect(result.rows).toEqual([[1]])
expect(result.row_count).toBe(1)
expect(result.truncated).toBe(false)
})
test("execute with limit truncation", async () => {
if (!duckdbReady) return
// Generate 5 rows, limit to 3
const result = await connector.execute(
"SELECT * FROM generate_series(1, 5)",
3,
)
expect(result.row_count).toBe(3)
expect(result.truncated).toBe(true)
})
test("listSchemas returns schemas", async () => {
if (!duckdbReady) return
const schemas = await connector.listSchemas()
expect(schemas).toContain("main")
})
test("listTables and describeTable", async () => {
if (!duckdbReady) return
// Use DROP IF EXISTS before CREATE to prevent cross-test interference
// when the shared connection already has this table from a prior run
await connector.execute("DROP TABLE IF EXISTS conn_test_table")
await connector.execute(
"CREATE TABLE conn_test_table (id INTEGER NOT NULL, name VARCHAR, active BOOLEAN)",
)
const tables = await connector.listTables("main")
const testTable = tables.find((t: any) => t.name === "conn_test_table")
expect(testTable).toBeDefined()
expect(testTable?.type).toBe("table")
const columns = await connector.describeTable("main", "conn_test_table")
expect(columns).toHaveLength(3)
expect(columns[0].name).toBe("id")
expect(columns[0].nullable).toBe(false)
expect(columns[1].name).toBe("name")
expect(columns[1].nullable).toBe(true)
})
})
// altimate_change end