From e58661abcfba0204512e14d1b467988aa7095351 Mon Sep 17 00:00:00 2001 From: Xinyuan Lin Date: Wed, 25 Nov 2026 22:00:53 -0800 Subject: [PATCH 1/2] test(frontend): share HTTP service and computing-unit fixtures The HTTP service specs each configured the testing module and flushed their expected requests by hand, and the computing-unit specs each built their unit records by hand; several also registered services that are already provided in root. They now share setupHttpServiceTest, flushHttpRequest and the computing-unit record builders, and drop the redundant registrations while keeping their named mocks. --- ...puting-unit-create-modal.component.spec.ts | 319 +++++++-------- .../computing-unit-status.service.spec.ts | 277 ++++++------- ...ow-computing-unit-managing.service.spec.ts | 86 ++-- .../deployment-version.service.spec.ts | 90 ++--- .../service/gmail/gmail.service.spec.ts | 58 ++- .../common/service/gui-config.service.spec.ts | 76 ++-- ...uthorized-http-interceptor.service.spec.ts | 65 ++- .../service/user/apple-auth.service.spec.ts | 11 +- .../common/service/user/auth.service.spec.ts | 373 +++++++----------- .../user/config/user-config.service.spec.ts | 37 +- .../service/user/google-auth.service.spec.ts | 11 +- .../warehouse/warehouse.service.spec.ts | 29 +- .../testing/computing-unit-test-fixtures.ts | 99 +++++ .../common/testing/http-service-test-utils.ts | 78 ++++ .../common/util/computing-unit.util.spec.ts | 118 +++--- .../admin-computing-unit.component.spec.ts | 59 ++- .../admin-cluster-capacity.component.spec.ts | 137 ++----- ...computing-unit-list-item.component.spec.ts | 82 +--- .../user-computing-unit.component.spec.ts | 69 +--- .../execution/admin-execution.service.spec.ts | 30 +- .../settings/admin-settings.service.spec.ts | 34 +- .../admin/user/admin-user.service.spec.ts | 41 +- .../user/feedback/feedback.service.spec.ts | 29 +- .../dashboard/type/dashboard-entry.spec.ts | 17 +- .../dashboard/type/type-predicates.spec.ts | 16 +- .../login/texera-login.component.spec.ts | 270 +++++-------- 26 files changed, 1051 insertions(+), 1460 deletions(-) create mode 100644 frontend/src/app/common/testing/computing-unit-test-fixtures.ts create mode 100644 frontend/src/app/common/testing/http-service-test-utils.ts diff --git a/frontend/src/app/common/component/computing-unit-create-modal/computing-unit-create-modal.component.spec.ts b/frontend/src/app/common/component/computing-unit-create-modal/computing-unit-create-modal.component.spec.ts index c3503910ab4..b507e4f6314 100644 --- a/frontend/src/app/common/component/computing-unit-create-modal/computing-unit-create-modal.component.spec.ts +++ b/frontend/src/app/common/component/computing-unit-create-modal/computing-unit-create-modal.component.spec.ts @@ -58,6 +58,41 @@ describe("ComputingUnitCreateModalComponent", () => { const createdUnit = { computingUnit: { cuid: 42 } } as unknown as DashboardWorkflowComputingUnit; + const stubTypes = (...typeOptions: WorkflowComputingUnitType[]) => + mockComputingUnitService.getComputingUnitTypes.mockReturnValue(of({ typeOptions })); + + const stubLimits = (cpu: string[], memory: string[], gpu: string[]) => + mockComputingUnitService.getComputingUnitLimitOptions.mockReturnValue( + of({ cpuLimitOptions: cpu, memoryLimitOptions: memory, gpuLimitOptions: gpu }) + ); + + const selectMemory = (memory: string): void => { + component.selectedMemory = memory; + component.onMemorySelectionChange(); + }; + + const setShm = (value: number, unit: "Mi" | "Gi"): void => { + component.shmSizeValue = value; + component.shmSizeUnit = unit; + }; + + const setVisible = (): void => { + component.visible = true; + fixture.detectChanges(); + }; + + const triggerVisible = (): void => { + component.visible = true; + component.ngOnChanges({ visible: { currentValue: true } as never }); + }; + + /** Renders the component, optionally fires ngOnChanges(visible=true) (for host dialogs), then settles. */ + const openModal = (emitChanges = false): void => { + fixture.detectChanges(); + if (emitChanges) triggerVisible(); + setVisible(); + }; + beforeEach(async () => { // No curated images by default, so the existing tests see today's behaviour. Cleared // as well as stubbed: the mock is shared, so call counts would carry between tests. @@ -69,10 +104,8 @@ describe("ComputingUnitCreateModalComponent", () => { createKubernetesBasedComputingUnit: vi.fn(), createLocalComputingUnit: vi.fn(), } as unknown as Mocked; - mockComputingUnitService.getComputingUnitTypes.mockReturnValue(of({ typeOptions: [] })); - mockComputingUnitService.getComputingUnitLimitOptions.mockReturnValue( - of({ cpuLimitOptions: [], memoryLimitOptions: [], gpuLimitOptions: [] }) - ); + stubTypes(); + stubLimits([], [], []); mockComputingUnitService.createKubernetesBasedComputingUnit.mockReturnValue(of(createdUnit)); mockComputingUnitService.createLocalComputingUnit.mockReturnValue(of(createdUnit)); @@ -101,19 +134,14 @@ describe("ComputingUnitCreateModalComponent", () => { component = fixture.componentInstance; }); - /** Both hosts render this modal always, so the list is read when it opens, not on init. */ - const openDialog = () => { - fixture.detectChanges(); - component.visible = true; - component.ngOnChanges({ visible: { currentValue: true } as never }); - fixture.detectChanges(); - }; + const stubImageError = (status: number, statusText: string) => + mockCuImageService.list.mockReturnValue(throwError(() => new HttpErrorResponse({ status, statusText }))); it("offers only ready images, and none when there are none", () => { mockCuImageService.list.mockReturnValue( of([curatedImage({ iid: 1 }), curatedImage({ iid: 2, name: "Still checking", status: "VALIDATING" })]) ); - openDialog(); + openModal(true); // A unit cannot start from an image that has not passed its check. expect(component.curatedImages.map(i => i.iid)).toEqual([1]); // Nothing is preselected: the default is the deployment's own image. @@ -123,20 +151,16 @@ describe("ComputingUnitCreateModalComponent", () => { // A 503 means the feature is off and is expected; anything else means the picker // vanished for a reason the user should hear about. it("says so when the images cannot be loaded for a real reason", () => { - mockCuImageService.list.mockReturnValue( - throwError(() => new HttpErrorResponse({ status: 500, statusText: "Server Error" })) - ); - openDialog(); + stubImageError(500, "Server Error"); + openModal(true); expect(component.curatedImages).toEqual([]); expect(mockNotificationService.error).toHaveBeenCalled(); }); it("shows no images when the deployment has the feature switched off", () => { // The API answers 503 there. The dropdown is hidden and nothing else changes. - mockCuImageService.list.mockReturnValue( - throwError(() => new HttpErrorResponse({ status: 503, statusText: "Service Unavailable" })) - ); - openDialog(); + stubImageError(503, "Service Unavailable"); + openModal(true); expect(component.curatedImages).toEqual([]); // Expected on such a deployment, so it is not reported. expect(mockNotificationService.error).not.toHaveBeenCalled(); @@ -144,11 +168,9 @@ describe("ComputingUnitCreateModalComponent", () => { it("sends the chosen image, and forgets it when the modal reopens", () => { mockCuImageService.list.mockReturnValue(of([curatedImage({ iid: 7 })])); - mockComputingUnitService.getComputingUnitTypes.mockReturnValue( - of({ typeOptions: ["kubernetes"] as WorkflowComputingUnitType[] }) - ); + stubTypes("kubernetes"); mockComputingUnitService.createKubernetesBasedComputingUnit.mockReturnValue(of(createdUnit)); - openDialog(); + openModal(true); component.newComputingUnitName = "On a curated image"; component.selectedImageId = 7; @@ -164,8 +186,7 @@ describe("ComputingUnitCreateModalComponent", () => { ); // The image is chosen per unit, so the next one must not inherit it. - component.visible = true; - component.ngOnChanges({ visible: { currentValue: true } as never }); + triggerVisible(); expect(component.selectedImageId).toBe(component.DEPLOYMENT_IMAGE); }); @@ -177,8 +198,7 @@ describe("ComputingUnitCreateModalComponent", () => { expect(mockCuImageService.list).not.toHaveBeenCalled(); mockCuImageService.list.mockReturnValue(of([curatedImage({ iid: 9, name: "Ready later" })])); - component.visible = true; - component.ngOnChanges({ visible: { currentValue: true } as never }); + triggerVisible(); expect(component.curatedImages.map(i => i.iid)).toEqual([9]); }); @@ -188,25 +208,19 @@ describe("ComputingUnitCreateModalComponent", () => { }); it("prefers the kubernetes type when available", () => { - mockComputingUnitService.getComputingUnitTypes.mockReturnValue( - of({ typeOptions: ["local", "kubernetes"] as WorkflowComputingUnitType[] }) - ); + stubTypes("local", "kubernetes"); fixture.detectChanges(); expect(component.selectedComputingUnitType).toBe("kubernetes"); }); it("falls back to the first available type when kubernetes is absent", () => { - mockComputingUnitService.getComputingUnitTypes.mockReturnValue( - of({ typeOptions: ["local"] as WorkflowComputingUnitType[] }) - ); + stubTypes("local"); fixture.detectChanges(); expect(component.selectedComputingUnitType).toBe("local"); }); it("applies fetched limit options with first-option defaults", () => { - mockComputingUnitService.getComputingUnitLimitOptions.mockReturnValue( - of({ cpuLimitOptions: ["2", "4"], memoryLimitOptions: ["2Gi", "4Gi"], gpuLimitOptions: ["0", "1"] }) - ); + stubLimits(["2", "4"], ["2Gi", "4Gi"], ["0", "1"]); fixture.detectChanges(); expect(component.cpuOptions).toEqual(["2", "4"]); expect(component.selectedCpu).toBe("2"); @@ -249,6 +263,11 @@ describe("ComputingUnitCreateModalComponent", () => { expect(mockComputingUnitService.createLocalComputingUnit).not.toHaveBeenCalled(); }); + const expectNoCreateCalls = (): void => { + expect(mockComputingUnitService.createKubernetesBasedComputingUnit).not.toHaveBeenCalled(); + expect(mockComputingUnitService.createLocalComputingUnit).not.toHaveBeenCalled(); + }; + it("rejects a create without a selected type", () => { fixture.detectChanges(); component.selectedComputingUnitType = undefined; @@ -256,8 +275,7 @@ describe("ComputingUnitCreateModalComponent", () => { component.startComputingUnit(); expect(mockNotificationService.error).toHaveBeenCalledWith("Please select a valid computing unit type"); - expect(mockComputingUnitService.createKubernetesBasedComputingUnit).not.toHaveBeenCalled(); - expect(mockComputingUnitService.createLocalComputingUnit).not.toHaveBeenCalled(); + expectNoCreateCalls(); }); it("emits unitCreated and a success toast on a successful kubernetes create", () => { @@ -268,8 +286,7 @@ describe("ComputingUnitCreateModalComponent", () => { component.selectedMemory = "4Gi"; component.selectedGpu = "0"; component.selectedJvmMemorySize = "2G"; - component.shmSizeValue = 128; - component.shmSizeUnit = "Mi"; + setShm(128, "Mi"); const unitCreatedSpy = vi.fn(); component.unitCreated.subscribe(unitCreatedSpy); @@ -297,14 +314,12 @@ describe("ComputingUnitCreateModalComponent", () => { component.handleAddComputeUnitModalCancel(); expect(visibleSpy).toHaveBeenCalledWith(false); - expect(mockComputingUnitService.createKubernetesBasedComputingUnit).not.toHaveBeenCalled(); - expect(mockComputingUnitService.createLocalComputingUnit).not.toHaveBeenCalled(); + expectNoCreateCalls(); }); it("reconfigures the JVM memory slider when the memory selection changes", () => { fixture.detectChanges(); - component.selectedMemory = "4Gi"; - component.onMemorySelectionChange(); + selectMemory("4Gi"); const expected = getJvmMemorySliderConfig("4Gi"); expect(component.jvmMemoryMax).toBe(expected.jvmMemoryMax); expect(component.showJvmMemorySlider).toBe(expected.showJvmMemorySlider); @@ -314,12 +329,10 @@ describe("ComputingUnitCreateModalComponent", () => { it("flags shared memory larger than total memory", () => { fixture.detectChanges(); component.selectedMemory = "1Gi"; - component.shmSizeValue = 2; - component.shmSizeUnit = "Gi"; + setShm(2, "Gi"); expect(component.isShmTooLarge()).toBe(true); - component.shmSizeValue = 64; - component.shmSizeUnit = "Mi"; + setShm(64, "Mi"); expect(component.isShmTooLarge()).toBe(false); }); @@ -344,10 +357,8 @@ describe("ComputingUnitCreateModalComponent", () => { it("resets the advanced values each time the modal opens", () => { fixture.detectChanges(); - component.selectedMemory = "8Gi"; - component.onMemorySelectionChange(); - component.shmSizeValue = 4; - component.shmSizeUnit = "Gi"; + selectMemory("8Gi"); + setShm(4, "Gi"); component.onJvmMemorySliderChange(component.jvmMemoryMax); component.ngOnChanges({ visible: new SimpleChange(false, true, false) }); @@ -359,18 +370,21 @@ describe("ComputingUnitCreateModalComponent", () => { expect(component.selectedJvmMemorySize).toBe(expected.selectedJvmMemorySize); // Closing the modal must not touch the values. - component.shmSizeValue = 2; - component.shmSizeUnit = "Gi"; + setShm(2, "Gi"); component.ngOnChanges({ visible: new SimpleChange(true, false, false) }); expect(component.shmSizeValue).toBe(2); expect(component.shmSizeUnit).toBe("Gi"); }); - it("surfaces the max-JVM warning on the collapsed header", () => { - vi.spyOn(component, "isShmTooLarge").mockReturnValue(false); - vi.spyOn(component, "isMaxJvmMemorySelected").mockReturnValue(true); - + const setupCollapsedWarning = (shmTooLarge: boolean, maxJvm?: boolean, memory?: string): void => { + vi.spyOn(component, "isShmTooLarge").mockReturnValue(shmTooLarge); + if (maxJvm !== undefined) vi.spyOn(component, "isMaxJvmMemorySelected").mockReturnValue(maxJvm); + if (memory !== undefined) component.selectedMemory = memory; component.showAdvancedSettings = false; + }; + + it("surfaces the max-JVM warning on the collapsed header", () => { + setupCollapsedWarning(false, true); expect(component.hasCollapsedWarning()).toBe(true); expect(component.collapsedWarningText()).toBe("JVM memory at maximum"); @@ -380,18 +394,12 @@ describe("ComputingUnitCreateModalComponent", () => { }); it("prefers the shm warning over the JVM warning when both apply", () => { - vi.spyOn(component, "isShmTooLarge").mockReturnValue(true); - vi.spyOn(component, "isMaxJvmMemorySelected").mockReturnValue(true); - - component.selectedMemory = "4Gi"; - component.showAdvancedSettings = false; + setupCollapsedWarning(true, true, "4Gi"); expect(component.collapsedWarningText()).toBe("Shared memory exceeds total"); }); it("flags a collapsed warning only when collapsed and shm exceeds memory", () => { - vi.spyOn(component, "isShmTooLarge").mockReturnValue(true); - component.selectedMemory = "4Gi"; - component.showAdvancedSettings = false; + setupCollapsedWarning(true, undefined, "4Gi"); expect(component.hasCollapsedWarning()).toBe(true); // Expanded: the inline warning is visible, so the header stays quiet. component.showAdvancedSettings = true; @@ -399,15 +407,12 @@ describe("ComputingUnitCreateModalComponent", () => { }); it("suppresses the shm warning until the memory options have loaded", () => { - vi.spyOn(component, "isShmTooLarge").mockReturnValue(true); - component.selectedMemory = ""; - component.showAdvancedSettings = false; + setupCollapsedWarning(true, undefined, ""); expect(component.hasCollapsedWarning()).toBe(false); }); it("does not flag a warning when shm fits within memory", () => { - vi.spyOn(component, "isShmTooLarge").mockReturnValue(false); - component.showAdvancedSettings = false; + setupCollapsedWarning(false); expect(component.hasCollapsedWarning()).toBe(false); }); @@ -425,20 +430,19 @@ describe("ComputingUnitCreateModalComponent", () => { ); }); + const expectErrorContaining = (fragment: string): void => + expect(mockNotificationService.error).toHaveBeenCalledWith(expect.stringContaining(fragment)); + it("toasts when fetching computing unit types fails", () => { mockComputingUnitService.getComputingUnitTypes.mockReturnValue(throwError(() => new Error("boom"))); fixture.detectChanges(); - expect(mockNotificationService.error).toHaveBeenCalledWith( - expect.stringContaining("Failed to fetch computing unit types") - ); + expectErrorContaining("Failed to fetch computing unit types"); }); it("toasts when fetching resource limit options fails", () => { mockComputingUnitService.getComputingUnitLimitOptions.mockReturnValue(throwError(() => new Error("boom"))); fixture.detectChanges(); - expect(mockNotificationService.error).toHaveBeenCalledWith( - expect.stringContaining("Failed to fetch resource options") - ); + expectErrorContaining("Failed to fetch resource options"); }); it("toasts when the create request fails", () => { @@ -451,9 +455,7 @@ describe("ComputingUnitCreateModalComponent", () => { component.startComputingUnit(); - expect(mockNotificationService.error).toHaveBeenCalledWith( - expect.stringContaining("Failed to start computing unit") - ); + expectErrorContaining("Failed to start computing unit"); expect(unitCreatedSpy).not.toHaveBeenCalled(); }); @@ -467,8 +469,7 @@ describe("ComputingUnitCreateModalComponent", () => { it("snaps the JVM memory slider to the nearest valid step", () => { fixture.detectChanges(); - component.selectedMemory = "8Gi"; - component.onMemorySelectionChange(); + selectMemory("8Gi"); component.onJvmMemorySliderChange(component.jvmMemoryMax - 1); @@ -478,8 +479,7 @@ describe("ComputingUnitCreateModalComponent", () => { it("flags max JVM memory only when the slider is shown at its maximum", () => { fixture.detectChanges(); - component.selectedMemory = "8Gi"; - component.onMemorySelectionChange(); + selectMemory("8Gi"); component.onJvmMemorySliderChange(component.jvmMemoryMax); expect(component.isMaxJvmMemorySelected()).toBe(true); @@ -490,12 +490,10 @@ describe("ComputingUnitCreateModalComponent", () => { it("preserves a valid previous JVM selection when switching between large memory options", () => { fixture.detectChanges(); - component.selectedMemory = "8Gi"; - component.onMemorySelectionChange(); + selectMemory("8Gi"); component.onJvmMemorySliderChange(1); // Index 1 for 4G in [2, 4, 6] - component.selectedMemory = "4096Mi"; - component.onMemorySelectionChange(); + selectMemory("4096Mi"); expect(component.jvmMemorySliderValue).toBe(1); expect(component.selectedJvmMemorySize).toBe("4G"); @@ -503,12 +501,10 @@ describe("ComputingUnitCreateModalComponent", () => { it("resets the JVM selection when switching to an unrecognized memory unit", () => { fixture.detectChanges(); - component.selectedMemory = "8Gi"; - component.onMemorySelectionChange(); + selectMemory("8Gi"); component.onJvmMemorySliderChange(1); - component.selectedMemory = "2"; - component.onMemorySelectionChange(); + selectMemory("2"); const expected = getJvmMemorySliderConfig("2"); expect(component.showJvmMemorySlider).toBe(expected.showJvmMemorySlider); @@ -516,27 +512,32 @@ describe("ComputingUnitCreateModalComponent", () => { }); describe("template rendering", () => { + const stubFullForm = (): void => { + stubTypes("kubernetes", "local"); + stubLimits(["1", "2"], ["8Gi", "16Gi"], ["0", "1"]); + }; + const openMinimalK8s = (): void => { + stubTypes("kubernetes"); + stubLimits(["1"], ["1Gi"], ["0"]); + openModal(); + }; + const expectPresent = (...selectors: string[]) => + selectors.forEach(s => expect(document.querySelector(s)).toBeTruthy()); + const expectAbsent = (...selectors: string[]) => + selectors.forEach(s => expect(document.querySelector(s)).toBeNull()); + afterEach(() => { document.querySelectorAll(".cdk-overlay-container").forEach(el => el.remove()); }); it("renders the full kubernetes form with GPU select, shm warning, JVM slider and max-memory alert", () => { - mockComputingUnitService.getComputingUnitTypes.mockReturnValue( - of({ typeOptions: ["kubernetes", "local"] as WorkflowComputingUnitType[] }) - ); - mockComputingUnitService.getComputingUnitLimitOptions.mockReturnValue( - of({ cpuLimitOptions: ["1", "2"], memoryLimitOptions: ["8Gi", "16Gi"], gpuLimitOptions: ["0", "1"] }) - ); + stubFullForm(); fixture.detectChanges(); component.onJvmMemorySliderChange(component.jvmMemoryMax); - component.shmSizeValue = 16; - component.shmSizeUnit = "Gi"; - component.visible = true; - fixture.detectChanges(); + setShm(16, "Gi"); + setVisible(); - expect(document.querySelector(".create-compute-unit-container")).toBeTruthy(); - expect(document.querySelector(".unit-name-input")).toBeTruthy(); - expect(document.querySelector(".gpu-selection")).toBeTruthy(); + expectPresent(".create-compute-unit-container", ".unit-name-input", ".gpu-selection"); // Collapsed: the invalid shm value is announced on the panel header. expect(document.querySelector(".advanced-settings-hint--warning")?.textContent).toContain( @@ -551,68 +552,45 @@ describe("ComputingUnitCreateModalComponent", () => { expect(document.querySelector(".shm-warning")?.textContent).toContain( "Shared memory cannot be greater than total memory." ); - expect(document.querySelector(".jvm-memory-slider")).toBeTruthy(); - expect(document.querySelector("nz-alert")).toBeTruthy(); - expect(document.querySelector(".unit-uri-input")).toBeNull(); + expectPresent(".jvm-memory-slider", "nz-alert"); + expectAbsent(".unit-uri-input"); }); it("expands and collapses the advanced panel when the toggle button is clicked", () => { - mockComputingUnitService.getComputingUnitTypes.mockReturnValue( - of({ typeOptions: ["kubernetes"] as WorkflowComputingUnitType[] }) - ); - mockComputingUnitService.getComputingUnitLimitOptions.mockReturnValue( - of({ cpuLimitOptions: ["1"], memoryLimitOptions: ["1Gi"], gpuLimitOptions: ["0"] }) - ); - fixture.detectChanges(); - component.visible = true; - fixture.detectChanges(); + openMinimalK8s(); const toggle = document.querySelector(".advanced-settings-toggle") as HTMLButtonElement; const body = document.querySelector(".advanced-settings-body") as HTMLElement; - expect(toggle.getAttribute("aria-expanded")).toBe("false"); - expect(body.classList.contains("expanded")).toBe(false); + const expectExpanded = (expanded: boolean): void => { + expect(toggle.getAttribute("aria-expanded")).toBe(String(expanded)); + expect(body.classList.contains("expanded")).toBe(expanded); + }; + expectExpanded(false); toggle.click(); fixture.detectChanges(); expect(component.showAdvancedSettings).toBe(true); - expect(toggle.getAttribute("aria-expanded")).toBe("true"); - expect(body.classList.contains("expanded")).toBe(true); + expectExpanded(true); toggle.click(); fixture.detectChanges(); expect(component.showAdvancedSettings).toBe(false); - expect(toggle.getAttribute("aria-expanded")).toBe("false"); - expect(body.classList.contains("expanded")).toBe(false); + expectExpanded(false); }); it("renders the minimal kubernetes form without GPU select, warnings, or slider", () => { - mockComputingUnitService.getComputingUnitTypes.mockReturnValue( - of({ typeOptions: ["kubernetes"] as WorkflowComputingUnitType[] }) - ); - mockComputingUnitService.getComputingUnitLimitOptions.mockReturnValue( - of({ cpuLimitOptions: ["1"], memoryLimitOptions: ["1Gi"], gpuLimitOptions: ["0"] }) - ); - fixture.detectChanges(); - component.visible = true; - fixture.detectChanges(); + openMinimalK8s(); - expect(document.querySelector(".create-compute-unit-container")).toBeTruthy(); - expect(document.querySelector(".gpu-selection")).toBeNull(); - expect(document.querySelector(".shm-warning")).toBeNull(); - expect(document.querySelector(".jvm-memory-slider")).toBeNull(); - expect(document.querySelector("nz-alert")).toBeNull(); + expectPresent(".create-compute-unit-container"); + expectAbsent(".gpu-selection", ".shm-warning", ".jvm-memory-slider", "nz-alert"); }); it("renders the local form with name and URI inputs", () => { - mockComputingUnitService.getComputingUnitTypes.mockReturnValue( - of({ typeOptions: ["local"] as WorkflowComputingUnitType[] }) - ); - fixture.detectChanges(); - component.visible = true; - fixture.detectChanges(); + stubTypes("local"); + openModal(); - expect(document.querySelector(".unit-uri-input")).toBeTruthy(); - expect(document.querySelector(".memory-selection")).toBeNull(); + expectPresent(".unit-uri-input"); + expectAbsent(".memory-selection"); }); // The modal body renders inside the CDK overlay, which is a view attached to @@ -647,15 +625,8 @@ describe("ComputingUnitCreateModalComponent", () => { }; it("updates the form state through the rendered controls", () => { - mockComputingUnitService.getComputingUnitTypes.mockReturnValue( - of({ typeOptions: ["kubernetes", "local"] as WorkflowComputingUnitType[] }) - ); - mockComputingUnitService.getComputingUnitLimitOptions.mockReturnValue( - of({ cpuLimitOptions: ["1", "2"], memoryLimitOptions: ["8Gi", "16Gi"], gpuLimitOptions: ["0", "1"] }) - ); - fixture.detectChanges(); - component.visible = true; - fixture.detectChanges(); + stubFullForm(); + openModal(); setInputValue(".unit-name-input", "Typed Name"); expect(component.newComputingUnitName).toBe("Typed Name"); @@ -668,17 +639,15 @@ describe("ComputingUnitCreateModalComponent", () => { setInputValue(".shm-size-input", "128"); expect(component.shmSizeValue).toBe(128); - clickSelectOption("memory-selection", "16Gi"); - expect(component.selectedMemory).toBe("16Gi"); - - clickSelectOption("cpu-selection", "2"); - expect(component.selectedCpu).toBe("2"); - - clickSelectOption("gpu-selection", "1"); - expect(component.selectedGpu).toBe("1"); - - clickSelectOption("shm-unit-select", "Gi"); - expect(component.shmSizeUnit).toBe("Gi"); + for (const [selectClass, optionText, readActual] of [ + ["memory-selection", "16Gi", () => component.selectedMemory], + ["cpu-selection", "2", () => component.selectedCpu], + ["gpu-selection", "1", () => component.selectedGpu], + ["shm-unit-select", "Gi", () => component.shmSizeUnit], + ] as const) { + clickSelectOption(selectClass, optionText); + expect(readActual()).toBe(optionText); + } // jsdom cannot produce meaningful slider drag geometry; emit the view-model // update at the NgModel seam, which is what a real drag/keypress triggers. @@ -701,14 +670,11 @@ describe("ComputingUnitCreateModalComponent", () => { }); it("falls back to a slider minimum of 0 when no JVM steps are configured", () => { - mockComputingUnitService.getComputingUnitTypes.mockReturnValue( - of({ typeOptions: ["kubernetes"] as WorkflowComputingUnitType[] }) - ); + stubTypes("kubernetes"); fixture.detectChanges(); component.showJvmMemorySlider = true; component.jvmMemorySteps = []; - component.visible = true; - fixture.detectChanges(); + setVisible(); const sliderEl = document.querySelector("nz-slider")!; const slider = (getDebugNode(sliderEl) as DebugElement).componentInstance as { nzMin: number }; @@ -716,12 +682,8 @@ describe("ComputingUnitCreateModalComponent", () => { }); it("wires the footer buttons to cancel and create", () => { - mockComputingUnitService.getComputingUnitTypes.mockReturnValue( - of({ typeOptions: ["kubernetes"] as WorkflowComputingUnitType[] }) - ); - fixture.detectChanges(); - component.visible = true; - fixture.detectChanges(); + stubTypes("kubernetes"); + openModal(); const visibleSpy = vi.fn(); const unitCreatedSpy = vi.fn(); component.visibleChange.subscribe(visibleSpy); @@ -733,8 +695,7 @@ describe("ComputingUnitCreateModalComponent", () => { expect(visibleSpy).toHaveBeenCalledWith(false); expect(unitCreatedSpy).not.toHaveBeenCalled(); - component.visible = true; - fixture.detectChanges(); + setVisible(); buttons[1].click(); expect(unitCreatedSpy).toHaveBeenCalledWith(createdUnit); expect(visibleSpy).toHaveBeenCalledTimes(2); diff --git a/frontend/src/app/common/service/computing-unit/computing-unit-status/computing-unit-status.service.spec.ts b/frontend/src/app/common/service/computing-unit/computing-unit-status/computing-unit-status.service.spec.ts index c90d40d2137..8ab4e160c81 100644 --- a/frontend/src/app/common/service/computing-unit/computing-unit-status/computing-unit-status.service.spec.ts +++ b/frontend/src/app/common/service/computing-unit/computing-unit-status/computing-unit-status.service.spec.ts @@ -37,10 +37,29 @@ describe("ComputingUnitStatusService", () => { let service: ComputingUnitStatusService; let websocketService: WorkflowWebsocketService; - const mockUnit = (cuid: number) => ({ computingUnit: { cuid } }) as unknown as DashboardWorkflowComputingUnit; + const mockUnit = (cuid: number, status?: string) => + (status + ? { computingUnit: { cuid }, status } + : { computingUnit: { cuid } }) as unknown as DashboardWorkflowComputingUnit; // What HttpClient delivers for a failed request; a dropped connection is the same type with status 0. const httpFailure = () => throwError(() => new HttpErrorResponse({ status: 500, statusText: "Internal Server Error" })); + const spyOpenWs = () => vi.spyOn(websocketService, "openWebsocket").mockImplementation(() => {}); + const seedUnits = (units: DashboardWorkflowComputingUnit[], selected?: DashboardWorkflowComputingUnit): void => { + (service as any).allComputingUnitsSubject.next(units); + if (selected !== undefined) { + (service as any).selectedUnitSubject.next(selected); + } + }; + const withFakePolling = (run: () => void): void => { + vi.useFakeTimers(); + try { + run(); + } finally { + (service as any).stopPollingSelectedUnit(); + vi.useRealTimers(); + } + }; beforeEach(() => { const managingStub = { @@ -52,9 +71,6 @@ describe("ComputingUnitStatusService", () => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [ - ComputingUnitStatusService, - WorkflowWebsocketService, - WorkflowStatusService, { provide: WorkflowComputingUnitManagingService, useValue: managingStub }, { provide: UserService, useClass: StubUserService }, { provide: AuthService, useClass: StubAuthService }, @@ -175,76 +191,33 @@ describe("ComputingUnitStatusService", () => { expect(service.getSelectedComputingUnitValue()).toBe(unit); }); - it("getStatus() maps a null selection to NoComputingUnit", () => { - let status: ComputingUnitState | undefined; - service.getStatus().subscribe(s => (status = s)); - expect(status).toBe(ComputingUnitState.NoComputingUnit); - }); - - it("getStatus() maps a Running unit to ComputingUnitState.Running", () => { - (service as any).selectedUnitSubject.next({ - computingUnit: { cuid: 1 }, - status: "Running", - } as unknown as DashboardWorkflowComputingUnit); - - let status: ComputingUnitState | undefined; - service.getStatus().subscribe(s => (status = s)); - expect(status).toBe(ComputingUnitState.Running); - }); - - it("getStatus() maps a Pending unit to ComputingUnitState.Pending", () => { - (service as any).selectedUnitSubject.next({ - computingUnit: { cuid: 1 }, - status: "Pending", - } as unknown as DashboardWorkflowComputingUnit); - - let status: ComputingUnitState | undefined; - service.getStatus().subscribe(s => (status = s)); - expect(status).toBe(ComputingUnitState.Pending); - }); - - it("getStatus() maps a Failed unit to ComputingUnitState.Failed", () => { - (service as any).selectedUnitSubject.next({ - computingUnit: { cuid: 1 }, - status: "Failed", - } as unknown as DashboardWorkflowComputingUnit); - - let status: ComputingUnitState | undefined; - service.getStatus().subscribe(s => (status = s)); - expect(status).toBe(ComputingUnitState.Failed); - }); - - it("getStatus() maps an Unknown unit to ComputingUnitState.Unknown", () => { - (service as any).selectedUnitSubject.next({ - computingUnit: { cuid: 1 }, - status: "Unknown", - } as unknown as DashboardWorkflowComputingUnit); - - let status: ComputingUnitState | undefined; - service.getStatus().subscribe(s => (status = s)); - expect(status).toBe(ComputingUnitState.Unknown); - }); - - it("getStatus() maps a Terminating unit to ComputingUnitState.Terminating", () => { - (service as any).selectedUnitSubject.next({ - computingUnit: { cuid: 1 }, - status: "Terminating", - } as unknown as DashboardWorkflowComputingUnit); - - let status: ComputingUnitState | undefined; - service.getStatus().subscribe(s => (status = s)); - expect(status).toBe(ComputingUnitState.Terminating); - }); - - it("getStatus() keeps an unrecognized future status on the Pending fallback", () => { - (service as any).selectedUnitSubject.next({ - computingUnit: { cuid: 1 }, - status: "FutureStatus", - } as unknown as DashboardWorkflowComputingUnit); - - let status: ComputingUnitState | undefined; - service.getStatus().subscribe(s => (status = s)); - expect(status).toBe(ComputingUnitState.Pending); + ( + [ + [undefined, ComputingUnitState.NoComputingUnit, "getStatus() maps a null selection to NoComputingUnit"], + ["Running", ComputingUnitState.Running, "getStatus() maps a Running unit to ComputingUnitState.Running"], + ["Pending", ComputingUnitState.Pending, "getStatus() maps a Pending unit to ComputingUnitState.Pending"], + ["Failed", ComputingUnitState.Failed, "getStatus() maps a Failed unit to ComputingUnitState.Failed"], + ["Unknown", ComputingUnitState.Unknown, "getStatus() maps an Unknown unit to ComputingUnitState.Unknown"], + [ + "Terminating", + ComputingUnitState.Terminating, + "getStatus() maps a Terminating unit to ComputingUnitState.Terminating", + ], + [ + "FutureStatus", + ComputingUnitState.Pending, + "getStatus() keeps an unrecognized future status on the Pending fallback", + ], + ] as const + ).forEach(([unitStatus, expected, title]) => { + it(title, () => { + if (unitStatus !== undefined) { + (service as any).selectedUnitSubject.next(mockUnit(1, unitStatus)); + } + let status: ComputingUnitState | undefined; + service.getStatus().subscribe(s => (status = s)); + expect(status).toBe(expected); + }); }); it("refreshComputingUnitList() re-fetches the list and pushes it to subscribers", () => { @@ -322,25 +295,25 @@ describe("ComputingUnitStatusService", () => { it("updateUnitInList replaces the matching unit and leaves the others untouched", () => { const unitA = mockUnit(1); const unitB = mockUnit(2); - (service as any).allComputingUnitsSubject.next([unitA, unitB]); + seedUnits([unitA, unitB]); - const updatedA = { computingUnit: { cuid: 1 }, status: "Running" } as unknown as DashboardWorkflowComputingUnit; + const updatedA = mockUnit(1, "Running"); (service as any).updateUnitInList(updatedA); expect((service as any).allComputingUnitsSubject.value).toEqual([updatedA, unitB]); }); it("setComputingUnitsState refreshes the selected unit when it is still present in the new list", () => { - (service as any).selectedUnitSubject.next(mockUnit(7)); + seedUnits([], mockUnit(7)); - const updated = { computingUnit: { cuid: 7 }, status: "Running" } as unknown as DashboardWorkflowComputingUnit; + const updated = mockUnit(7, "Running"); (service as any).setComputingUnitsState([updated]); expect(service.getSelectedComputingUnitValue()).toBe(updated); }); it("setComputingUnitsState clears the selection and stops polling when the selected unit disappears", () => { - (service as any).selectedUnitSubject.next(mockUnit(7)); + seedUnits([], mockUnit(7)); const stopSpy = vi.spyOn(service as any, "stopPollingSelectedUnit"); (service as any).setComputingUnitsState([mockUnit(8)]); @@ -350,12 +323,11 @@ describe("ComputingUnitStatusService", () => { }); it("startPollingSelectedUnit polls the unit on each interval tick and merges the result", () => { - vi.useFakeTimers(); - try { + withFakePolling(() => { const managing = TestBed.inject(WorkflowComputingUnitManagingService); - const polled = { computingUnit: { cuid: 3 }, status: "Running" } as unknown as DashboardWorkflowComputingUnit; + const polled = mockUnit(3, "Running"); const getSpy = vi.spyOn(managing, "getComputingUnit").mockReturnValue(of(polled)); - (service as any).allComputingUnitsSubject.next([mockUnit(3)]); + seedUnits([mockUnit(3)]); (service as any).startPollingSelectedUnit(3); // interval() fires only after the first period elapses @@ -365,17 +337,11 @@ describe("ComputingUnitStatusService", () => { expect(getSpy).toHaveBeenCalledWith(3); expect((service as any).allComputingUnitsSubject.value).toEqual([polled]); - } finally { - // Stop the interval poll here so the test is self-contained rather than - // relying on afterEach's ngOnDestroy to tear it down. - (service as any).stopPollingSelectedUnit(); - vi.useRealTimers(); - } + }); }); it("stopPollingSelectedUnit halts further polling", () => { - vi.useFakeTimers(); - try { + withFakePolling(() => { const managing = TestBed.inject(WorkflowComputingUnitManagingService); const getSpy = vi.spyOn(managing, "getComputingUnit").mockReturnValue(of(mockUnit(3))); @@ -385,24 +351,20 @@ describe("ComputingUnitStatusService", () => { vi.advanceTimersByTime(10000); expect(getSpy).not.toHaveBeenCalled(); - } finally { - vi.useRealTimers(); - } + }); }); it("keeps polling the selected unit through a failed fetch and leaves the selection intact", () => { - vi.useFakeTimers(); - try { + withFakePolling(() => { const managing = TestBed.inject(WorkflowComputingUnitManagingService); const original = mockUnit(3); - const polled = { computingUnit: { cuid: 3 }, status: "Running" } as unknown as DashboardWorkflowComputingUnit; + const polled = mockUnit(3, "Running"); const getSpy = vi .spyOn(managing, "getComputingUnit") .mockReturnValueOnce(httpFailure()) .mockReturnValue(of(polled)); const stopSpy = vi.spyOn(service as any, "stopPollingSelectedUnit"); - (service as any).allComputingUnitsSubject.next([original]); - (service as any).selectedUnitSubject.next(original); + seedUnits([original], original); (service as any).startPollingSelectedUnit(3); vi.advanceTimersByTime((service as any).REFRESH_INTERVAL_MS); @@ -417,50 +379,45 @@ describe("ComputingUnitStatusService", () => { // Every later tick still fetches, and the next good result replaces the selection. expect(getSpy).toHaveBeenCalledTimes(5); expect(service.getSelectedComputingUnitValue()).toBe(polled); - } finally { - (service as any).stopPollingSelectedUnit(); - vi.useRealTimers(); - } + }); }); it("logs a non-HTTP poll failure and keeps polling, but stays silent for an HTTP failure", () => { - vi.useFakeTimers(); const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {}); try { - const managing = TestBed.inject(WorkflowComputingUnitManagingService); - const polled = { computingUnit: { cuid: 3 }, status: "Running" } as unknown as DashboardWorkflowComputingUnit; - const bug = new TypeError("cannot read resource"); - const getSpy = vi - .spyOn(managing, "getComputingUnit") - .mockReturnValueOnce(throwError(() => bug)) - .mockReturnValueOnce(httpFailure()) - .mockReturnValue(of(polled)); - (service as any).allComputingUnitsSubject.next([mockUnit(3)]); - (service as any).selectedUnitSubject.next(mockUnit(3)); - - (service as any).startPollingSelectedUnit(3); - vi.advanceTimersByTime((service as any).REFRESH_INTERVAL_MS); - // A failure outside HTTP is a bug and must stay visible. - expect(errorSpy).toHaveBeenCalledTimes(1); - expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("status poll"), bug); - - vi.advanceTimersByTime((service as any).REFRESH_INTERVAL_MS); - // An HTTP failure is not logged. - expect(errorSpy).toHaveBeenCalledTimes(1); - - vi.advanceTimersByTime((service as any).REFRESH_INTERVAL_MS); - expect(getSpy).toHaveBeenCalledTimes(3); - expect(service.getSelectedComputingUnitValue()).toBe(polled); + withFakePolling(() => { + const managing = TestBed.inject(WorkflowComputingUnitManagingService); + const polled = mockUnit(3, "Running"); + const bug = new TypeError("cannot read resource"); + const getSpy = vi + .spyOn(managing, "getComputingUnit") + .mockReturnValueOnce(throwError(() => bug)) + .mockReturnValueOnce(httpFailure()) + .mockReturnValue(of(polled)); + seedUnits([mockUnit(3)], mockUnit(3)); + + (service as any).startPollingSelectedUnit(3); + vi.advanceTimersByTime((service as any).REFRESH_INTERVAL_MS); + // A failure outside HTTP is a bug and must stay visible. + expect(errorSpy).toHaveBeenCalledTimes(1); + expect(errorSpy).toHaveBeenCalledWith(expect.stringContaining("status poll"), bug); + + vi.advanceTimersByTime((service as any).REFRESH_INTERVAL_MS); + // An HTTP failure is not logged. + expect(errorSpy).toHaveBeenCalledTimes(1); + + vi.advanceTimersByTime((service as any).REFRESH_INTERVAL_MS); + expect(getSpy).toHaveBeenCalledTimes(3); + expect(service.getSelectedComputingUnitValue()).toBe(polled); + }); } finally { - (service as any).stopPollingSelectedUnit(); errorSpy.mockRestore(); - vi.useRealTimers(); } }); describe("selectComputingUnit() cache-miss and guard branches", () => { it("refreshes then selects a unit that is not yet in the cache", () => { - const openSpy = vi.spyOn(websocketService, "openWebsocket").mockImplementation(() => {}); + const openSpy = spyOpenWs(); const managing = TestBed.inject(WorkflowComputingUnitManagingService); const unit9 = mockUnit(9); // The cache starts empty, so cuid 9 is a miss: selection must trigger a @@ -476,8 +433,8 @@ describe("ComputingUnitStatusService", () => { }); it("does not reopen the websocket when the identical unit is re-selected", () => { - const openSpy = vi.spyOn(websocketService, "openWebsocket").mockImplementation(() => {}); - (service as any).allComputingUnitsSubject.next([mockUnit(7)]); + const openSpy = spyOpenWs(); + seedUnits([mockUnit(7)]); service.selectComputingUnit(5, 7); // Same wid + cuid → shouldReconnect is false → the guarded block is skipped. @@ -487,8 +444,8 @@ describe("ComputingUnitStatusService", () => { }); it("does nothing when the workflow id is undefined", () => { - const openSpy = vi.spyOn(websocketService, "openWebsocket").mockImplementation(() => {}); - (service as any).allComputingUnitsSubject.next([mockUnit(7)]); + const openSpy = spyOpenWs(); + seedUnits([mockUnit(7)]); // The unit is cached and shouldReconnect is true, so only the isDefined(wid) // guard can stop the selection: no socket is opened and nothing is selected. @@ -501,8 +458,8 @@ describe("ComputingUnitStatusService", () => { }); it("reconnects when the same unit is opened under a different workflow (wid change alone)", () => { - const openSpy = vi.spyOn(websocketService, "openWebsocket").mockImplementation(() => {}); - (service as any).allComputingUnitsSubject.next([mockUnit(7)]); + const openSpy = spyOpenWs(); + seedUnits([mockUnit(7)]); service.selectComputingUnit(5, 7); expect(openSpy).toHaveBeenCalledTimes(1); @@ -530,18 +487,23 @@ describe("ComputingUnitStatusService", () => { }); describe("terminateComputingUnit()", () => { - it("closes the socket and clears status when terminating the connected selection", () => { + function runTerminate(connected: boolean, selectedCuid: number, response = of({} as Response)) { const managing = TestBed.inject(WorkflowComputingUnitManagingService); const workflowStatusService = TestBed.inject(WorkflowStatusService); const closeSpy = vi.spyOn(websocketService, "closeWebsocket").mockImplementation(() => {}); const clearSpy = vi.spyOn(workflowStatusService, "clearStatus").mockImplementation(() => {}); - vi.spyOn(websocketService, "isConnected", "get").mockReturnValue(true); - const termSpy = vi.spyOn(managing, "terminateComputingUnit").mockReturnValue(of({} as Response)); + vi.spyOn(websocketService, "isConnected", "get").mockReturnValue(connected); + const termSpy = vi.spyOn(managing, "terminateComputingUnit").mockReturnValue(response); const refreshSpy = vi.spyOn(service, "refreshComputingUnitList").mockImplementation(() => {}); - (service as any).selectedUnitSubject.next(mockUnit(7)); + seedUnits([], mockUnit(selectedCuid)); let result: boolean | undefined; service.terminateComputingUnit(7).subscribe(r => (result = r)); + return { closeSpy, clearSpy, termSpy, refreshSpy, result }; + } + + it("closes the socket and clears status when terminating the connected selection", () => { + const { closeSpy, clearSpy, termSpy, refreshSpy, result } = runTerminate(true, 7); expect(closeSpy).toHaveBeenCalled(); expect(clearSpy).toHaveBeenCalled(); @@ -552,46 +514,27 @@ describe("ComputingUnitStatusService", () => { }); it("leaves the socket untouched when terminating a non-selected unit", () => { - const managing = TestBed.inject(WorkflowComputingUnitManagingService); - const closeSpy = vi.spyOn(websocketService, "closeWebsocket").mockImplementation(() => {}); // isConnected is true, but isSelected short-circuits the guard to false. - vi.spyOn(websocketService, "isConnected", "get").mockReturnValue(true); - vi.spyOn(managing, "terminateComputingUnit").mockReturnValue(of({} as Response)); - vi.spyOn(service, "refreshComputingUnitList").mockImplementation(() => {}); - (service as any).selectedUnitSubject.next(mockUnit(8)); - - let result: boolean | undefined; - service.terminateComputingUnit(7).subscribe(r => (result = r)); + const { closeSpy, result } = runTerminate(true, 8); expect(closeSpy).not.toHaveBeenCalled(); expect(result).toBe(true); }); it("skips socket teardown when the selected unit is not connected", () => { - const managing = TestBed.inject(WorkflowComputingUnitManagingService); - const closeSpy = vi.spyOn(websocketService, "closeWebsocket").mockImplementation(() => {}); // isSelected is true, but the socket is down → the guarded teardown is skipped. - vi.spyOn(websocketService, "isConnected", "get").mockReturnValue(false); - vi.spyOn(managing, "terminateComputingUnit").mockReturnValue(of({} as Response)); - vi.spyOn(service, "refreshComputingUnitList").mockImplementation(() => {}); - (service as any).selectedUnitSubject.next(mockUnit(7)); - - let result: boolean | undefined; - service.terminateComputingUnit(7).subscribe(r => (result = r)); + const { closeSpy, result } = runTerminate(false, 7); expect(closeSpy).not.toHaveBeenCalled(); expect(result).toBe(true); }); it("resolves to false when the termination request errors", () => { - const managing = TestBed.inject(WorkflowComputingUnitManagingService); - vi.spyOn(websocketService, "isConnected", "get").mockReturnValue(false); - vi.spyOn(managing, "terminateComputingUnit").mockReturnValue(throwError(() => new Error("boom"))); - const refreshSpy = vi.spyOn(service, "refreshComputingUnitList").mockImplementation(() => {}); - (service as any).selectedUnitSubject.next(mockUnit(7)); - - let result: boolean | undefined; - service.terminateComputingUnit(7).subscribe(r => (result = r)); + const { refreshSpy, result } = runTerminate( + false, + 7, + throwError(() => new Error("boom")) + ); // The error is swallowed by catchError, which emits false; no refresh runs. expect(result).toBe(false); diff --git a/frontend/src/app/common/service/computing-unit/workflow-computing-unit/workflow-computing-unit-managing.service.spec.ts b/frontend/src/app/common/service/computing-unit/workflow-computing-unit/workflow-computing-unit-managing.service.spec.ts index 021a59d14ac..5a188377a46 100644 --- a/frontend/src/app/common/service/computing-unit/workflow-computing-unit/workflow-computing-unit-managing.service.spec.ts +++ b/frontend/src/app/common/service/computing-unit/workflow-computing-unit/workflow-computing-unit-managing.service.spec.ts @@ -17,9 +17,9 @@ * under the License. */ -import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing"; +import { HttpTestingController } from "@angular/common/http/testing"; import { HttpErrorResponse } from "@angular/common/http"; -import { TestBed } from "@angular/core/testing"; +import { flushHttpRequest, setupHttpServiceTest } from "../../../testing/http-service-test-utils"; import { AppSettings } from "../../../app-setting"; import { WorkflowComputingUnitManagingService, @@ -39,12 +39,7 @@ describe("WorkflowComputingUnitManagingService", () => { const unitWithResource = (resource: any) => ({ computingUnit: { cuid: 1, name: "u", resource } }) as any; beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - providers: [WorkflowComputingUnitManagingService], - }); - service = TestBed.inject(WorkflowComputingUnitManagingService); - httpMock = TestBed.inject(HttpTestingController); + ({ service, httpMock } = setupHttpServiceTest(WorkflowComputingUnitManagingService)); }); afterEach(() => { @@ -60,20 +55,24 @@ describe("WorkflowComputingUnitManagingService", () => { let result: any; service.createKubernetesBasedComputingUnit("k8s", "2", "4G", "1", "1G", "64M").subscribe(r => (result = r)); - const req = httpMock.expectOne(`${api}/${COMPUTING_UNIT_CREATE_URL}`); - expect(req.request.method).toEqual("POST"); - expect(req.request.body).toEqual({ - name: "k8s", - cpuLimit: "2", - memoryLimit: "4G", - gpuLimit: "1", - jvmMemorySize: "1G", - shmSize: "64M", - uri: "", - unitType: "kubernetes", - }); - - req.flush(unitWithResource('{"cpuLimit":"2","memoryLimit":"4G"}')); + flushHttpRequest( + httpMock, + `${api}/${COMPUTING_UNIT_CREATE_URL}`, + "POST", + unitWithResource('{"cpuLimit":"2","memoryLimit":"4G"}'), + { + body: { + name: "k8s", + cpuLimit: "2", + memoryLimit: "4G", + gpuLimit: "1", + jvmMemorySize: "1G", + shmSize: "64M", + uri: "", + unitType: "kubernetes", + }, + } + ); expect(result.computingUnit.resource).toEqual({ cpuLimit: "2", memoryLimit: "4G" }); }); }); @@ -132,32 +131,31 @@ describe("WorkflowComputingUnitManagingService", () => { it("terminateComputingUnit() DELETEs the terminate endpoint", () => { service.terminateComputingUnit(9).subscribe(); - const req = httpMock.expectOne(`${api}/${COMPUTING_UNIT_BASE_URL}/9/terminate`); - expect(req.request.method).toEqual("DELETE"); - req.flush({}); + flushHttpRequest(httpMock, `${api}/${COMPUTING_UNIT_BASE_URL}/9/terminate`, "DELETE", {}); }); it("getComputingUnitLimitOptions() GETs the limits endpoint", () => { service.getComputingUnitLimitOptions().subscribe(); - const req = httpMock.expectOne(`${api}/${COMPUTING_UNIT_BASE_URL}/limits`); - expect(req.request.method).toEqual("GET"); - req.flush({ cpuLimitOptions: [], memoryLimitOptions: [], gpuLimitOptions: [] }); + flushHttpRequest(httpMock, `${api}/${COMPUTING_UNIT_BASE_URL}/limits`, "GET", { + cpuLimitOptions: [], + memoryLimitOptions: [], + gpuLimitOptions: [], + }); }); it("getComputingUnitTypes() GETs the types endpoint", () => { service.getComputingUnitTypes().subscribe(); - const req = httpMock.expectOne(`${api}/${COMPUTING_UNIT_TYPES_URL}`); - expect(req.request.method).toEqual("GET"); - req.flush({ typeOptions: [] }); + flushHttpRequest(httpMock, `${api}/${COMPUTING_UNIT_TYPES_URL}`, "GET", { typeOptions: [] }); }); it("listComputingUnits() GETs the list endpoint and parses every unit's resource", () => { let result: any[] = []; service.listComputingUnits().subscribe(r => (result = r)); - const req = httpMock.expectOne(`${api}/${COMPUTING_UNIT_LIST_URL}`); - expect(req.request.method).toEqual("GET"); - req.flush([unitWithResource('{"cpuLimit":"1"}'), unitWithResource('{"cpuLimit":"2"}')]); + flushHttpRequest(httpMock, `${api}/${COMPUTING_UNIT_LIST_URL}`, "GET", [ + unitWithResource('{"cpuLimit":"1"}'), + unitWithResource('{"cpuLimit":"2"}'), + ]); expect(result.map(u => u.computingUnit.resource)).toEqual([{ cpuLimit: "1" }, { cpuLimit: "2" }]); }); @@ -166,9 +164,10 @@ describe("WorkflowComputingUnitManagingService", () => { let result: any[] = []; service.listAllComputingUnits().subscribe(r => (result = r)); - const req = httpMock.expectOne(`${api}/${COMPUTING_UNIT_ADMIN_LIST_URL}`); - expect(req.request.method).toEqual("GET"); - req.flush([unitWithResource('{"cpuLimit":"1"}'), unitWithResource('{"cpuLimit":"2"}')]); + flushHttpRequest(httpMock, `${api}/${COMPUTING_UNIT_ADMIN_LIST_URL}`, "GET", [ + unitWithResource('{"cpuLimit":"1"}'), + unitWithResource('{"cpuLimit":"2"}'), + ]); expect(result.map(u => u.computingUnit.resource)).toEqual([{ cpuLimit: "1" }, { cpuLimit: "2" }]); }); @@ -194,9 +193,7 @@ describe("WorkflowComputingUnitManagingService", () => { let result: ClusterCapacity | undefined; service.getClusterCapacity().subscribe(r => (result = r)); - const req = httpMock.expectOne(`${api}/computing-unit/admin/cluster-capacity`); - expect(req.request.method).toEqual("GET"); - req.flush(capacity); + flushHttpRequest(httpMock, `${api}/computing-unit/admin/cluster-capacity`, "GET", capacity); expect(result).toEqual(capacity); }); @@ -215,8 +212,11 @@ describe("WorkflowComputingUnitManagingService", () => { it("renameComputingUnit() PUTs to a URI-encoded rename endpoint", () => { service.renameComputingUnit(3, "my unit/name").subscribe(); - const req = httpMock.expectOne(`${api}/${COMPUTING_UNIT_BASE_URL}/3/rename/${encodeURIComponent("my unit/name")}`); - expect(req.request.method).toEqual("PUT"); - req.flush({}); + flushHttpRequest( + httpMock, + `${api}/${COMPUTING_UNIT_BASE_URL}/3/rename/${encodeURIComponent("my unit/name")}`, + "PUT", + {} + ); }); }); diff --git a/frontend/src/app/common/service/deployment-version/deployment-version.service.spec.ts b/frontend/src/app/common/service/deployment-version/deployment-version.service.spec.ts index 25de07b1290..f84fda149fe 100644 --- a/frontend/src/app/common/service/deployment-version/deployment-version.service.spec.ts +++ b/frontend/src/app/common/service/deployment-version/deployment-version.service.spec.ts @@ -17,11 +17,12 @@ * under the License. */ -import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing"; -import { TestBed, fakeAsync, tick } from "@angular/core/testing"; +import { HttpTestingController } from "@angular/common/http/testing"; +import { fakeAsync, TestBed, tick } from "@angular/core/testing"; import { NzMessageService } from "ng-zorro-antd/message"; import { NzNotificationRef, NzNotificationService } from "ng-zorro-antd/notification"; import { Subject } from "rxjs"; +import { setupHttpServiceTest } from "../../testing/http-service-test-utils"; import { NotificationService } from "../notification/notification.service"; import { DeploymentVersionService, VERSION_MANIFEST_URL, VERSION_POLL_INTERVAL_MS } from "./deployment-version.service"; @@ -36,18 +37,13 @@ describe("DeploymentVersionService", () => { beforeEach(() => { notificationClick = new Subject(); - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - providers: [ - NotificationService, - // ng-zorro's lower-level services are not under test; stub them so the - // real NotificationService can be constructed and spied on. - { provide: NzNotificationService, useValue: { blank: vi.fn(), remove: vi.fn() } }, - { provide: NzMessageService, useValue: {} }, - ], - }); - service = TestBed.inject(DeploymentVersionService); - httpMock = TestBed.inject(HttpTestingController); + ({ service, httpMock } = setupHttpServiceTest(DeploymentVersionService, [ + NotificationService, + // ng-zorro's lower-level services are not under test; stub them so the + // real NotificationService can be constructed and spied on. + { provide: NzNotificationService, useValue: { blank: vi.fn(), remove: vi.fn() } }, + { provide: NzMessageService, useValue: {} }, + ])); notification = TestBed.inject(NotificationService); blankSpy = vi.spyOn(notification, "blank").mockReturnValue({ onClick: notificationClick, @@ -86,48 +82,38 @@ describe("DeploymentVersionService", () => { }); describe("checkForUpdate (malformed manifest)", () => { - it("ignores a manifest with no buildNumber field", () => { - const out = check(); - takeManifestRequest().flush({}); - expect(out.value).toBe(false); - }); - - it("ignores an empty-string buildNumber", () => { - const out = check(); - takeManifestRequest().flush({ buildNumber: "" }); - expect(out.value).toBe(false); - }); - - it("ignores a non-string buildNumber", () => { - const out = check(); - takeManifestRequest().flush({ buildNumber: 12345 }); - expect(out.value).toBe(false); - }); - - it("ignores a null response body", () => { - const out = check(); - takeManifestRequest().flush(null); - expect(out.value).toBe(false); + ( + [ + ["ignores a manifest with no buildNumber field", {}], + ["ignores an empty-string buildNumber", { buildNumber: "" }], + ["ignores a non-string buildNumber", { buildNumber: 12345 }], + ["ignores a null response body", null], + ] as const + ).forEach(([label, body]) => { + it(label, () => { + const out = check(); + takeManifestRequest().flush(body); + expect(out.value).toBe(false); + }); }); }); describe("checkForUpdate (transport failures stay silent)", () => { - it("returns false on a network error", () => { - const out = check(); - takeManifestRequest().error(new ProgressEvent("error")); - expect(out.value).toBe(false); - }); - - it("returns false on a 404 (manifest not deployed)", () => { - const out = check(); - takeManifestRequest().flush("not found", { status: 404, statusText: "Not Found" }); - expect(out.value).toBe(false); - }); - - it("returns false on a 500 server error", () => { - const out = check(); - takeManifestRequest().flush("boom", { status: 500, statusText: "Server Error" }); - expect(out.value).toBe(false); + ( + [ + ["returns false on a network error", r => r.error(new ProgressEvent("error"))], + [ + "returns false on a 404 (manifest not deployed)", + r => r.flush("not found", { status: 404, statusText: "Not Found" }), + ], + ["returns false on a 500 server error", r => r.flush("boom", { status: 500, statusText: "Server Error" })], + ] as [string, (req: ReturnType) => void][] + ).forEach(([label, respond]) => { + it(label, () => { + const out = check(); + respond(takeManifestRequest()); + expect(out.value).toBe(false); + }); }); }); diff --git a/frontend/src/app/common/service/gmail/gmail.service.spec.ts b/frontend/src/app/common/service/gmail/gmail.service.spec.ts index 08ee8f09bb5..3839a07d46f 100644 --- a/frontend/src/app/common/service/gmail/gmail.service.spec.ts +++ b/frontend/src/app/common/service/gmail/gmail.service.spec.ts @@ -17,8 +17,8 @@ * under the License. */ -import { TestBed } from "@angular/core/testing"; -import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing"; +import { HttpTestingController } from "@angular/common/http/testing"; +import { flushHttpRequest, setupHttpServiceTest } from "../../testing/http-service-test-utils"; import { GmailService } from "./gmail.service"; import { NotificationService } from "../notification/notification.service"; @@ -29,12 +29,9 @@ describe("GmailService", () => { beforeEach(() => { notificationSpy = { success: vi.fn(), error: vi.fn() }; - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - providers: [GmailService, { provide: NotificationService, useValue: notificationSpy }], - }); - service = TestBed.inject(GmailService); - httpTestingController = TestBed.inject(HttpTestingController); + ({ service, httpMock: httpTestingController } = setupHttpServiceTest(GmailService, [ + { provide: NotificationService, useValue: notificationSpy }, + ])); }); afterEach(() => { @@ -45,8 +42,7 @@ describe("GmailService", () => { it("should show a success toast when the backend accepts the send request", () => { service.sendEmail("subj", "body", "to@example.com"); - const req = httpTestingController.expectOne(r => r.url.endsWith("/gmail/send") && r.method === "PUT"); - req.flush(null); + flushHttpRequest(httpTestingController, r => r.url.endsWith("/gmail/send"), "PUT", null); expect(notificationSpy.success).toHaveBeenCalledWith("Email sent successfully"); expect(notificationSpy.error).not.toHaveBeenCalled(); @@ -55,25 +51,26 @@ describe("GmailService", () => { it("sends the correct PUT body for sendEmail with an explicit receiver", () => { service.sendEmail("subj", "body", "to@example.com"); - const req = httpTestingController.expectOne(r => r.url.endsWith("/gmail/send") && r.method === "PUT"); - expect(req.request.body).toEqual({ receiver: "to@example.com", subject: "subj", content: "body" }); - req.flush(null); + flushHttpRequest(httpTestingController, r => r.url.endsWith("/gmail/send"), "PUT", null, { + body: { receiver: "to@example.com", subject: "subj", content: "body" }, + }); }); it("defaults the receiver to an empty string when it is omitted", () => { service.sendEmail("subj", "body"); - const req = httpTestingController.expectOne(r => r.url.endsWith("/gmail/send") && r.method === "PUT"); - expect(req.request.body).toEqual({ receiver: "", subject: "subj", content: "body" }); - req.flush(null); + flushHttpRequest(httpTestingController, r => r.url.endsWith("/gmail/send"), "PUT", null, { + body: { receiver: "", subject: "subj", content: "body" }, + }); }); it("shows an error toast and logs to the console on a failed send", () => { const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {}); service.sendEmail("subj", "body", "to@example.com"); - const req = httpTestingController.expectOne(r => r.url.endsWith("/gmail/send") && r.method === "PUT"); - req.flush("boom", { status: 502, statusText: "Bad Gateway" }); + flushHttpRequest(httpTestingController, r => r.url.endsWith("/gmail/send"), "PUT", "boom", { + error: { status: 502, statusText: "Bad Gateway" }, + }); expect(notificationSpy.error).toHaveBeenCalledWith("Failed to send email. Please try again or contact admin."); expect(notificationSpy.success).not.toHaveBeenCalled(); @@ -84,10 +81,9 @@ describe("GmailService", () => { let emitted: string | undefined; service.getSenderEmail().subscribe(value => (emitted = value as string)); - const req = httpTestingController.expectOne( - r => r.url.endsWith("/gmail/sender/email") && r.method === "GET" && r.responseType === "text" - ); - req.flush("sender@example.com"); + flushHttpRequest(httpTestingController, r => r.url.endsWith("/gmail/sender/email"), "GET", "sender@example.com", { + responseType: "text", + }); expect(emitted).toBe("sender@example.com"); expect(notificationSpy.success).not.toHaveBeenCalled(); @@ -97,19 +93,15 @@ describe("GmailService", () => { it("sends the correct POST body for notifyUnauthorizedLogin", () => { service.notifyUnauthorizedLogin("u@example.com", "ACME", "for research"); - const req = httpTestingController.expectOne( - r => r.url.endsWith("/gmail/notify-unauthorized") && r.method === "POST" - ); - expect(req.request.body).toEqual({ receiver: "u@example.com", affiliation: "ACME", reason: "for research" }); - req.flush(null); + flushHttpRequest(httpTestingController, r => r.url.endsWith("/gmail/notify-unauthorized"), "POST", null, { + body: { receiver: "u@example.com", affiliation: "ACME", reason: "for research" }, + }); }); it("shows a success toast when the unauthorized-login notification is accepted", () => { service.notifyUnauthorizedLogin("u@example.com", "ACME", "for research"); - httpTestingController - .expectOne(r => r.url.endsWith("/gmail/notify-unauthorized") && r.method === "POST") - .flush(null); + flushHttpRequest(httpTestingController, r => r.url.endsWith("/gmail/notify-unauthorized"), "POST", null); expect(notificationSpy.success).toHaveBeenCalledWith("An admin has been notified about your account request."); }); @@ -118,9 +110,9 @@ describe("GmailService", () => { const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {}); service.notifyUnauthorizedLogin("u@example.com", "ACME", "for research"); - httpTestingController - .expectOne(r => r.url.endsWith("/gmail/notify-unauthorized") && r.method === "POST") - .flush("boom", { status: 500, statusText: "Internal Server Error" }); + flushHttpRequest(httpTestingController, r => r.url.endsWith("/gmail/notify-unauthorized"), "POST", "boom", { + error: { status: 500, statusText: "Internal Server Error" }, + }); expect(notificationSpy.error).toHaveBeenCalledWith("Failed to notify admin about your account request."); expect(consoleSpy).toHaveBeenCalledWith("Notify error:", "boom"); diff --git a/frontend/src/app/common/service/gui-config.service.spec.ts b/frontend/src/app/common/service/gui-config.service.spec.ts index c8c6d215a7b..95ab7ddd5ad 100644 --- a/frontend/src/app/common/service/gui-config.service.spec.ts +++ b/frontend/src/app/common/service/gui-config.service.spec.ts @@ -17,10 +17,10 @@ * under the License. */ -import { TestBed } from "@angular/core/testing"; -import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing"; +import { HttpTestingController } from "@angular/common/http/testing"; import { firstValueFrom } from "rxjs"; +import { flushHttpRequest, setupHttpServiceTest } from "../testing/http-service-test-utils"; import { GuiConfigService } from "./gui-config.service"; import { AppSettings } from "../app-setting"; @@ -51,12 +51,7 @@ describe("GuiConfigService", () => { beforeEach(() => { localStorage.removeItem(TOKEN_KEY); - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - providers: [GuiConfigService], - }); - service = TestBed.inject(GuiConfigService); - http = TestBed.inject(HttpTestingController); + ({ service, httpMock: http } = setupHttpServiceTest(GuiConfigService)); vi.spyOn(AppSettings, "getApiEndpoint").mockReturnValue(API); }); @@ -65,16 +60,26 @@ describe("GuiConfigService", () => { http.verify(); }); - // ─── loadPreLogin ───────────────────────────────────────────────────────── - - it("loadPreLogin fetches /config/pre-login and merges the response into env", async () => { + async function loadPreLogin(payload: Record = PRE_LOGIN_PAYLOAD): Promise { const pending = firstValueFrom(service.loadPreLogin()); + flushHttpRequest(http, `${API}/config/pre-login`, "GET", payload); + await pending; + } - const req = http.expectOne(`${API}/config/pre-login`); - expect(req.request.method).toBe("GET"); - req.flush(PRE_LOGIN_PAYLOAD); - + async function loadPostLogin( + gui: Record = GUI_PAYLOAD, + amber: Record = AMBER_PAYLOAD + ): Promise { + const pending = firstValueFrom(service.loadPostLogin()); + flushHttpRequest(http, `${API}/config/gui`, "GET", gui); + flushHttpRequest(http, `${API}/config/amber`, "GET", amber); await pending; + } + + // ─── loadPreLogin ───────────────────────────────────────────────────────── + + it("loadPreLogin fetches /config/pre-login and merges the response into env", async () => { + await loadPreLogin(); expect(service.env.localLogin).toBe(true); expect(service.env.googleLogin).toBe(false); expect(service.env.defaultLocalUser).toEqual({ username: "demo", password: "demo-pw" }); @@ -117,14 +122,8 @@ describe("GuiConfigService", () => { // Guards a refactor that overwrites the merged map with the gui/amber // response shape. Without this assertion, pre-login fields could silently // disappear from env after post-login completes. - const preLoginPending = firstValueFrom(service.loadPreLogin()); - http.expectOne(`${API}/config/pre-login`).flush(PRE_LOGIN_PAYLOAD); - await preLoginPending; - - const postLoginPending = firstValueFrom(service.loadPostLogin()); - http.expectOne(`${API}/config/gui`).flush(GUI_PAYLOAD); - http.expectOne(`${API}/config/amber`).flush(AMBER_PAYLOAD); - await postLoginPending; + await loadPreLogin(); + await loadPostLogin(); expect(service.env.localLogin).toBe(true); expect(service.env.defaultLocalUser).toEqual({ username: "demo", password: "demo-pw" }); @@ -200,9 +199,7 @@ describe("GuiConfigService", () => { // ─── env reference stability ─────────────────────────────────────────────── it("env returns a stable reference between loads so two-way bindings persist", async () => { - const pending = firstValueFrom(service.loadPreLogin()); - http.expectOne(`${API}/config/pre-login`).flush(PRE_LOGIN_PAYLOAD); - await pending; + await loadPreLogin(); // Repeated reads must return the same object (relied on by change detection // and by the [(ngModel)] write-through at menu.component.html). @@ -214,15 +211,10 @@ describe("GuiConfigService", () => { }); it("env reference is rebuilt after a new source loads", async () => { - const preLoginPending = firstValueFrom(service.loadPreLogin()); - http.expectOne(`${API}/config/pre-login`).flush(PRE_LOGIN_PAYLOAD); - await preLoginPending; + await loadPreLogin(); const before = service.env; - const postLoginPending = firstValueFrom(service.loadPostLogin()); - http.expectOne(`${API}/config/gui`).flush(GUI_PAYLOAD); - http.expectOne(`${API}/config/amber`).flush(AMBER_PAYLOAD); - await postLoginPending; + await loadPostLogin(); expect(service.env).not.toBe(before); expect(service.env.defaultDataTransferBatchSize).toBe(400); @@ -235,17 +227,12 @@ describe("GuiConfigService", () => { // survive a re-fetch (e.g. a fresh login re-running loadPostLogin). This is // intentional (config reloads are authoritative) and is locked in here so a // future "persist edits across reloads" change is a deliberate decision. - const preLoginPending = firstValueFrom(service.loadPreLogin()); - http.expectOne(`${API}/config/pre-login`).flush(PRE_LOGIN_PAYLOAD); - await preLoginPending; + await loadPreLogin(); (service.env as any).workflowEmailNotificationEnabled = true; expect(service.env.workflowEmailNotificationEnabled).toBe(true); - const postLoginPending = firstValueFrom(service.loadPostLogin()); - http.expectOne(`${API}/config/gui`).flush(GUI_PAYLOAD); - http.expectOne(`${API}/config/amber`).flush(AMBER_PAYLOAD); - await postLoginPending; + await loadPostLogin(); expect(service.env.workflowEmailNotificationEnabled).toBeUndefined(); }); @@ -257,15 +244,10 @@ describe("GuiConfigService", () => { // the public API, but the merge reduce implements "later source wins" and // nothing else covers it. Inject overlapping keys via the raw payloads to // lock the documented order (preLogin, gui, amber). - const preLoginPending = firstValueFrom(service.loadPreLogin()); - http.expectOne(`${API}/config/pre-login`).flush({ ...PRE_LOGIN_PAYLOAD, copilotEnabled: false }); - await preLoginPending; + await loadPreLogin({ ...PRE_LOGIN_PAYLOAD, copilotEnabled: false }); expect(service.env.copilotEnabled).toBe(false); - const postLoginPending = firstValueFrom(service.loadPostLogin()); - http.expectOne(`${API}/config/gui`).flush({ ...GUI_PAYLOAD, defaultDataTransferBatchSize: 1 }); - http.expectOne(`${API}/config/amber`).flush(AMBER_PAYLOAD); - await postLoginPending; + await loadPostLogin({ ...GUI_PAYLOAD, defaultDataTransferBatchSize: 1 }, AMBER_PAYLOAD); // gui comes after preLogin, and amber after gui, so the later value wins each time. expect(service.env.copilotEnabled).toBe(true); diff --git a/frontend/src/app/common/service/unauthorized-http-interceptor.service.spec.ts b/frontend/src/app/common/service/unauthorized-http-interceptor.service.spec.ts index 82e28194d79..79b1e832532 100644 --- a/frontend/src/app/common/service/unauthorized-http-interceptor.service.spec.ts +++ b/frontend/src/app/common/service/unauthorized-http-interceptor.service.spec.ts @@ -18,10 +18,11 @@ */ import { HTTP_INTERCEPTORS, HttpClient } from "@angular/common/http"; -import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing"; +import { HttpTestingController } from "@angular/common/http/testing"; import { TestBed } from "@angular/core/testing"; import { Router } from "@angular/router"; import { LOGIN } from "../../app-routing.constant"; +import { setupHttpServiceTest } from "../testing/http-service-test-utils"; import { NotificationService } from "./notification/notification.service"; import { UserService } from "./user/user.service"; import { UnauthorizedHttpInterceptor } from "./unauthorized-http-interceptor.service"; @@ -38,35 +39,39 @@ describe("UnauthorizedHttpInterceptor", () => { notificationSpy = { error: vi.fn() }; userServiceSpy = { logout: vi.fn(), isLogin: vi.fn().mockReturnValue(true) }; - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - providers: [ - { provide: HTTP_INTERCEPTORS, useClass: UnauthorizedHttpInterceptor, multi: true }, - { provide: Router, useValue: routerSpy }, - { provide: NotificationService, useValue: notificationSpy }, - { provide: UserService, useValue: userServiceSpy }, - ], - }); - - http = TestBed.inject(HttpClient); - httpMock = TestBed.inject(HttpTestingController); + ({ service: http, httpMock } = setupHttpServiceTest(HttpClient, [ + { provide: HTTP_INTERCEPTORS, useClass: UnauthorizedHttpInterceptor, multi: true }, + { provide: Router, useValue: routerSpy }, + { provide: NotificationService, useValue: notificationSpy }, + { provide: UserService, useValue: userServiceSpy }, + ])); }); afterEach(() => { httpMock.verify(); }); + function getWithStatus(url: string, status: number, statusText: string, headers?: Record): void { + http.get(url, headers ? { headers } : undefined).subscribe({ error: () => {} }); + httpMock.expectOne(url).flush(null, { status, statusText }); + } + function authedGet(url: string) { return http.get(url, { headers: { Authorization: "Bearer stale-token" } }); } + function expectNoLogoutSideEffects(): void { + expect(userServiceSpy.logout).not.toHaveBeenCalled(); + expect(notificationSpy.error).not.toHaveBeenCalled(); + expect(routerSpy.navigate).not.toHaveBeenCalled(); + } + it("logs out, notifies, and redirects to LOGIN on 401 for an authenticated request", () => { // The decision to log out hinges on whether *this* request was authenticated. // A 401 from an anonymous request is the server saying "you need to log in", // not "your session is invalid" — clearing the session there would wipe a // freshly-stored token (e.g. mid-login race). - authedGet("/api/secret").subscribe({ error: () => {} }); - httpMock.expectOne("/api/secret").flush(null, { status: 401, statusText: "Unauthorized" }); + getWithStatus("/api/secret", 401, "Unauthorized", { Authorization: "Bearer stale-token" }); expect(userServiceSpy.logout).toHaveBeenCalledTimes(1); expect(notificationSpy.error).toHaveBeenCalledTimes(1); @@ -80,27 +85,18 @@ describe("UnauthorizedHttpInterceptor", () => { // Reproduces the #5026 / #4903-revert scenario: a public endpoint (or one // whose token JwtModule skipped because it was expired) returning 401 // must NOT trigger a logout — the user may not even be logged in yet. - http.get("/api/public").subscribe({ error: () => {} }); - httpMock.expectOne("/api/public").flush(null, { status: 401, statusText: "Unauthorized" }); - - expect(userServiceSpy.logout).not.toHaveBeenCalled(); - expect(notificationSpy.error).not.toHaveBeenCalled(); - expect(routerSpy.navigate).not.toHaveBeenCalled(); + getWithStatus("/api/public", 401, "Unauthorized"); + expectNoLogoutSideEffects(); }); it("does not log out on non-401 errors even when Authorization was sent", () => { - authedGet("/api/oops").subscribe({ error: () => {} }); - httpMock.expectOne("/api/oops").flush(null, { status: 500, statusText: "Server Error" }); - - expect(userServiceSpy.logout).not.toHaveBeenCalled(); - expect(notificationSpy.error).not.toHaveBeenCalled(); - expect(routerSpy.navigate).not.toHaveBeenCalled(); + getWithStatus("/api/oops", 500, "Server Error", { Authorization: "Bearer stale-token" }); + expectNoLogoutSideEffects(); }); it("omits returnUrl when the current route is the root", () => { routerSpy.url = "/"; - authedGet("/api/secret").subscribe({ error: () => {} }); - httpMock.expectOne("/api/secret").flush(null, { status: 401, statusText: "Unauthorized" }); + getWithStatus("/api/secret", 401, "Unauthorized", { Authorization: "Bearer stale-token" }); expect(routerSpy.navigate).toHaveBeenCalledWith([LOGIN], { queryParams: { returnUrl: null } }); }); @@ -120,20 +116,15 @@ describe("UnauthorizedHttpInterceptor", () => { authPaths.forEach(path => { it(`does not log out on 401 from ${path}`, () => { - authedGet(path).subscribe({ error: () => {} }); - httpMock.expectOne(path).flush(null, { status: 401, statusText: "Unauthorized" }); - - expect(userServiceSpy.logout).not.toHaveBeenCalled(); - expect(notificationSpy.error).not.toHaveBeenCalled(); - expect(routerSpy.navigate).not.toHaveBeenCalled(); + getWithStatus(path, 401, "Unauthorized", { Authorization: "Bearer stale-token" }); + expectNoLogoutSideEffects(); }); }); it("still logs out on 401 from a URL that merely contains 'login' in a non-auth segment", () => { // Guards against an over-broad regex like /login/ that would skip e.g. // /api/dashboard/recent-logins. - authedGet("/api/dashboard/recent-logins").subscribe({ error: () => {} }); - httpMock.expectOne("/api/dashboard/recent-logins").flush(null, { status: 401, statusText: "Unauthorized" }); + getWithStatus("/api/dashboard/recent-logins", 401, "Unauthorized", { Authorization: "Bearer stale-token" }); expect(userServiceSpy.logout).toHaveBeenCalledTimes(1); }); diff --git a/frontend/src/app/common/service/user/apple-auth.service.spec.ts b/frontend/src/app/common/service/user/apple-auth.service.spec.ts index 9fb38ca2a0d..464f8d3f81f 100644 --- a/frontend/src/app/common/service/user/apple-auth.service.spec.ts +++ b/frontend/src/app/common/service/user/apple-auth.service.spec.ts @@ -17,8 +17,8 @@ * under the License. */ -import { TestBed } from "@angular/core/testing"; -import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing"; +import { HttpTestingController } from "@angular/common/http/testing"; +import { setupHttpServiceTest } from "../../testing/http-service-test-utils"; import { firstValueFrom } from "rxjs"; import { vi } from "vitest"; @@ -61,12 +61,7 @@ describe("AppleAuthService", () => { appleId = { auth: { init: vi.fn(), signIn: vi.fn().mockResolvedValue({ authorization: { id_token: "apple-id-token" } }) }, }; - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - providers: [AppleAuthService], - }); - service = TestBed.inject(AppleAuthService); - httpTestingController = TestBed.inject(HttpTestingController); + ({ service, httpMock: httpTestingController } = setupHttpServiceTest(AppleAuthService)); }); afterEach(() => { diff --git a/frontend/src/app/common/service/user/auth.service.spec.ts b/frontend/src/app/common/service/user/auth.service.spec.ts index aa04bbc67a4..edf5a9be82b 100644 --- a/frontend/src/app/common/service/user/auth.service.spec.ts +++ b/frontend/src/app/common/service/user/auth.service.spec.ts @@ -17,7 +17,8 @@ * under the License. */ -import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing"; +import { HttpTestingController, TestRequest } from "@angular/common/http/testing"; +import { flushHttpRequest, setupHttpServiceTest } from "../../testing/http-service-test-utils"; import { TestBed } from "@angular/core/testing"; import { firstValueFrom, Observable } from "rxjs"; import { JwtHelperService } from "@auth0/angular-jwt"; @@ -29,6 +30,8 @@ import { NotificationService } from "../notification/notification.service"; import { GmailService } from "../gmail/gmail.service"; import { GuiConfigService } from "../gui-config.service"; +type FlushBody = Parameters[0]; + describe("AuthService", () => { let service: AuthService; let httpMock: HttpTestingController; @@ -52,6 +55,89 @@ describe("AuthService", () => { comment: "c", joiningReason: "r", }; + const emaillessClaims = (role: Role = Role.REGULAR) => ({ ...claims, email: null, role }); + + function seed(decoded: Record = claims, inviteOnly?: boolean): void { + AuthService.setAccessToken("tok"); + if (inviteOnly !== undefined) config.env.inviteOnly = inviteOnly; + jwt.decodeToken.mockReturnValue(decoded); + } + + function expectReq( + endpoint: string, + body: unknown, + method = "POST", + response: FlushBody = { accessToken: "t" }, + contentType?: string + ): void { + flushHttpRequest(httpMock, `${api}/${endpoint}`, method, response, { body, contentType }); + } + + async function expectRejected( + endpoint: string, + status: number, + statusText: string, + message: string, + accepted = openPrompt() + ): Promise { + httpMock.expectOne(`${api}/${endpoint}`).flush({ message }, { status, statusText }); + expect(await accepted).toBe(false); + expect(notification.error).toHaveBeenCalledWith(message); + } + + async function expectInvalidEmail(endpoint: string, accepted: Promise): Promise { + expect(await accepted).toBe(false); + expect(notification.error).toHaveBeenCalledWith("Email format is invalid."); + httpMock.expectNone(`${api}/${endpoint}`); + } + + function expectProbe(reply: boolean, checkGet = false): void { + const req = httpMock.expectOne(r => r.url === `${api}/user/joining-reason/required`); + if (checkGet) expect(req.request.method).toEqual("GET"); + expect(req.request.params.get("uid")).toEqual("5"); + req.flush(reply); + } + + function stubModal(values: Record, modalTitle = "t", updateConfig = vi.fn()): void { + modal.create.mockReturnValue({ + getContentComponent: () => ({ modalTitle, getValues: () => values }), + updateConfig, + }); + } + + function confirmModal(): Promise { + return modal.create.mock.calls[0][0].nzOnOk(); + } + + function openPrompt(role: Role = Role.REGULAR): Promise { + seed(emaillessClaims(role)); + service.loginWithExistingToken(); + return confirmModal(); + } + + function cancelPrompt(): void { + seed(emaillessClaims()); + service.loginWithExistingToken(); + modal.create.mock.calls[0][0].nzOnCancel(); + } + + function expectPending(inviteOnly: boolean): void { + seed({ ...claims, role: Role.INACTIVE }, inviteOnly); + expect(service.loginWithExistingToken()).toBeUndefined(); + expectProbe(false, inviteOnly); + expect(modal.info).toHaveBeenCalledTimes(1); + expect(AuthService.getAccessToken()).toBeNull(); + } + + function scheduleAutoLogout(expired: boolean, expiryMs?: number) { + vi.useFakeTimers(); + seed(); + jwt.isTokenExpired.mockReturnValue(expired); + if (expiryMs !== undefined) jwt.getTokenExpirationDate.mockReturnValue(new Date(Date.now() + expiryMs)); + const spy = vi.spyOn(service, "logout"); + (service as any).registerAutoLogout(); + return spy; + } beforeEach(() => { localStorage.clear(); @@ -64,19 +150,13 @@ describe("AuthService", () => { config = { env: { inviteOnly: false, emailVerification: false } }; modal = { info: vi.fn(), create: vi.fn() }; - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - providers: [ - AuthService, - { provide: JwtHelperService, useValue: jwt }, - { provide: NotificationService, useValue: notification }, - { provide: GmailService, useValue: {} }, - { provide: GuiConfigService, useValue: config }, - { provide: NzModalService, useValue: modal }, - ], - }); - service = TestBed.inject(AuthService); - httpMock = TestBed.inject(HttpTestingController); + ({ service, httpMock } = setupHttpServiceTest(AuthService, [ + { provide: JwtHelperService, useValue: jwt }, + { provide: NotificationService, useValue: notification }, + { provide: GmailService, useValue: {} }, + { provide: GuiConfigService, useValue: config }, + { provide: NzModalService, useValue: modal }, + ])); }); afterEach(() => { @@ -107,36 +187,22 @@ describe("AuthService", () => { describe("HTTP auth endpoints", () => { it("register() POSTs username/email/password to the register endpoint", () => { service.register("alice", "alice@example.com", "pw").subscribe(); - const req = httpMock.expectOne(`${api}/${AuthService.REGISTER_ENDPOINT}`); - expect(req.request.method).toEqual("POST"); - expect(req.request.body).toEqual({ username: "alice", email: "alice@example.com", password: "pw" }); - req.flush({ accessToken: "t" }); + expectReq(AuthService.REGISTER_ENDPOINT, { username: "alice", email: "alice@example.com", password: "pw" }); }); it("auth() POSTs username/password to the login endpoint", () => { service.auth("alice", "pw").subscribe(); - const req = httpMock.expectOne(`${api}/${AuthService.LOGIN_ENDPOINT}`); - expect(req.request.method).toEqual("POST"); - expect(req.request.body).toEqual({ username: "alice", password: "pw" }); - req.flush({ accessToken: "t" }); + expectReq(AuthService.LOGIN_ENDPOINT, { username: "alice", password: "pw" }); }); it("orcidAuth() POSTs the raw authorization code with a text/plain content type", () => { service.orcidAuth("auth-code").subscribe(); - const req = httpMock.expectOne(`${api}/${AuthService.ORCID_LOGIN_ENDPOINT}`); - expect(req.request.method).toEqual("POST"); - expect(req.request.body).toEqual("auth-code"); - expect(req.request.headers.get("Content-Type")).toEqual("text/plain"); - req.flush({ accessToken: "t" }); + expectReq(AuthService.ORCID_LOGIN_ENDPOINT, "auth-code", "POST", { accessToken: "t" }, "text/plain"); }); it("googleAuth() POSTs the raw credential with a text/plain content type", () => { service.googleAuth("cred").subscribe(); - const req = httpMock.expectOne(`${api}/${AuthService.GOOGLE_LOGIN_ENDPOINT}`); - expect(req.request.method).toEqual("POST"); - expect(req.request.body).toEqual("cred"); - expect(req.request.headers.get("Content-Type")).toEqual("text/plain"); - req.flush({ accessToken: "t" }); + expectReq(AuthService.GOOGLE_LOGIN_ENDPOINT, "cred", "POST", { accessToken: "t" }, "text/plain"); }); // Annotated because the calls return differently-shaped observables (a registration result vs a @@ -208,47 +274,24 @@ describe("AuthService", () => { }); it("reads the avatar from a pre-rename googleAvatar claim", () => { - AuthService.setAccessToken("tok"); const { avatar, ...legacyClaims } = claims; - jwt.decodeToken.mockReturnValue({ ...legacyClaims, googleAvatar: "legacy-a" }); + seed({ ...legacyClaims, googleAvatar: "legacy-a" }); expect(service.loginWithExistingToken()?.avatar).toEqual("legacy-a"); }); it("in invite-only mode, an inactive user is logged out and registration is checked", () => { - AuthService.setAccessToken("tok"); - config.env.inviteOnly = true; - jwt.decodeToken.mockReturnValue({ ...claims, role: Role.INACTIVE }); - - const result = service.loginWithExistingToken(); - - expect(result).toBeUndefined(); - const req = httpMock.expectOne(r => r.url === `${api}/user/joining-reason/required`); - expect(req.request.params.get("uid")).toEqual("5"); - req.flush(false); - - expect(modal.info).toHaveBeenCalledTimes(1); - expect(AuthService.getAccessToken()).toBeNull(); + expectPending(true); }); // Admins can turn invite-only off while accounts are still waiting. Those accounts stay // INACTIVE and every request they make is refused, so they keep the pending screen. it("treats an inactive user as pending even while invite-only is off", () => { - AuthService.setAccessToken("tok"); - config.env.inviteOnly = false; - jwt.decodeToken.mockReturnValue({ ...claims, role: Role.INACTIVE }); - - const result = service.loginWithExistingToken(); - - expect(result).toBeUndefined(); - httpMock.expectOne(r => r.url === `${api}/user/joining-reason/required`).flush(false); - expect(modal.info).toHaveBeenCalledTimes(1); - expect(AuthService.getAccessToken()).toBeNull(); + expectPending(false); }); it("signs in an account that is not inactive, whatever invite-only says", () => { - AuthService.setAccessToken("tok"); - config.env.inviteOnly = true; + seed(claims, true); expect(service.loginWithExistingToken()?.role).toEqual(Role.REGULAR); httpMock.expectNone(r => r.url === `${api}/user/joining-reason/required`); @@ -260,20 +303,14 @@ describe("AuthService", () => { // creating credentialed accounts. The contract under test: such a token yields no `User` at all, // rather than one with the field blank. describe("the missing-email prompt", () => { - const emaillessClaims = (role: Role = Role.REGULAR) => ({ ...claims, email: null, role }); - beforeEach(() => { - modal.create.mockReturnValue({ - getContentComponent: () => ({ modalTitle: "t", getValues: () => ({ email: "typed@x.com" }) }), - updateConfig: vi.fn(), - }); + stubModal({ email: "typed@x.com" }); }); // The load-bearing assertion: no User escapes while the account has no address, so nothing // downstream ever sees `User.email` absent and the type stays honest. it("hands out no user and opens the prompt when the token carries no email", () => { - AuthService.setAccessToken("tok"); - jwt.decodeToken.mockReturnValue(emaillessClaims()); + seed(emaillessClaims()); const result = service.loginWithExistingToken(); @@ -295,8 +332,7 @@ describe("AuthService", () => { // loginWithExistingToken runs on every token refresh; a second dialog stacked on the one still // waiting for an answer would be unanswerable. it("does not stack a second prompt while one is open", () => { - AuthService.setAccessToken("tok"); - jwt.decodeToken.mockReturnValue(emaillessClaims()); + seed(emaillessClaims()); service.loginWithExistingToken(); service.loginWithExistingToken(); @@ -307,9 +343,7 @@ describe("AuthService", () => { // The address has to be collected before the invite-only branch, not after: that branch mails // the admin the account's address, and /gmail/notify-unauthorized rejects a null one. it("asks for an address instead of making the invite-only request", () => { - AuthService.setAccessToken("tok"); - config.env.inviteOnly = true; - jwt.decodeToken.mockReturnValue(emaillessClaims(Role.INACTIVE)); + seed(emaillessClaims(Role.INACTIVE), true); expect(service.loginWithExistingToken()).toBeUndefined(); @@ -318,28 +352,19 @@ describe("AuthService", () => { }); it("still runs the invite-only request for an inactive user that has an address", () => { - AuthService.setAccessToken("tok"); - config.env.inviteOnly = true; - jwt.decodeToken.mockReturnValue({ ...claims, role: Role.INACTIVE }); + seed({ ...claims, role: Role.INACTIVE }, true); service.loginWithExistingToken(); expect(modal.create).not.toHaveBeenCalled(); - httpMock.expectOne(r => r.url === `${api}/user/joining-reason/required`).flush(false); + expectProbe(false); }); it("stores the reissued token and announces it once the address is saved", async () => { - AuthService.setAccessToken("tok"); - jwt.decodeToken.mockReturnValue(emaillessClaims()); const announced = firstValueFrom(service.sessionChanged()); + const accepted = openPrompt(); - service.loginWithExistingToken(); - const accepted = modal.create.mock.calls[0][0].nzOnOk(); - - const req = httpMock.expectOne(`${api}/${AuthService.SET_EMAIL_ENDPOINT}`); - expect(req.request.method).toEqual("PUT"); - expect(req.request.body).toEqual({ email: "typed@x.com" }); - req.flush({ accessToken: "fresh-token" }); + expectReq(AuthService.SET_EMAIL_ENDPOINT, { email: "typed@x.com" }, "PUT", { accessToken: "fresh-token" }); expect(await accepted).toBe(true); expect(AuthService.getAccessToken()).toEqual("fresh-token"); @@ -349,11 +374,7 @@ describe("AuthService", () => { // The reissued token carries an address, so the very next pass produces a real user — which is // what turns the prompt into a way through rather than a dead end. it("hands out a user once the reissued token carries an address", async () => { - AuthService.setAccessToken("tok"); - jwt.decodeToken.mockReturnValue(emaillessClaims()); - - service.loginWithExistingToken(); - const accepted = modal.create.mock.calls[0][0].nzOnOk(); + const accepted = openPrompt(); httpMock.expectOne(`${api}/${AuthService.SET_EMAIL_ENDPOINT}`).flush({ accessToken: "fresh-token" }); await accepted; @@ -362,47 +383,24 @@ describe("AuthService", () => { }); it("keeps the dialog open and reports why when the address is refused", async () => { - AuthService.setAccessToken("tok"); - jwt.decodeToken.mockReturnValue(emaillessClaims()); - - service.loginWithExistingToken(); - const accepted = modal.create.mock.calls[0][0].nzOnOk(); - - httpMock - .expectOne(`${api}/${AuthService.SET_EMAIL_ENDPOINT}`) - .flush( - { message: "That email address already belongs to an account." }, - { status: 409, statusText: "Conflict" } - ); - - expect(await accepted).toBe(false); - expect(notification.error).toHaveBeenCalledWith("That email address already belongs to an account."); + await expectRejected( + AuthService.SET_EMAIL_ENDPOINT, + 409, + "Conflict", + "That email address already belongs to an account." + ); // The old token is untouched, so the user can try another address. expect(AuthService.getAccessToken()).toEqual("tok"); }); it("rejects a malformed address without calling the backend", async () => { - AuthService.setAccessToken("tok"); - jwt.decodeToken.mockReturnValue(emaillessClaims()); - modal.create.mockReturnValue({ - getContentComponent: () => ({ modalTitle: "t", getValues: () => ({ email: "not-an-address" }) }), - updateConfig: vi.fn(), - }); - - service.loginWithExistingToken(); - - expect(await modal.create.mock.calls[0][0].nzOnOk()).toBe(false); - expect(notification.error).toHaveBeenCalledWith("Email format is invalid."); - httpMock.expectNone(`${api}/${AuthService.SET_EMAIL_ENDPOINT}`); + stubModal({ email: "not-an-address" }); + await expectInvalidEmail(AuthService.SET_EMAIL_ENDPOINT, openPrompt()); }); it("signs out and announces the change when the prompt is cancelled", async () => { - AuthService.setAccessToken("tok"); - jwt.decodeToken.mockReturnValue(emaillessClaims()); const announced = firstValueFrom(service.sessionChanged()); - - service.loginWithExistingToken(); - modal.create.mock.calls[0][0].nzOnCancel(); + cancelPrompt(); expect(AuthService.getAccessToken()).toBeNull(); await expect(announced).resolves.toBeUndefined(); @@ -411,11 +409,7 @@ describe("AuthService", () => { // A second prompt has to be possible after a cancel, or a user who dismissed it once could // never be asked again for the life of the tab. it("can prompt again after a cancel", () => { - AuthService.setAccessToken("tok"); - jwt.decodeToken.mockReturnValue(emaillessClaims()); - - service.loginWithExistingToken(); - modal.create.mock.calls[0][0].nzOnCancel(); + cancelPrompt(); AuthService.setAccessToken("tok"); service.loginWithExistingToken(); @@ -427,7 +421,6 @@ describe("AuthService", () => { // and the second presents it. Nothing is stored server-side in between, so the address has to // travel with the code on the second call. describe("the missing-email prompt with verification on", () => { - const emaillessClaims = () => ({ ...claims, email: null }); let content: { modalTitle: string; step: string; getValues: () => { email: string; code: string } }; let updateConfig: ReturnType; @@ -442,22 +435,14 @@ describe("AuthService", () => { modal.create.mockReturnValue({ getContentComponent: () => content, updateConfig }); }); - const openPrompt = () => { - AuthService.setAccessToken("tok"); - jwt.decodeToken.mockReturnValue(emaillessClaims()); - service.loginWithExistingToken(); - }; - it("mails a code on the first confirm, then sends it with the address on the second", async () => { - openPrompt(); + seed(emaillessClaims()); + service.loginWithExistingToken(); expect(modal.create.mock.calls[0][0].nzOkText).toBe("Send code"); // First confirm: a code goes out and the dialog stays open on the code step. - const first = modal.create.mock.calls[0][0].nzOnOk(); - const codeReq = httpMock.expectOne(`${api}/${AuthService.SET_EMAIL_CODE_ENDPOINT}`); - expect(codeReq.request.method).toEqual("POST"); - expect(codeReq.request.body).toEqual({ email: "typed@x.com" }); - codeReq.flush(null); + const first = confirmModal(); + expectReq(AuthService.SET_EMAIL_CODE_ENDPOINT, { email: "typed@x.com" }, "POST", null); // False keeps the modal open; the address is not written yet. expect(await first).toBe(false); @@ -465,78 +450,56 @@ describe("AuthService", () => { expect(updateConfig).toHaveBeenCalledWith({ nzOkText: "Verify" }); // Second confirm: the address travels with the code, not a server-side pending row. - const second = modal.create.mock.calls[0][0].nzOnOk(); - const setReq = httpMock.expectOne(`${api}/${AuthService.SET_EMAIL_ENDPOINT}`); - expect(setReq.request.method).toEqual("PUT"); - expect(setReq.request.body).toEqual({ email: "typed@x.com", code: "123456" }); - setReq.flush({ accessToken: "fresh-token" }); + const second = confirmModal(); + expectReq(AuthService.SET_EMAIL_ENDPOINT, { email: "typed@x.com", code: "123456" }, "PUT", { + accessToken: "fresh-token", + }); expect(await second).toBe(true); expect(AuthService.getAccessToken()).toEqual("fresh-token"); }); it("keeps the dialog on the address step and reports why when the code cannot be sent", async () => { - openPrompt(); - - const accepted = modal.create.mock.calls[0][0].nzOnOk(); - httpMock - .expectOne(`${api}/${AuthService.SET_EMAIL_CODE_ENDPOINT}`) - .flush({ message: "A code was just sent." }, { status: 429, statusText: "Too Many Requests" }); - - expect(await accepted).toBe(false); + await expectRejected(AuthService.SET_EMAIL_CODE_ENDPOINT, 429, "Too Many Requests", "A code was just sent."); expect(content.step).toBe("address"); - expect(notification.error).toHaveBeenCalledWith("A code was just sent."); }); it("rejects a malformed address before asking for a code", async () => { - openPrompt(); + seed(emaillessClaims()); + service.loginWithExistingToken(); content.getValues = () => ({ email: "nope", code: "" }); - - const accepted = modal.create.mock.calls[0][0].nzOnOk(); - - expect(await accepted).toBe(false); - expect(notification.error).toHaveBeenCalledWith("Email format is invalid."); - httpMock.expectNone(`${api}/${AuthService.SET_EMAIL_CODE_ENDPOINT}`); + await expectInvalidEmail(AuthService.SET_EMAIL_CODE_ENDPOINT, confirmModal()); }); it("reports a refused code and keeps the dialog open", async () => { - openPrompt(); - const first = modal.create.mock.calls[0][0].nzOnOk(); + const first = openPrompt(); httpMock.expectOne(`${api}/${AuthService.SET_EMAIL_CODE_ENDPOINT}`).flush(null); await first; - const accepted = modal.create.mock.calls[0][0].nzOnOk(); - httpMock - .expectOne(`${api}/${AuthService.SET_EMAIL_ENDPOINT}`) - .flush({ message: "That code is not valid or has expired." }, { status: 406, statusText: "Not Acceptable" }); - - expect(await accepted).toBe(false); - expect(notification.error).toHaveBeenCalledWith("That code is not valid or has expired."); + await expectRejected( + AuthService.SET_EMAIL_ENDPOINT, + 406, + "Not Acceptable", + "That code is not valid or has expired.", + confirmModal() + ); }); }); describe("registration endpoints", () => { it("registerVerify() POSTs the same fields plus the code", () => { service.registerVerify("alice", "alice@example.com", "pw", "123456").subscribe(); - - const req = httpMock.expectOne(`${api}/${AuthService.REGISTER_VERIFY_ENDPOINT}`); - expect(req.request.method).toEqual("POST"); - expect(req.request.body).toEqual({ + expectReq(AuthService.REGISTER_VERIFY_ENDPOINT, { username: "alice", email: "alice@example.com", password: "pw", code: "123456", }); - req.flush({ accessToken: "tok" }); }); it("requestEmailCode() POSTs the address to the code endpoint", () => { service.requestEmailCode("a@b.com").subscribe(); - - const req = httpMock.expectOne(`${api}/${AuthService.SET_EMAIL_CODE_ENDPOINT}`); - expect(req.request.method).toEqual("POST"); - expect(req.request.body).toEqual({ email: "a@b.com" }); - req.flush(null); + expectReq(AuthService.SET_EMAIL_CODE_ENDPOINT, { email: "a@b.com" }, "POST", null); }); }); @@ -547,14 +510,7 @@ describe("AuthService", () => { }); it("schedules a logout that fires once the token expiry elapses", () => { - vi.useFakeTimers(); - AuthService.setAccessToken("tok"); - jwt.isTokenExpired.mockReturnValue(false); - // Expiry one second into the (frozen) fake clock. - jwt.getTokenExpirationDate.mockReturnValue(new Date(Date.now() + 1000)); - const logoutSpy = vi.spyOn(service, "logout"); - - (service as any).registerAutoLogout(); + const logoutSpy = scheduleAutoLogout(false, 1000); expect(logoutSpy).not.toHaveBeenCalled(); vi.advanceTimersByTime(1000); @@ -562,14 +518,8 @@ describe("AuthService", () => { }); it("does not schedule a logout when the token is already expired", () => { - vi.useFakeTimers(); - AuthService.setAccessToken("tok"); - jwt.isTokenExpired.mockReturnValue(true); - const logoutSpy = vi.spyOn(service, "logout"); - - (service as any).registerAutoLogout(); + const logoutSpy = scheduleAutoLogout(true); vi.advanceTimersByTime(1_000_000); - expect(logoutSpy).not.toHaveBeenCalled(); }); }); @@ -579,26 +529,15 @@ describe("AuthService", () => { // answers the registration-required probe with `true`, which is what makes // openRegistrationModal run. const openModalViaInactiveLogin = (): void => { - AuthService.setAccessToken("tok"); - config.env.inviteOnly = true; - jwt.decodeToken.mockReturnValue({ ...claims, role: Role.INACTIVE }); + seed({ ...claims, role: Role.INACTIVE }, true); expect(service.loginWithExistingToken()).toBeUndefined(); - const req = httpMock.expectOne(r => r.url === `${api}/user/joining-reason/required`); - expect(req.request.method).toEqual("GET"); - expect(req.request.params.get("uid")).toEqual("5"); - req.flush(true); + expectProbe(true, true); }; it("opens the registration modal when registration is required", () => { - modal.create.mockReturnValue({ - getContentComponent: () => ({ - modalTitle: "Request Access", - getValues: () => ({ affiliation: "", reason: "" }), - }), - updateConfig: vi.fn(), - }); + stubModal({ affiliation: "", reason: "" }, "Request Access"); openModalViaInactiveLogin(); @@ -614,23 +553,13 @@ describe("AuthService", () => { it("submitRegistration PUTs the affiliation/reason when the modal is confirmed", async () => { const gmail = TestBed.inject(GmailService) as unknown as { notifyUnauthorizedLogin: ReturnType }; gmail.notifyUnauthorizedLogin = vi.fn(); - modal.create.mockReturnValue({ - getContentComponent: () => ({ - modalTitle: "Request Access", - getValues: () => ({ affiliation: "Texera", reason: "research" }), - }), - updateConfig: vi.fn(), - }); + stubModal({ affiliation: "Texera", reason: "research" }, "Request Access"); openModalViaInactiveLogin(); - const okHandler = modal.create.mock.calls[0][0].nzOnOk as () => Promise; - const okPromise = okHandler(); + const okPromise = confirmModal(); - const req = httpMock.expectOne(`${api}/user/joining-reason`); - expect(req.request.method).toEqual("PUT"); - expect(req.request.body).toEqual({ uid: 5, affiliation: "Texera", joiningReason: "research" }); - req.flush(null); + expectReq("user/joining-reason", { uid: 5, affiliation: "Texera", joiningReason: "research" }, "PUT", null); await expect(okPromise).resolves.toBe(true); expect(gmail.notifyUnauthorizedLogin).toHaveBeenCalledWith("u@x.com", "Texera", "research"); diff --git a/frontend/src/app/common/service/user/config/user-config.service.spec.ts b/frontend/src/app/common/service/user/config/user-config.service.spec.ts index cd7b3101b77..1115323de5d 100644 --- a/frontend/src/app/common/service/user/config/user-config.service.spec.ts +++ b/frontend/src/app/common/service/user/config/user-config.service.spec.ts @@ -20,6 +20,7 @@ import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing"; import { TestBed } from "@angular/core/testing"; import { AppSettings } from "src/app/common/app-setting"; +import { flushHttpRequest, setupHttpServiceTest } from "../../../testing/http-service-test-utils"; import { UserConfigService, UserConfig } from "./user-config.service"; import { UserService } from "../user.service"; import { StubUserService, MOCK_USER } from "../stub-user.service"; @@ -34,14 +35,10 @@ describe("UserConfigService", () => { const endpoint = `${AppSettings.getApiEndpoint()}/${UserConfigService.USER_DICTIONARY_ENDPOINT}`; beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - providers: [{ provide: UserService, useClass: StubUserService }, UserConfigService], - }); - + ({ service, httpMock } = setupHttpServiceTest(UserConfigService, [ + { provide: UserService, useClass: StubUserService }, + ])); stubUserService = TestBed.inject(UserService) as unknown as StubUserService; - service = TestBed.inject(UserConfigService); - httpMock = TestBed.inject(HttpTestingController); // The constructor calls fetchAll() because StubUserService starts logged in. // Flush the request with an empty dictionary so each test starts from a clean slate. @@ -126,12 +123,8 @@ describe("UserConfigService", () => { describe("set", () => { it("issues a PUT with the value as the body and updates the local dict", () => { service.set("alpha", "one"); + flushHttpRequest(httpMock, `${endpoint}/alpha`, "PUT", null, { body: "one" }); - const req = httpMock.expectOne(`${endpoint}/alpha`); - expect(req.request.method).toEqual("PUT"); - expect(req.request.body).toEqual("one"); - - req.flush(null); service.delete("alpha"); httpMock.expectOne(`${endpoint}/alpha`).flush(null); @@ -144,10 +137,7 @@ describe("UserConfigService", () => { httpMock.expectOne(`${endpoint}/alpha`).flush(null); service.set("alpha", "one"); - const req = httpMock.expectOne(`${endpoint}/alpha`); - expect(req.request.method).toEqual("PUT"); - expect(req.request.body).toEqual("one"); - req.flush(null); + flushHttpRequest(httpMock, `${endpoint}/alpha`, "PUT", null, { body: "one" }); service.delete("alpha"); httpMock.expectOne(`${endpoint}/alpha`).flush(null); @@ -171,10 +161,7 @@ describe("UserConfigService", () => { it("issues a DELETE to the per-key endpoint and removes the entry from the local dict", () => { service.delete("alpha"); - - const req = httpMock.expectOne(`${endpoint}/alpha`); - expect(req.request.method).toEqual("DELETE"); - req.flush(null); + flushHttpRequest(httpMock, `${endpoint}/alpha`, "DELETE", null); service.delete("alpha"); httpMock.expectNone(`${endpoint}/alpha`); @@ -219,10 +206,7 @@ describe("UserConfigService", () => { describe("user-change reactions", () => { it("re-fetches the dictionary when a logged-in user is emitted on userChanged", () => { stubUserService.userChangeSubject.next(MOCK_USER); - - const req = httpMock.expectOne(endpoint); - expect(req.request.method).toEqual("GET"); - req.flush({ rehydrated: "yes" }); + flushHttpRequest(httpMock, endpoint, "GET", { rehydrated: "yes" }); service.delete("rehydrated"); httpMock.expectOne(`${endpoint}/rehydrated`).flush(null); @@ -269,10 +253,7 @@ describe("UserConfigService (constructed while logged out)", () => { beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], - providers: [ - { provide: UserService, useValue: { isLogin: () => false, userChanged: () => new Subject() } }, - UserConfigService, - ], + providers: [{ provide: UserService, useValue: { isLogin: () => false, userChanged: () => new Subject() } }], }); httpMock = TestBed.inject(HttpTestingController); }); diff --git a/frontend/src/app/common/service/user/google-auth.service.spec.ts b/frontend/src/app/common/service/user/google-auth.service.spec.ts index 0c7bf1d95d3..0922424e0b6 100644 --- a/frontend/src/app/common/service/user/google-auth.service.spec.ts +++ b/frontend/src/app/common/service/user/google-auth.service.spec.ts @@ -17,8 +17,8 @@ * under the License. */ -import { TestBed } from "@angular/core/testing"; -import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing"; +import { HttpTestingController } from "@angular/common/http/testing"; +import { setupHttpServiceTest } from "../../testing/http-service-test-utils"; import { firstValueFrom } from "rxjs"; import { GoogleAuthService } from "./google-auth.service"; @@ -30,12 +30,7 @@ describe("GoogleAuthService", () => { const expectedUrl = `${AppSettings.getApiEndpoint()}/auth/google/clientid`; beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - providers: [GoogleAuthService], - }); - service = TestBed.inject(GoogleAuthService); - httpTestingController = TestBed.inject(HttpTestingController); + ({ service, httpMock: httpTestingController } = setupHttpServiceTest(GoogleAuthService)); }); afterEach(() => { diff --git a/frontend/src/app/common/service/warehouse/warehouse.service.spec.ts b/frontend/src/app/common/service/warehouse/warehouse.service.spec.ts index aea048c9952..4e6b49ca3f8 100644 --- a/frontend/src/app/common/service/warehouse/warehouse.service.spec.ts +++ b/frontend/src/app/common/service/warehouse/warehouse.service.spec.ts @@ -17,8 +17,8 @@ * under the License. */ -import { TestBed } from "@angular/core/testing"; -import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing"; +import { HttpTestingController } from "@angular/common/http/testing"; +import { flushHttpRequest, setupHttpServiceTest } from "../../testing/http-service-test-utils"; import { AppSettings } from "../../app-setting"; import { WAREHOUSE_BASE_URL, WAREHOUSE_STATUS_URL, WarehouseService } from "./warehouse.service"; import { DashboardWarehouse, WarehouseStatus } from "../../type/warehouse"; @@ -38,12 +38,7 @@ describe("WarehouseService", () => { }; beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - providers: [WarehouseService], - }); - service = TestBed.inject(WarehouseService); - httpMock = TestBed.inject(HttpTestingController); + ({ service, httpMock } = setupHttpServiceTest(WarehouseService)); }); afterEach(() => { @@ -54,9 +49,10 @@ describe("WarehouseService", () => { let received: WarehouseStatus | undefined; service.getStatus().subscribe(status => (received = status)); - const req = httpMock.expectOne(`${AppSettings.getApiEndpoint()}/${WAREHOUSE_STATUS_URL}`); - expect(req.request.method).toBe("GET"); - req.flush({ enabled: true, warehouses: [warehouse] }); + flushHttpRequest(httpMock, `${AppSettings.getApiEndpoint()}/${WAREHOUSE_STATUS_URL}`, "GET", { + enabled: true, + warehouses: [warehouse], + }); expect(received).toEqual({ enabled: true, warehouses: [warehouse] }); }); @@ -65,10 +61,9 @@ describe("WarehouseService", () => { let received: DashboardWarehouse | undefined; service.createWarehouse("mybucket").subscribe(created => (received = created)); - const req = httpMock.expectOne(`${AppSettings.getApiEndpoint()}/${WAREHOUSE_BASE_URL}`); - expect(req.request.method).toBe("POST"); - expect(req.request.body).toEqual({ name: "mybucket" }); - req.flush(warehouse); + flushHttpRequest(httpMock, `${AppSettings.getApiEndpoint()}/${WAREHOUSE_BASE_URL}`, "POST", warehouse, { + body: { name: "mybucket" }, + }); expect(received).toEqual(warehouse); }); @@ -77,9 +72,7 @@ describe("WarehouseService", () => { let completed = false; service.deleteWarehouse(7).subscribe({ complete: () => (completed = true) }); - const req = httpMock.expectOne(`${AppSettings.getApiEndpoint()}/${WAREHOUSE_BASE_URL}/7`); - expect(req.request.method).toBe("DELETE"); - req.flush(null); + flushHttpRequest(httpMock, `${AppSettings.getApiEndpoint()}/${WAREHOUSE_BASE_URL}/7`, "DELETE", null); expect(completed).toBe(true); }); diff --git a/frontend/src/app/common/testing/computing-unit-test-fixtures.ts b/frontend/src/app/common/testing/computing-unit-test-fixtures.ts new file mode 100644 index 00000000000..addf2ce3c4d --- /dev/null +++ b/frontend/src/app/common/testing/computing-unit-test-fixtures.ts @@ -0,0 +1,99 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { + DashboardWorkflowComputingUnit, + WorkflowComputingUnit, + WorkflowComputingUnitResourceLimit, +} from "../type/workflow-computing-unit"; + +export const NAN_COMPUTING_UNIT_RESOURCE: WorkflowComputingUnitResourceLimit = { + cpuLimit: "NaN", + memoryLimit: "NaN", + gpuLimit: "NaN", + jvmMemorySize: "NaN", + shmSize: "NaN", + nodeAddresses: [], +}; + +export type ComputingUnitFixtureOverrides = Omit, "computingUnit"> & { + computingUnit?: Omit, "resource"> & { + resource?: Partial; + }; +}; + +/** + * Builds a {@link DashboardWorkflowComputingUnit} fixture, deep-merging optional + * `computingUnit` and `computingUnit.resource` partial overrides. + */ +export function makeDashboardComputingUnit( + overrides: ComputingUnitFixtureOverrides = {} +): DashboardWorkflowComputingUnit { + const { computingUnit: cuOverride, ...topOverrides } = overrides; + const hasExplicitResource = cuOverride !== undefined && "resource" in cuOverride; + const defaultResource: WorkflowComputingUnitResourceLimit = { + cpuLimit: "1", + memoryLimit: "1Gi", + gpuLimit: "0", + jvmMemorySize: "0", + shmSize: "0", + nodeAddresses: [], + }; + const resource = + hasExplicitResource && cuOverride?.resource === undefined + ? (undefined as unknown as WorkflowComputingUnitResourceLimit) + : { ...defaultResource, ...(cuOverride?.resource ?? {}) }; + + return { + status: "Running", + metrics: { cpuUsage: "N/A", memoryUsage: "N/A" }, + isOwner: true, + accessPrivilege: "WRITE", + ownerAvatar: "", + ownerName: "owner", + ...topOverrides, + computingUnit: { + cuid: 1, + uid: 1, + name: "unit-1", + creationTime: 0, + terminateTime: undefined, + type: "local", + uri: "", + ...(cuOverride ?? {}), + resource, + }, + }; +} + +/** Builds a local computing-unit fixture with NaN resource placeholders. */ +export function makeLocalComputingUnit( + cuid = 1, + base: ComputingUnitFixtureOverrides = {} +): DashboardWorkflowComputingUnit { + return makeDashboardComputingUnit({ + ...base, + computingUnit: { + ...(base.computingUnit ?? {}), + cuid, + type: "local", + resource: NAN_COMPUTING_UNIT_RESOURCE, + }, + }); +} diff --git a/frontend/src/app/common/testing/http-service-test-utils.ts b/frontend/src/app/common/testing/http-service-test-utils.ts new file mode 100644 index 00000000000..98edbcdcb85 --- /dev/null +++ b/frontend/src/app/common/testing/http-service-test-utils.ts @@ -0,0 +1,78 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { HttpRequest } from "@angular/common/http"; +import { HttpClientTestingModule, HttpTestingController, TestRequest } from "@angular/common/http/testing"; +import { Provider, Type } from "@angular/core"; +import { TestBed } from "@angular/core/testing"; + +type RequestMatcher = string | ((req: HttpRequest) => boolean); + +/** + * Configures TestBed with `HttpClientTestingModule` for an Angular service spec and + * returns both the service instance and `HttpTestingController`. + */ +export function setupHttpServiceTest( + serviceType: Type, + providers: Provider[] = [] +): { service: T; httpMock: HttpTestingController } { + TestBed.configureTestingModule({ + imports: [HttpClientTestingModule], + providers: [serviceType, ...providers], + }); + return { + service: TestBed.inject(serviceType), + httpMock: TestBed.inject(HttpTestingController), + }; +} + +/** + * Matches one pending HTTP request, asserts its method and optional body, responseType, + * content type, or query params. Flushes `response` (optionally with an error status). + */ +export function flushHttpRequest( + httpMock: HttpTestingController, + matcher: RequestMatcher, + method: string, + response: Parameters[0], + options?: { + body?: unknown; + responseType?: string; + contentType?: string; + params?: Record; + error?: { status: number; statusText: string }; + } +): TestRequest { + const req = httpMock.expectOne(matcher); + expect(req.request.method).toBe(method); + if (options?.responseType !== undefined) { + expect(req.request.responseType).toBe(options.responseType); + } + if (options?.body !== undefined) { + expect(req.request.body).toEqual(options.body); + } + if (options?.contentType) { + expect(req.request.headers.get("Content-Type")).toEqual(options.contentType); + } + for (const [key, expected] of Object.entries(options?.params ?? {})) { + expect(req.request.params.get(key)).toBe(expected); + } + req.flush(response, options?.error); + return req; +} diff --git a/frontend/src/app/common/util/computing-unit.util.spec.ts b/frontend/src/app/common/util/computing-unit.util.spec.ts index 88ff3e514c0..6ff7e9a3981 100644 --- a/frontend/src/app/common/util/computing-unit.util.spec.ts +++ b/frontend/src/app/common/util/computing-unit.util.spec.ts @@ -21,6 +21,7 @@ import { TestBed, ComponentFixture } from "@angular/core/testing"; import { NZ_MODAL_DATA } from "ng-zorro-antd/modal"; import type { DashboardWorkflowComputingUnit } from "../type/workflow-computing-unit"; import { ComputingUnitState } from "../type/computing-unit-connection.interface"; +import { ComputingUnitFixtureOverrides, makeDashboardComputingUnit } from "../testing/computing-unit-test-fixtures"; import { ComputingUnitMetadataComponent, unavailableComputingUnitReason, @@ -42,36 +43,26 @@ import { buildLocalComputingUnitUri, } from "./computing-unit.util"; -function makeUnit(overrides: Partial = {}): DashboardWorkflowComputingUnit { - return { - status: "Running", - metrics: { cpuUsage: "N/A", memoryUsage: "N/A" }, - isOwner: true, +function makeUnit(overrides: ComputingUnitFixtureOverrides = {}): DashboardWorkflowComputingUnit { + return makeDashboardComputingUnit({ accessPrivilege: "READ", - ownerAvatar: "", - ownerName: "owner", ...overrides, - // Set computingUnit last so a `computingUnit` override merges into (rather than replaces) - // the nested default object, keeping fixtures valid even for partial overrides. computingUnit: { - cuid: 1, - uid: 1, name: "unit-a", creationTime: 1700000000000, - terminateTime: undefined, type: "kubernetes", uri: "http://localhost/wsapi", + ...(overrides.computingUnit ?? {}), resource: { cpuLimit: "1000m", memoryLimit: "2Gi", gpuLimit: "1", jvmMemorySize: "2G", shmSize: "64Mi", - nodeAddresses: [], + ...(overrides.computingUnit?.resource ?? {}), }, - ...(overrides.computingUnit ?? {}), }, - }; + }); } describe("parseResourceUnit", () => { @@ -235,55 +226,33 @@ describe("unavailableComputingUnitReason", () => { describe("getComputingUnitStatusTooltip", () => { it("should map statuses to tooltip text", () => { - expect(getComputingUnitStatusTooltip({ status: "Running" } as unknown as DashboardWorkflowComputingUnit)).toBe( - "Ready to use" - ); - expect(getComputingUnitStatusTooltip({ status: "Pending" } as unknown as DashboardWorkflowComputingUnit)).toBe( - "Computing unit is starting up" - ); + expect(getComputingUnitStatusTooltip(makeUnit({ status: "Running" }))).toBe("Ready to use"); + expect(getComputingUnitStatusTooltip(makeUnit({ status: "Pending" }))).toBe("Computing unit is starting up"); }); it("should show the backend's status reason whenever one is present", () => { // An authorized viewer's reason is already user-friendly, so it wins over every canned text: // a failure explanation, a Pending unschedulable note, or a Running recovered-OOM warning. - expect( - getComputingUnitStatusTooltip({ - status: "Failed", - statusReason: "The computing unit keeps crashing because it runs out of memory.", - } as unknown as DashboardWorkflowComputingUnit) - ).toBe("The computing unit keeps crashing because it runs out of memory."); - expect( - getComputingUnitStatusTooltip({ - status: "Running", - statusReason: "The last run was terminated because the computing unit ran out of memory.", - } as unknown as DashboardWorkflowComputingUnit) - ).toBe("The last run was terminated because the computing unit ran out of memory."); - expect( - getComputingUnitStatusTooltip({ - status: "Pending", - statusReason: "The computing unit is waiting for cluster resources to become available.", - } as unknown as DashboardWorkflowComputingUnit) - ).toBe("The computing unit is waiting for cluster resources to become available."); + for (const [status, statusReason] of [ + ["Failed", "The computing unit keeps crashing because it runs out of memory."], + ["Running", "The last run was terminated because the computing unit ran out of memory."], + ["Pending", "The computing unit is waiting for cluster resources to become available."], + ] as const) { + expect(getComputingUnitStatusTooltip(makeUnit({ status, statusReason }))).toBe(statusReason); + } }); it("should show a generic unavailable message for reason-less failure states", () => { - expect(getComputingUnitStatusTooltip({ status: "Failed" } as unknown as DashboardWorkflowComputingUnit)).toBe( - "This computing unit is unavailable." - ); - expect(getComputingUnitStatusTooltip({ status: "Unknown" } as unknown as DashboardWorkflowComputingUnit)).toBe( - "This computing unit is unavailable." - ); + expect(getComputingUnitStatusTooltip(makeUnit({ status: "Failed" }))).toBe("This computing unit is unavailable."); + expect(getComputingUnitStatusTooltip(makeUnit({ status: "Unknown" }))).toBe("This computing unit is unavailable."); }); it("should not let an empty-string statusReason shadow the canned fallback", () => { // The backend omits the reason (undefined) for ordinary shared users, but an empty string // must behave the same way: it is falsy, so the status switch still decides the text. - expect( - getComputingUnitStatusTooltip({ - status: "Failed", - statusReason: "", - } as unknown as DashboardWorkflowComputingUnit) - ).toBe("This computing unit is unavailable."); + expect(getComputingUnitStatusTooltip(makeUnit({ status: "Failed", statusReason: "" }))).toBe( + "This computing unit is unavailable." + ); }); it("should fall back to the canned text when the backend sends a null status reason", () => { @@ -370,19 +339,31 @@ describe("isComputingUnitShmTooLarge", () => { }); }); +function expectSliderConfig( + selectedMemory: string, + steps: number[], + selectedJvmMemorySize: string, + showSlider?: boolean, + sliderValue?: number +): void { + const config = getJvmMemorySliderConfig(selectedMemory); + if (showSlider !== undefined) { + expect(config.showJvmMemorySlider).toBe(showSlider); + } + expect(config.jvmMemorySteps).toEqual(steps); + expect(config.selectedJvmMemorySize).toBe(selectedJvmMemorySize); + if (sliderValue !== undefined) { + expect(config.jvmMemorySliderValue).toBe(sliderValue); + } +} + describe("getJvmMemorySliderConfig", () => { it("should hide the slider for small memory sizes", () => { - const config = getJvmMemorySliderConfig("1Gi"); - expect(config.showJvmMemorySlider).toBe(false); - expect(config.jvmMemorySteps).toEqual([1]); - expect(config.selectedJvmMemorySize).toBe("1G"); + expectSliderConfig("1Gi", [1], "1G", false); }); it("should show the slider and build doubling steps for larger memory sizes", () => { - const config = getJvmMemorySliderConfig("8Gi"); - expect(config.showJvmMemorySlider).toBe(true); - expect(config.jvmMemorySteps).toEqual([2, 4, 8]); - expect(config.selectedJvmMemorySize).toBe("2G"); + expectSliderConfig("8Gi", [2, 4, 8], "2G", true); }); }); @@ -448,33 +429,22 @@ describe("isComputingUnitShmTooLarge (non-Gi selected memory)", () => { describe("getJvmMemorySliderConfig (memory unit handling)", () => { it("should convert a Mi memory value to whole GiB", () => { // 2048Mi -> 2Gi -> small path (<=3), defaultValue 2 (not 1) - const config = getJvmMemorySliderConfig("2048Mi"); - expect(config.showJvmMemorySlider).toBe(false); - expect(config.jvmMemorySteps).toEqual([1, 2]); - expect(config.selectedJvmMemorySize).toBe("2G"); - expect(config.jvmMemorySliderValue).toBe(1); + expectSliderConfig("2048Mi", [1, 2], "2G", false, 1); }); it("should floor sub-GiB Mi values up to a minimum of 1 GiB", () => { // 512Mi -> floor(512/1024)=0 -> Math.max(1, 0) = 1 - const config = getJvmMemorySliderConfig("512Mi"); - expect(config.jvmMemorySteps).toEqual([1]); - expect(config.selectedJvmMemorySize).toBe("1G"); + expectSliderConfig("512Mi", [1], "1G"); }); it("should build slider steps from a larger Mi value", () => { // 8192Mi -> 8Gi -> slider path - const config = getJvmMemorySliderConfig("8192Mi"); - expect(config.showJvmMemorySlider).toBe(true); - expect(config.jvmMemorySteps).toEqual([2, 4, 8]); - expect(config.selectedJvmMemorySize).toBe("2G"); + expectSliderConfig("8192Mi", [2, 4, 8], "2G", true); }); it("should default to 1 GiB for a value with an unrecognized memory unit", () => { // "Ki" is neither Gi nor Mi, so memoryToGb falls back to 1 - const config = getJvmMemorySliderConfig("500Ki"); - expect(config.jvmMemorySteps).toEqual([1]); - expect(config.selectedJvmMemorySize).toBe("1G"); + expectSliderConfig("500Ki", [1], "1G"); }); }); diff --git a/frontend/src/app/dashboard/component/admin/computing-unit/admin-computing-unit.component.spec.ts b/frontend/src/app/dashboard/component/admin/computing-unit/admin-computing-unit.component.spec.ts index 39d8da6fe37..2249e628f8f 100644 --- a/frontend/src/app/dashboard/component/admin/computing-unit/admin-computing-unit.component.spec.ts +++ b/frontend/src/app/dashboard/component/admin/computing-unit/admin-computing-unit.component.spec.ts @@ -27,64 +27,59 @@ import { WorkflowComputingUnitManagingService } from "../../../../common/service import { ComputingUnitActionsService } from "../../../../common/service/computing-unit/computing-unit-actions/computing-unit-actions.service"; import { DashboardWorkflowComputingUnit, - WorkflowComputingUnit, WorkflowComputingUnitResourceLimit, } from "../../../../common/type/workflow-computing-unit"; import { ComputingUnitState } from "../../../../common/type/computing-unit-connection.interface"; import { commonTestImports, commonTestProviders } from "../../../../common/testing/test-utils"; import { UserService } from "../../../../common/service/user/user.service"; import { StubUserService } from "../../../../common/service/user/stub-user.service"; - -function makeUnit(over: Partial = {}): DashboardWorkflowComputingUnit { - return { +import { + ComputingUnitFixtureOverrides, + NAN_COMPUTING_UNIT_RESOURCE, + makeDashboardComputingUnit, + makeLocalComputingUnit, +} from "../../../../common/testing/computing-unit-test-fixtures"; + +function makeUnit(over: ComputingUnitFixtureOverrides = {}): DashboardWorkflowComputingUnit { + return makeDashboardComputingUnit({ + metrics: { cpuUsage: "NaN", memoryUsage: "NaN" }, + isOwner: false, + ownerName: "alice", + ...over, computingUnit: { - cuid: 1, uid: 100, name: "cu", creationTime: 1_700_000_000_000, - terminateTime: undefined, type: "kubernetes", uri: "uri", + ...(over.computingUnit ?? {}), resource: { cpuLimit: "2", memoryLimit: "4Gi", - gpuLimit: "0", jvmMemorySize: "2G", shmSize: "64Mi", - nodeAddresses: [], + ...(over.computingUnit?.resource ?? {}), }, }, - status: "Running", - metrics: { cpuUsage: "NaN", memoryUsage: "NaN" }, - isOwner: false, - accessPrivilege: "WRITE", - ownerAvatar: "", - ownerName: "alice", - ...over, - }; + }); } // Overrides fields of the nested `computingUnit`, so a test need not respread it. -function withCu(over: Partial): Partial { - return { computingUnit: { ...makeUnit().computingUnit, ...over } }; +function withCu(over: ComputingUnitFixtureOverrides["computingUnit"]): ComputingUnitFixtureOverrides { + return { computingUnit: over }; } -// The all-placeholder resource a local unit carries. -const NAN_RESOURCE: WorkflowComputingUnitResourceLimit = { - cpuLimit: "NaN", - memoryLimit: "NaN", - gpuLimit: "NaN", - jvmMemorySize: "NaN", - shmSize: "NaN", - nodeAddresses: [], -}; - -function withResource(over: Partial): Partial { - return withCu({ resource: { ...makeUnit().computingUnit.resource, ...over } }); +function withResource(over: Partial): ComputingUnitFixtureOverrides { + return withCu({ resource: over }); } function localUnit(cuid = 1): DashboardWorkflowComputingUnit { - return makeUnit(withCu({ cuid, type: "local", resource: NAN_RESOURCE })); + return makeLocalComputingUnit(cuid, { + metrics: { cpuUsage: "NaN", memoryUsage: "NaN" }, + isOwner: false, + ownerName: "alice", + computingUnit: { uid: 100, name: "cu", creationTime: 1_700_000_000_000, uri: "uri" }, + }); } describe("AdminComputingUnitComponent", () => { @@ -473,7 +468,7 @@ describe("AdminComputingUnitComponent", () => { }); it("falls back to a dash when a non-local unit reports no usable spec", () => { - const blank = makeUnit(withCu({ resource: { ...NAN_RESOURCE, memoryLimit: "" } })); + const blank = makeUnit(withCu({ resource: { ...NAN_COMPUTING_UNIT_RESOURCE, memoryLimit: "" } })); expect(component.resourceSummary(blank)).toBe("—"); }); diff --git a/frontend/src/app/dashboard/component/admin/computing-unit/cluster-capacity/admin-cluster-capacity.component.spec.ts b/frontend/src/app/dashboard/component/admin/computing-unit/cluster-capacity/admin-cluster-capacity.component.spec.ts index da65998601a..4cd21dd678e 100644 --- a/frontend/src/app/dashboard/component/admin/computing-unit/cluster-capacity/admin-cluster-capacity.component.spec.ts +++ b/frontend/src/app/dashboard/component/admin/computing-unit/cluster-capacity/admin-cluster-capacity.component.spec.ts @@ -19,7 +19,7 @@ import { HttpErrorResponse } from "@angular/common/http"; import { ComponentFixture, TestBed } from "@angular/core/testing"; -import { of, Subject, throwError } from "rxjs"; +import { Observable, of, Subject, throwError } from "rxjs"; import { AdminClusterCapacityComponent } from "./admin-cluster-capacity.component"; import { WorkflowComputingUnitManagingService } from "../../../../../common/service/computing-unit/workflow-computing-unit/workflow-computing-unit-managing.service"; import { ClusterCapacity, ResourceCapacity } from "../../../../../common/type/workflow-computing-unit"; @@ -72,6 +72,16 @@ describe("AdminClusterCapacityComponent", () => { }); const render = () => fixture.detectChanges(); + const renderWith = (src: Observable) => { + vi.mocked(service.getClusterCapacity).mockReturnValue(src); + render(); + }; + const renderCapacity = (over: Partial = {}) => renderWith(of(capacity(over))); + const renderSequence = (...sources: Observable[]) => { + const spy = vi.mocked(service.getClusterCapacity); + sources.forEach(src => spy.mockReturnValueOnce(src)); + render(); + }; const advance = (ms: number) => { vi.advanceTimersByTime(ms); fixture.detectChanges(); @@ -85,6 +95,9 @@ describe("AdminClusterCapacityComponent", () => { return row!; }; const text = (resource: string, cell: string) => rowFor(resource).querySelector(`.${cell}`)?.textContent?.trim(); + const expectCells = (resource: string, expected: Record) => { + for (const [cell, value] of Object.entries(expected)) expect(text(resource, cell)).toBe(value); + }; const figures = (resource: string) => ["allocated", "available", "total"].map(cell => text(resource, cell)); const fillWidth = (resource: string) => rowFor(resource).querySelector(".meter-fill")?.style.width ?? "no meter"; @@ -105,66 +118,34 @@ describe("AdminClusterCapacityComponent", () => { }); it("says 1 core in the singular and groups the thousands", () => { - vi.mocked(service.getClusterCapacity).mockReturnValue( - of(capacity({ cpu: { total: 2_048_000, allocated: 250, available: 1000 } })) - ); - - render(); - - expect(text("CPU", "available")).toBe("1 core"); - expect(text("CPU", "total")).toBe("2,048 cores"); + renderCapacity({ cpu: { total: 2_048_000, allocated: 250, available: 1000 } }); + expectCells("CPU", { available: "1 core", total: "2,048 cores" }); }); // 999m is just under a core, the figure that would round to a plural "1". it("shows cores to the millicore, without rounding", () => { - vi.mocked(service.getClusterCapacity).mockReturnValue( - of(capacity({ cpu: { total: 3920, allocated: 125, available: 999 } })) - ); - - render(); - - expect(text("CPU", "allocated")).toBe("0.125 cores"); - expect(text("CPU", "available")).toBe("0.999 cores"); - expect(text("CPU", "total")).toBe("3.92 cores"); + renderCapacity({ cpu: { total: 3920, allocated: 125, available: 999 } }); + expectCells("CPU", { allocated: "0.125 cores", available: "0.999 cores", total: "3.92 cores" }); }); it("picks the memory unit by size and drops a trailing .0", () => { - vi.mocked(service.getClusterCapacity).mockReturnValue( - of(capacity({ memory: { total: 2 * TiB, allocated: 512 * MiB, available: 1.5 * GiB } })) - ); - - render(); - - expect(text("Memory", "allocated")).toBe("512 MiB"); - expect(text("Memory", "available")).toBe("1.5 GiB"); - expect(text("Memory", "total")).toBe("2 TiB"); + renderCapacity({ memory: { total: 2 * TiB, allocated: 512 * MiB, available: 1.5 * GiB } }); + expectCells("Memory", { allocated: "512 MiB", available: "1.5 GiB", total: "2 TiB" }); }); it("moves up a unit when rounding reaches it, so it never shows 1,024 of the smaller one", () => { - vi.mocked(service.getClusterCapacity).mockReturnValue(of(capacity({ memory: used(GiB - 1, 1023.99 * MiB) }))); - - render(); - - expect(text("Memory", "allocated")).toBe("1 GiB"); - expect(text("Memory", "total")).toBe("1 GiB"); + renderCapacity({ memory: used(GiB - 1, 1023.99 * MiB) }); + expectCells("Memory", { allocated: "1 GiB", total: "1 GiB" }); }); it("shows zero bytes as 0 B", () => { - vi.mocked(service.getClusterCapacity).mockReturnValue(of(capacity({ memory: used(64 * GiB, 0) }))); - - render(); - - expect(text("Memory", "allocated")).toBe("0 B"); - expect(text("Memory", "percent-used")).toBe("0%"); + renderCapacity({ memory: used(64 * GiB, 0) }); + expectCells("Memory", { allocated: "0 B", "percent-used": "0%" }); }); // 15.99 of 16 cores must not read full, and 29 / 100 * 100 is 28.999… in floating point. it("rounds the share down, so 100% shows only when nothing is left", () => { - vi.mocked(service.getClusterCapacity).mockReturnValue( - of(capacity({ cpu: used(16000, 15990), memory: used(64 * GiB, 64 * GiB), gpu: used(100, 29) })) - ); - - render(); + renderCapacity({ cpu: used(16000, 15990), memory: used(64 * GiB, 64 * GiB), gpu: used(100, 29) }); expect(text("CPU", "percent-used")).toBe("99%"); expect(text("Memory", "percent-used")).toBe("100%"); @@ -172,21 +153,14 @@ describe("AdminClusterCapacityComponent", () => { }); it("shows a share over 100% when pods request more than the nodes offer, with the bar capped at full", () => { - vi.mocked(service.getClusterCapacity).mockReturnValue(of(capacity({ cpu: used(1000, 1500) }))); + renderCapacity({ cpu: used(1000, 1500) }); - render(); - - expect(text("CPU", "percent-used")).toBe("150%"); + expectCells("CPU", { "percent-used": "150%", available: "0 cores" }); expect(fillWidth("CPU")).toBe("100%"); - expect(text("CPU", "available")).toBe("0 cores"); }); it("flags a resource from 80% as running low and from 95% as nearly full, with an icon and a label", () => { - vi.mocked(service.getClusterCapacity).mockReturnValue( - of(capacity({ cpu: used(100, 79), memory: used(100, 80), gpu: used(20, 19) })) - ); - - render(); + renderCapacity({ cpu: used(100, 79), memory: used(100, 80), gpu: used(20, 19) }); const status = (resource: string) => rowFor(resource).querySelector(".status-icon")?.getAttribute("aria-label"); expect(rowFor("CPU").className).not.toMatch(/capacity-(warning|critical)/); @@ -198,14 +172,10 @@ describe("AdminClusterCapacityComponent", () => { }); it("says the cluster has none of a resource instead of dividing by zero", () => { - vi.mocked(service.getClusterCapacity).mockReturnValue(of(capacity({ gpu: used(0, 0) }))); - - render(); + renderCapacity({ gpu: used(0, 0) }); - expect(text("GPU", "usage")).toBe("None in the cluster"); - expect(text("GPU", "percent-used")).toBeUndefined(); + expectCells("GPU", { usage: "None in the cluster", "percent-used": undefined, total: "0" }); expect(fillWidth("GPU")).toBe("no meter"); - expect(text("GPU", "total")).toBe("0"); }); it("shows a resource the response leaves out or garbles as not reported, and still shows the rest", () => { @@ -213,9 +183,7 @@ describe("AdminClusterCapacityComponent", () => { cpu: { total: "lots", allocated: 1, available: 1 }, memory: capacity().memory, } as unknown as ClusterCapacity; - vi.mocked(service.getClusterCapacity).mockReturnValue(of(garbled)); - - render(); + renderWith(of(garbled)); for (const resource of ["CPU", "GPU"]) { expect(text(resource, "usage")).toBe("Not reported"); @@ -226,16 +194,10 @@ describe("AdminClusterCapacityComponent", () => { // A browser drops a negative width, so the bar would show full. it("shows a resource with a negative figure as not reported", () => { - vi.mocked(service.getClusterCapacity).mockReturnValue( - of( - capacity({ - cpu: { total: 1000, allocated: -50, available: 1050 }, - gpu: { total: -1, allocated: 0, available: 0 }, - }) - ) - ); - - render(); + renderCapacity({ + cpu: { total: 1000, allocated: -50, available: 1050 }, + gpu: { total: -1, allocated: 0, available: 0 }, + }); expect(text("CPU", "usage")).toBe("Not reported"); expect(text("GPU", "usage")).toBe("Not reported"); @@ -245,9 +207,7 @@ describe("AdminClusterCapacityComponent", () => { describe("loading and polling", () => { it("renders nothing until the first answer", () => { const first = new Subject(); - vi.mocked(service.getClusterCapacity).mockReturnValue(first); - - render(); + renderWith(first); expect(panel()).toBeNull(); first.next(capacity()); @@ -257,9 +217,7 @@ describe("AdminClusterCapacityComponent", () => { }); it("stays hidden and stops polling when computing units do not run on Kubernetes", () => { - vi.mocked(service.getClusterCapacity).mockReturnValue(failWith(404, "not on Kubernetes")); - - render(); + renderWith(failWith(404, "not on Kubernetes")); advance(120_000); expect(panel()).toBeNull(); @@ -267,9 +225,7 @@ describe("AdminClusterCapacityComponent", () => { }); it("shows the cluster's message when the first load fails, e.g. a missing read grant", () => { - vi.mocked(service.getClusterCapacity).mockReturnValue(failWith(500, "nodes is forbidden")); - - render(); + renderWith(failWith(500, "nodes is forbidden")); expect(panel()).not.toBeNull(); expect(alertText()).toContain("Could not load cluster capacity: nodes is forbidden"); @@ -278,12 +234,7 @@ describe("AdminClusterCapacityComponent", () => { // An empty message is falsy, and would leave the alert ending on a bare colon. it("still reports a failure whose message is empty, and says no details were given", () => { - vi.mocked(service.getClusterCapacity) - .mockReturnValueOnce(failWith(500, "")) - .mockReturnValueOnce(of(capacity())) - .mockReturnValueOnce(failWith(500, "")); - - render(); + renderSequence(failWith(500, ""), of(capacity()), failWith(500, "")); expect(alertText()).toContain("Could not load cluster capacity: the server gave no details"); advance(30_000); @@ -301,12 +252,7 @@ describe("AdminClusterCapacityComponent", () => { }); it("keeps the last capacity and warns when a refresh fails, then clears the warning once one succeeds", () => { - vi.mocked(service.getClusterCapacity) - .mockReturnValueOnce(of(capacity())) - .mockReturnValueOnce(failWith(500, "boom")) - .mockReturnValueOnce(of(capacity({ cpu: used(16000, 8000) }))); - - render(); + renderSequence(of(capacity()), failWith(500, "boom"), of(capacity({ cpu: used(16000, 8000) }))); advance(30_000); expect(text("CPU", "percent-used")).toBe("25%"); @@ -333,9 +279,8 @@ describe("AdminClusterCapacityComponent", () => { it("ignores a refresh click while a fetch is still in flight", () => { const inFlight = new Subject(); - vi.mocked(service.getClusterCapacity).mockReturnValueOnce(of(capacity())).mockReturnValueOnce(inFlight); + renderSequence(of(capacity()), inFlight); - render(); const button = fixture.nativeElement.querySelector(".refresh-button"); button.click(); button.click(); diff --git a/frontend/src/app/dashboard/component/user/user-computing-unit/user-computing-unit-list-item/user-computing-unit-list-item.component.spec.ts b/frontend/src/app/dashboard/component/user/user-computing-unit/user-computing-unit-list-item/user-computing-unit-list-item.component.spec.ts index 1e8624714c9..1620cafb575 100644 --- a/frontend/src/app/dashboard/component/user/user-computing-unit/user-computing-unit-list-item/user-computing-unit-list-item.component.spec.ts +++ b/frontend/src/app/dashboard/component/user/user-computing-unit/user-computing-unit-list-item/user-computing-unit-list-item.component.spec.ts @@ -35,8 +35,9 @@ import { DashboardWorkflowComputingUnit } from "../../../../../common/type/workf import { GuiConfigService } from "../../../../../common/service/gui-config.service"; import { commonTestProviders } from "../../../../../common/testing/test-utils"; import { ComputingUnitMetadataComponent } from "../../../../../common/util/computing-unit.util"; +import { makeDashboardComputingUnit } from "../../../../../common/testing/computing-unit-test-fixtures"; -function bareComponent(entry: DashboardWorkflowComputingUnit): UserComputingUnitListItemComponent { +function bareComponent(entry?: DashboardWorkflowComputingUnit): UserComputingUnitListItemComponent { const item = new UserComputingUnitListItemComponent( {} as any, {} as any, @@ -46,38 +47,13 @@ function bareComponent(entry: DashboardWorkflowComputingUnit): UserComputingUnit {} as any, {} as any ); - item.entry = entry; + if (entry !== undefined) { + item.entry = entry; + } return item; } -function makeEntry(overrides: Partial = {}): DashboardWorkflowComputingUnit { - return { - computingUnit: { - cuid: 1, - uid: 1, - name: "unit-1", - creationTime: 0, - terminateTime: undefined, - type: "local", - uri: "", - resource: { - cpuLimit: "1", - memoryLimit: "1Gi", - gpuLimit: "0", - jvmMemorySize: "0", - shmSize: "0", - nodeAddresses: [], - }, - }, - status: "Running", - metrics: { cpuUsage: "N/A", memoryUsage: "N/A" }, - isOwner: true, - accessPrivilege: "WRITE", - ownerAvatar: "", - ownerName: "owner", - ...overrides, - }; -} +const makeEntry = makeDashboardComputingUnit; describe("UserComputingUnitListItemComponent", () => { let fixture: ComponentFixture; @@ -160,25 +136,15 @@ describe("UserComputingUnitListItemComponent", () => { }); describe("entry and unit getters", () => { - function bare(): UserComputingUnitListItemComponent { - return new UserComputingUnitListItemComponent( - {} as any, - {} as any, - {} as any, - {} as any, - {} as any, - {} as any, - {} as any - ); - } - it("throws when entry is accessed before being set", () => { - expect(() => bare().entry).toThrowError("entry property must be provided to UserComputingUnitListItemComponent."); + expect(() => bareComponent().entry).toThrowError( + "entry property must be provided to UserComputingUnitListItemComponent." + ); }); it("returns the entry once set", () => { const entry = makeEntry(); - const item = bare(); + const item = bareComponent(); item.entry = entry; expect(item.entry).toBe(entry); }); @@ -188,11 +154,10 @@ describe("UserComputingUnitListItemComponent", () => { }); it("throws when the entry has no computing unit", () => { - const item = bare(); - item.entry = { + const item = bareComponent({ ...makeEntry(), computingUnit: undefined as unknown as DashboardWorkflowComputingUnit["computingUnit"], - }; + }); expect(() => item.unit).toThrowError( "Incorrect type of DashboardEntry provided to UserComputingUnitListItemComponent. Entry must be computing unit." ); @@ -412,14 +377,7 @@ describe("UserComputingUnitListItemComponent", () => { const coreEntry = bareComponent(makeEntry()); expect(coreEntry.getCpuLimitUnit()).toBe("CPU"); - const milliEntry = bareComponent( - makeEntry({ - computingUnit: { - ...makeEntry().computingUnit, - resource: { ...makeEntry().computingUnit.resource, cpuLimit: "2000m" }, - }, - }) - ); + const milliEntry = bareComponent(makeEntry({ computingUnit: { resource: { cpuLimit: "2000m" } } })); expect(milliEntry.getCpuLimitUnit()).toBe("m"); }); @@ -430,13 +388,9 @@ describe("UserComputingUnitListItemComponent", () => { describe("getCpuValue / getMemoryValue with real usage", () => { function entryWith(cpuLimit: string, memoryLimit: string, cpuUsage: string, memoryUsage: string) { - const base = makeEntry(); return makeEntry({ metrics: { cpuUsage, memoryUsage }, - computingUnit: { - ...base.computingUnit, - resource: { ...base.computingUnit.resource, cpuLimit, memoryLimit }, - }, + computingUnit: { resource: { cpuLimit, memoryLimit } }, }); } @@ -455,12 +409,10 @@ describe("UserComputingUnitListItemComponent", () => { describe("fallback getters when metrics/resource are absent", () => { it("returns N/A for every usage and limit getter", () => { - const base = makeEntry(); const item = bareComponent( makeEntry({ metrics: undefined, computingUnit: { - ...base.computingUnit, resource: undefined as unknown as DashboardWorkflowComputingUnit["computingUnit"]["resource"], }, }) @@ -611,12 +563,8 @@ describe("UserComputingUnitListItemComponent", () => { }); it("the metrics popover adds the GPU, JVM and shared-memory rows when those limits are set", () => { - const base = makeEntry(); component.entry = makeEntry({ - computingUnit: { - ...base.computingUnit, - resource: { ...base.computingUnit.resource, gpuLimit: "2", jvmMemorySize: "2Gi", shmSize: "1Gi" }, - }, + computingUnit: { resource: { gpuLimit: "2", jvmMemorySize: "2Gi", shmSize: "1Gi" } }, }); fixture.detectChanges(); diff --git a/frontend/src/app/dashboard/component/user/user-computing-unit/user-computing-unit.component.spec.ts b/frontend/src/app/dashboard/component/user/user-computing-unit/user-computing-unit.component.spec.ts index 05114c17574..55c9f9b6969 100644 --- a/frontend/src/app/dashboard/component/user/user-computing-unit/user-computing-unit.component.spec.ts +++ b/frontend/src/app/dashboard/component/user/user-computing-unit/user-computing-unit.component.spec.ts @@ -37,6 +37,19 @@ import { of } from "rxjs"; import type { Mocked } from "vitest"; import { CdkVirtualScrollViewport } from "@angular/cdk/scrolling"; import { UserComputingUnitListItemComponent } from "./user-computing-unit-list-item/user-computing-unit-list-item.component"; +import { makeDashboardComputingUnit } from "../../../../common/testing/computing-unit-test-fixtures"; + +function makeUnit(cuid: number): DashboardWorkflowComputingUnit { + return makeDashboardComputingUnit({ + computingUnit: { + cuid, + name: `unit-${cuid}`, + type: "kubernetes", + uri: `uri-${cuid}`, + resource: { jvmMemorySize: "1Gi", shmSize: "64Mi" }, + }, + }); +} describe("UserComputingUnitComponent", () => { let component: UserComputingUnitComponent; let fixture: ComponentFixture; @@ -97,34 +110,6 @@ describe("UserComputingUnitComponent", () => { }); describe("fetching, polling and termination", () => { - function makeUnit(cuid: number): DashboardWorkflowComputingUnit { - return { - computingUnit: { - cuid, - uid: 1, - name: `unit-${cuid}`, - creationTime: 0, - terminateTime: undefined, - type: "kubernetes", - uri: `uri-${cuid}`, - resource: { - cpuLimit: "1", - memoryLimit: "1Gi", - gpuLimit: "0", - jvmMemorySize: "1Gi", - shmSize: "64Mi", - nodeAddresses: [], - }, - }, - status: "Running", - metrics: { cpuUsage: "N/A", memoryUsage: "N/A" }, - isOwner: true, - accessPrivilege: "WRITE", - ownerAvatar: "", - ownerName: "owner", - } as DashboardWorkflowComputingUnit; - } - afterEach(() => { // ngOnInit starts a 1s interval; destroying the fixture unsubscribes it so it // cannot tick into a later test. @@ -196,34 +181,6 @@ describe("UserComputingUnitComponent", () => { * no layout, which is why the list looked empty: the viewport measures 0px and renders no rows. */ describe("rendered page", () => { - function makeUnit(cuid: number): DashboardWorkflowComputingUnit { - return { - computingUnit: { - cuid, - uid: 1, - name: `unit-${cuid}`, - creationTime: 0, - terminateTime: undefined, - type: "kubernetes", - uri: `uri-${cuid}`, - resource: { - cpuLimit: "1", - memoryLimit: "1Gi", - gpuLimit: "0", - jvmMemorySize: "1Gi", - shmSize: "64Mi", - nodeAddresses: [], - }, - }, - status: "Running", - metrics: { cpuUsage: "N/A", memoryUsage: "N/A" }, - isOwner: true, - accessPrivilege: "WRITE", - ownerAvatar: "", - ownerName: "owner", - } as DashboardWorkflowComputingUnit; - } - /** Renders the page with the given units and forces the virtual list to materialize its rows. */ function renderUnits(units: DashboardWorkflowComputingUnit[]): void { const statusService = TestBed.inject(ComputingUnitStatusService); diff --git a/frontend/src/app/dashboard/service/admin/execution/admin-execution.service.spec.ts b/frontend/src/app/dashboard/service/admin/execution/admin-execution.service.spec.ts index d45b21f70eb..85891af8769 100644 --- a/frontend/src/app/dashboard/service/admin/execution/admin-execution.service.spec.ts +++ b/frontend/src/app/dashboard/service/admin/execution/admin-execution.service.spec.ts @@ -17,8 +17,8 @@ * under the License. */ -import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing"; -import { TestBed } from "@angular/core/testing"; +import { HttpTestingController } from "@angular/common/http/testing"; +import { flushHttpRequest, setupHttpServiceTest } from "../../../../common/testing/http-service-test-utils"; import { AdminExecutionService, WORKFLOW_BASE_URL } from "./admin-execution.service"; describe("AdminExecutionService", () => { @@ -26,12 +26,7 @@ describe("AdminExecutionService", () => { let httpMock: HttpTestingController; beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - providers: [AdminExecutionService], - }); - service = TestBed.inject(AdminExecutionService); - httpMock = TestBed.inject(HttpTestingController); + ({ service, httpMock } = setupHttpServiceTest(AdminExecutionService)); }); afterEach(() => { @@ -49,20 +44,18 @@ describe("AdminExecutionService", () => { service.getExecutionList(10, 2, "name", "asc", ["running", "failed"]).subscribe(r => (result = r)); - const req = httpMock.expectOne(r => r.url === `${WORKFLOW_BASE_URL}/executionList/10/2/name/asc`); - expect(req.request.method).toEqual("GET"); - expect(req.request.params.get("filter")).toEqual("running,failed"); - - req.flush(payload); + flushHttpRequest(httpMock, r => r.url === `${WORKFLOW_BASE_URL}/executionList/10/2/name/asc`, "GET", payload, { + params: { filter: "running,failed" }, + }); expect(result).toEqual(payload); }); it("sends an empty filter param when no filters are supplied", () => { service.getExecutionList(5, 0, "id", "desc", []).subscribe(); - const req = httpMock.expectOne(r => r.url === `${WORKFLOW_BASE_URL}/executionList/5/0/id/desc`); - expect(req.request.params.get("filter")).toEqual(""); - req.flush([]); + flushHttpRequest(httpMock, r => r.url === `${WORKFLOW_BASE_URL}/executionList/5/0/id/desc`, "GET", [], { + params: { filter: "" }, + }); }); }); @@ -72,10 +65,7 @@ describe("AdminExecutionService", () => { service.getTotalWorkflows().subscribe(c => (count = c)); - const req = httpMock.expectOne(`${WORKFLOW_BASE_URL}/totalWorkflow`); - expect(req.request.method).toEqual("GET"); - req.flush(123); - + flushHttpRequest(httpMock, `${WORKFLOW_BASE_URL}/totalWorkflow`, "GET", 123); expect(count).toEqual(123); }); }); diff --git a/frontend/src/app/dashboard/service/admin/settings/admin-settings.service.spec.ts b/frontend/src/app/dashboard/service/admin/settings/admin-settings.service.spec.ts index a2255b10f2a..ac29d519d3d 100644 --- a/frontend/src/app/dashboard/service/admin/settings/admin-settings.service.spec.ts +++ b/frontend/src/app/dashboard/service/admin/settings/admin-settings.service.spec.ts @@ -17,8 +17,8 @@ * under the License. */ -import { TestBed } from "@angular/core/testing"; -import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing"; +import { HttpTestingController } from "@angular/common/http/testing"; +import { flushHttpRequest, setupHttpServiceTest } from "../../../../common/testing/http-service-test-utils"; import { AdminSettingsService } from "./admin-settings.service"; describe("AdminSettingsService", () => { @@ -28,13 +28,7 @@ describe("AdminSettingsService", () => { const PUBLIC_URL = "/api/config/settings/public"; beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - providers: [AdminSettingsService], - }); - - httpTestingController = TestBed.inject(HttpTestingController); - service = TestBed.inject(AdminSettingsService); + ({ service, httpMock: httpTestingController } = setupHttpServiceTest(AdminSettingsService)); }); afterEach(() => { @@ -48,8 +42,7 @@ describe("AdminSettingsService", () => { service.getPublicSetting("logo").subscribe(value => (logo = value)); service.getPublicSetting("hub_enabled").subscribe(value => (hubEnabled = value)); - const req = httpTestingController.expectOne(PUBLIC_URL); - req.flush({ logo: "custom.png", hub_enabled: "true" }); + httpTestingController.expectOne(PUBLIC_URL).flush({ logo: "custom.png", hub_enabled: "true" }); expect(logo).toEqual("custom.png"); expect(hubEnabled).toEqual("true"); @@ -81,11 +74,10 @@ describe("AdminSettingsService", () => { httpTestingController.expectOne(PUBLIC_URL).flush({ logo: "old.png" }); service.updateSetting("logo", "new.png").subscribe(); - const put = httpTestingController.expectOne("/api/config/settings/logo"); - expect(put.request.method).toEqual("PUT"); - expect(put.request.body).toEqual({ value: "new.png" }); + const put = flushHttpRequest(httpTestingController, "/api/config/settings/logo", "PUT", null, { + body: { value: "new.png" }, + }); expect(put.request.withCredentials).toBe(true); - put.flush(null); let logo: string | null | undefined; service.getPublicSetting("logo").subscribe(value => (logo = value)); @@ -98,10 +90,7 @@ describe("AdminSettingsService", () => { httpTestingController.expectOne(PUBLIC_URL).flush({ logo: "old.png" }); service.resetSetting("logo").subscribe(); - const post = httpTestingController.expectOne("/api/config/settings/reset/logo"); - expect(post.request.method).toEqual("POST"); - expect(post.request.body).toEqual({}); - post.flush(null); + flushHttpRequest(httpTestingController, "/api/config/settings/reset/logo", "POST", null, { body: {} }); service.getPublicSetting("logo").subscribe(); httpTestingController.expectOne(PUBLIC_URL).flush({ logo: "default.png" }); @@ -111,9 +100,10 @@ describe("AdminSettingsService", () => { let settings: Record | undefined; service.getAllSettings().subscribe(value => (settings = value)); - const req = httpTestingController.expectOne("/api/config/settings"); - expect(req.request.method).toEqual("GET"); - req.flush({ logo: "a.png", csv_parser_max_columns: "4096" }); + flushHttpRequest(httpTestingController, "/api/config/settings", "GET", { + logo: "a.png", + csv_parser_max_columns: "4096", + }); expect(settings).toEqual({ logo: "a.png", csv_parser_max_columns: "4096" }); }); diff --git a/frontend/src/app/dashboard/service/admin/user/admin-user.service.spec.ts b/frontend/src/app/dashboard/service/admin/user/admin-user.service.spec.ts index f53eb8629c3..7e8729c57b3 100644 --- a/frontend/src/app/dashboard/service/admin/user/admin-user.service.spec.ts +++ b/frontend/src/app/dashboard/service/admin/user/admin-user.service.spec.ts @@ -17,8 +17,8 @@ * under the License. */ -import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing"; -import { TestBed } from "@angular/core/testing"; +import { HttpTestingController } from "@angular/common/http/testing"; +import { flushHttpRequest, setupHttpServiceTest } from "../../../../common/testing/http-service-test-utils"; import { AdminUserService, USER_LIST_URL, @@ -38,12 +38,7 @@ describe("AdminUserService", () => { let httpMock: HttpTestingController; beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - providers: [AdminUserService], - }); - service = TestBed.inject(AdminUserService); - httpMock = TestBed.inject(HttpTestingController); + ({ service, httpMock } = setupHttpServiceTest(AdminUserService)); }); afterEach(() => { @@ -59,35 +54,22 @@ describe("AdminUserService", () => { let result: readonly any[] | undefined; service.getUserList().subscribe(r => (result = r)); - const req = httpMock.expectOne(USER_LIST_URL); - expect(req.request.method).toEqual("GET"); - req.flush(users); - + flushHttpRequest(httpMock, USER_LIST_URL, "GET", users); expect(result).toEqual(users); }); it("updateUser() PUTs the full user record", () => { service.updateUser(1, "Alice", "alice@x.com", Role.ADMIN, "vip").subscribe(); - const req = httpMock.expectOne(USER_UPDATE_URL); - expect(req.request.method).toEqual("PUT"); - expect(req.request.body).toEqual({ - uid: 1, - name: "Alice", - email: "alice@x.com", - role: Role.ADMIN, - comment: "vip", + flushHttpRequest(httpMock, USER_UPDATE_URL, "PUT", null, { + body: { uid: 1, name: "Alice", email: "alice@x.com", role: Role.ADMIN, comment: "vip" }, }); - req.flush(null); }); it("addUser() POSTs an empty body to the trailing-slash add endpoint", () => { service.addUser().subscribe(); - const req = httpMock.expectOne(`${USER_ADD_URL}/`); - expect(req.request.method).toEqual("POST"); - expect(req.request.body).toEqual({}); - req.flush({}); + flushHttpRequest(httpMock, `${USER_ADD_URL}/`, "POST", {}, { body: {} }); }); const userResourceQueryCases: { name: string; call: (uid: number) => Observable; url: string }[] = [ @@ -101,19 +83,14 @@ describe("AdminUserService", () => { it(`${name}() sends the uid as a user_id query param`, () => { call(3).subscribe(); - const req = httpMock.expectOne(r => r.url === url); - expect(req.request.method).toEqual("GET"); - expect(req.request.params.get("user_id")).toEqual("3"); - req.flush([]); + flushHttpRequest(httpMock, r => r.url === url, "GET", [], { params: { user_id: "3" } }); }); }); it("deleteExecutionCollection() DELETEs the per-execution endpoint", () => { service.deleteExecutionCollection(77).subscribe(); - const req = httpMock.expectOne(`${USER_DELETE_EXECUTION_COLLECTION}/77`); - expect(req.request.method).toEqual("DELETE"); - req.flush(null); + flushHttpRequest(httpMock, `${USER_DELETE_EXECUTION_COLLECTION}/77`, "DELETE", null); }); describe("error propagation", () => { diff --git a/frontend/src/app/dashboard/service/user/feedback/feedback.service.spec.ts b/frontend/src/app/dashboard/service/user/feedback/feedback.service.spec.ts index 37a4217b8c1..2920af616ff 100644 --- a/frontend/src/app/dashboard/service/user/feedback/feedback.service.spec.ts +++ b/frontend/src/app/dashboard/service/user/feedback/feedback.service.spec.ts @@ -17,12 +17,12 @@ * under the License. */ -import { TestBed } from "@angular/core/testing"; -import { HttpClientTestingModule, HttpTestingController } from "@angular/common/http/testing"; +import { HttpTestingController } from "@angular/common/http/testing"; import { firstValueFrom } from "rxjs"; import { FeedbackService } from "./feedback.service"; import { AppSettings } from "../../../../common/app-setting"; +import { flushHttpRequest, setupHttpServiceTest } from "../../../../common/testing/http-service-test-utils"; import { commonTestProviders } from "../../../../common/testing/test-utils"; import { Feedback, FeedbackCount } from "../../../type/feedback.interface"; @@ -33,12 +33,7 @@ describe("FeedbackService", () => { let http: HttpTestingController; beforeEach(() => { - TestBed.configureTestingModule({ - imports: [HttpClientTestingModule], - providers: [FeedbackService, ...commonTestProviders], - }); - service = TestBed.inject(FeedbackService); - http = TestBed.inject(HttpTestingController); + ({ service, httpMock: http } = setupHttpServiceTest(FeedbackService, commonTestProviders)); vi.spyOn(AppSettings, "getApiEndpoint").mockReturnValue(API); }); @@ -48,37 +43,27 @@ describe("FeedbackService", () => { it("submitFeedback POSTs the message to /feedback", () => { service.submitFeedback("hello world").subscribe(); - const req = http.expectOne(`${API}/feedback`); - expect(req.request.method).toBe("POST"); - expect(req.request.body).toEqual({ message: "hello world" }); - req.flush(null); + flushHttpRequest(http, `${API}/feedback`, "POST", null, { body: { message: "hello world" } }); }); it("getMyFeedback GETs /feedback and returns the list", async () => { const expected: ReadonlyArray = [{ fid: 1, uid: 7, message: "m", creationTime: 123 }]; const pending = firstValueFrom(service.getMyFeedback()); - const req = http.expectOne(`${API}/feedback`); - expect(req.request.method).toBe("GET"); - req.flush(expected); + flushHttpRequest(http, `${API}/feedback`, "GET", expected); expect(await pending).toEqual(expected); }); it("getFeedbackCounts GETs /feedback/counts", async () => { const expected: ReadonlyArray = [{ uid: 7, count: 3 }]; const pending = firstValueFrom(service.getFeedbackCounts()); - const req = http.expectOne(`${API}/feedback/counts`); - expect(req.request.method).toBe("GET"); - req.flush(expected); + flushHttpRequest(http, `${API}/feedback/counts`, "GET", expected); expect(await pending).toEqual(expected); }); it("getUserFeedback GETs /feedback/user with a user_id query param", async () => { const expected: ReadonlyArray = [{ fid: 2, uid: 42, message: "x", creationTime: 9 }]; const pending = firstValueFrom(service.getUserFeedback(42)); - const req = http.expectOne(r => r.url === `${API}/feedback/user`); - expect(req.request.method).toBe("GET"); - expect(req.request.params.get("user_id")).toBe("42"); - req.flush(expected); + flushHttpRequest(http, r => r.url === `${API}/feedback/user`, "GET", expected, { params: { user_id: "42" } }); expect(await pending).toEqual(expected); }); }); diff --git a/frontend/src/app/dashboard/type/dashboard-entry.spec.ts b/frontend/src/app/dashboard/type/dashboard-entry.spec.ts index 5dcdd53db39..8b00a8bdeeb 100644 --- a/frontend/src/app/dashboard/type/dashboard-entry.spec.ts +++ b/frontend/src/app/dashboard/type/dashboard-entry.spec.ts @@ -24,6 +24,7 @@ import { DashboardDataset } from "./dashboard-dataset.interface"; import { DashboardModel } from "./dashboard-model.interface"; import { DashboardWorkflowComputingUnit } from "../../common/type/workflow-computing-unit"; import { ExecutionMode } from "../../common/type/workflow"; +import { makeDashboardComputingUnit } from "../../common/testing/computing-unit-test-fixtures"; // Each factory returns a fresh fixture that satisfies exactly one type predicate, // so DashboardEntry's ordered if/else dispatch routes it to the intended branch. @@ -99,34 +100,26 @@ function makeModel(): DashboardModel { } function makeComputingUnit(): DashboardWorkflowComputingUnit { - return { + return makeDashboardComputingUnit({ computingUnit: { cuid: 505, uid: 50, name: "My Computing Unit", creationTime: 1700000005000, - terminateTime: undefined, type: "kubernetes", uri: "urn:texera:cu:505", resource: { cpuLimit: "2", memoryLimit: "4Gi", - gpuLimit: "0", jvmMemorySize: "2G", shmSize: "64Mi", nodeAddresses: ["10.0.0.1"], }, }, - status: "Running", - metrics: { - cpuUsage: "0.5", - memoryUsage: "1Gi", - }, - isOwner: true, - accessPrivilege: "WRITE", - ownerAvatar: "avatar", + metrics: { cpuUsage: "0.5", memoryUsage: "1Gi" }, ownerName: "Bob", - }; + ownerAvatar: "avatar", + }); } describe("DashboardEntry", () => { diff --git a/frontend/src/app/dashboard/type/type-predicates.spec.ts b/frontend/src/app/dashboard/type/type-predicates.spec.ts index 90a3894da73..2db110d3af4 100644 --- a/frontend/src/app/dashboard/type/type-predicates.spec.ts +++ b/frontend/src/app/dashboard/type/type-predicates.spec.ts @@ -22,6 +22,7 @@ import { DashboardWorkflow } from "./dashboard-workflow.interface"; import { DashboardDataset } from "./dashboard-dataset.interface"; import { DashboardWorkflowComputingUnit } from "../../common/type/workflow-computing-unit"; import { ExecutionMode } from "../../common/type/workflow"; +import { makeDashboardComputingUnit } from "../../common/testing/computing-unit-test-fixtures"; const workflowFixture: DashboardWorkflow = { isOwner: true, @@ -68,34 +69,25 @@ const datasetFixture: DashboardDataset = { size: 2048, }; -const computingUnitFixture: DashboardWorkflowComputingUnit = { +const computingUnitFixture: DashboardWorkflowComputingUnit = makeDashboardComputingUnit({ computingUnit: { cuid: 9, uid: 10, name: "My Computing Unit", creationTime: 1700000000000, - terminateTime: undefined, type: "kubernetes", uri: "urn:texera:cu:9", resource: { cpuLimit: "2", memoryLimit: "4Gi", - gpuLimit: "0", jvmMemorySize: "2G", shmSize: "64Mi", nodeAddresses: ["10.0.0.1"], }, }, - status: "Running", - metrics: { - cpuUsage: "0.5", - memoryUsage: "1Gi", - }, - isOwner: true, - accessPrivilege: "WRITE", - ownerAvatar: "", + metrics: { cpuUsage: "0.5", memoryUsage: "1Gi" }, ownerName: "Alice", -}; +}); describe("isDashboardWorkflow", () => { it("should return true for a realistic DashboardWorkflow", () => { diff --git a/frontend/src/app/hub/component/login/texera-login.component.spec.ts b/frontend/src/app/hub/component/login/texera-login.component.spec.ts index d1fd7040cbd..7f62645692b 100644 --- a/frontend/src/app/hub/component/login/texera-login.component.spec.ts +++ b/frontend/src/app/hub/component/login/texera-login.component.spec.ts @@ -92,6 +92,20 @@ describe("TexeraLoginComponent", () => { component = fixture.componentInstance; }; + const SIGNUP_FIELDS = { + username: "alice", + email: "alice@example.com", + password: "secret1", + confirm: "secret1", + }; + const setConfig = (cfg: Parameters[0]): void => { + (TestBed.inject(GuiConfigService) as unknown as MockGuiConfigService).setConfig(cfg); + }; + const submitForm = (patch: Record): void => { + component.form.patchValue(patch); + component.submit(); + }; + beforeEach(async () => { await createComponent(); }); @@ -107,8 +121,7 @@ describe("TexeraLoginComponent", () => { describe("ngOnInit", () => { it("prefills username/password from defaultLocalUser when populated", () => { - const config = TestBed.inject(GuiConfigService) as unknown as MockGuiConfigService; - config.setConfig({ defaultLocalUser: { username: "preset-user", password: "preset-pass" } }); + setConfig({ defaultLocalUser: { username: "preset-user", password: "preset-pass" } }); component.ngOnInit(); @@ -117,8 +130,7 @@ describe("TexeraLoginComponent", () => { }); it("does not prefill when defaultLocalUser is empty", () => { - const config = TestBed.inject(GuiConfigService) as unknown as MockGuiConfigService; - config.setConfig({ defaultLocalUser: {} }); + setConfig({ defaultLocalUser: {} }); component.ngOnInit(); @@ -148,8 +160,7 @@ describe("TexeraLoginComponent", () => { }); it("skips the prefill and the Google subscription when already signed in", () => { - const config = TestBed.inject(GuiConfigService) as unknown as MockGuiConfigService; - config.setConfig({ defaultLocalUser: { username: "preset-user", password: "preset-pass" } }); + setConfig({ defaultLocalUser: { username: "preset-user", password: "preset-pass" } }); (userServiceMock.isLogin as any).mockReturnValue(true); component.ngOnInit(); @@ -184,7 +195,7 @@ describe("TexeraLoginComponent", () => { }); it("drops the button when the provider is disabled", () => { - (TestBed.inject(GuiConfigService) as unknown as MockGuiConfigService).setConfig({ appleLogin: false }); + setConfig({ appleLogin: false }); fixture.detectChanges(); expect(host().querySelector("button.apple-button")).toBeNull(); @@ -265,22 +276,19 @@ describe("TexeraLoginComponent", () => { beforeEach(() => component.setMode("signin")); it("short-circuits and sets errorMessage when the username is blank", () => { - component.form.patchValue({ username: " ", password: "secret1" }); - component.submit(); + submitForm({ username: " ", password: "secret1" }); expect(userServiceMock.login).not.toHaveBeenCalled(); expect(component.errorMessage).toBeTruthy(); }); it("sets errorMessage when the password is shorter than 6 characters", () => { - component.form.patchValue({ username: "alice", password: "abc" }); - component.submit(); + submitForm({ username: "alice", password: "abc" }); expect(userServiceMock.login).not.toHaveBeenCalled(); expect(component.errorMessage).toBe("Password length should be greater than 5."); }); it("calls UserService.login with a trimmed username and navigates to USER_WORKFLOW", () => { - component.form.patchValue({ username: " alice ", password: "secret1" }); - component.submit(); + submitForm({ username: " alice ", password: "secret1" }); expect(userServiceMock.login).toHaveBeenCalledWith("alice", "secret1"); expect(routerMock.navigateByUrl).toHaveBeenCalledWith(USER_WORKFLOW); }); @@ -288,23 +296,20 @@ describe("TexeraLoginComponent", () => { it("navigates to queryParams.returnUrl when present", async () => { await createComponent({ returnUrl: "/user/dataset" }); component.setMode("signin"); - component.form.patchValue({ username: "alice", password: "secret1" }); - component.submit(); + submitForm({ username: "alice", password: "secret1" }); expect(routerMock.navigateByUrl).toHaveBeenCalledWith("/user/dataset"); }); it("surfaces the error message on login failure and does not navigate", () => { (userServiceMock.login as any).mockReturnValue(throwError(() => new Error("bad credentials"))); - component.form.patchValue({ username: "alice", password: "secret1" }); - component.submit(); + submitForm({ username: "alice", password: "secret1" }); expect(component.errorMessage).toBe("bad credentials"); expect(routerMock.navigateByUrl).not.toHaveBeenCalled(); }); it("falls back to a default message when the login error has no message", () => { (userServiceMock.login as any).mockReturnValue(throwError(() => ({}))); - component.form.patchValue({ username: "alice", password: "secret1" }); - component.submit(); + submitForm({ username: "alice", password: "secret1" }); expect(component.errorMessage).toBe("Incorrect username or password"); }); }); @@ -314,87 +319,55 @@ describe("TexeraLoginComponent", () => { // Registration requires an email; the backend's register endpoint takes one. it("sets errorMessage when the email is missing or malformed", () => { - component.form.patchValue({ - username: "alice", - email: "not-an-email", - password: "secret1", - confirm: "secret1", - }); - component.submit(); + submitForm({ ...SIGNUP_FIELDS, email: "not-an-email" }); expect(userServiceMock.register).not.toHaveBeenCalled(); expect(component.errorMessage).toBeTruthy(); }); it("sets errorMessage when passwords are inconsistent", () => { - component.form.patchValue({ - username: "alice", - email: "alice@example.com", - password: "secret1", - confirm: "secret2", - }); - component.submit(); + submitForm({ ...SIGNUP_FIELDS, confirm: "secret2" }); expect(userServiceMock.register).not.toHaveBeenCalled(); expect(component.errorMessage).toBe("Two passwords are inconsistent."); }); it("calls UserService.register with username, email and password, then notifies success", () => { - component.form.patchValue({ - username: " alice ", - email: " alice@example.com ", - password: "secret1", - confirm: "secret1", - }); - component.submit(); + submitForm({ ...SIGNUP_FIELDS, username: " alice ", email: " alice@example.com " }); expect(userServiceMock.register).toHaveBeenCalledWith("alice", "alice@example.com", "secret1"); expect(notificationServiceMock.success).toHaveBeenCalled(); }); - const fillSignup = () => - component.form.patchValue({ - username: "alice", - email: "alice@example.com", - password: "secret1", - confirm: "secret1", - }); const signedInAs = (role: Role) => (userServiceMock.getCurrentUser as any).mockReturnValue({ uid: 7, name: "alice", role } as User); + const expectCreated = (redirect: boolean): void => { + expect(notificationServiceMock.success).toHaveBeenCalledWith( + redirect + ? "Your account has been created." + : "Your account has been created. Please contact the Texera administrator to activate your account." + ); + if (redirect) expect(routerMock.navigateByUrl).toHaveBeenCalledWith(USER_WORKFLOW); + else expect(routerMock.navigateByUrl).not.toHaveBeenCalled(); + }; // With invite-only off the account is REGULAR and registering has already signed the user in, // so the page goes where a sign-in would rather than telling them to wait for an admin. it("opens the dashboard when the new account can be used at once", () => { signedInAs(Role.REGULAR); - fillSignup(); - - component.submit(); - - expect(notificationServiceMock.success).toHaveBeenCalledWith("Your account has been created."); - expect(routerMock.navigateByUrl).toHaveBeenCalledWith(USER_WORKFLOW); + submitForm(SIGNUP_FIELDS); + expectCreated(true); }); // With invite-only on the account is INACTIVE, and signing in with it signs straight back out. it("asks the user to wait for an admin when the new account is not signed in", () => { - fillSignup(); - - component.submit(); - - expect(notificationServiceMock.success).toHaveBeenCalledWith( - "Your account has been created. Please contact the Texera administrator to activate your account." - ); - expect(routerMock.navigateByUrl).not.toHaveBeenCalled(); + submitForm(SIGNUP_FIELDS); + expectCreated(false); }); // An INACTIVE account can do nothing yet, so even a session that is still around for one is not // sent to the dashboard. it("does not open the dashboard for an INACTIVE account", () => { signedInAs(Role.INACTIVE); - fillSignup(); - - component.submit(); - - expect(notificationServiceMock.success).toHaveBeenCalledWith( - "Your account has been created. Please contact the Texera administrator to activate your account." - ); - expect(routerMock.navigateByUrl).not.toHaveBeenCalled(); + submitForm(SIGNUP_FIELDS); + expectCreated(false); }); // Where verification is on the code field is present from the outset, and mailing the code is @@ -402,19 +375,22 @@ describe("TexeraLoginComponent", () => { // submit that silently sent mail and a second that completed. describe("with email verification on", () => { beforeEach(() => { - const config = TestBed.inject(GuiConfigService) as unknown as MockGuiConfigService; - config.setConfig({ emailVerification: true }); + setConfig({ emailVerification: true }); (userServiceMock.register as any).mockReturnValue(of({ verificationRequired: true })); component.setMode("signup"); }); - const fillForm = () => + const fillForm = (code?: string) => component.form.patchValue({ + ...SIGNUP_FIELDS, username: " alice ", email: " alice@example.com ", - password: "secret1", - confirm: "secret1", + ...(code !== undefined ? { code } : {}), }); + const submitWithCode = (code: string) => { + fillForm(code); + component.submit(); + }; it("mails a code when asked, without creating the account", () => { fillForm(); @@ -431,10 +407,7 @@ describe("TexeraLoginComponent", () => { // Pressing Sign up must not put mail in someone's inbox: that is what the separate button is // for, and the user may never have asked for it. it("does not mail anything when the form is submitted", () => { - fillForm(); - component.form.patchValue({ code: "123456" }); - - component.submit(); + submitWithCode("123456"); expect(userServiceMock.register).not.toHaveBeenCalled(); expect(userServiceMock.registerVerify).toHaveBeenCalledWith("alice", "alice@example.com", "secret1", "123456"); @@ -473,10 +446,7 @@ describe("TexeraLoginComponent", () => { }); it("submits the typed code with the same fields", () => { - fillForm(); - component.form.patchValue({ code: " 123456 " }); - - component.submit(); + submitWithCode(" 123456 "); expect(userServiceMock.registerVerify).toHaveBeenCalledWith("alice", "alice@example.com", "secret1", "123456"); expect(notificationServiceMock.success).toHaveBeenCalled(); @@ -484,13 +454,8 @@ describe("TexeraLoginComponent", () => { it("opens the dashboard once the code completes a sign-up that can be used at once", () => { signedInAs(Role.REGULAR); - fillForm(); - component.form.patchValue({ code: "123456" }); - - component.submit(); - - expect(notificationServiceMock.success).toHaveBeenCalledWith("Your account has been created."); - expect(routerMock.navigateByUrl).toHaveBeenCalledWith(USER_WORKFLOW); + submitWithCode("123456"); + expectCreated(true); }); // The button only shows where the config says verification is on. A server that disagrees has @@ -502,8 +467,7 @@ describe("TexeraLoginComponent", () => { component.sendCode(); - expect(notificationServiceMock.success).toHaveBeenCalledWith("Your account has been created."); - expect(routerMock.navigateByUrl).toHaveBeenCalledWith(USER_WORKFLOW); + expectCreated(true); }); it("asks for the code rather than submitting an empty one", () => { @@ -519,17 +483,13 @@ describe("TexeraLoginComponent", () => { (userServiceMock.registerVerify as any).mockReturnValue( throwError(() => new Error("That code is not valid or has expired.")) ); - fillForm(); - component.form.patchValue({ code: "000000" }); - - component.submit(); + submitWithCode("000000"); expect(component.errorMessage).toBe("That code is not valid or has expired."); }); it("clears a code that was typed when the tab changes", () => { - fillForm(); - component.form.patchValue({ code: "123456" }); + fillForm("123456"); component.setMode("signin"); @@ -539,13 +499,7 @@ describe("TexeraLoginComponent", () => { it("surfaces the error message on registration failure", () => { (userServiceMock.register as any).mockReturnValue(throwError(() => new Error("username taken"))); - component.form.patchValue({ - username: "alice", - email: "alice@example.com", - password: "secret1", - confirm: "secret1", - }); - component.submit(); + submitForm(SIGNUP_FIELDS); expect(component.errorMessage).toBe("username taken"); }); }); @@ -689,7 +643,7 @@ describe("TexeraLoginComponent", () => { orcidLogin: boolean; appleLogin: boolean; }): void { - (TestBed.inject(GuiConfigService) as unknown as MockGuiConfigService).setConfig(flags); + setConfig(flags); fixture.detectChanges(); } @@ -707,71 +661,49 @@ describe("TexeraLoginComponent", () => { const appleButton = (): HTMLElement | null => host().querySelector("button.apple-button"); describe("provider flags", () => { - it("renders the local form and every social button when all are enabled", () => { - render({ localLogin: true, googleLogin: true, orcidLogin: true, appleLogin: true }); + const expectProviderDom = ( + [localLogin, googleLogin, orcidLogin, appleLogin]: [boolean, boolean, boolean, boolean], + expected: Array + ): void => { + render({ localLogin, googleLogin, orcidLogin, appleLogin }); + const nodes = [ + host().querySelector("nz-tabs"), + host().querySelector("form"), + host().querySelector("asl-google-signin-button"), + orcidButton(), + appleButton(), + host().querySelector("nz-divider"), + ]; + expected.forEach((want, i) => { + if (want === true) expect(nodes[i]).toBeTruthy(); + else if (want === false) expect(nodes[i]).toBeNull(); + }); + }; - expect(host().querySelector("nz-tabs")).toBeTruthy(); - expect(host().querySelector("form")).toBeTruthy(); - expect(host().querySelector("asl-google-signin-button")).toBeTruthy(); - expect(orcidButton()).toBeTruthy(); - expect(appleButton()).toBeTruthy(); - // The "or continue with" divider only makes sense when the local form has company. - expect(host().querySelector("nz-divider")).toBeTruthy(); + it("renders the local form and every social button when all are enabled", () => { + expectProviderDom([true, true, true, true], [true, true, true, true, true, true]); }); it("drops every social button but keeps the form when only local login is enabled", () => { - render({ localLogin: true, googleLogin: false, orcidLogin: false, appleLogin: false }); - - expect(host().querySelector("nz-tabs")).toBeTruthy(); - expect(host().querySelector("form")).toBeTruthy(); - expect(host().querySelector("asl-google-signin-button")).toBeNull(); - expect(orcidButton()).toBeNull(); - expect(appleButton()).toBeNull(); - expect(host().querySelector("nz-divider")).toBeNull(); + expectProviderDom([true, false, false, false], [true, true, false, false, false, false]); }); it("drops the tabs and the form but keeps the google button when only google is enabled", () => { - render({ localLogin: false, googleLogin: true, orcidLogin: false, appleLogin: false }); - - expect(host().querySelector("nz-tabs")).toBeNull(); - expect(host().querySelector("form")).toBeNull(); - expect(host().querySelector("asl-google-signin-button")).toBeTruthy(); - expect(orcidButton()).toBeNull(); - expect(appleButton()).toBeNull(); - expect(host().querySelector("nz-divider")).toBeNull(); + expectProviderDom([false, true, false, false], [false, false, true, false, false, false]); }); // ORCID carries the divider on its own: it is a second way to "continue with" // something other than the local form, so the label still reads correctly. it("keeps the orcid button and the divider when google is disabled but orcid is not", () => { - render({ localLogin: true, googleLogin: false, orcidLogin: true, appleLogin: false }); - - expect(host().querySelector("form")).toBeTruthy(); - expect(host().querySelector("asl-google-signin-button")).toBeNull(); - expect(orcidButton()).toBeTruthy(); - expect(host().querySelector("nz-divider")).toBeTruthy(); + expectProviderDom([true, false, true, false], [null, true, false, true, null, true]); }); it("drops the tabs and the form but keeps the orcid button when only orcid is enabled", () => { - render({ localLogin: false, googleLogin: false, orcidLogin: true, appleLogin: false }); - - expect(host().querySelector("nz-tabs")).toBeNull(); - expect(host().querySelector("form")).toBeNull(); - expect(host().querySelector("asl-google-signin-button")).toBeNull(); - expect(orcidButton()).toBeTruthy(); - expect(appleButton()).toBeNull(); - expect(host().querySelector("nz-divider")).toBeNull(); + expectProviderDom([false, false, true, false], [false, false, false, true, false, false]); }); it("renders no sign-in path when every provider is disabled", () => { - render({ localLogin: false, googleLogin: false, orcidLogin: false, appleLogin: false }); - - expect(host().querySelector("nz-tabs")).toBeNull(); - expect(host().querySelector("form")).toBeNull(); - expect(host().querySelector("asl-google-signin-button")).toBeNull(); - expect(orcidButton()).toBeNull(); - expect(appleButton()).toBeNull(); - expect(host().querySelector("nz-divider")).toBeNull(); + expectProviderDom([false, false, false, false], [false, false, false, false, false, false]); // The brand and footer are outside every flag, so the card is never empty. expect(host().querySelector(".brand")).toBeTruthy(); expect(host().querySelector("p.foot")).toBeTruthy(); @@ -780,21 +712,11 @@ describe("TexeraLoginComponent", () => { // Apple alone alongside the form still earns the divider. Nothing covered this before, // which is what let the divider condition and the render helper drift apart. it("keeps the divider when Apple is the only social provider", () => { - render({ localLogin: true, googleLogin: false, orcidLogin: false, appleLogin: true }); - - expect(host().querySelector("form")).toBeTruthy(); - expect(host().querySelector("asl-google-signin-button")).toBeNull(); - expect(appleButton()).toBeTruthy(); - expect(host().querySelector("nz-divider")).toBeTruthy(); + expectProviderDom([true, false, false, true], [null, true, false, null, true, true]); }); it("drops the tabs and the form but keeps Apple's slot when only Apple is enabled", () => { - render({ localLogin: false, googleLogin: false, orcidLogin: false, appleLogin: true }); - - expect(host().querySelector("nz-tabs")).toBeNull(); - expect(host().querySelector("form")).toBeNull(); - expect(appleButton()).toBeTruthy(); - expect(host().querySelector("nz-divider")).toBeNull(); + expectProviderDom([false, false, false, true], [false, false, false, null, true, false]); }); }); @@ -825,7 +747,7 @@ describe("TexeraLoginComponent", () => { }); it("says an admin has to activate the account while invite-only is on", () => { - (TestBed.inject(GuiConfigService) as unknown as MockGuiConfigService).setConfig({ inviteOnly: true }); + setConfig({ inviteOnly: true }); component.setMode("signup"); fixture.detectChanges(); @@ -869,6 +791,12 @@ describe("TexeraLoginComponent", () => { }); describe("password visibility", () => { + const triggerIcon = (eventName: string, event: Event) => { + passwordIcons()[0].triggerEventHandler(eventName, event); + fixture.detectChanges(); + }; + const clickToggle = () => triggerIcon("click", new MouseEvent("click")); + beforeEach(() => { render({ localLogin: true, googleLogin: true, orcidLogin: true, appleLogin: true }); component.setMode("signup"); @@ -884,8 +812,7 @@ describe("TexeraLoginComponent", () => { }); it("reveals both password fields when the toggle is clicked", () => { - passwordIcons()[0].triggerEventHandler("click", new MouseEvent("click")); - fixture.detectChanges(); + clickToggle(); expect(component.passwordVisible).toBe(true); expect(input("password")?.type).toBe("text"); @@ -894,18 +821,15 @@ describe("TexeraLoginComponent", () => { }); it("also toggles from the keyboard, so the control is reachable without a mouse", () => { - passwordIcons()[0].triggerEventHandler("keydown.enter", new KeyboardEvent("keydown", { key: "Enter" })); - fixture.detectChanges(); + triggerIcon("keydown.enter", new KeyboardEvent("keydown", { key: "Enter" })); expect(component.passwordVisible).toBe(true); expect(input("password")?.type).toBe("text"); }); it("hides them again on a second click", () => { - passwordIcons()[0].triggerEventHandler("click", new MouseEvent("click")); - fixture.detectChanges(); - passwordIcons()[0].triggerEventHandler("click", new MouseEvent("click")); - fixture.detectChanges(); + clickToggle(); + clickToggle(); expect(component.passwordVisible).toBe(false); expect(input("password")?.type).toBe("password"); From 73f57f69667aa03324c7c61ce01f72f12eefe34b Mon Sep 17 00:00:00 2001 From: Xinyuan Lin Date: Thu, 26 Nov 2026 10:54:32 -0800 Subject: [PATCH 2/2] test(frontend): name the login provider checks and keep fixture inputs local - The login spec's provider cases name each node they check. As on main, the Apple-only case does not check the Google button. - The dashboard-entry case gets its asserted WRITE access from its own input, not the shared default. - makeDashboardComputingUnit always merges the resource limits. The one case that needs no resource clears the field itself. --- .../testing/computing-unit-test-fixtures.ts | 6 +- ...computing-unit-list-item.component.spec.ts | 12 +-- .../dashboard/type/dashboard-entry.spec.ts | 1 + .../login/texera-login.component.spec.ts | 75 +++++++++++++------ 4 files changed, 58 insertions(+), 36 deletions(-) diff --git a/frontend/src/app/common/testing/computing-unit-test-fixtures.ts b/frontend/src/app/common/testing/computing-unit-test-fixtures.ts index addf2ce3c4d..7d4755851fe 100644 --- a/frontend/src/app/common/testing/computing-unit-test-fixtures.ts +++ b/frontend/src/app/common/testing/computing-unit-test-fixtures.ts @@ -46,7 +46,6 @@ export function makeDashboardComputingUnit( overrides: ComputingUnitFixtureOverrides = {} ): DashboardWorkflowComputingUnit { const { computingUnit: cuOverride, ...topOverrides } = overrides; - const hasExplicitResource = cuOverride !== undefined && "resource" in cuOverride; const defaultResource: WorkflowComputingUnitResourceLimit = { cpuLimit: "1", memoryLimit: "1Gi", @@ -55,10 +54,7 @@ export function makeDashboardComputingUnit( shmSize: "0", nodeAddresses: [], }; - const resource = - hasExplicitResource && cuOverride?.resource === undefined - ? (undefined as unknown as WorkflowComputingUnitResourceLimit) - : { ...defaultResource, ...(cuOverride?.resource ?? {}) }; + const resource = { ...defaultResource, ...(cuOverride?.resource ?? {}) }; return { status: "Running", diff --git a/frontend/src/app/dashboard/component/user/user-computing-unit/user-computing-unit-list-item/user-computing-unit-list-item.component.spec.ts b/frontend/src/app/dashboard/component/user/user-computing-unit/user-computing-unit-list-item/user-computing-unit-list-item.component.spec.ts index 1620cafb575..e908e0bf16c 100644 --- a/frontend/src/app/dashboard/component/user/user-computing-unit/user-computing-unit-list-item/user-computing-unit-list-item.component.spec.ts +++ b/frontend/src/app/dashboard/component/user/user-computing-unit/user-computing-unit-list-item/user-computing-unit-list-item.component.spec.ts @@ -409,14 +409,10 @@ describe("UserComputingUnitListItemComponent", () => { describe("fallback getters when metrics/resource are absent", () => { it("returns N/A for every usage and limit getter", () => { - const item = bareComponent( - makeEntry({ - metrics: undefined, - computingUnit: { - resource: undefined as unknown as DashboardWorkflowComputingUnit["computingUnit"]["resource"], - }, - }) - ); + const entry = makeEntry({ metrics: undefined }); + entry.computingUnit.resource = + undefined as unknown as DashboardWorkflowComputingUnit["computingUnit"]["resource"]; + const item = bareComponent(entry); expect(item.getCurrentComputingUnitCpuUsage()).toBe("N/A"); expect(item.getCurrentComputingUnitMemoryUsage()).toBe("N/A"); diff --git a/frontend/src/app/dashboard/type/dashboard-entry.spec.ts b/frontend/src/app/dashboard/type/dashboard-entry.spec.ts index 8b00a8bdeeb..bc5a02dc6cf 100644 --- a/frontend/src/app/dashboard/type/dashboard-entry.spec.ts +++ b/frontend/src/app/dashboard/type/dashboard-entry.spec.ts @@ -117,6 +117,7 @@ function makeComputingUnit(): DashboardWorkflowComputingUnit { }, }, metrics: { cpuUsage: "0.5", memoryUsage: "1Gi" }, + accessPrivilege: "WRITE", ownerName: "Bob", ownerAvatar: "avatar", }); diff --git a/frontend/src/app/hub/component/login/texera-login.component.spec.ts b/frontend/src/app/hub/component/login/texera-login.component.spec.ts index 7f62645692b..52fe186da4b 100644 --- a/frontend/src/app/hub/component/login/texera-login.component.spec.ts +++ b/frontend/src/app/hub/component/login/texera-login.component.spec.ts @@ -661,49 +661,72 @@ describe("TexeraLoginComponent", () => { const appleButton = (): HTMLElement | null => host().querySelector("button.apple-button"); describe("provider flags", () => { + type ProviderNode = "tabs" | "form" | "google" | "orcid" | "apple" | "divider"; + const providerNodes: Record Element | null> = { + tabs: () => host().querySelector("nz-tabs"), + form: () => host().querySelector("form"), + google: () => host().querySelector("asl-google-signin-button"), + orcid: orcidButton, + apple: appleButton, + divider: () => host().querySelector("nz-divider"), + }; + + // Renders the card with the given flags, then checks each named node: true expects it + // rendered, false expects it absent, and a node left out is not checked. const expectProviderDom = ( - [localLogin, googleLogin, orcidLogin, appleLogin]: [boolean, boolean, boolean, boolean], - expected: Array + flags: Parameters[0], + expected: Partial> ): void => { - render({ localLogin, googleLogin, orcidLogin, appleLogin }); - const nodes = [ - host().querySelector("nz-tabs"), - host().querySelector("form"), - host().querySelector("asl-google-signin-button"), - orcidButton(), - appleButton(), - host().querySelector("nz-divider"), - ]; - expected.forEach((want, i) => { - if (want === true) expect(nodes[i]).toBeTruthy(); - else if (want === false) expect(nodes[i]).toBeNull(); - }); + render(flags); + for (const node of Object.keys(expected) as ProviderNode[]) { + if (expected[node]) expect(providerNodes[node]()).toBeTruthy(); + else expect(providerNodes[node]()).toBeNull(); + } }; it("renders the local form and every social button when all are enabled", () => { - expectProviderDom([true, true, true, true], [true, true, true, true, true, true]); + // The "or continue with" divider only makes sense when the local form has company. + expectProviderDom( + { localLogin: true, googleLogin: true, orcidLogin: true, appleLogin: true }, + { tabs: true, form: true, google: true, orcid: true, apple: true, divider: true } + ); }); it("drops every social button but keeps the form when only local login is enabled", () => { - expectProviderDom([true, false, false, false], [true, true, false, false, false, false]); + expectProviderDom( + { localLogin: true, googleLogin: false, orcidLogin: false, appleLogin: false }, + { tabs: true, form: true, google: false, orcid: false, apple: false, divider: false } + ); }); it("drops the tabs and the form but keeps the google button when only google is enabled", () => { - expectProviderDom([false, true, false, false], [false, false, true, false, false, false]); + expectProviderDom( + { localLogin: false, googleLogin: true, orcidLogin: false, appleLogin: false }, + { tabs: false, form: false, google: true, orcid: false, apple: false, divider: false } + ); }); // ORCID carries the divider on its own: it is a second way to "continue with" // something other than the local form, so the label still reads correctly. it("keeps the orcid button and the divider when google is disabled but orcid is not", () => { - expectProviderDom([true, false, true, false], [null, true, false, true, null, true]); + expectProviderDom( + { localLogin: true, googleLogin: false, orcidLogin: true, appleLogin: false }, + { form: true, google: false, orcid: true, divider: true } + ); }); it("drops the tabs and the form but keeps the orcid button when only orcid is enabled", () => { - expectProviderDom([false, false, true, false], [false, false, false, true, false, false]); + expectProviderDom( + { localLogin: false, googleLogin: false, orcidLogin: true, appleLogin: false }, + { tabs: false, form: false, google: false, orcid: true, apple: false, divider: false } + ); }); it("renders no sign-in path when every provider is disabled", () => { - expectProviderDom([false, false, false, false], [false, false, false, false, false, false]); + expectProviderDom( + { localLogin: false, googleLogin: false, orcidLogin: false, appleLogin: false }, + { tabs: false, form: false, google: false, orcid: false, apple: false, divider: false } + ); // The brand and footer are outside every flag, so the card is never empty. expect(host().querySelector(".brand")).toBeTruthy(); expect(host().querySelector("p.foot")).toBeTruthy(); @@ -712,11 +735,17 @@ describe("TexeraLoginComponent", () => { // Apple alone alongside the form still earns the divider. Nothing covered this before, // which is what let the divider condition and the render helper drift apart. it("keeps the divider when Apple is the only social provider", () => { - expectProviderDom([true, false, false, true], [null, true, false, null, true, true]); + expectProviderDom( + { localLogin: true, googleLogin: false, orcidLogin: false, appleLogin: true }, + { form: true, google: false, apple: true, divider: true } + ); }); it("drops the tabs and the form but keeps Apple's slot when only Apple is enabled", () => { - expectProviderDom([false, false, false, true], [false, false, false, null, true, false]); + expectProviderDom( + { localLogin: false, googleLogin: false, orcidLogin: false, appleLogin: true }, + { tabs: false, form: false, apple: true, divider: false } + ); }); });