-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathresolve-target.test.ts
More file actions
844 lines (728 loc) · 28.8 KB
/
resolve-target.test.ts
File metadata and controls
844 lines (728 loc) · 28.8 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
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
/**
* Tests for resolve-target utilities
*
* Property-based and unit tests for pure functions in the resolve-target module.
* Integration tests for async resolution functions are in e2e tests due to
* the complexity of mocking module dependencies in Bun's test environment.
*/
import { array, constantFrom, assert as fcAssert, property } from "fast-check";
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import { parseOrgProjectArg } from "../../src/lib/arg-parsing.js";
import { DEFAULT_SENTRY_URL } from "../../src/lib/constants.js";
import { setAuthToken } from "../../src/lib/db/auth.js";
import {
cacheProjectsForOrg,
clearProjectCache,
getCachedProjectBySlug,
} from "../../src/lib/db/project-cache.js";
import { setOrgRegion } from "../../src/lib/db/regions.js";
import {
AuthError,
ContextError,
ResolutionError,
} from "../../src/lib/errors.js";
import {
fetchProjectId,
isValidDirNameForInference,
resolveAllTargets,
resolveOrg,
resolveOrgAndProject,
resolveOrgOptionalProjectTarget,
resolveOrgsForListing,
toNumericId,
tryFuzzyProjectRecovery,
} from "../../src/lib/resolve-target.js";
import { mockFetch, useTestConfigDir } from "../helpers.js";
// ============================================================================
// Arbitraries for Property-Based Testing
// ============================================================================
/** Characters valid in directory names (no leading dot) */
const dirNameChars = "abcdefghijklmnopqrstuvwxyz0123456789-_";
/** Generate valid directory names (2+ chars, alphanumeric with hyphens/underscores) */
const validDirNameArb = array(constantFrom(...dirNameChars.split("")), {
minLength: 2,
maxLength: 30,
}).map((chars) => chars.join(""));
/** Generate single characters */
const singleCharArb = constantFrom(...dirNameChars.split(""));
// ============================================================================
// Property Tests for isValidDirNameForInference
// ============================================================================
describe("property: isValidDirNameForInference", () => {
test("rejects empty string", () => {
expect(isValidDirNameForInference("")).toBe(false);
});
test("rejects single characters", () => {
fcAssert(
property(singleCharArb, (char) => {
expect(isValidDirNameForInference(char)).toBe(false);
}),
{ numRuns: 50 }
);
});
test("rejects names starting with dot (hidden directories)", () => {
fcAssert(
property(validDirNameArb, (suffix) => {
// .anything should be rejected - hidden directories are not valid
const name = `.${suffix}`;
expect(isValidDirNameForInference(name)).toBe(false);
}),
{ numRuns: 100 }
);
});
test("accepts valid directory names (2+ chars, not starting with dot)", () => {
fcAssert(
property(validDirNameArb, (name) => {
// Valid names with 2+ chars that don't start with dot should be accepted
expect(isValidDirNameForInference(name)).toBe(true);
}),
{ numRuns: 100 }
);
});
});
// ============================================================================
// Example-Based Tests for Edge Cases and Documentation
// ============================================================================
describe("isValidDirNameForInference edge cases", () => {
test("real-world valid names", () => {
expect(isValidDirNameForInference("cli")).toBe(true);
expect(isValidDirNameForInference("my-project")).toBe(true);
expect(isValidDirNameForInference("sentry-cli")).toBe(true);
expect(isValidDirNameForInference("frontend")).toBe(true);
expect(isValidDirNameForInference("my_app")).toBe(true);
});
test("hidden directories are rejected", () => {
expect(isValidDirNameForInference(".env")).toBe(false);
expect(isValidDirNameForInference(".git")).toBe(false);
expect(isValidDirNameForInference(".config")).toBe(false);
expect(isValidDirNameForInference(".")).toBe(false);
expect(isValidDirNameForInference("..")).toBe(false);
});
test("two-character names are the minimum", () => {
expect(isValidDirNameForInference("ab")).toBe(true);
expect(isValidDirNameForInference("a1")).toBe(true);
expect(isValidDirNameForInference("--")).toBe(true);
});
});
// ============================================================================
// toNumericId — pure function for ID coercion
// ============================================================================
describe("toNumericId", () => {
test("returns undefined for undefined", () => {
expect(toNumericId(undefined)).toBeUndefined();
});
test("returns undefined for null", () => {
expect(toNumericId(null)).toBeUndefined();
});
test("converts string number to number", () => {
expect(toNumericId("123")).toBe(123);
});
test("returns number as-is", () => {
expect(toNumericId(123)).toBe(123);
});
test("returns undefined for string '0' (not a valid Sentry ID)", () => {
expect(toNumericId("0")).toBeUndefined();
});
test("returns undefined for numeric 0 (not a valid Sentry ID)", () => {
expect(toNumericId(0)).toBeUndefined();
});
test("returns undefined for negative numbers (not valid Sentry IDs)", () => {
expect(toNumericId(-1)).toBeUndefined();
});
test("returns undefined for non-integer floats", () => {
expect(toNumericId(1.5)).toBeUndefined();
});
test("returns undefined for empty string", () => {
expect(toNumericId("")).toBeUndefined();
});
test("returns undefined for non-numeric string", () => {
expect(toNumericId("abc")).toBeUndefined();
});
test("returns undefined for negative numbers", () => {
expect(toNumericId(-1)).toBeUndefined();
expect(toNumericId("-5")).toBeUndefined();
});
test("returns undefined for Infinity", () => {
expect(toNumericId(Number.POSITIVE_INFINITY)).toBeUndefined();
expect(toNumericId(Number.NEGATIVE_INFINITY)).toBeUndefined();
expect(toNumericId("Infinity")).toBeUndefined();
});
});
// ============================================================================
// Environment Variable Resolution (SENTRY_ORG / SENTRY_PROJECT)
//
// These tests call the REAL resolve functions with env vars set.
// When both SENTRY_ORG and SENTRY_PROJECT are provided, the resolve
// functions short-circuit at step 2 and never reach DB/DSN/API calls,
// so no mocking is needed.
// ============================================================================
describe("Environment variable resolution (SENTRY_ORG / SENTRY_PROJECT)", () => {
useTestConfigDir("test-resolve-target-");
// Silence unmocked fetch calls from resolution cascade fall-through.
// Tests that set valid env vars short-circuit before fetch; tests that
// fall through (empty/whitespace env vars) trigger DSN detection and
// directory inference which call the API. A silent 404 prevents preload
// warnings while preserving the catch-and-continue behavior.
let originalFetch: typeof globalThis.fetch;
beforeEach(() => {
originalFetch = globalThis.fetch;
globalThis.fetch = mockFetch(
async () =>
new Response(JSON.stringify({ detail: "Not found" }), { status: 404 })
);
delete process.env.SENTRY_ORG;
delete process.env.SENTRY_PROJECT;
});
afterEach(() => {
globalThis.fetch = originalFetch;
delete process.env.SENTRY_ORG;
delete process.env.SENTRY_PROJECT;
});
// --- resolveOrg ---
test("resolveOrg: returns org from SENTRY_ORG", async () => {
process.env.SENTRY_ORG = "test-org";
const result = await resolveOrg({ cwd: "/tmp" });
expect(result?.org).toBe("test-org");
});
test("resolveOrg: SENTRY_PROJECT=org/project combo extracts org", async () => {
process.env.SENTRY_PROJECT = "combo-org/combo-project";
const result = await resolveOrg({ cwd: "/tmp" });
expect(result?.org).toBe("combo-org");
});
test("resolveOrg: CLI flag takes priority over env var", async () => {
process.env.SENTRY_ORG = "env-org";
const result = await resolveOrg({ org: "flag-org", cwd: "/tmp" });
expect(result?.org).toBe("flag-org");
});
// --- resolveOrgAndProject ---
test("resolveOrgAndProject: returns from SENTRY_ORG + SENTRY_PROJECT", async () => {
process.env.SENTRY_ORG = "test-org";
process.env.SENTRY_PROJECT = "test-project";
const result = await resolveOrgAndProject({ cwd: "/tmp" });
expect(result?.org).toBe("test-org");
expect(result?.project).toBe("test-project");
expect(result?.detectedFrom).toContain("env var");
});
test("resolveOrgAndProject: SENTRY_PROJECT combo notation", async () => {
process.env.SENTRY_PROJECT = "my-org/my-project";
const result = await resolveOrgAndProject({ cwd: "/tmp" });
expect(result?.org).toBe("my-org");
expect(result?.project).toBe("my-project");
expect(result?.detectedFrom).toContain("SENTRY_PROJECT");
});
test("resolveOrgAndProject: env vars override config defaults", async () => {
process.env.SENTRY_ORG = "env-org";
process.env.SENTRY_PROJECT = "env-project";
const result = await resolveOrgAndProject({ cwd: "/tmp" });
expect(result?.org).toBe("env-org");
expect(result?.project).toBe("env-project");
});
test("resolveOrgAndProject: CLI flags override env vars", async () => {
process.env.SENTRY_ORG = "env-org";
process.env.SENTRY_PROJECT = "env-project";
const result = await resolveOrgAndProject({
org: "flag-org",
project: "flag-project",
cwd: "/tmp",
});
expect(result?.org).toBe("flag-org");
expect(result?.project).toBe("flag-project");
// Explicit path no longer fetches projectId
expect(result?.projectId).toBeUndefined();
});
test("resolveOrgAndProject: ignores empty/whitespace-only values", async () => {
process.env.SENTRY_ORG = " ";
process.env.SENTRY_PROJECT = "";
// Both empty after trim — should not use env vars
// This will fall through and return null since /tmp has no DSN
const result = await resolveOrgAndProject({ cwd: "/tmp" });
// Should return null or a result that's not from env vars
if (result) {
expect(result.detectedFrom ?? "").not.toContain("env var");
}
});
test("resolveOrgAndProject: SENTRY_ORG alone not enough for org+project", async () => {
process.env.SENTRY_ORG = "my-org";
// No SENTRY_PROJECT — resolveFromEnvVars returns org-only
// resolveOrgAndProject needs project, so env vars don't satisfy it
const result = await resolveOrgAndProject({ cwd: "/tmp" });
// If result exists (from DSN or dir inference), it should not claim env var source
if (result) {
expect(result.detectedFrom ?? "").not.toContain("SENTRY_ORG env var");
}
});
test("resolveOrgAndProject: trailing slash in combo is ignored (no project)", async () => {
process.env.SENTRY_PROJECT = "my-org/";
process.env.SENTRY_ORG = "other-org";
// Malformed combo — slash present but empty project
// Should fall through; SENTRY_ORG provides org-only
const result = await resolveOrgAndProject({ cwd: "/tmp" });
// No project from env vars, so result should not have env-var detectedFrom
if (result) {
expect(result.project).not.toContain("/");
}
});
// --- resolveAllTargets ---
test("resolveAllTargets: returns target from SENTRY_ORG + SENTRY_PROJECT", async () => {
process.env.SENTRY_ORG = "test-org";
process.env.SENTRY_PROJECT = "test-project";
const result = await resolveAllTargets({ cwd: "/tmp" });
expect(result.targets).toHaveLength(1);
expect(result.targets[0]?.org).toBe("test-org");
expect(result.targets[0]?.project).toBe("test-project");
});
test("resolveAllTargets: env vars override config defaults", async () => {
process.env.SENTRY_ORG = "env-org";
process.env.SENTRY_PROJECT = "env-project";
const result = await resolveAllTargets({ cwd: "/tmp" });
expect(result.targets[0]?.org).toBe("env-org");
});
test("resolveAllTargets: CLI flags override env vars", async () => {
process.env.SENTRY_ORG = "env-org";
process.env.SENTRY_PROJECT = "env-project";
const result = await resolveAllTargets({
org: "flag-org",
project: "flag-project",
cwd: "/tmp",
});
expect(result.targets[0]?.org).toBe("flag-org");
expect(result.targets[0]?.project).toBe("flag-project");
// Explicit path no longer fetches projectId
expect(result.targets[0]?.projectId).toBeUndefined();
});
// --- resolveOrgsForListing ---
test("resolveOrgsForListing: returns org from env vars when no flag/defaults", async () => {
process.env.SENTRY_ORG = "env-org";
const result = await resolveOrgsForListing(undefined, "/tmp");
expect(result.orgs).toContain("env-org");
});
});
// ============================================================================
// fetchProjectId — async project ID lookup with error handling
// ============================================================================
describe("fetchProjectId", () => {
useTestConfigDir("test-fetchProjectId-");
let originalFetch: typeof globalThis.fetch;
beforeEach(() => {
originalFetch = globalThis.fetch;
});
afterEach(() => {
globalThis.fetch = originalFetch;
});
test("returns numeric project ID on success", async () => {
await setAuthToken("test-token");
setOrgRegion("test-org", DEFAULT_SENTRY_URL);
globalThis.fetch = mockFetch(async (input, init) => {
const req = new Request(input, init);
if (req.url.includes("/api/0/projects/test-org/test-project/")) {
return Response.json({ id: "456", slug: "test-project" });
}
return new Response("Not found", { status: 404 });
});
const result = await fetchProjectId("test-org", "test-project");
expect(result).toBe(456);
});
test("throws ResolutionError on 404", async () => {
await setAuthToken("test-token");
setOrgRegion("test-org", DEFAULT_SENTRY_URL);
globalThis.fetch = mockFetch(
async () =>
new Response(JSON.stringify({ detail: "Not found" }), {
status: 404,
})
);
await expect(fetchProjectId("test-org", "test-project")).rejects.toThrow(
ResolutionError
);
});
test("includes similar project suggestions on 404 when projects exist", async () => {
await setAuthToken("test-token");
setOrgRegion("test-org", DEFAULT_SENTRY_URL);
// Mock: getProject returns 404, but listProjects returns available projects.
// The two calls hit different URL patterns.
globalThis.fetch = mockFetch(async (input, init) => {
const req = new Request(input, init);
const url = req.url;
// listProjects → GET /api/0/organizations/<org>/projects/
if (url.includes("/organizations/test-org/projects")) {
return Response.json([
{ id: "1", slug: "test-project-api", name: "Test Project API" },
{ id: "2", slug: "test-project-web", name: "Test Project Web" },
{ id: "3", slug: "unrelated", name: "Unrelated" },
]);
}
// getProject → GET /api/0/projects/<org>/<slug>/ → 404
return new Response(JSON.stringify({ detail: "Not found" }), {
status: 404,
});
});
try {
await fetchProjectId("test-org", "test-project");
expect.unreachable("should have thrown");
} catch (error) {
expect(error).toBeInstanceOf(ResolutionError);
const msg = (error as ResolutionError).message;
// Should include fuzzy-matched similar projects
expect(msg).toContain("test-project-api");
expect(msg).toContain("test-project-web");
// Should not include unrelated projects (Levenshtein distance too high)
expect(msg).not.toContain("unrelated");
// Should suggest listing projects
expect(msg).toContain("sentry project list test-org/");
}
});
test("includes project list suggestion even when listProjects fails", async () => {
await setAuthToken("test-token");
setOrgRegion("test-org", DEFAULT_SENTRY_URL);
// Mock: all requests return 404 (both getProject and listProjects fail)
globalThis.fetch = mockFetch(
async () =>
new Response(JSON.stringify({ detail: "Not found" }), {
status: 404,
})
);
try {
await fetchProjectId("test-org", "test-project");
expect.unreachable("should have thrown");
} catch (error) {
expect(error).toBeInstanceOf(ResolutionError);
const msg = (error as ResolutionError).message;
// No similar projects (listProjects also 404'd), but should still
// suggest the project list command
expect(msg).toContain("sentry project list test-org/");
expect(msg).not.toContain("Similar projects:");
}
});
test("rethrows AuthError when not authenticated", async () => {
// No auth token set — refreshToken() will throw AuthError
const saved = process.env.SENTRY_AUTH_TOKEN;
delete process.env.SENTRY_AUTH_TOKEN;
setOrgRegion("test-org", DEFAULT_SENTRY_URL);
try {
await expect(fetchProjectId("test-org", "test-project")).rejects.toThrow(
AuthError
);
} finally {
if (saved !== undefined) {
process.env.SENTRY_AUTH_TOKEN = saved;
}
}
});
test("returns undefined on transient server error", async () => {
await setAuthToken("test-token");
setOrgRegion("test-org", DEFAULT_SENTRY_URL);
globalThis.fetch = mockFetch(
async () =>
new Response(JSON.stringify({ detail: "Internal error" }), {
status: 500,
})
);
const result = await fetchProjectId("test-org", "test-project");
expect(result).toBeUndefined();
});
test("returns cached project ID without hitting the API", async () => {
await setAuthToken("test-token");
setOrgRegion("test-org", DEFAULT_SENTRY_URL);
clearProjectCache();
// Seed the cache via cacheProjectsForOrg (the `list:` key path) as
// `listProjects()` does in production.
cacheProjectsForOrg("test-org", "Test Org", [
{ id: "999", slug: "cached-project", name: "Cached Project" },
]);
let apiCalled = false;
globalThis.fetch = mockFetch(async () => {
apiCalled = true;
return new Response("should not be called", { status: 500 });
});
const result = await fetchProjectId("test-org", "cached-project");
expect(result).toBe(999);
expect(apiCalled).toBe(false);
});
test("writes the response to the project cache on a cache miss", async () => {
await setAuthToken("test-token");
setOrgRegion("test-org", DEFAULT_SENTRY_URL);
clearProjectCache();
globalThis.fetch = mockFetch(async (input, init) => {
const req = new Request(input, init);
if (req.url.includes("/api/0/projects/test-org/fresh-project/")) {
return Response.json({
id: "1234",
slug: "fresh-project",
name: "Fresh Project",
organization: {
id: "500",
slug: "test-org",
name: "Test Org",
},
});
}
return new Response("Not found", { status: 404 });
});
await fetchProjectId("test-org", "fresh-project");
// After the call, the cache should be populated so a subsequent call
// skips the API entirely.
const cached = getCachedProjectBySlug("test-org", "fresh-project");
expect(cached).toBeDefined();
expect(cached?.projectId).toBe("1234");
expect(cached?.projectName).toBe("Fresh Project");
});
test("falls through to API when the cache has no projectId (legacy rows)", async () => {
await setAuthToken("test-token");
setOrgRegion("test-org", DEFAULT_SENTRY_URL);
clearProjectCache();
// Seed a cache entry WITHOUT a projectId (mirrors pre-schema-v7 rows).
const { setCachedProject } = await import(
"../../src/lib/db/project-cache.js"
);
setCachedProject("org-id", "proj-id", {
orgSlug: "test-org",
orgName: "Test Org",
projectSlug: "legacy-project",
projectName: "Legacy",
});
let apiCalled = false;
globalThis.fetch = mockFetch(async (input, init) => {
const req = new Request(input, init);
if (req.url.includes("/api/0/projects/test-org/legacy-project/")) {
apiCalled = true;
return Response.json({ id: "777", slug: "legacy-project" });
}
return new Response("Not found", { status: 404 });
});
const result = await fetchProjectId("test-org", "legacy-project");
expect(result).toBe(777);
expect(apiCalled).toBe(true);
});
});
// ============================================================================
// tryFuzzyProjectRecovery
//
// Tests the discriminated-result fuzzy recovery function. Mocks
// globalThis.fetch to control which projects the API returns per org.
// ============================================================================
describe("tryFuzzyProjectRecovery", () => {
useTestConfigDir("test-fuzzy-recovery-");
let originalFetch: typeof globalThis.fetch;
beforeEach(async () => {
originalFetch = globalThis.fetch;
await setAuthToken("test-token");
});
afterEach(() => {
globalThis.fetch = originalFetch;
});
/**
* Build a mock fetch that responds to list-projects endpoints.
*
* @param projectsByOrg - Map of org slug → list of project slugs
*/
function mockListProjects(
projectsByOrg: Record<string, string[]>
): typeof fetch {
return mockFetch(async (input, init) => {
const req = new Request(input, init);
const url = req.url;
// Match /organizations/<org>/projects/
const orgMatch = url.match(/\/organizations\/([^/]+)\/projects/);
if (orgMatch) {
const org = orgMatch[1] as string;
const slugs = projectsByOrg[org];
if (slugs) {
const projects = slugs.map((slug, i) => ({
id: String(i + 1),
slug,
name: slug,
}));
return Response.json(projects);
}
}
return new Response(JSON.stringify({ detail: "Not found" }), {
status: 404,
});
});
}
test("returns 'match' when exactly one similar project exists", async () => {
setOrgRegion("test-org", DEFAULT_SENTRY_URL);
globalThis.fetch = mockListProjects({
"test-org": ["app-frontend", "app-backend", "admin-panel"],
});
const result = await tryFuzzyProjectRecovery("app-front", [
{ slug: "test-org" },
]);
expect(result.kind).toBe("match");
if (result.kind === "match") {
expect(result.project).toBe("app-frontend");
expect(result.org).toBe("test-org");
}
});
test("returns 'suggestions' when multiple similar projects exist", async () => {
setOrgRegion("test-org", DEFAULT_SENTRY_URL);
globalThis.fetch = mockListProjects({
"test-org": ["app-frontend", "app-backend", "app-worker"],
});
const result = await tryFuzzyProjectRecovery("app", [{ slug: "test-org" }]);
expect(result.kind).toBe("suggestions");
if (result.kind === "suggestions") {
expect(result.suggestions.length).toBeGreaterThan(0);
expect(result.suggestions[0]).toContain("test-org");
}
});
test("returns 'none' when no similar projects exist", async () => {
setOrgRegion("test-org", DEFAULT_SENTRY_URL);
globalThis.fetch = mockListProjects({
"test-org": ["completely-different-name"],
});
const result = await tryFuzzyProjectRecovery("zzz-no-match-zzz", [
{ slug: "test-org" },
]);
expect(result.kind).toBe("none");
});
test("returns 'none' when all orgs fail to respond", async () => {
setOrgRegion("test-org", DEFAULT_SENTRY_URL);
globalThis.fetch = mockFetch(
async () =>
new Response(JSON.stringify({ detail: "Error" }), { status: 500 })
);
const result = await tryFuzzyProjectRecovery("some-slug", [
{ slug: "test-org" },
]);
expect(result.kind).toBe("none");
});
test("returns 'none' with empty orgs list", async () => {
const result = await tryFuzzyProjectRecovery("anything", []);
expect(result.kind).toBe("none");
});
test("searches across multiple orgs", async () => {
setOrgRegion("org-alpha", DEFAULT_SENTRY_URL);
setOrgRegion("org-beta", DEFAULT_SENTRY_URL);
globalThis.fetch = mockListProjects({
"org-alpha": ["web-client", "api-server"],
"org-beta": ["mobile-app", "web-portal"],
});
const result = await tryFuzzyProjectRecovery("web-portal", [
{ slug: "org-alpha" },
{ slug: "org-beta" },
]);
expect(result.kind).toBe("match");
if (result.kind === "match") {
expect(result.project).toBe("web-portal");
expect(result.org).toBe("org-beta");
}
});
test("deduplicates slugs across orgs for fuzzy matching", async () => {
setOrgRegion("org-one", DEFAULT_SENTRY_URL);
setOrgRegion("org-two", DEFAULT_SENTRY_URL);
// Same project slug in two orgs — should return suggestions, not crash
globalThis.fetch = mockListProjects({
"org-one": ["shared-service"],
"org-two": ["shared-service"],
});
const result = await tryFuzzyProjectRecovery("shared-servic", [
{ slug: "org-one" },
{ slug: "org-two" },
]);
// Both orgs have the matching slug, so it returns suggestions (not a
// single match) since there are 2 org-qualified entries
expect(result.kind).toBe("suggestions");
});
test("gracefully handles partial org failures", async () => {
setOrgRegion("good-org", DEFAULT_SENTRY_URL);
setOrgRegion("bad-org", DEFAULT_SENTRY_URL);
globalThis.fetch = mockFetch(async (input, init) => {
const req = new Request(input, init);
const url = req.url;
if (url.includes("good-org")) {
return Response.json([
{ id: "1", slug: "target-project", name: "target-project" },
]);
}
// bad-org returns error
return new Response(JSON.stringify({ detail: "Error" }), { status: 500 });
});
const result = await tryFuzzyProjectRecovery("target-project", [
{ slug: "good-org" },
{ slug: "bad-org" },
]);
expect(result.kind).toBe("match");
if (result.kind === "match") {
expect(result.project).toBe("target-project");
expect(result.org).toBe("good-org");
}
});
});
// ============================================================================
// resolveOrgOptionalProjectTarget — org-optional resolution for commands
// that accept org-all mode (e.g., sentry explore)
// ============================================================================
describe("resolveOrgOptionalProjectTarget", () => {
useTestConfigDir("test-resolve-optional-");
let originalFetch: typeof globalThis.fetch;
beforeEach(() => {
originalFetch = globalThis.fetch;
// Silence unmocked fetch calls — resolveEffectiveOrg catches errors and
// returns the original slug, so a 404 is sufficient.
globalThis.fetch = mockFetch(
async () =>
new Response(JSON.stringify({ detail: "Not found" }), { status: 404 })
);
delete process.env.SENTRY_ORG;
delete process.env.SENTRY_PROJECT;
});
afterEach(() => {
globalThis.fetch = originalFetch;
delete process.env.SENTRY_ORG;
delete process.env.SENTRY_PROJECT;
});
test("org-all mode returns org without project", async () => {
const parsed = parseOrgProjectArg("myorg/");
expect(parsed.type).toBe("org-all");
const result = await resolveOrgOptionalProjectTarget(
parsed,
"/tmp",
"explore"
);
expect(result.org).toBe("myorg");
expect(result.project).toBeUndefined();
});
test("explicit mode returns both org and project", async () => {
const parsed = parseOrgProjectArg("myorg/myproject");
expect(parsed.type).toBe("explicit");
const result = await resolveOrgOptionalProjectTarget(
parsed,
"/tmp",
"explore"
);
expect(result.org).toBe("myorg");
expect(result.project).toBe("myproject");
});
test("auto-detect mode returns org only when SENTRY_ORG is set", async () => {
process.env.SENTRY_ORG = "env-org";
const parsed = parseOrgProjectArg(undefined);
expect(parsed.type).toBe("auto-detect");
const result = await resolveOrgOptionalProjectTarget(
parsed,
"/tmp",
"explore"
);
expect(result.org).toBe("env-org");
expect(result.project).toBeUndefined();
});
test("auto-detect mode throws ContextError when nothing resolves", async () => {
// No env vars, no defaults, no DSN — resolveOrg returns null
const parsed = parseOrgProjectArg(undefined);
await expect(
resolveOrgOptionalProjectTarget(parsed, "/tmp", "explore")
).rejects.toThrow(ContextError);
});
test("auto-detect ContextError mentions the command name", async () => {
const parsed = parseOrgProjectArg(undefined);
try {
await resolveOrgOptionalProjectTarget(parsed, "/tmp", "explore");
// Should not reach here
expect(true).toBe(false);
} catch (err) {
expect(err).toBeInstanceOf(ContextError);
expect((err as ContextError).message).toContain("Organization");
expect((err as ContextError).command).toContain("explore");
}
});
});