Файли
openidea/src/features/dotnet/edit.test.ts
T
LU XIANGRUIтаwildcatDownstairs 4e5ae49aa9 feat(dotnet): edit solutions and project references from the Project view (#7426)
Add Existing Project, Add/Remove Project Reference and Remove from Solution on .NET solution and project nodes, running dotnet sln/reference one at a time.

Queued edits are cancelled when the workspace changes, the tree refreshes after a partially failed CLI edit, and solution paths are normalized before comparing them.

Co-authored-by: wildcatDownstairs <[email protected]>
2026-12-02 18:05:25 +08:00

301 рядки
12 KiB
TypeScript

import { execFile, execFileSync } from "node:child_process";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
vi.setConfig({ testTimeout: 90_000, hookTimeout: 90_000 });
const mocks = vi.hoisted(() => ({ reload: vi.fn(async () => {}), pick: vi.fn(), notify: vi.fn() }));
vi.mock("./store", async (orig) => ({ ...(await orig<typeof import("./store")>()), reloadDotnet: mocks.reload }));
vi.mock("@/platform/choosePath", () => ({ choosePaths: mocks.pick }));
// The real `dotnet` CLI stands in for the Tauri process host: the arguments under test run unchanged.
vi.mock("@/platform/dotnet", async (orig) => ({
...(await orig<typeof import("@/platform/dotnet")>()),
dotnet: (args: string[], cwd: string, signal?: AbortSignal) =>
new Promise<string>((resolve, reject) => {
const child = execFile(
"dotnet",
args,
{ cwd, signal, env: { ...process.env, DOTNET_CLI_UI_LANGUAGE: "en" } },
(err, out, errOut) => (err ? reject(new Error(`${out}${errOut}`.trim() || err.message)) : resolve(out)),
);
child.on("error", reject);
}),
}));
import { useProject } from "@/platform/project";
import { provideNotificationService } from "@/workbench/contributions";
import { useDotnet } from "./store";
import {
addProjectReference,
addProjectsToSolution,
cancelDotnetEdit,
editItems,
referenceArgs,
removeProjectFromSolution,
removeProjectReference,
slnArgs,
} from "./edit";
const hasDotnet = (() => {
try {
execFileSync("dotnet", ["--version"], { stdio: "ignore" });
return true;
} catch {
return false;
}
})();
// CI installs the SDK (setup-dotnet), so a missing one there must fail, not skip.
const real = it.skipIf(!hasDotnet && !process.env.CI);
const csproj = (extra = "") =>
`<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><TargetFramework>net9.0</TargetFramework></PropertyGroup>${extra}</Project>`;
let dir = "";
const file = (rel: string, text = csproj()) => {
const path = join(dir, rel);
mkdirSync(join(path, ".."), { recursive: true });
writeFileSync(path, text);
return path;
};
const solution = (format: "sln" | "slnx", name = "App") => {
mkdirSync(join(dir, "sln"), { recursive: true });
execFileSync("dotnet", ["new", "sln", "-n", name, "--format", format, "-o", join(dir, "sln")], { stdio: "ignore" });
return join(dir, "sln", `${name}.${format}`);
};
const read = (path: string) => readFileSync(path, "utf8");
beforeEach(() => {
dir = mkdtempSync(join(tmpdir(), "dotnet-edit-"));
mocks.reload.mockClear();
mocks.notify.mockClear();
provideNotificationService({ notify: mocks.notify });
});
afterEach(() => rmSync(dir, { recursive: true, force: true }));
describe("CLI arguments", () => {
it("builds solution and reference commands", () => {
expect(slnArgs("add", "/a/App.sln", ["/a/B.csproj"])).toEqual(["sln", "/a/App.sln", "add", "/a/B.csproj"]);
expect(referenceArgs("remove", "/a/A.csproj", ["/b/B.csproj"])).toEqual([
"remove",
"/a/A.csproj",
"reference",
"/b/B.csproj",
]);
});
});
it("does not run an edit queued for the previous project", async () => {
const previous = useProject.getState().project;
const projectAt = (root: string) => ({ root }) as NonNullable<typeof previous>;
useProject.setState({ project: projectAt("/first") });
try {
const queued = removeProjectFromSolution("/first/App.sln", "/first/App.csproj");
useProject.setState({ project: projectAt("/second") });
await queued;
expect(mocks.notify).not.toHaveBeenCalled();
expect(mocks.reload).not.toHaveBeenCalled();
} finally {
useProject.setState({ project: previous });
}
});
describe.each(["sln", "slnx"] as const)("solution edits on .%s (real dotnet CLI)", (format) => {
real("adds a project, then removes it, reloading after each", async () => {
const sln = solution(format);
const project = file("src/Lib/Lib.csproj");
await addProjectsToSolution(sln, [project]);
expect(read(sln)).toContain("Lib.csproj");
expect(mocks.reload).toHaveBeenCalledTimes(1);
await removeProjectFromSolution(sln, project);
expect(read(sln)).not.toContain("Lib.csproj");
expect(mocks.reload).toHaveBeenCalledTimes(2);
expect(mocks.notify).not.toHaveBeenCalled();
});
real("an empty solution gains its first project", async () => {
const sln = solution(format);
expect(read(sln)).not.toContain("proj");
await addProjectsToSolution(sln, [file("A/A.csproj")]);
expect(read(sln)).toContain("A.csproj");
});
real("adds a project outside the solution folder (relative .. path)", async () => {
const sln = solution(format);
await addProjectsToSolution(sln, [file("elsewhere/Out/Out.csproj")]);
expect(read(sln).replace(/\\/g, "/")).toContain("../elsewhere/Out/Out.csproj");
});
real("handles spaces and non-ASCII (中文) in paths", async () => {
const sln = solution(format);
const project = file("my 项目/测试 App/测试 App.csproj");
await addProjectsToSolution(sln, [project]);
expect(read(sln)).toContain("测试 App.csproj");
await removeProjectFromSolution(sln, project);
expect(read(sln)).not.toContain("测试 App.csproj");
});
real("a project that was added raises no warning (relative .. path resolved against the list)", async () => {
const sln = solution(format);
await addProjectsToSolution(sln, [file("out/Out/Out.csproj"), file("in/In.csproj")]);
expect(mocks.notify).not.toHaveBeenCalled();
});
real("adds several picked projects in one command", async () => {
const sln = solution(format);
await addProjectsToSolution(sln, [file("A/A.csproj"), file("B/B.csproj")]);
expect(read(sln)).toContain("A.csproj");
expect(read(sln)).toContain("B.csproj");
});
real("same-named projects from two folders: the CLI keeps the first and a warning names the other", async () => {
const sln = solution(format);
await addProjectsToSolution(sln, [file("one/Core/Core.csproj"), file("two/Core/Core.csproj")]);
// `dotnet sln add` matches by file name and exits 0 with "already contains project".
expect(read(sln).match(/Core\.csproj/g)).toHaveLength(1);
expect(mocks.notify).toHaveBeenCalledTimes(1);
expect(mocks.notify.mock.calls[0]![0]).toMatchObject({
level: "warning",
body: expect.stringContaining("Core.csproj"),
});
expect(mocks.reload).toHaveBeenCalledTimes(1);
});
real("removes a project whose file was deleted from disk", async () => {
const sln = solution(format);
const project = file("Gone/Gone.csproj");
await addProjectsToSolution(sln, [project]);
rmSync(join(dir, "Gone"), { recursive: true });
await removeProjectFromSolution(sln, project);
// The CLI refuses a missing file on some SDKs: either it is gone from the file, or an error was reported.
expect(read(sln).includes("Gone.csproj") ? mocks.notify.mock.calls.length : 1).toBeGreaterThan(0);
});
real("a project in two solutions is edited in one only", async () => {
const a = solution(format, "A");
const b = solution(format, "B");
const project = file("Shared/Shared.csproj");
await addProjectsToSolution(a, [project]);
await addProjectsToSolution(b, [project]);
await removeProjectFromSolution(a, project);
expect(read(a)).not.toContain("Shared.csproj");
expect(read(b)).toContain("Shared.csproj");
});
real("reports a CLI failure and refreshes the model after the process exits", async () => {
const sln = solution(format);
await addProjectsToSolution(sln, [join(dir, "missing/Nope.csproj")]);
expect(mocks.notify).toHaveBeenCalledTimes(1);
expect(mocks.notify.mock.calls[0]![0]).toMatchObject({
level: "error",
title: expect.stringContaining("solution"),
});
expect(mocks.reload).toHaveBeenCalledTimes(1);
});
real("a read-only solution file fails with a notification", async () => {
if (process.platform === "win32" || process.getuid?.() === 0) return;
const sln = solution(format);
execFileSync("chmod", ["444", sln]);
await addProjectsToSolution(sln, [file("A/A.csproj")]);
expect(mocks.notify).toHaveBeenCalledTimes(1);
expect(mocks.reload).toHaveBeenCalledTimes(1);
});
real("concurrent edits run one after another and both land", async () => {
const sln = solution(format);
await Promise.all([
addProjectsToSolution(sln, [file("A/A.csproj")]),
addProjectsToSolution(sln, [file("B/B.csproj")]),
]);
expect(read(sln)).toContain("A.csproj");
expect(read(sln)).toContain("B.csproj");
expect(mocks.reload).toHaveBeenCalledTimes(2);
});
it("no pick means no command", async () => {
mocks.pick.mockResolvedValue([]);
await addProjectsToSolution("/nowhere/App.sln");
expect(mocks.notify).not.toHaveBeenCalled();
expect(mocks.reload).not.toHaveBeenCalled();
});
});
describe("project reference edits (real dotnet CLI)", () => {
real("adds and removes a reference, also for a multi-targeted project", async () => {
const lib = file("Lib/Lib.csproj", csproj().replace("net9.0", "net8.0"));
const app = file(
"App/App.csproj",
csproj().replace(
"<TargetFramework>net9.0</TargetFramework>",
"<TargetFrameworks>net8.0;net9.0</TargetFrameworks>",
),
);
await addProjectReference(app, lib);
expect(read(app)).toContain("ProjectReference");
await removeProjectReference(app, lib);
expect(read(app)).not.toContain("ProjectReference");
expect(mocks.reload).toHaveBeenCalledTimes(2);
expect(mocks.notify).not.toHaveBeenCalled();
});
real("handles spaces and non-ASCII in the referenced path", async () => {
const lib = file("库 文件/库 Lib/库 Lib.csproj");
const app = file("App/App.csproj");
await addProjectReference(app, lib);
expect(read(app)).toContain("库 Lib.csproj");
});
real("reports a reference to a missing project", async () => {
const app = file("App/App.csproj");
await addProjectReference(app, join(dir, "nope/Nope.csproj"));
expect(mocks.notify).toHaveBeenCalledTimes(1);
expect(mocks.reload).toHaveBeenCalledTimes(1);
});
real("cancelling a queued edit reports nothing and skips the reload", async () => {
const sln = solution("sln");
const running = addProjectsToSolution(sln, [file("A/A.csproj")]);
cancelDotnetEdit();
await running;
expect(mocks.notify).not.toHaveBeenCalled();
expect(mocks.reload).not.toHaveBeenCalled();
});
});
describe("Project view menu items", () => {
const project = (path: string, references: string[] = []) => ({ path, name: path, references }) as never;
beforeEach(() => {
useDotnet.setState({
model: {
projects: [project("/s/A/A.csproj", ["/s/B/B.csproj"]), project("/s/B/B.csproj")],
solutions: [
{ path: "/s/One.sln", projects: ["/s/A/A.csproj"] },
{ path: "/s/Two.slnx", projects: ["/s/A/A.csproj"] },
],
},
});
});
afterEach(() => useDotnet.setState({ model: { projects: [], solutions: [] } }));
it("a solution offers Add Existing Project", () => {
expect(editItems("/s/One.sln")).toContainEqual(
expect.objectContaining({ action: "dotnet.solution.addProject", arg: { solution: "/s/One.sln" } }),
);
});
it("a project offers add / remove reference and one removal per owning solution", () => {
const items = editItems("/s/A/A.csproj");
expect(items.filter((i) => "action" in i && i.action === "dotnet.solution.removeProject")).toHaveLength(2);
expect(items.some((i) => "submenu" in i)).toBe(true);
expect(items).toContainEqual(expect.objectContaining({ action: "dotnet.project.addReference" }));
});
it("a project without references or solutions offers only Add Project Reference", () => {
const items = editItems("/s/B/B.csproj");
expect(items.some((i) => "submenu" in i)).toBe(false);
expect(items.filter((i) => "action" in i)).toHaveLength(1);
});
});