aboutsummaryrefslogtreecommitdiff
path: root/src/config.test.ts
blob: 456a6e377d3e2def1c7dcd5e52bbcae48a5c03d2 (plain) (blame)
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
const exit = jest
  .spyOn(process, "exit")
  .mockImplementation(() => undefined as never);

import winston from "winston";
import {
  configOrError,
  persistTemplate,
  handleStartup,
  handleShutdown,
} from "./config";
import { MongoClient, MongoError } from "mongodb";
import { Server } from "http";
import path from "path";
import fs from "fs";

import loggerConfig from "./util/logger";
import * as templates from "./templates";
import Metadata, { EnvConfig } from "./metadata";

jest.mock("./util/logger", () => ({
  __esModule: true,
  default: () => ({
    format: winston.format.combine(
      winston.format.splat(),
      winston.format.simple()
    ),
    transports: [new winston.transports.Console({ silent: true })],
  }),
}));

const LOGGER = winston.createLogger(loggerConfig("TEST", "debug"));

describe("configOrError", () => {
  beforeEach(() => {
    exit.mockClear();
  });

  it("should exit when a env var does not exist", () => {
    // Arrange

    // Act
    let result;
    try {
      result = configOrError("APPLESAUCE", LOGGER);
    } catch (err) {
      //
    }

    // Assert
    expect(result).toBeUndefined();
    expect(exit).toHaveBeenCalledWith(1);
  });

  it("should return the expected env var", () => {
    // Arrange
    process.env.CHRYSANTHEMUM = "hello";

    // Act
    const result = configOrError("CHRYSANTHEMUM", LOGGER);

    // Assert
    expect(result).toEqual(process.env.CHRYSANTHEMUM);
    expect(exit).toHaveBeenCalledTimes(0);
  });
});

describe("persistTemplate", () => {
  beforeEach(() => {
    exit.mockClear();
  });

  it("should generate a template without error", async () => {
    const template = {
      inputFile: "/mnt/c/Windows/System32",
      outputFile: "./helloworld.txt",
      context: { EXAMPLE: "this" },
    } as templates.Template;
    const processTemplate = jest
      .spyOn(templates, "default")
      .mockImplementation(
        (template: templates.Template) => new Promise((res) => res(template))
      );
    const fsAccess = jest.spyOn(fs.promises, "access").mockResolvedValue();

    await persistTemplate(template, LOGGER);

    expect(processTemplate).toHaveBeenCalledWith(template);
    expect(fsAccess).not.toHaveBeenCalled();
    expect(exit).not.toHaveBeenCalled();
    processTemplate.mockRestore();
    fsAccess.mockRestore();
  });

  it("should exit without error if template does not generate but file already exists", async () => {
    const template = {
      inputFile: "/mnt/c/Windows/System32",
      outputFile: "./helloworld.txt",
      context: { EXAMPLE: "this" },
    } as templates.Template;
    const processTemplate = jest
      .spyOn(templates, "default")
      .mockRejectedValue("baa");
    const fsAccess = jest.spyOn(fs.promises, "access").mockResolvedValue();

    await persistTemplate(template, LOGGER);

    expect(processTemplate).toHaveBeenCalledWith(template);
    expect(fsAccess).toHaveBeenCalledWith(
      template.outputFile,
      fs.constants.R_OK
    );
    expect(exit).not.toHaveBeenCalled();
    processTemplate.mockRestore();
    fsAccess.mockRestore();
  });

  it("should exit with error if template does not generate and file does not exist", async () => {
    const template = {
      inputFile: "/mnt/c/Windows/System32",
      outputFile: "./helloworld.txt",
      context: { EXAMPLE: "this" },
    } as templates.Template;
    const processTemplate = jest
      .spyOn(templates, "default")
      .mockRejectedValue("baz");
    const fsAccess = jest.spyOn(fs.promises, "access").mockRejectedValue("bar");

    await persistTemplate(template, LOGGER);

    expect(processTemplate).toHaveBeenCalledWith(template);
    expect(fsAccess).toHaveBeenCalledWith(
      template.outputFile,
      fs.constants.R_OK
    );
    expect(exit).toHaveBeenCalledWith(1);
    processTemplate.mockRestore();
    fsAccess.mockRestore();
  });
});

