import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" vi.mock("@/env/server", () => ({ env: { NODE_ENV: "test", }, })) import { env } from "../../../env/server" import { getPrefix } from "./getPrefix" const mockedEnv = env as { BRANCH: string; GIT_SHA: string } describe("getPrefix", () => { beforeEach(() => { vi.resetModules() }) afterEach(() => { vi.unstubAllEnvs() }) it.each([ "prod", "production", "release", "release-v1", "release-v2", "release-v2-alpha", "release-v2.1-alpha", "release-v2.1.2-alpha", ])( "should return gitsha for production branches when name is '%s'", (branchName: string) => { mockedEnv.BRANCH = branchName mockedEnv.GIT_SHA = "gitsha" const result = getPrefix({ includeGitHashInKey: true, includeBranchPrefix: true, }) expect(result).toBe("gitsha") } ) it.each([ "fix/stuff", "feat/my-feature", "feature/my-feature", "releasee", "release-vA", "FEAT", ])( "should return branch name and gitsha for non-production branches when name is '%s'", (branchName: string) => { mockedEnv.BRANCH = branchName mockedEnv.GIT_SHA = "gitsha" const result = getPrefix({ includeGitHashInKey: true, includeBranchPrefix: true, }) expect(result).toBe(`${"gitsha"}:${branchName}`) } ) it("should throw if BRANCH and/or GIT_SHA is not set", () => { mockedEnv.BRANCH = "hasBranch" mockedEnv.GIT_SHA = "" expect(() => getPrefix({ includeBranchPrefix: true, includeGitHashInKey: true, }) ).toThrow("Unable to getPrefix, GIT_SHA must be set") mockedEnv.BRANCH = "" mockedEnv.GIT_SHA = "hasGitSha" expect(() => getPrefix({ includeBranchPrefix: true, includeGitHashInKey: true, }) ).toThrow("Unable to getPrefix, BRANCH must be set") }) it("should return dev or local user if running locally", () => { vi.stubEnv("NODE_ENV", "development") vi.stubEnv("USER", "test_user") vi.stubEnv("USERNAME", "test_username") mockedEnv.BRANCH = "" mockedEnv.GIT_SHA = "" expect( getPrefix({ includeGitHashInKey: false, includeBranchPrefix: false, }) ).toBe("test_user") process.env.USER = "" expect( getPrefix({ includeGitHashInKey: false, includeBranchPrefix: false, }) ).toBe("test_username") process.env.USERNAME = "" expect( getPrefix({ includeGitHashInKey: false, includeBranchPrefix: false, }) ).toBe("dev") }) })