npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, πŸ‘‹, I’m Ryan HefnerΒ  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you πŸ™

Β© 2024 – Pkg Stats / Ryan Hefner

ava-postgres

v7.3.1

Published

`ava-postgres` is a test fixture for [AVA](https://github.com/avajs/ava) that provides you with nearly-instant access to a fresh Postgres database for every test.

Downloads

13,261

Readme

ava-postgres

ava-postgres is a test fixture for AVA that provides you with nearly-instant access to a fresh Postgres database for every test.

ava-postgres's only dependency is a running instance of Docker.

Installation

npm install --save-dev ava-postgres

or

yarn add --dev ava-postgres

Usage

ava-postgres's main export is a factory function, so you'll probably want to create a file like tests/fixtures/get-test-database.ts:

import { getTestPostgresDatabaseFactory } from "ava-postgres"

export const getTestDatabase = getTestPostgresDatabaseFactory({
  // Any tag for the official Postgres Docker image, defaults to "14"
  postgresVersion: "14",
})

Then, in your tests, you can use the getTestDatabase() function to get a fresh database for each test:

import test from "ava"
import { getTestDatabase } from "./fixtures/get-test-database"

test("foo bar", async (t) => {
  const { pool } = await getTestDatabase()

  await pool.query("SELECT 1")

  t.pass()
})

Full list of connection details returned by getTestDatabase

Database setup

ava-postgres uses Postgres templates so you only pay the setup cost once. After a template has been created, Postgres can create a new database from it in milliseconds.

If you want to perform common database setup, you can use a hook and pass parameters to the getTestDatabase() function:

import { getTestPostgresDatabaseFactory } from "ava-postgres"

type GetTestDatabaseParams = {
  shouldMigrate?: boolean
  shouldSeed?: boolean
}

export const getTestDatabase =
  getTestPostgresDatabaseFactory<GetTestDatabaseParams>({
    beforeTemplateIsBaked: async ({
      connection: { pool },
      params: { shouldMigrate, shouldSeed },
    }) => {
      if (shouldMigrate) {
        await pool.query("CREATE TABLE foo (id int)")
      }

      if (shouldSeed) {
        await pool.query("INSERT INTO foo VALUES (1)")
      }
    },
  })

Then, in your tests, you can pass parameters to the getTestDatabase() function:

import test from "ava"
import { getTestDatabase } from "./fixtures/get-test-database"

test("foo bar", async (t) => {
  const { pool } = await getTestDatabase({
    shouldMigrate: true,
    shouldSeed: true,
  })

  await pool.query("SELECT * FROM foo")

  t.pass()
})

Advanced Usage

Postgres container de-duping

In rare cases, you may want to spawn more than one Postgres container.

Internally, this library uses an AVA "shared worker". A shared worker is a singleton shared with the entire running test suite, and so one ava-postgres shared worker maps to exactly one Postgres container.

To spawn separate shared workers and thus additional Postgres containers, you have two options:

Specify different version strings for the postgresVersion option in the factory function:

const getTestPostgresDatabase = getTestPostgresDatabaseFactory({
  postgresVersion: "14",
})

Each unique version will map to a unique shared worker.

Set the workerDedupeKey option in the factory function:

const getTestPostgresDatabase = getTestPostgresDatabaseFactory({
  workerDedupeKey: "foo",
})

Each unique key will map to a unique shared worker.

Database de-duping

By default, ava-postgres will create a new database for each test. If you want to share a database between tests, you can use the databaseDedupeKey option:

import test from "ava"
const getTestPostgresDatabase = getTestPostgresDatabaseFactory({})

test("foo", async (t) => {
  const connection1 = await getTestPostgresDatabase(t, null, {
    databaseDedupeKey: "foo",
  })
  const connection2 = await getTestPostgresDatabase(t, null, {
    databaseDedupeKey: "foo",
  })
  t.is(connection1.database, connection2.database)
})

This works across the entire test suite.

Note that if unique parameters are passed to the beforeTemplateIsBaked (null in the above example), separate databases will still be created.

Manual template creation

In some cases, if you do extensive setup in your beforeTemplateIsBaked hook, you might want to obtain a separate, additional database within it if your application uses several databases for different purposes. This is possible by using the manuallyBuildAdditionalTemplate() function passed to your hook callback:

import test from "ava"

const getTestDatabase = getTestPostgresDatabaseFactory<DatabaseParams>({
  beforeTemplateIsBaked: async ({
    params,
    connection: { pool },
    manuallyBuildAdditionalTemplate,
  }) => {
    await pool.query(`CREATE TABLE "bar" ("id" SERIAL PRIMARY KEY)`)

    const fooTemplateBuilder = await manuallyBuildAdditionalTemplate()
    await fooTemplateBuilder.connection.pool.query(
      `CREATE TABLE "foo" ("id" SERIAL PRIMARY KEY)`
    )
    const { templateName: fooTemplateName } = await fooTemplateBuilder.finish()

    return { fooTemplateName }
  },
})

test("foo", async (t) => {
  const barDatabase = await getTestDatabase({ type: "bar" })

  // the "bar" database has the "bar" table...
  await t.notThrowsAsync(async () => {
    await barDatabase.pool.query(`SELECT * FROM "bar"`)
  })

  // ...but not the "foo" table...
  await t.throwsAsync(async () => {
    await barDatabase.pool.query(`SELECT * FROM "foo"`)
  })

  // ...and we can obtain a separate database with the "foo" table
  const fooDatabase = await getTestDatabase.fromTemplate(
    t,
    barDatabase.beforeTemplateIsBakedResult.fooTemplateName
  )
  await t.notThrowsAsync(async () => {
    await fooDatabase.pool.query(`SELECT * FROM "foo"`)
  })
})

Bind mounts & execing in the container

ava-postgres uses testcontainers under the hood to manage the Postgres container.

In some scenarios you might want to mount a SQL script into the container and manually load it using psql.

You can do this with the bindMounts option:

const getTestPostgresDatabase = getTestPostgresDatabaseFactory({
  container: {
    bindMounts: [
      {
        source: "/path/on/host",
        target: "/test.sql",
      },
    ],
  },
  beforeTemplateIsBaked: async ({
    connection: { username, database },
    containerExec,
  }) => {
    const { exitCode } = await containerExec(
      `psql -U ${username} -d ${database} -f /test.sql`.split(" ")
    )

    if (exitCode !== 0) {
      throw new Error(`Failed to load test file`)
    }
  },
})