• Stars
    star
    111
  • Rank 303,710 (Top 7 %)
  • Language
    TypeScript
  • Created almost 5 years ago
  • Updated 10 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A collection of data model agnostic test utils.

๐Ÿƒ prisma-test-utils

npm version CircleCI codecov

โš ๏ธ This project is temporarily unmaintained. See this issue.

In testing workflows, generating seed data usually includes a lot of boilerplate and hardcoded fixtures that need to be migrated with changing code.

prisma-test-utils solves this by generating test util functions based on your Prisma Schema. As your application evolves, the generated data also evolves deterministically.

Features

  • ๐Ÿ™ˆ Data model agnostic: Optimised for you datamodel.
  • ๐Ÿฆ‘ Flexible: Cherry picked default settings.
  • ๐Ÿถ Out-of-the-box usage: Plug-in generator for your Prisma Schema.
  • ๐Ÿ  Seeds mock data: Populates your database with mock data.
  • ๐Ÿฆ‹ Per-test database: Creates an isolated database for each test.

Installation

TBD

Configuration

generator testutils {
  provider = "prisma-test-utils"
  output = "node_modules/@generated/prisma-test-utils"
}

Usage

prisma-test-utils packs two incredibly useful functions. The first one, seed, helps you populate your data with vast amount of data. The second one, pool, can be used to create a pool of databases that you can use during testing, and are wiped after you've finished.

Seeding

import Photon from '@generated/photon'
import seed from '@generated/test-utils/seed'

test('test with seed data', async () => {
  await seed({
    client,
    models: kit => ({
      _: {
        /* Default number of instances. */
        amount: 500,
      },
      Blog: {
        factory: {
          /* Use functions from the kit. */
          name: kit.faker.sentence,
          /* Define custom mocks. */
          description: 'My custom blog description',
          /* Define custom mock functions. */
          entry: () => {
            return `A generated entry from the function.`
          },
          /* Manage relations. */
          posts: {
            max: 100,
          },
        },
      },
    }),
  })

  const blogs = await client.blogs()
})

Options

It is possible to selectively override the seed generation making the seeding workflow very flexible.

All options are autogenerated and checked at compile time. You'll be warned about any relation constraints that your datamodel presents.

beforeAll(async () => {
  const data = await seed(
    photon,
    bag => ({
      Post: {
        amount: 5,
        factory: {
          published: 'false',
        },
      },
    }),
    {
      seed: 42,
      silent: false,
      instances: 5,
    },
  )
})

Database Pools

We can configure our pool requirements before running any test cases.

import SQLitePool, { Pool } from '@generated/prisma-test-utils'

let pool: Pool

beforeAll(async () => {
  pool = new SQLitePool({
    pool: {
      min: 3,
      max: 5,
    },
  })
})

This allows us to request an isolated database per test case

test('one of my parallel tests', async () => {
  /* Acquire new db instance. */
  const db = await pool.getDBInstance()

  // Write the test case logic
  const client = new Photon({
    datasources: {
      db: db.url,
    },
  })

  /* Release the instance. */
  client.disconnect()
  pool.releaseDBInstance(db)
})

API

/* All pool instances. */

class Pool {
  async getDBInstance(): Promise<DBInstance>
  async releaseDBInstance(db: DBInstance): Promise<void>
  async run<T>(fn: (db: DBInstance) => Promise<T>): Promise<T>
  async drain(): Promise<void>
}

/* PostgreSQL */

interface PostgreSQLConnection {
  host: string
  port: number
  user: string
  password?: string
  database: string
  schema: string
}

interface PostgreSQLPoolOptions {
  connection: (id: string) => PostgreSQLConnection
  pool?: {
    max?: number
  }
}

/* MySQL */

interface MySQLConnection {
  host: string
  port: string
  user: string
  password?: string
  database: string
}

interface MySQLPoolOptions {
  connection: (id string) => MySQLConnection
  pool?: {
    max?: number
  }
}

/* SQLite */

interface SQLitePoolOptions {
  databasePath: (id: string) => string
  pool?: {
    max?: number
  }
}

Local development

๐Ÿšง NOTE: Please comment your work and read the comments that are already in there.

I didn't want to remove half the files of this library - the pool part - and that's why there's more files than you'll usually need for developing seed utils. Please don't remove the extra files as this work very nicely the way it is.

The most important file for seeding is src/static/seed.ts and src/intellisense/seed.ts. The first one is the logic and the second one provides customized types.

Furthermore:

  • To create a new DB instance: Spin up the docker-compose up -d and use TablePlus or alternative to import the sql.

  • To examine the behaviour of the library: Uncomment src/__test file and start the debugger. src/__test file references files in the tests/seed folder. Read on about that!

  • To setup tests/seed folder: Navigate to that directory and use yarn prisma2 <cmd> to setup everything that you need. I usually use one of these functions:

    • yarn prisma2 introspect yarn prisma2 introspect --url="postgresql://prisma:[email protected]/ruma"
    • yarn prisma2 migrate up --experimental
    • yarn prisma2 migrate save --name "init" --experimental
    • yarn prisma2 generate. I have also added the README.md file in there with missing generator definitions from introspection. Copy and paste them to the top.
  • To push changes: Preferablly do a PR, and don't forget to comment out src/__test file.

  • To publish a new version: I use npx np --no-tests.

  • To apply changes in the intellisense: Run yarn build.

  • To test the utils outside debugger: Run yarn build:runtime.

  • To get new VSCode type definitions after changing the schema: Reload VSCode ๐Ÿ™‚

