Skip to content

Commit

Permalink
test(cli): migrate cli tests to vitest
Browse files Browse the repository at this point in the history
  • Loading branch information
binoy14 committed Nov 1, 2024
1 parent 3048630 commit c532a76
Show file tree
Hide file tree
Showing 25 changed files with 129 additions and 155 deletions.
11 changes: 0 additions & 11 deletions packages/@sanity/cli/jest.config.mjs

This file was deleted.

3 changes: 1 addition & 2 deletions packages/@sanity/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@
"clean": "rimraf lib",
"lint": "eslint .",
"prepublishOnly": "turbo run build",
"test": "jest",
"test": "vitest",
"ts": "node -r esbuild-register",
"watch": "pkg-utils watch"
},
Expand All @@ -75,7 +75,6 @@
"validate-npm-package-name": "^3.0.0"
},
"devDependencies": {
"@jest/globals": "^29.7.0",
"@repo/package.config": "workspace:*",
"@repo/test-config": "workspace:*",
"@rexxars/gitconfiglocal": "^3.0.1",
Expand Down
12 changes: 6 additions & 6 deletions packages/@sanity/cli/test/__snapshots__/typegen.test.ts.snap
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`CLI: \`sanity typegen\` sanity typegen generate: formats code 1`] = `
exports[`CLI: \`sanity typegen\` > sanity typegen generate: formats code 1`] = `
"/**
* ---------------------------------------------------------------------------------
* This file has been generated by Sanity TypeGen.
Expand Down Expand Up @@ -36,20 +36,20 @@ export type AllSanitySchemaTypes = Person | Slug;
export declare const internalGroqTypeReferenceTo: unique symbol;
// Source: ./src/queries.ts
// Variable: PAGE_QUERY
// Query: *[_type == \\"page\\" && slug.current == $slug][0]
// Query: *[_type == "page" && slug.current == $slug][0]
export type PAGE_QUERYResult = null;
// Query TypeMap
import '@sanity/client';
declare module '@sanity/client' {
interface SanityQueries {
'*[_type == \\"page\\" && slug.current == $slug][0]': PAGE_QUERYResult;
'*[_type == "page" && slug.current == $slug][0]': PAGE_QUERYResult;
}
}
"
`;

exports[`CLI: \`sanity typegen\` sanity typegen generate: with overloadClientMethods false 1`] = `
exports[`CLI: \`sanity typegen\` > sanity typegen generate: with overloadClientMethods false 1`] = `
"/**
* ---------------------------------------------------------------------------------
* This file has been generated by Sanity TypeGen.
Expand Down Expand Up @@ -85,7 +85,7 @@ export type AllSanitySchemaTypes = Person | Slug;
export declare const internalGroqTypeReferenceTo: unique symbol;
// Source: ./src/queries.ts
// Variable: PAGE_QUERY
// Query: *[_type == \\"page\\" && slug.current == $slug][0]
// Query: *[_type == "page" && slug.current == $slug][0]
export type PAGE_QUERYResult = null;
"
`;
4 changes: 2 additions & 2 deletions packages/@sanity/cli/test/alias.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import {describe, expect, jest} from '@jest/globals'
import {describe, expect, vi} from 'vitest'

import {describeCliTest, testConcurrent} from './shared/describe'
import {getTestRunArgs, runSanityCmdCommand, studioVersions} from './shared/environment'

