Skip to content

Commit

Permalink
Cleanup the test-utils package code
Browse files Browse the repository at this point in the history
  • Loading branch information
timleslie committed Jun 8, 2021
1 parent 12d2c02 commit 7560be3
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 39 deletions.
5 changes: 5 additions & 0 deletions .changeset/three-lemons-invent.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@keystone-next/test-utils-legacy': minor
---

Added exports for the `TestKeystoneConfig` and `Setup` types.
60 changes: 21 additions & 39 deletions packages/test-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,51 +13,48 @@ import {
requirePrismaClient,
generateNodeModulesArtifacts,
} from '@keystone-next/keystone/artifacts';
import type { KeystoneConfig, KeystoneContext } from '@keystone-next/types';
import type { DatabaseConfig, KeystoneConfig, KeystoneContext } from '@keystone-next/types';
import memoizeOne from 'memoize-one';

export type ProviderName = 'postgresql' | 'sqlite';
export type ProviderName = NonNullable<DatabaseConfig['provider']>;

const hashPrismaSchema = memoizeOne(prismaSchema =>
const _hashPrismaSchema = memoizeOne(prismaSchema =>
crypto.createHash('md5').update(prismaSchema).digest('hex')
);

// Users should use testConfig({ ... }) in place of config({ ... }) when setting up
// their system for test. We explicitly don't allow them to control the 'db' or 'ui'
// properties as we're going to set that up as part of setupFromConfig.
type TestKeystoneConfig = Omit<KeystoneConfig, 'db' | 'ui'>;
export type TestKeystoneConfig = Omit<KeystoneConfig, 'db' | 'ui'>;
export const testConfig = (config: TestKeystoneConfig) => config;

const alreadyGeneratedProjects = new Set<string>();
const _alreadyGeneratedProjects = new Set<string>();

async function setupFromConfig({
export async function setupFromConfig({
provider,
config: _config,
}: {
provider: ProviderName;
config: TestKeystoneConfig;
}) {
const enableLogging = false; // Turn this on if you need verbose debug info
const config = initConfig({
..._config,
db: {
url: process.env.DATABASE_URL!,
provider,
enableLogging: false, // Turn this on if you need verbose debug info
},
db: { url: process.env.DATABASE_URL!, provider, enableLogging },
ui: { isDisabled: true },
});

const { graphQLSchema, getKeystone } = createSystem(config);

const prismaClient = await (async () => {
const artifacts = await getCommittedArtifacts(graphQLSchema, config);
const hash = hashPrismaSchema(artifacts.prisma);
const hash = _hashPrismaSchema(artifacts.prisma);
if (provider === 'postgresql') {
config.db.url = `${config.db.url}?schema=${hash.toString()}`;
}
const cwd = path.resolve('.api-test-prisma-clients', hash);
if (!alreadyGeneratedProjects.has(hash)) {
alreadyGeneratedProjects.add(hash);
if (!_alreadyGeneratedProjects.has(hash)) {
_alreadyGeneratedProjects.add(hash);
fs.mkdirSync(cwd, { recursive: true });
await writeCommittedArtifacts(artifacts, cwd);
await generateNodeModulesArtifacts(graphQLSchema, config, cwd);
Expand All @@ -71,26 +68,15 @@ async function setupFromConfig({
return requirePrismaClient(cwd);
})();

const keystone = getKeystone(prismaClient);

const app = await createExpressServer(
config,
graphQLSchema,
keystone.createContext,
true,
'',
false
);

return {
connect: () => keystone.connect(),
disconnect: () => keystone.disconnect(),
context: keystone.createContext().sudo(),
app,
};
const { connect, disconnect, createContext } = getKeystone(prismaClient);

// (config, graphQLSchema, createContext, dev, projectAdminPath, isVerbose)
const app = await createExpressServer(config, graphQLSchema, createContext, true, '', false);

return { connect, disconnect, context: createContext().sudo(), app };
}

function networkedGraphqlRequest({
export function networkedGraphqlRequest({
app,
query,
variables = undefined,
Expand All @@ -115,12 +101,10 @@ function networkedGraphqlRequest({
expect(res.statusCode).toBe(expectedStatusCode);
return { ...JSON.parse(res.text), res };
})
.catch((error: Error) => ({
errors: [error],
}));
.catch((error: Error) => ({ errors: [error] }));
}

type Setup = {
export type Setup = {
connect: () => Promise<void>;
disconnect: () => Promise<void>;
context: KeystoneContext;
Expand Down Expand Up @@ -173,7 +157,7 @@ function _after(tearDownFunction: () => Promise<void> | void) {
};
}

function multiAdapterRunners(only = process.env.TEST_ADAPTER) {
export function multiAdapterRunners(only = process.env.TEST_ADAPTER) {
return (['postgresql', 'sqlite'] as const)
.filter(provider => typeof only === 'undefined' || provider === only)
.map(provider => ({
Expand All @@ -183,5 +167,3 @@ function multiAdapterRunners(only = process.env.TEST_ADAPTER) {
after: _after(() => {}),
}));
}

export { setupFromConfig, multiAdapterRunners, networkedGraphqlRequest };

0 comments on commit 7560be3

Please sign in to comment.