Skip to content

Commit

Permalink
test: ensure unique repository name for all tests
Browse files Browse the repository at this point in the history
  • Loading branch information
lihbr committed Sep 5, 2024
1 parent e824a33 commit 4bc610d
Show file tree
Hide file tree
Showing 29 changed files with 204 additions and 108 deletions.
7 changes: 5 additions & 2 deletions test/__testutils__/createClient.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { TaskContext } from "vitest"

import fetch from "node-fetch"

import { createRepositoryName } from "./createRepositoryName"
Expand All @@ -14,13 +16,14 @@ type CreateTestClientArgs = (
apiEndpoint?: string
}
) & {
ctx: TaskContext
clientConfig?: prismic.ClientConfig
}

export const createTestClient = (
args: CreateTestClientArgs = {},
args: CreateTestClientArgs,
): prismic.Client => {
const repositoryName = args.repositoryName || createRepositoryName()
const repositoryName = args.repositoryName || createRepositoryName(args.ctx)

return prismic.createClient(args.apiEndpoint || repositoryName, {
fetch,
Expand Down
5 changes: 2 additions & 3 deletions test/__testutils__/createRepositoryName.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import type { TaskContext } from "vitest"
import { expect } from "vitest"

import * as crypto from "node:crypto"

export const createRepositoryName = (ctx?: TaskContext): string => {
const seed = ctx?.task.name || expect.getState().currentTestName
export const createRepositoryName = (ctx: TaskContext): string => {
const seed = ctx.task.name
if (!seed) {
throw new Error(
`createRepositoryName() can only be called within a Vitest test.`,
Expand Down
44 changes: 40 additions & 4 deletions test/__testutils__/mockPrismicAssetAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,17 @@ type MockPrismicAssetAPIArgs = {
client: WriteClient
writeToken?: string
getRequiredParams?: Record<string, string | string[]>
existingAssets?: Asset[][]
existingAssets?: Asset[][] | number[]
newAssets?: Asset[]
existingTags?: AssetTag[]
newTags?: AssetTag[]
}

type MockPrismicAssetAPIReturnType = {
assetsDatabase: Asset[][]
tagsDatabase: AssetTag[]
}

const DEFAULT_ASSET: Asset = {
id: "Yz7kzxAAAB0AREK7",
uploader_id: "uploader_id",
Expand All @@ -47,12 +52,37 @@ const DEFAULT_ASSET: Asset = {
tags: [],
}

export const mockPrismicAssetAPI = (args: MockPrismicAssetAPIArgs): void => {
export const mockAsset = (ctx: TestContext): Asset => {
const { id, url, alt, copyright } = ctx.mock.value.image({
state: "filled",
})

return {
...DEFAULT_ASSET,
id,
url,
alt: alt ?? undefined,
credits: copyright ?? undefined,
}
}

export const mockPrismicAssetAPI = (
args: MockPrismicAssetAPIArgs,
): MockPrismicAssetAPIReturnType => {
const repositoryName = args.client.repositoryName
const assetAPIEndpoint = args.client.assetAPIEndpoint
const writeToken = args.writeToken || args.client.writeToken

const assetsDatabase: Asset[][] = args.existingAssets || []
const assetsDatabase: Asset[][] =
args.existingAssets?.map((assets) => {
if (typeof assets === "number") {
return Array(assets)
.fill(1)
.map(() => mockAsset(args.ctx))
}

return assets
}) || []
const tagsDatabase: AssetTag[] = args.existingTags || []

args.ctx.server.use(
Expand Down Expand Up @@ -97,7 +127,8 @@ export const mockPrismicAssetAPI = (args: MockPrismicAssetAPIArgs): void => {
return res(ctx.status(401), ctx.json({ error: "unauthorized" }))
}

const response: PostAssetResult = args.newAssets?.pop() ?? DEFAULT_ASSET
const response: PostAssetResult =
args.newAssets?.shift() ?? mockAsset(args.ctx)

// Save the asset in DB
assetsDatabase.push([response])
Expand Down Expand Up @@ -180,4 +211,9 @@ export const mockPrismicAssetAPI = (args: MockPrismicAssetAPIArgs): void => {
return res(ctx.status(201), ctx.json(response))
}),
)

return {
assetsDatabase,
tagsDatabase,
}
}
70 changes: 61 additions & 9 deletions test/__testutils__/mockPrismicMigrationAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { TestContext } from "vitest"

import { rest } from "msw"

import type { WriteClient } from "../../src"
import type { PrismicDocument, WriteClient } from "../../src"
import type {
PostDocumentParams,
PostDocumentResult,
Expand All @@ -15,17 +15,53 @@ type MockPrismicMigrationAPIArgs = {
client: WriteClient
writeToken?: string
migrationAPIKey?: string
expectedID?: string
existingDocuments?: (PostDocumentResult | PrismicDocument)[] | number
newDocuments?: { id: string; masterLanguageDocumentID?: string }[]
}

type MockPrismicMigrationAPIReturnType = {
documentsDatabase: Record<string, PostDocumentResult>
}

export const mockPrismicMigrationAPI = (
args: MockPrismicMigrationAPIArgs,
): void => {
): MockPrismicMigrationAPIReturnType => {
const repositoryName = args.client.repositoryName
const migrationAPIEndpoint = args.client.migrationAPIEndpoint
const writeToken = args.writeToken || args.client.writeToken
const migrationAPIKey = args.migrationAPIKey || args.client.migrationAPIKey

const documentsDatabase: Record<string, PostDocumentResult> = {}

if (args.existingDocuments) {
if (typeof args.existingDocuments === "number") {
for (let i = 0; i < args.existingDocuments; i++) {
const document = args.ctx.mock.value.document()
documentsDatabase[document.id] = {
title: args.ctx.mock.value.keyText({ state: "filled" }),
id: document.id,
lang: document.lang,
type: document.type,
uid: document.uid,
}
}
} else {
for (const document of args.existingDocuments) {
if ("title" in document) {
documentsDatabase[document.id] = document
} else {
documentsDatabase[document.id] = {
title: args.ctx.mock.value.keyText({ state: "filled" }),
id: document.id,
lang: document.lang,
type: document.type,
uid: document.uid,
}
}
}
}
}

args.ctx.server.use(
rest.post(`${migrationAPIEndpoint}documents`, async (req, res, ctx) => {
if (
Expand All @@ -36,9 +72,17 @@ export const mockPrismicMigrationAPI = (
return res(ctx.status(403), ctx.json({ Message: "forbidden" }))
}

const id = args.expectedID || args.ctx.mock.value.document().id
const body = await req.json<PostDocumentParams>()

const newDocument = args.newDocuments?.shift()
const id = newDocument?.id || args.ctx.mock.value.document().id

if (newDocument?.masterLanguageDocumentID) {
args.ctx
.expect(body.alternate_language_id)
.toBe(newDocument.masterLanguageDocumentID)
}

const response: PostDocumentResult = {
title: body.title,
id,
Expand All @@ -47,6 +91,9 @@ export const mockPrismicMigrationAPI = (
uid: body.uid,
}

// Save the document in DB
documentsDatabase[id] = response

return res(ctx.status(201), ctx.json(response))
}),
rest.put(`${migrationAPIEndpoint}documents/:id`, async (req, res, ctx) => {
Expand All @@ -58,23 +105,28 @@ export const mockPrismicMigrationAPI = (
return res(ctx.status(403), ctx.json({ Message: "forbidden" }))
}

if (req.params.id !== args.expectedID) {
const document = documentsDatabase[req.params.id as string]

if (!document) {
return res(ctx.status(404))
}

const document = args.ctx.mock.value.document()
const id = args.expectedID || document.id
const body = await req.json<PutDocumentParams>()

const response: PutDocumentResult = {
title: body.title || args.ctx.mock.value.keyText({ state: "filled" }),
id,
title: body.title || document.title,
id: req.params.id as string,
lang: document.lang,
type: document.type,
uid: body.uid,
}

// Update the document in DB
documentsDatabase[req.params.id as string] = response

return res(ctx.json(response))
}),
)

return { documentsDatabase }
}
6 changes: 3 additions & 3 deletions test/__testutils__/mockPrismicRestAPIV2.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { TestContext } from "vitest"
import type { TaskContext, TestContext } from "vitest"
import { expect } from "vitest"

import { rest } from "msw"
Expand All @@ -10,7 +10,7 @@ import type * as prismic from "../../src"
const DEFAULT_DELAY = 0

type MockPrismicRestAPIV2Args = {
ctx: TestContext
ctx: TestContext & TaskContext
accessToken?: string
repositoryResponse?: prismic.Repository
queryResponse?: prismic.Query | prismic.Query[]
Expand All @@ -19,7 +19,7 @@ type MockPrismicRestAPIV2Args = {
}

export const mockPrismicRestAPIV2 = (args: MockPrismicRestAPIV2Args): void => {
const repositoryName = createRepositoryName()
const repositoryName = createRepositoryName(args.ctx)
const repositoryEndpoint = `https://${repositoryName}.cdn.prismic.io/api/v2`
const queryEndpoint = new URL(
"documents/search",
Expand Down
4 changes: 2 additions & 2 deletions test/__testutils__/testAbortableMethod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export const testAbortableMethod = (

mockPrismicRestAPIV2({ ctx })

const client = createTestClient()
const client = createTestClient({ ctx })

await expect(async () => {
await args.run(client, {
Expand All @@ -43,7 +43,7 @@ export const testAbortableMethod = (

mockPrismicRestAPIV2({ ctx })

const client = createTestClient()
const client = createTestClient({ ctx })

await expect(async () => {
await args.run(client, {
Expand Down
1 change: 1 addition & 0 deletions test/__testutils__/testAnyGetMethod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ export const testAnyGetMethodFactory = (

const client = createTestClient({
clientConfig: args.clientConfig,
ctx,
})

const res = await args.run(client)
Expand Down
4 changes: 2 additions & 2 deletions test/__testutils__/testConcurrentMethod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,9 @@ export const testConcurrentMethod = (
queryDelay: 10,
})

const client = createTestClient({ clientConfig: { fetch: fetchSpy } })
const client = createTestClient({ clientConfig: { fetch: fetchSpy }, ctx })

const graphqlURL = `https://${createRepositoryName()}.cdn.prismic.io/graphql`
const graphqlURL = `https://${createRepositoryName(ctx)}.cdn.prismic.io/graphql`
const graphqlResponse = { foo: "bar" }
ctx.server.use(
rest.get(graphqlURL, (req, res, ctx) => {
Expand Down
2 changes: 2 additions & 0 deletions test/__testutils__/testFetchOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export const testFetchOptions = (
fetch: fetchSpy,
fetchOptions,
},
ctx,
})

await args.run(client)
Expand Down Expand Up @@ -90,6 +91,7 @@ export const testFetchOptions = (
clientConfig: {
fetch: fetchSpy,
},
ctx,
})

await args.run(client, { fetchOptions })
Expand Down
4 changes: 2 additions & 2 deletions test/__testutils__/testGetTTL.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export const testGetWithinTTL = (
ctx,
})

const client = createTestClient()
const client = createTestClient({ ctx })

if (args.beforeFirstGet) {
args.beforeFirstGet({ client })
Expand Down Expand Up @@ -112,7 +112,7 @@ export const testGetOutsideTTL = (
ctx,
})

const client = createTestClient()
const client = createTestClient({ ctx })

if (args.beforeFirstGet) {
args.beforeFirstGet({ client })
Expand Down
8 changes: 4 additions & 4 deletions test/client-buildQueryURL.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ it("builds a query URL using the master ref", async (ctx) => {
ctx,
})

const client = createTestClient()
const client = createTestClient({ ctx })
const res = await client.buildQueryURL()
const url = new URL(res)

Expand All @@ -40,7 +40,7 @@ it("includes params if provided", async (ctx) => {

mockPrismicRestAPIV2({ ctx })

const client = createTestClient()
const client = createTestClient({ ctx })
const res = await client.buildQueryURL(params)
const url = new URL(res)

Expand Down Expand Up @@ -69,7 +69,7 @@ it("includes default params if provided", async (ctx) => {

mockPrismicRestAPIV2({ ctx })

const client = createTestClient({ clientConfig })
const client = createTestClient({ clientConfig, ctx })
const res = await client.buildQueryURL()
const url = new URL(res)

Expand Down Expand Up @@ -101,7 +101,7 @@ it("merges params and default params if provided", async (ctx) => {

mockPrismicRestAPIV2({ ctx })

const client = createTestClient({ clientConfig })
const client = createTestClient({ clientConfig, ctx })
const res = await client.buildQueryURL(params)
const url = new URL(res)

Expand Down
4 changes: 2 additions & 2 deletions test/client-dangerouslyGetAll.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ it("throttles requests past first page", async (ctx) => {
queryDelay,
})

const client = createTestClient()
const client = createTestClient({ ctx })

const startTime = Date.now()
await client.dangerouslyGetAll()
Expand Down Expand Up @@ -173,7 +173,7 @@ it("does not throttle single page queries", async (ctx) => {
queryDelay,
})

const client = createTestClient()
const client = createTestClient({ ctx })

const startTime = Date.now()
await client.dangerouslyGetAll()
Expand Down
Loading

0 comments on commit 4bc610d

Please sign in to comment.