Skip to content

Commit 0d8c90a

Browse files
committed
Remove fs mocking from no-workspace tests
1 parent f13f0b3 commit 0d8c90a

5 files changed

Lines changed: 104 additions & 99 deletions

File tree

extensions/ql-vscode/test/vscode-tests/no-workspace/contextual/queryResolver.test.ts

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,6 @@ import { CodeQLCliServer } from "../../../../src/cli";
1313
import { DatabaseItem } from "../../../../src/databases";
1414

1515
describe("queryResolver", () => {
16-
let writeFileSpy: jest.SpiedFunction<typeof fs.writeFile>;
17-
1816
let getQlPackForDbschemeSpy: jest.SpiedFunction<
1917
typeof helpers.getQlPackForDbscheme
2018
>;
@@ -30,10 +28,6 @@ describe("queryResolver", () => {
3028
};
3129

3230
beforeEach(() => {
33-
writeFileSpy = jest
34-
.spyOn(fs, "writeFile")
35-
.mockImplementation(() => Promise.resolve());
36-
3731
getQlPackForDbschemeSpy = jest
3832
.spyOn(helpers, "getQlPackForDbscheme")
3933
.mockResolvedValue({
@@ -61,13 +55,15 @@ describe("queryResolver", () => {
6155
KeyType.DefinitionQuery,
6256
);
6357
expect(result).toEqual(["a", "b"]);
64-
expect(writeFileSpy).toHaveBeenNthCalledWith(
65-
1,
66-
expect.stringMatching(/.qls$/),
67-
expect.anything(),
68-
expect.anything(),
58+
59+
expect(mockCli.resolveQueriesInSuite).toHaveBeenCalledWith(
60+
expect.stringMatching(/\.qls$/),
61+
[],
6962
);
70-
expect(load(writeFileSpy.mock.calls[0][1])).toEqual([
63+
64+
const fileName = mockCli.resolveQueriesInSuite.mock.calls[0][0];
65+
66+
expect(load(await fs.readFile(fileName, "utf-8"))).toEqual([
7167
{
7268
from: "my-qlpack",
7369
queries: ".",
@@ -95,13 +91,15 @@ describe("queryResolver", () => {
9591
KeyType.DefinitionQuery,
9692
);
9793
expect(result).toEqual(["a", "b"]);
98-
expect(writeFileSpy).toHaveBeenNthCalledWith(
99-
1,
100-
expect.stringMatching(/.qls$/),
101-
expect.anything(),
102-
expect.anything(),
94+
95+
expect(mockCli.resolveQueriesInSuite).toHaveBeenCalledWith(
96+
expect.stringMatching(/\.qls$/),
97+
[],
10398
);
104-
expect(load(writeFileSpy.mock.calls[0][1])).toEqual([
99+
100+
const fileName = mockCli.resolveQueriesInSuite.mock.calls[0][0];
101+
102+
expect(load(await fs.readFile(fileName, "utf-8"))).toEqual([
105103
{
106104
from: "my-qlpack2",
107105
queries: ".",

extensions/ql-vscode/test/vscode-tests/no-workspace/distribution.test.ts

Lines changed: 41 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,30 @@
1-
import { sep } from "path";
21
import * as fetch from "node-fetch";
32
import { Range } from "semver";
43

54
import * as helpers from "../../../src/helpers";
65
import { extLogger } from "../../../src/common";
76
import * as fs from "fs-extra";
7+
import * as path from "path";
88
import * as os from "os";
9+
import * as tmp from "tmp-promise";
910
import {
1011
GithubRelease,
1112
GithubReleaseAsset,
1213
ReleasesApiConsumer,
1314
getExecutableFromDirectory,
1415
DistributionManager,
1516
} from "../../../src/distribution";
17+
import { DirectoryResult } from "tmp-promise";
18+
19+
jest.mock("os", () => {
20+
const original = jest.requireActual("os");
21+
return {
22+
...original,
23+
platform: jest.fn(),
24+
};
25+
});
26+
27+
const mockedOS = jest.mocked(os);
1628

1729
describe("Releases API consumer", () => {
1830
const owner = "someowner";
@@ -192,40 +204,42 @@ describe("Releases API consumer", () => {
192204
});
193205

194206
describe("Launcher path", () => {
195-
const pathToCmd = `abc${sep}codeql.cmd`;
196-
const pathToExe = `abc${sep}codeql.exe`;
197-
198207
let warnSpy: jest.SpiedFunction<typeof helpers.showAndLogWarningMessage>;
199208
let errorSpy: jest.SpiedFunction<typeof helpers.showAndLogErrorMessage>;
200209
let logSpy: jest.SpiedFunction<typeof extLogger.log>;
201-
let pathExistsSpy: jest.SpiedFunction<typeof fs.pathExists>;
202210

203-
let launcherThatExists = "";
211+
let directory: DirectoryResult;
204212

205-
beforeEach(() => {
213+
let pathToCmd: string;
214+
let pathToExe: string;
215+
216+
beforeEach(async () => {
206217
warnSpy = jest
207218
.spyOn(helpers, "showAndLogWarningMessage")
208219
.mockResolvedValue(undefined);
209220
errorSpy = jest
210221
.spyOn(helpers, "showAndLogErrorMessage")
211222
.mockResolvedValue(undefined);
212223
logSpy = jest.spyOn(extLogger, "log").mockResolvedValue(undefined);
213-
pathExistsSpy = jest
214-
.spyOn(fs, "pathExists")
215-
.mockImplementation(async (path: string) => {
216-
return path.endsWith(launcherThatExists);
217-
});
218224

219-
jest.spyOn(os, "platform").mockReturnValue("win32");
225+
mockedOS.platform.mockReturnValue("win32");
226+
227+
directory = await tmp.dir({
228+
unsafeCleanup: true,
229+
});
230+
231+
pathToCmd = path.join(directory.path, "codeql.cmd");
232+
pathToExe = path.join(directory.path, "codeql.exe");
233+
});
234+
235+
afterEach(async () => {
236+
await directory.cleanup();
220237
});
221238

222239
it("should not warn with proper launcher name", async () => {
223-
launcherThatExists = "codeql.exe";
224-
const result = await getExecutableFromDirectory("abc");
225-
expect(pathExistsSpy).toBeCalledWith(pathToExe);
240+
await fs.writeFile(pathToExe, "");
226241

227-
// correct launcher has been found, so alternate one not looked for
228-
expect(pathExistsSpy).not.toBeCalledWith(pathToCmd);
242+
const result = await getExecutableFromDirectory(directory.path);
229243

230244
// no warning message
231245
expect(warnSpy).not.toHaveBeenCalled();
@@ -235,10 +249,9 @@ describe("Launcher path", () => {
235249
});
236250

237251
it("should warn when using a hard-coded deprecated launcher name", async () => {
238-
launcherThatExists = "codeql.cmd";
239-
const result = await getExecutableFromDirectory("abc");
240-
expect(pathExistsSpy).toBeCalledWith(pathToExe);
241-
expect(pathExistsSpy).toBeCalledWith(pathToCmd);
252+
await fs.writeFile(pathToCmd, "");
253+
254+
const result = await getExecutableFromDirectory(directory.path);
242255

243256
// Should have opened a warning message
244257
expect(warnSpy).toHaveBeenCalled();
@@ -248,10 +261,7 @@ describe("Launcher path", () => {
248261
});
249262

250263
it("should avoid warn when no launcher is found", async () => {
251-
launcherThatExists = "xxx";
252-
const result = await getExecutableFromDirectory("abc", false);
253-
expect(pathExistsSpy).toBeCalledWith(pathToExe);
254-
expect(pathExistsSpy).toBeCalledWith(pathToCmd);
264+
const result = await getExecutableFromDirectory(directory.path, false);
255265

256266
// no warning message
257267
expect(warnSpy).not.toHaveBeenCalled();
@@ -261,10 +271,7 @@ describe("Launcher path", () => {
261271
});
262272

263273
it("should warn when no launcher is found", async () => {
264-
launcherThatExists = "xxx";
265274
const result = await getExecutableFromDirectory("abc", true);
266-
expect(pathExistsSpy).toBeCalledWith(pathToExe);
267-
expect(pathExistsSpy).toBeCalledWith(pathToCmd);
268275

269276
// no warning message
270277
expect(warnSpy).not.toHaveBeenCalled();
@@ -274,12 +281,13 @@ describe("Launcher path", () => {
274281
});
275282

276283
it("should not warn when deprecated launcher is used, but no new launcher is available", async function () {
284+
await fs.writeFile(pathToCmd, "");
285+
277286
const manager = new DistributionManager(
278287
{ customCodeQlPath: pathToCmd } as any,
279288
{} as any,
280289
undefined as any,
281290
);
282-
launcherThatExists = "codeql.cmd";
283291

284292
const result = await manager.getCodeQlPathWithoutVersionCheck();
285293
expect(result).toBe(pathToCmd);
@@ -290,12 +298,14 @@ describe("Launcher path", () => {
290298
});
291299

292300
it("should warn when deprecated launcher is used, and new launcher is available", async () => {
301+
await fs.writeFile(pathToCmd, "");
302+
await fs.writeFile(pathToExe, "");
303+
293304
const manager = new DistributionManager(
294305
{ customCodeQlPath: pathToCmd } as any,
295306
{} as any,
296307
undefined as any,
297308
);
298-
launcherThatExists = ""; // pretend both launchers exist
299309

300310
const result = await manager.getCodeQlPathWithoutVersionCheck();
301311
expect(result).toBe(pathToCmd);
@@ -311,7 +321,6 @@ describe("Launcher path", () => {
311321
{} as any,
312322
undefined as any,
313323
);
314-
launcherThatExists = "xxx"; // pretend neither launcher exists
315324

316325
const result = await manager.getCodeQlPathWithoutVersionCheck();
317326
expect(result).toBeUndefined();

extensions/ql-vscode/test/vscode-tests/no-workspace/remote-queries/repository-selection.test.ts

Lines changed: 34 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import { QuickPickItem, window } from "vscode";
2-
import * as fs from "fs-extra";
2+
import { join } from "path";
3+
import { DirectoryResult } from "tmp-promise";
4+
import * as tmp from "tmp-promise";
5+
import { ensureDir, writeFile, writeJson } from "fs-extra";
36
import { UserCancellationException } from "../../../../src/commandRunner";
47

58
import * as config from "../../../../src/config";
@@ -126,10 +129,6 @@ describe("repository selection", () => {
126129
typeof config.getRemoteRepositoryListsPath
127130
>;
128131

129-
let pathExistsStub: jest.SpiedFunction<typeof fs.pathExists>;
130-
let fsStatStub: jest.SpiedFunction<typeof fs.stat>;
131-
let fsReadFileStub: jest.SpiedFunction<typeof fs.readFile>;
132-
133132
beforeEach(() => {
134133
quickPickSpy = jest
135134
.spyOn(window, "showQuickPick")
@@ -144,16 +143,6 @@ describe("repository selection", () => {
144143
getRemoteRepositoryListsPathSpy = jest
145144
.spyOn(config, "getRemoteRepositoryListsPath")
146145
.mockReturnValue(undefined);
147-
148-
pathExistsStub = jest
149-
.spyOn(fs, "pathExists")
150-
.mockImplementation(() => false);
151-
fsStatStub = jest
152-
.spyOn(fs, "stat")
153-
.mockRejectedValue(new Error("not found"));
154-
fsReadFileStub = jest
155-
.spyOn(fs, "readFile")
156-
.mockRejectedValue(new Error("not found"));
157146
});
158147
describe("repo lists from settings", () => {
159148
it("should allow selection from repo lists from your pre-defined config", async () => {
@@ -362,80 +351,78 @@ describe("repository selection", () => {
362351
});
363352

364353
describe("external repository lists file", () => {
354+
let directory: DirectoryResult;
355+
356+
beforeEach(async () => {
357+
directory = await tmp.dir({
358+
unsafeCleanup: true,
359+
});
360+
});
361+
362+
afterEach(async () => {
363+
await directory.cleanup();
364+
});
365+
365366
it("should fail if path does not exist", async () => {
366-
const fakeFilePath = "/path/that/does/not/exist.json";
367-
getRemoteRepositoryListsPathSpy.mockReturnValue(fakeFilePath);
368-
pathExistsStub.mockImplementation(() => false);
367+
const nonExistingFile = join(directory.path, "non-existing-file.json");
368+
getRemoteRepositoryListsPathSpy.mockReturnValue(nonExistingFile);
369369

370370
await expect(getRepositorySelection()).rejects.toThrow(
371-
`External repository lists file does not exist at ${fakeFilePath}`,
371+
`External repository lists file does not exist at ${nonExistingFile}`,
372372
);
373373
});
374374

375375
it("should fail if path points to directory", async () => {
376-
const fakeFilePath = "/path/to/dir";
377-
getRemoteRepositoryListsPathSpy.mockReturnValue(fakeFilePath);
378-
pathExistsStub.mockImplementation(() => true);
379-
fsStatStub.mockResolvedValue({ isDirectory: () => true } as any);
376+
const existingDirectory = join(directory.path, "directory");
377+
await ensureDir(existingDirectory);
378+
getRemoteRepositoryListsPathSpy.mockReturnValue(existingDirectory);
380379

381380
await expect(getRepositorySelection()).rejects.toThrow(
382381
"External repository lists path should not point to a directory",
383382
);
384383
});
385384

386385
it("should fail if file does not have valid JSON", async () => {
387-
const fakeFilePath = "/path/to/file.json";
388-
getRemoteRepositoryListsPathSpy.mockReturnValue(fakeFilePath);
389-
pathExistsStub.mockImplementation(() => true);
390-
fsStatStub.mockResolvedValue({ isDirectory: () => false } as any);
391-
fsReadFileStub.mockResolvedValue("not-json" as any as Buffer);
386+
const existingFile = join(directory.path, "repository-lists.json");
387+
await writeFile(existingFile, "not-json");
388+
getRemoteRepositoryListsPathSpy.mockReturnValue(existingFile);
392389

393390
await expect(getRepositorySelection()).rejects.toThrow(
394391
"Invalid repository lists file. It should contain valid JSON.",
395392
);
396393
});
397394

398395
it("should fail if file contains array", async () => {
399-
const fakeFilePath = "/path/to/file.json";
400-
getRemoteRepositoryListsPathSpy.mockReturnValue(fakeFilePath);
401-
pathExistsStub.mockImplementation(() => true);
402-
fsStatStub.mockResolvedValue({ isDirectory: () => false } as any);
403-
fsReadFileStub.mockResolvedValue("[]" as any as Buffer);
396+
const existingFile = join(directory.path, "repository-lists.json");
397+
await writeJson(existingFile, []);
398+
getRemoteRepositoryListsPathSpy.mockReturnValue(existingFile);
404399

405400
await expect(getRepositorySelection()).rejects.toThrow(
406401
"Invalid repository lists file. It should be an object mapping names to a list of repositories.",
407402
);
408403
});
409404

410405
it("should fail if file does not contain repo lists in the right format", async () => {
411-
const fakeFilePath = "/path/to/file.json";
412-
getRemoteRepositoryListsPathSpy.mockReturnValue(fakeFilePath);
413-
pathExistsStub.mockImplementation(() => true);
414-
fsStatStub.mockResolvedValue({ isDirectory: () => false } as any);
406+
const existingFile = join(directory.path, "repository-lists.json");
415407
const repoLists = {
416408
list1: "owner1/repo1",
417409
};
418-
fsReadFileStub.mockResolvedValue(
419-
JSON.stringify(repoLists) as any as Buffer,
420-
);
410+
await writeJson(existingFile, repoLists);
411+
getRemoteRepositoryListsPathSpy.mockReturnValue(existingFile);
421412

422413
await expect(getRepositorySelection()).rejects.toThrow(
423414
"Invalid repository lists file. It should contain an array of repositories for each list.",
424415
);
425416
});
426417

427418
it("should get repo lists from file", async () => {
428-
const fakeFilePath = "/path/to/file.json";
429-
getRemoteRepositoryListsPathSpy.mockReturnValue(fakeFilePath);
430-
pathExistsStub.mockImplementation(() => true);
431-
fsStatStub.mockResolvedValue({ isDirectory: () => false } as any);
419+
const existingFile = join(directory.path, "repository-lists.json");
432420
const repoLists = {
433421
list1: ["owner1/repo1", "owner2/repo2"],
434422
list2: ["owner3/repo3"],
435423
};
436-
fsReadFileStub.mockResolvedValue(
437-
JSON.stringify(repoLists) as any as Buffer,
438-
);
424+
await writeJson(existingFile, repoLists);
425+
getRemoteRepositoryListsPathSpy.mockReturnValue(existingFile);
439426
getRemoteRepositoryListsSpy.mockReturnValue({
440427
list3: ["onwer4/repo4"],
441428
list4: [],

0 commit comments

Comments
 (0)