Security

If you have a security issue to report, please contact us at [email protected]

LICENSE

MIT @ Prisma

More Repositories

1

prisma

Next-generation ORM for Node.js & TypeScript | PostgreSQL, MySQL, MariaDB, SQL Server, SQLite, MongoDB and CockroachDB
TypeScript
36,195
star
2

prisma1

๐Ÿ’พ Database Tools incl. ORM, Migrations and Admin UI (Postgres, MySQL & MongoDB) [deprecated]
Scala
16,608
star
3

prisma-examples

๐Ÿš€ Ready-to-run Prisma example projects
TypeScript
5,760
star
4

studio

๐ŸŽ™๏ธ The easiest way to explore and manipulate your data in all of your Prisma projects.
1,722
star
5

prisma-client-js

Type-safe database client for TypeScript & Node.js (ORM replacement)
TypeScript
1,466
star
6

prisma-engines

๐Ÿš‚ Engine components of Prisma ORM
Rust
1,095
star
7

docs

๐Ÿ“š Prisma Documentation
MDX
940
star
8

migrate

Issues for Prisma Migrate are now tracked at prisma/prisma. This repo was used to track issues for Prisma Migrate Experimental and is now deprecated.
TypeScript
766
star
9

quaint

SQL Query AST and Visitor for Rust
Rust
583
star
10

tiberius

TDS 7.2+ (Microsoft SQL Server) driver for Rust
Rust
291
star
11

lens

๐Ÿ”ฌ Prisma design system
TypeScript
287
star
12

language-tools

๐ŸŒ Prisma Language Tools = Language Server and Prisma's VS Code extension.
TypeScript
243
star
13

awesome-links

Users browse through a list of curated links and bookmark their favorite ones. Code for prisma.io course.
TypeScript
199
star
14

ecosystem-tests

๐Ÿฅผ๐Ÿงฌ๐Ÿงช๐Ÿ”ฌ๐Ÿงซ๐Ÿฆ  - Continuously tests Prisma Client with various operating systems, frameworks, platforms, databases and more.
JavaScript
180
star
15

database-schema-examples

Database Schema Examples we strive to support in Prisma
TSQL
171
star
16

dataguide

๐Ÿ—„๏ธ Prisma's Data Guide - A growing library of articles focused on making databases more approachable.
MDX
142
star
17

prisma-client-extensions

Examples of Prisma Client extensions.
TypeScript
130
star
18

blog-backend-rest-api-nestjs-prisma

A simple backend REST API for a blog built using NestJS, Prisma, PostgreSQL and Swagger.
TypeScript
130
star
19

blogr-nextjs-prisma

TypeScript
107
star
20

specs

โš  This repository is not actively used any more, please check out the Prisma Documentation for updated information on Prisma. โš 
Go
87
star
21

fullstack-prisma-nextjs-blog

Fullstack Blog with Next.js and Prisma
TypeScript
85
star
22

extension-read-replicas

Prisma Client Extension to add read replica support to your Prisma Client
TypeScript
84
star
23

deployment-example-vercel

Prisma deployment to Vercel example
JavaScript
74
star
24

text-editors

TypeScript
73
star
25

faunadb-rust

FaundaDB client for Rust
Rust
62
star
26

prisma-templates

Prisma templates for major cloud providers
52
star
27

prisma1-upgrade

Prisma 1 Upgrade is a CLI tool to help Prisma 1 users upgrade to Prisma 2.x or newer.
TypeScript
51
star
28

try-prisma

TypeScript
45
star
29

women-world-wide

JavaScript
41
star
30

codemods

A Collection of Codemods for Prisma 2
JavaScript
34
star
31

vim-prisma

Prisma support for Vim
Vim Script
32
star
32

nestjs-workshop-prisma-day-22

REST API for a rudimentary blog - from Prisma Day 22 NestJS workshop
TypeScript
25
star
33

prisma-nuxt

Prisma example showing how to use Prisma in a Nuxt application.
Vue
25
star
34

engines-wrapper

๐ŸŒฏ @prisma/engines-version npm package
TypeScript
20
star
35

accelerate-speed-test

TypeScript
18
star
36

deployment-example-netlify

Prisma deployment to Netlify example
JavaScript
16
star
37

quickstart

๐Ÿ Starter templates for the 5min Quickstart in the Prisma docs.
JavaScript
16
star
38

prisma-edge-functions

TypeScript
15
star
39

studio-vercel-guide

A guide to deploying Studio alongside your app on Vercel
JavaScript
13
star
40

prisma-fmt-wasm

๐Ÿ’พ Build and release automation for @prisma/prisma-fmt-wasm
Shell
12
star
41

ent

