Swadhin Biswas feat(cli): expand command coverage and config support · 3/6/2026
7e372c1
66 lines · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { mkdtempSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";

type AuthModule = typeof import("./auth.js");
type ConfigModule = typeof import("../lib/config.js");

let authMod: AuthModule;
let configMod: ConfigModule;

beforeAll(async () => {
  const tmpDir = mkdtempSync(path.join(os.tmpdir(), "och-cli-auth-test-"));
  process.env.XDG_CONFIG_HOME = tmpDir;
  process.env.XDG_DATA_HOME = tmpDir;
  process.env.OCH_DISABLE_KEYCHAIN = "1";
  process.env.CI = "1";

  configMod = await import("../lib/config.js");
  authMod = await import("./auth.js");
});

beforeEach(() => {
  configMod.clearConfig();
  vi.restoreAllMocks();
});

describe("auth commands", () => {
  it("status reports unauthenticated when token is missing", async () => {
    const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});

    await authMod.authCommands.parseAsync(["status"], {
      from: "user",
    });

    expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("Not authenticated"));
  });

  it("login with token stores username and token", async () => {
    const fetchMock = vi.fn(async () =>
      new Response(JSON.stringify({ data: { username: "alice" } }), {
        status: 200,
        headers: { "content-type": "application/json" },
      }),
    );
    vi.stubGlobal("fetch", fetchMock);

    await authMod.authCommands.parseAsync(
      [
        "login",
        "--url",
        "https://git.example.com",
        "--token",
        "token_12345678",
      ],
      { from: "user" },
    );

    const cfg = configMod.getConfig();
    expect(cfg.serverUrl).toBe("https://git.example.com");
    expect(cfg.username).toBe("alice");
    expect(cfg.token).toBe("token_12345678");
    expect(fetchMock).toHaveBeenCalled();
  });
});