denodrivers / postgres

PostgreSQL driver for Deno

Home Page:https://denodrivers.github.io/postgres

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Test failing when using pool: AssertionError: Test case is leaking async ops.

TriForMine opened this issue · comments

When using a pool client connection in a deno test, the test will fail with the following error:

AssertionError: Test case is leaking async ops.

Code used:

import { assertEquals } from "https://deno.land/std@0.88.0/testing/asserts.ts";
import { Pool } from "https://deno.land/x/postgres/mod.ts";
import { PoolClient } from "https://deno.land/x/postgres/client.ts";

const dbPool = new Pool({
    hostname: "HOSTNAME",
    user: "USER",
    password: "PASSWORD",
    database: "DATABASE",
    port: 6432
}, 1);

Deno.test("Get one character", async () => {
    const client: PoolClient = await dbPool.connect();
    const characters = await client.queryObject<{ id: number, color: string, name: string, images: string[] }>(
        `SELECT "id", "color", "name", "images" FROM "characters" LIMIT 1;`,
    );
    await client.release();
    assertEquals(characters.rows.length, 1);
});

Hmm, I think you need to instantiate Pool inside a test function and call Pool.end like this:

Deno.test("Get one character", async () => {
    const dbPool = new Pool({
        hostname: "HOSTNAME",
        user: "USER",
        password: "PASSWORD",
        database: "DATABASE",
        port: 6432
    }, 1);
    try {
        const client: PoolClient = await dbPool.connect();
        const characters = await client.queryObject<{ id: number, color: string, name: string, images: string[] }>(
            `SELECT "id", "color", "name", "images" FROM "characters" LIMIT 1;`,
        );
        await client.release();
        assertEquals(characters.rows.length, 1);
    } finally {
        await dbPool.end();
    }
});

A pool opens all connections at the moment you instantiate new Pool, so when Deno runs the Test, it detects that in your case you had one connection open after the test has finished, triggering the error.

In order to solve this, you can abstract the whole process with a function similar to the following

function testPool(
  t: (pool: Pool) => void | Promise<void>,
) {
  const fn = async () => {
    const POOL = new Pool(your_configuration, 1);
    try {
      await t(POOL);
    } finally {
      await POOL.end();
    }
  };
  const name = t.name;
  Deno.test({ fn, name });
}

And use it like this:

testPool(async function simpleQuery(POOL) {
  const client = await POOL.connect();
  const result = await client.queryArray`SELECT * FROM ids`;
  assertEquals(result.rows.length, 2);
  await client.release();
});

That way all the connections you need are created only when you need them and you can do this for as many tests as you want without writing more