An entity layer for Prisma 1 that uses the DataMapper pattern.
TypeScript
12
star
42

connection-string

connection-string + @pimeys/connection-string
Rust
12
star
43

reflector

๐Ÿชž Utilities for meta-level interactions with the Prisma toolkit in Node.js.
TypeScript
12
star
44

engine-images

๐Ÿ–ผ๏ธ Build & test images for Prisma engines.
Shell
11
star
45

prisma-client-extension-starter

Starter template repository for building publishable Prisma Client extensions
TypeScript
10
star
46

prisma1-json-schema

JSON schema of prisma.yml files
TypeScript
10
star
47

eslint-config-prisma

๐Ÿงน Prisma's .eslintrc as an extensible shared config.
JavaScript
10
star
48

templates

Prisma templates packaged up for programatic consumption.
TypeScript
10
star
49

styles

Shared style resources between Graphcool projects
CSS
9
star
50

demo-sveltekit

Demo app for Sveltekit article
Svelte
8
star
51

pris.ly

Prisma shortlink service (hosted on Vercel)
7
star
52

prisma1-examples

TypeScript
7
star
53

prisma2-development-environment

This project combines prisma2, lift and photonjs into one workspace, builds and installs all dependencies for you.
TypeScript
7
star
54

sublimeText3

Sublime Text 3 package supporting syntax highlighting.
6
star
55

migrate-from-sequelize-to-prisma

A migration guide from Sequelize to Prisma example
JavaScript
6
star
56

pulse-starter

A Pulse starter project. To be used inside of a railway.app template, locally, or with another Pulse-ready database.
TypeScript
6
star
57

opentls

TLS connections for Rust using OpenSSL
Rust
6
star
58

prisma-admin-custom-components

Examples of custom components for Prisma Admin
JavaScript
6
star
59

prisma-content-feedback

Feedback for documentation, articles, tutorials, examples, ...
6
star
60

prisma-admin-feedback

Feedback for Prisma Admin (currently in invite-only preview)
6
star
61

prisma-1-cloud-feedback

Feedback for Prisma Cloud
5
star
62

migrate-from-typeorm-to-prisma

TypeScript
5
star
63

binding-argument-transform

A library to make Prisma 1 arguments compatible with Prisma 2.
TypeScript
5
star
64

pulse-starter-old

A starter project to get you up and running with pulse.
TypeScript
4
star
65

nextjs-edge-functions

Demo of using Next.js with Prisma ORM deployed to Vercel Edge Functions
TypeScript
4
star
66

prisma-day

Prisma Day Code of Conduct
4
star
67

prisma-read-replica-middleware

TypeScript
4
star
68

prisma-platformatic

Prisma ๐Ÿ’š Platformatic exploration
JavaScript
4
star
69

p1-to-p2-upgrade-path-feedback

4
star
70

presskit

Presskit for Prisma
3
star
71

deployment-example-cloudflare-workers

Cloudflare workers deployment example
TypeScript
3
star
72

prisma-example-starter-template

3
star
73

metrics-tutorial-prisma

Database Metrics with Prisma, Prometheus & Grafana
TypeScript
3
star
74

tech-writer-task-template

This repository is a template for Technical Writer candidates to use.
JavaScript
3
star
75

read-replicas-demo

TypeScript
2
star
76

pulse-railway-pg-config

A railway.app project template. Contains a Pulse ready postgres database and set up service. Read more about pulse
TypeScript
2
star
77

db-push-non-idempotent-schemas

Collection of schemas that don't roundtrip if you db pull, then db push
Nix
2
star
78

prisma-indexes

TypeScript
2
star
79

prisma-fundamentals

An Instruqt lab to introduce students to the Prisma Schema
Shell
2
star
80

.github

Org level configuration for installed GitHub apps
2
star
81

benching_setup

TypeScript
2
star
82

migrate-from-mongoose-to-prisma

JavaScript
1
star
83

prisma-client-lib-go

Runtime of Prisma (v1) Go Client.
Go
1
star
84

fivetran-npm-downloads

Python
1
star
85

fullstack-prisma-turso

TypeScript
1
star
86

accelerate-nextjs-starter

TypeScript
1
star
87

fullstack-prisma-turso-embedded-db

TypeScript
1
star
88

ci-reports

Repository for various reports from pull requests
HTML
1
star
89

pulse-resend-demo

TypeScript
1
star
90

deployment-example-lambda-serverless-framework

TypeScript
1
star
91

language-tools-gitpod

Shell
1
star
92

test-vercel-access

HTML
1
star
93

client-planning

Placeholder repository for client planning tickets
1
star
94

action-node-cache-dependencies

Install and cache node modules.
1
star
95

docs-tools

Python
1
star
96

orm-cloudflare-worker-list-binaries

A cloudflare worker to list the contents of the `prisma-builds` bucket
TypeScript
1
star
97

tracing-tutorial-prisma

Reference code for "Get Started With Tracing Using OpenTelemetry and Prisma Tracing".
TypeScript
1
star
98

react-native-prisma

TypeScript
1
star
99

pdp-spike-nextjs-opentelemetry

TypeScript
1
star