Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Large diffs are not rendered by default.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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(() => {
Expand All @@ -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" });
});
});
Expand Down Expand Up @@ -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" }]);
});
Expand All @@ -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" }]);
});
Expand All @@ -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);
});
Expand All @@ -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",
{}
);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -36,18 +37,13 @@ describe("DeploymentVersionService", () => {

beforeEach(() => {
notificationClick = new Subject<MouseEvent>();
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,
Expand Down Expand Up @@ -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<typeof takeManifestRequest>) => void][]
).forEach(([label, respond]) => {
it(label, () => {
const out = check();
respond(takeManifestRequest());
expect(out.value).toBe(false);
});
});
});

Expand Down
58 changes: 25 additions & 33 deletions frontend/src/app/common/service/gmail/gmail.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -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(() => {
Expand All @@ -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();
Expand All @@ -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();
Expand All @@ -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();
Expand All @@ -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.");
});
Expand All @@ -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");
Expand Down
Loading
Loading