credentialFault.test.ts 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { tmpdir } from "node:os";
  4. import { expect, it } from "vitest";
  5. import { atomicWritePrivateTextFile, withFileLock } from "@zcode/shared/node";
  6. import { withCredentialFault } from "#e2e/helpers/credential-fault";
  7. it.each([undefined, "original"])(
  8. "故障收尾只恢复注入键,保留连接期间新增的 SSH 凭据 (%s)",
  9. async (original) => {
  10. const directory = await mkdtemp(join(tmpdir(), "credential-fault-"));
  11. const file = join(directory, "credentials.json");
  12. const initial = original === undefined ? {} : { oauth: original };
  13. try {
  14. await writeFile(file, JSON.stringify(initial));
  15. await expect(
  16. withCredentialFault(file, "oauth", "invalid", async () => {
  17. await withFileLock(file, async () => {
  18. const current = JSON.parse(await readFile(file, "utf8"));
  19. expect(current.oauth).toBe("invalid");
  20. await atomicWritePrivateTextFile(
  21. file,
  22. JSON.stringify({ ...current, ssh: "new-credential" }),
  23. );
  24. });
  25. throw new Error("injected failure");
  26. }),
  27. ).rejects.toThrow("injected failure");
  28. expect(JSON.parse(await readFile(file, "utf8"))).toEqual({
  29. ...initial,
  30. ssh: "new-credential",
  31. });
  32. } finally {
  33. await rm(directory, { recursive: true, force: true });
  34. }
  35. },
  36. );