import * as assert from "assert"; import { sandboxed, pgPromiseStubber } from "@wealthbar/test-helpers"; import { dbConfigCtor } from "./"; describe("dbConfig", async () => { it("returns settings", async () => { await sandboxed(async (sinon) => { const { db, pgPromiseFactory } = pgPromiseStubber(sinon); const settings = { a: "b" }; db.one = sinon.stub(); db.one.resolves({ settings }); const { execute } = dbConfigCtor(pgPromiseFactory); const actual = await execute(); assert.equal(actual, settings); }); }); it("defaults CONFIG_ENV to dev", async () => { await sandboxed(async (sinon) => { sinon.stub(process, "env").value({ CONFIG_ENV: null }); const { db, pgPromiseFactory } = pgPromiseStubber(sinon); db.one = sinon.stub(); db.one.resolves({ settings: {} }); const { execute } = dbConfigCtor(pgPromiseFactory); await execute(); assert(db.one.called); assert.equal(db.one.getCall(0).args[1].CONFIG_ENV, "dev"); }); }); it("uses CONFIG_ENV", async () => { await sandboxed(async (sinon) => { const configEnv = "config_env_value"; sinon.stub(process, "env").value({ CONFIG_ENV: configEnv }); const { db, pgPromiseFactory } = pgPromiseStubber(sinon); db.one = sinon.stub(); db.one.resolves({ settings: {} }); const { execute } = dbConfigCtor(pgPromiseFactory); await execute(); assert(db.one.called); assert.equal(db.one.getCall(0).args[1].CONFIG_ENV, configEnv); }); }); it("throws is CONFIG_ENV is not found in db", async () => { await sandboxed(async (sinon) => { const configEnv = "config_env_value"; sinon.stub(process, "env").value({ CONFIG_ENV: configEnv }); const { db, pgPromiseFactory } = pgPromiseStubber(sinon); db.one = sinon.stub(); db.one.resolves(null); const { execute } = dbConfigCtor(pgPromiseFactory); // can't use assert.throws w/ async. try { await execute(); assert.fail("expected exception to prevent us from reaching here"); } catch (e) { assert.ok("expected exception thrown"); } }); }); it("throws if db does not return settings", async () => { await sandboxed(async (sinon) => { const configEnv = "config_env_value"; sinon.stub(process, "env").value({ CONFIG_ENV: configEnv }); const { db, pgPromiseFactory } = pgPromiseStubber(sinon); db.one = sinon.stub(); db.one.resolves({}); const { execute } = dbConfigCtor(pgPromiseFactory); try { await execute(); assert.fail("expected exception to prevent us from reaching here"); } catch (e) { assert.ok("expected exception thrown"); } }); }); it("caches settings for 1 minute", async () => { await sandboxed(async (sinon) => { const { db, pgPromiseFactory } = pgPromiseStubber(sinon); db.one = sinon.stub(); db.one.resolves({ settings: {} }); const { execute } = dbConfigCtor(pgPromiseFactory); await execute(); assert(db.one.called); db.one.reset(); db.one.resolves({ settings: {} }); sinon.clock.tick(59000); await execute(); assert(!db.one.called); db.one.reset(); db.one.resolves({ settings: {} }); sinon.clock.tick(1000); await execute(); assert(db.one.called); }); }); });