Skip to content

Commit

Permalink
chore(test): #12 make tests not overwrite ~/.ocpi
Browse files Browse the repository at this point in the history
  • Loading branch information
reinierl committed Jan 21, 2023
1 parent ee941de commit 36b04e4
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 6 deletions.
10 changes: 9 additions & 1 deletion src/commands/login.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import axios, { AxiosError, AxiosResponse } from "axios";
import { describe, expect, jest, test } from "@jest/globals";
import { OcpiResponse } from "../ocpi-request";
import { login } from "./login";
import { readFile } from "node:fs/promises";
import { mkdir, mkdtemp, readFile, rm, rmdir } from "node:fs/promises";
import path from "node:path";
import os from "node:os";

jest.mock("axios");

Expand Down Expand Up @@ -40,6 +42,9 @@ describe("The login command", () => {
};
mockXios.mockResolvedValue(testResponse);

const tempdir = await mkdtemp(path.join(os.tmpdir(), "ocpi-tool-tests-"));
process.env["HOME"] = tempdir;

await login(
"https://example.org/ocpi/2.1.1",
"whatever-token-abc",
Expand All @@ -49,5 +54,8 @@ describe("The login command", () => {
await expect(
readFile(`${process.env.HOME}/.ocpi`, { encoding: "utf-8" })
).resolves.toMatch("locations");

await rm(`${tempdir}/.ocpi`);
await rmdir(tempdir);
});
});
12 changes: 7 additions & 5 deletions src/ocpi-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,9 +90,6 @@ export type OcpiSession = {

export type OcpiRequestMethod = "get" | "post" | "put" | "delete";

const SESSION_FILE =
process.env.OCPI_SESSION_FILE ?? `${process.env.HOME}/.ocpi`;

export async function ocpiRequest<T>(
method: OcpiRequestMethod,
url: string,
Expand Down Expand Up @@ -335,12 +332,17 @@ async function pullPageOfData<N extends ModuleID>(
}

export async function loadSession(): Promise<OcpiSession> {
const sessionFileContents = await readFile(SESSION_FILE, {
const sessionFileContents = await readFile(sessionFile(), {
encoding: "utf-8",
});
return JSON.parse(sessionFileContents).session as OcpiSession;
}

export async function setSession(session: OcpiSession): Promise<void> {
return writeFile(SESSION_FILE, JSON.stringify({ session }), { mode: "0600" });
return writeFile(sessionFile(), JSON.stringify({ session }), {
mode: "0600",
});
}

const sessionFile: () => string = () =>
process.env.OCPI_SESSION_FILE ?? `${process.env.HOME}/.ocpi`;

0 comments on commit 36b04e4

Please sign in to comment.