describe("handleStartup", () => {
  beforeEach(() => {
    exit.mockClear();
  });

  const config = {
    hostDir: "/apple",
    publicDir: "/public",
    dbUri: "localhost:27017",
    dbName: "bongo",
    targetUrl: "localhost",
    logLevel: "trace",
  } as EnvConfig;
  const confStartup = (): Promise<Metadata> =>
    handleStartup(config, undefined, LOGGER);

  it("should exit if HOST_DIR is not read/write accessible", async () => {
    const superClient = {} as MongoClient;
    const fsAccess = jest.spyOn(fs.promises, "access").mockRejectedValue("boo");
    const pathAbsolute = jest.spyOn(path, "isAbsolute").mockReturnValue(true);
    const pathJoin = jest.spyOn(path, "join").mockReturnValue("path");
    const mongoClient = jest
      .spyOn(MongoClient, "connect")
      .mockImplementation(
        () => new Promise<MongoClient>((res) => res(superClient))
      );
    const processTemplate = jest
      .spyOn(templates, "default")
      .mockImplementation(
        (template: templates.Template) => new Promise((res) => res(template))
      );

    const result = await confStartup();

    expect(fsAccess).toHaveBeenCalledTimes(1);
    expect(exit).toHaveBeenCalledWith(1);
    expect(pathAbsolute).not.toHaveBeenCalled();
    expect(mongoClient).not.toHaveBeenCalled();
    expect(processTemplate).not.toHaveBeenCalled();
    expect(result).toBeUndefined();
    processTemplate.mockRestore();
    mongoClient.mockRestore();
    pathAbsolute.mockRestore();
    pathJoin.mockRestore();
    fsAccess.mockRestore();
  });

  it("should exit if HOST_DIR is not absolute path", async () => {
    const superClient = {} as MongoClient;
    const fsAccess = jest.spyOn(fs.promises, "access").mockResolvedValue();
    const pathAbsolute = jest.spyOn(path, "isAbsolute").mockReturnValue(false);
    const pathJoin = jest.spyOn(path, "join").mockReturnValue("path");
    const mongoClient = jest
      .spyOn(MongoClient, "connect")
      .mockImplementation(
        () => new Promise<MongoClient>((res) => res(superClient))
      );
    const processTemplate = jest
      .spyOn(templates, "default")
      .mockImplementation(
        (template: templates.Template) => new Promise((res) => res(template))
      );

    const result = await confStartup();

    expect(fsAccess).toHaveBeenCalledTimes(1);
    expect(pathAbsolute).toHaveBeenCalledTimes(1);
    expect(exit).toHaveBeenCalledWith(1);
    expect(mongoClient).not.toHaveBeenCalled();
    expect(processTemplate).not.toHaveBeenCalled();
    expect(result).toBeUndefined();
    processTemplate.mockRestore();
    mongoClient.mockRestore();
    pathAbsolute.mockRestore();
    pathJoin.mockRestore();
    fsAccess.mockRestore();
  });

  it("should exit if MongoClient has error", async () => {
    const fsAccess = jest.spyOn(fs.promises, "access").mockResolvedValue();
    const pathAbsolute = jest.spyOn(path, "isAbsolute").mockReturnValue(true);
    const pathJoin = jest.spyOn(path, "join").mockReturnValue("path");
    const mongoClient = jest
      .spyOn(MongoClient, "connect")
      .mockImplementation(
        () => new Promise((_, rej) => rej({ message: "aaahhh" } as MongoError))
      );
    const processTemplate = jest
      .spyOn(templates, "default")
      .mockImplementation(
        (template: templates.Template) => new Promise((res) => res(template))
      );

    const result = await confStartup();

    expect(fsAccess).toHaveBeenCalledTimes(1);
    expect(pathAbsolute).toHaveBeenCalledTimes(1);
    expect(mongoClient).toHaveBeenCalledTimes(1);
    expect(exit).toHaveBeenCalledWith(1);
    expect(processTemplate).not.toHaveBeenCalled();
    expect(result).toBeUndefined();
    processTemplate.mockRestore();
    mongoClient.mockRestore();
    pathAbsolute.mockRestore();
    pathJoin.mockRestore();
    fsAccess.mockRestore();
  });
});

describe("handleShutdown", () => {
  beforeEach(() => {
    exit.mockClear();
    // we don't use the MongoMock or ServerMock to directly test, so no mockClear needed
  });

  it("should exit gracefully without error", async () => {
    // Arrange
    const metadata = {
      close: () => Promise.resolve(),
    } as Metadata;
    const server = {
      close: (callback?: ((err?: Error | undefined) => void) | undefined) => {
        callback !== undefined && callback();
      },
    } as Server;

    // Act
    try {
      await handleShutdown(metadata, server, LOGGER)("SIGINT");
    } catch (err) {
      //
    }

    // Assert
    expect(exit).toHaveBeenCalledWith(0);
  });

  it("should exit with error with Metadata error", async () => {
    // Arrange
    const metadata = {
      close: () => Promise.reject(),
    } as Metadata;
    const server = {
      close: (callback?: ((err?: Error | undefined) => void) | undefined) => {
        callback !== undefined && callback();
      },
    } as Server;

    // Act
    try {
      await handleShutdown(metadata, server, LOGGER)("SIGINT");
    } catch (err) {
      //
    }

    // Assert
    expect(exit).toHaveBeenCalledWith(1);
  });

  it("should exit with error with Server error", async () => {
    // Arrange
    const metadata = {
      close: () => Promise.resolve(),
    } as Metadata;
    const server = {
      close: (callback?: ((err?: Error | undefined) => void) | undefined) => {
        callback !== undefined && callback(Error("NOOO"));
      },
    } as Server;

    // Act
    try {
      await handleShutdown(metadata, server, LOGGER)("SIGINT");
    } catch (err) {
      //
    }

    // Assert
    expect(exit).toHaveBeenCalledWith(1);
  });
});