describeCliTest('CLI: `sanity dataset alias`', () => {
describe.each(studioVersions)('%s', (version) => {
jest.setTimeout(30 * 1000)
vi.setConfig({testTimeout: 30 * 1000})

const testRunArgs = getTestRunArgs(version)

Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/cli/test/basics.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import path from 'node:path'

import {describe, expect} from '@jest/globals'
import {describe, expect} from 'vitest'

import {describeCliTest, testConcurrent} from './shared/describe'
import {getCliUserEmail, runSanityCmdCommand, studioVersions} from './shared/environment'
Expand Down
4 changes: 2 additions & 2 deletions packages/@sanity/cli/test/build.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {readdir, readFile, stat} from 'node:fs/promises'
import path from 'node:path'

import {describe, expect, jest, test} from '@jest/globals'
import {describe, expect, test, vi} from 'vitest'

import {describeCliTest, testConcurrent} from './shared/describe'
import {runSanityCmdCommand, studiosPath, studioVersions} from './shared/environment'
Expand All @@ -11,7 +11,7 @@ describeCliTest('CLI: `sanity build` / `sanity deploy`', () => {
const testConcurrentV3 = version === 'v3' ? testConcurrent : test.skip

// Builds can take a bit of time with lots of concurrent tasks and slow CIs
jest.setTimeout(240 * 1000)
vi.setConfig({testTimeout: 240 * 1000})

const studioPath = path.join(studiosPath, version)

Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/cli/test/cors.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {describe, expect} from '@jest/globals'
import {describe, expect} from 'vitest'

import {describeCliTest, testConcurrent} from './shared/describe'
import {getTestRunArgs, runSanityCmdCommand, studioVersions, testClient} from './shared/environment'
Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/cli/test/dataset.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {describe, expect} from '@jest/globals'
import {describe, expect} from 'vitest'

import {describeCliTest, testConcurrent} from './shared/describe'
import {getTestRunArgs, runSanityCmdCommand, studioVersions, testClient} from './shared/environment'
Expand Down
4 changes: 2 additions & 2 deletions packages/@sanity/cli/test/datasetCopy.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import {describe, expect, jest, test} from '@jest/globals'
import {describe, expect, test, vi} from 'vitest'

import {describeCliTest} from './shared/describe'
import {getTestRunArgs, runSanityCmdCommand, studioVersions} from './shared/environment'

describeCliTest('CLI: `sanity dataset copy`', () => {
describe.each(studioVersions)('%s', (version) => {
// Copy tests can be fairly slow even on small datasets
jest.setTimeout(120 * 1000)
vi.setConfig({testTimeout: 120 * 1000})

const testRunArgs = getTestRunArgs(version)

Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/cli/test/dev.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {createHash} from 'node:crypto'
import {readFile} from 'node:fs/promises'
import path from 'node:path'

import {describe, expect, test} from '@jest/globals'
import {describe, expect, test} from 'vitest'

import {describeCliTest} from './shared/describe'
import {testServerCommand} from './shared/devServer'
Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/cli/test/documents.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {describe, expect} from '@jest/globals'
import {describe, expect} from 'vitest'

import {describeCliTest, testConcurrent} from './shared/describe'
import {getTestRunArgs, runSanityCmdCommand, studioVersions, testClient} from './shared/environment'
Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/cli/test/exec.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {describe, expect} from '@jest/globals'
import {describe, expect} from 'vitest'

import {describeCliTest, testConcurrent} from './shared/describe'
import {getCliUserEmail, runSanityCmdCommand, studioVersions} from './shared/environment'
Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/cli/test/exportImport.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import {stat} from 'node:fs/promises'
import path from 'node:path'

import {describe, expect} from '@jest/globals'
import tar from 'tar'
import {describe, expect} from 'vitest'

import {describeCliTest, testConcurrent} from './shared/describe'
import {
Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/cli/test/graphql.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {expect} from '@jest/globals'
import {expect} from 'vitest'

import {describeCliTest, testConcurrent} from './shared/describe'
import {getTestRunArgs, runSanityCmdCommand, studioVersions, testClient} from './shared/environment'
Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/cli/test/init.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import fs from 'node:fs/promises'
import path from 'node:path'

import {describe, expect} from '@jest/globals'
import {describe, expect} from 'vitest'

import templates from '../src/actions/init-project/templates'
import {describeCliTest, testConcurrent} from './shared/describe'
Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/cli/test/preview.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import path from 'node:path'

import {describe, expect} from '@jest/globals'
import {describe, expect} from 'vitest'

import {describeCliTest, testConcurrent} from './shared/describe'
import {testServerCommand} from './shared/devServer'
Expand Down
2 changes: 1 addition & 1 deletion packages/@sanity/cli/test/shared/describe.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {describe, test} from '@jest/globals'
import {describe, test} from 'vitest'

import {cliUserToken, hasBuiltCli} from './environment'

Expand Down
86 changes: 84 additions & 2 deletions packages/@sanity/cli/test/shared/globalSetup.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
/* eslint-disable no-process-exit */
import {execFileSync, spawnSync} from 'node:child_process'
import {copyFile, mkdir, readFile, rename, stat, writeFile} from 'node:fs/promises'
import {copyFile, mkdir, readFile, rename, rm, stat, writeFile} from 'node:fs/promises'
import {hostname} from 'node:os'
import path from 'node:path'

import {createClient} from '@sanity/client'
import Configstore from 'configstore'
import {copy as copyCb} from 'cpx'

import {cleanupDangling} from './cleanupDangling'
import {
baseTestPath,
cliApiHost,
Expand All @@ -25,12 +26,13 @@ import {
packPath,
studiosPath,
studioVersions,
testClient,
testIdPath,
} from './environment'

const SYMLINK_SCRIPT = path.resolve(__dirname, '../../../../../scripts/symlinkDependencies.js')

export default async function globalSetup(): Promise<void> {
export async function setup(): Promise<void> {
// Write a file with the test id, so it can be shared across workers
const localHost = hostname().toLowerCase().split('.')[0]
const testId = `${localHost}-${process.ppid || process.pid}`
Expand Down Expand Up @@ -231,3 +233,83 @@ function copy(src: string, dest: string, options: {dereference?: boolean}): Prom
copyCb(src, dest, options, (err) => (err ? reject(err) : resolve())),
)
}

export async function teardown(): Promise<void> {
if (!cliUserToken || !hasBuiltCli) {
return
}

for (const version of studioVersions) {
const args = getTestRunArgs(version)
await deleteCorsOrigins(args.corsOrigin)
await deleteAliases(args.alias)
await deleteGraphQLAPIs(args.graphqlDataset)
await deleteDatasets(args)
}

await rm(baseTestPath, {recursive: true, force: true})

// Very hacky, but good enough for now:
// Force a cleanup of dangling entities left over from previous test runs
await cleanupDangling()
}

function getErrorWarner(entity: string, id: string) {
return (err: unknown) => {
if (err instanceof Error) {
console.warn(`WARN: ${entity} "${id}" cleanup failed: ${err.message}`)
} else {
console.warn(`WARN: ${entity} "${id}" cleanup failed: ${err}`)
}
}
}

async function deleteAliases(baseAlias: string) {
const aliases = await testClient.request<{name: string}[]>({url: '/aliases'})
const created = aliases.filter(({name}) => name.startsWith(baseAlias))
await Promise.all(
created.map((alias) =>
testClient
.request({method: 'DELETE', uri: `/aliases/${alias.name}`})
.catch(getErrorWarner('dataset alias', alias.name)),
),
)
}

async function deleteGraphQLAPIs(graphqlDataset: string) {
const apis = await testClient.request<{dataset: string; tag: string}[]>({url: '/apis/graphql'})
const created = apis.filter(({dataset}) => dataset === graphqlDataset)
await Promise.all(
created.map(({dataset, tag}) =>
testClient
.request({url: `/apis/graphql/${dataset}/${tag}`, method: 'DELETE'})
.catch(getErrorWarner('graphql api', `${dataset}/${tag}`)),
),
)
}

async function deleteCorsOrigins(baseOrigin: string) {
const origins = await testClient.request<{id: number; origin: string}[]>({url: '/cors'})
const created = origins.filter(({origin}) => origin.startsWith(baseOrigin))
await Promise.all(
created.map((origin) =>
testClient
.request({method: 'DELETE', uri: `/cors/${origin.id}`})
.catch(getErrorWarner('cors origin', origin.origin)),
),
)
}

async function deleteDatasets(args: ReturnType<typeof getTestRunArgs>) {
const datasets = [
args.dataset,
args.datasetCopy,
args.documentsDataset,
args.graphqlDataset,
args.aclDataset,
]

await Promise.all(
datasets.map((ds) => testClient.datasets.delete(ds).catch(getErrorWarner('dataset', ds))),
)
}
Loading

0 comments on commit c532a76

Please sign in to comment.