Mulf's Musings

REST API Testing

Admittedly, I have skipped testing for a large part of my time writing code. Not on everything - smart contracts get extensive unit, fuzz, and invariant testing. But REST APIs, a lot less so.

Such is the life of a dev in a startup. API contracts and boundaries do not much matter when the motto is move fast and break things - just send the fix with the PR. The only users of the endpoint are the company devs so you just patch all places its called and move on. So I decided to fill in some gaps of my experience and understanding.

Baseline

Typescript is my sharpest tool so that is the code you will see below. The methodology will translate to whatever language and stack you prefer. Our test framework is the venerable Vitest, although the built in Nodejs test runner has come along way. And based on what I am seeing in the v26 docs, many of the things i like about Vitest are either experimental or in early development. I have been through a few iterations of testing frameworks, but I always prefer a standard library/runtime option if I can get it. But for now we press on.

Why and What to Test

For the purposes of this post we shall keep it simple. A user resource for authentication with get and post methods. A user should be able to sign up and log in. Also, we will want to check the users session is still valid before doing certain protected operations.

Some quick example code:

app.post("/", { schema: userSchema }, async (req, res) => {
        const hashedPw = await hash(req.body.password);
        await db
            .insert(user)
            .values({ email: req.body.email.trim().toLowerCase(), password: hashedPw });
        return res.code(201).send({ message: "user created" });
    });
    app.post("/login", { schema: userSchema }, async (req, res) => {
        const [foundUser] = await db
            .select()
            .from(user)
            .where(eq(user.email, req.body.email.toLowerCase()));

        if (!foundUser) {
            throw new ApiError("user not found", 404);
        }

        const doesPasswordMatch = await verify(foundUser.password, req.body.password);

        if (!doesPasswordMatch) {
            throw new ApiError("incorrect username or password", 401);
        }

        await req.session.regenerate();
        req.session.set("userId", foundUser.id);
        return res.send({ message: "logged in" });
    });
    app.post("/logout", async (req, res) => {
        await req.session.destroy();
        return res.send({ message: "logged out" });
    });
    app.get("/me", async (req, res) => {
        const userId = req.session.userId;
        if (!userId) {
            throw new ApiError("not logged in", 400);
        }
        const cookie = req.session.cookie;
        if (!cookie?.expires) {
            throw new ApiError("bad session", 400);
        }
        const sessionExpiresTimestamp = Date.parse(cookie.expires.toString());

        if (sessionExpiresTimestamp <= Date.now()) {
            await req.session.destroy();
            throw new ApiError("session expired", 400);
        }

        res.send({ message: "validated" });
    });
});

You may notice a lack of try/catch in this code. That is intentional and a benefit of our framework of choice - fastify. It may appear that i have not validated this input at all, but we are use route level schema validation to ensure our handler doesn't run unless the shape of an incoming request is correct.

const userSchema = {
  body: {
    type: "object",
    required: ["email", "password"],
    properties: {
      email: {
        type: "string",
        maxLength: 128,
        minLength: 4,
        pattern: "^[^@\\s]+@[^@\\s]+\\.[^@\\s]+$",
      },
      password: {
        type: "string",
        maxLength: 128,
        minLength: 12,
      },
    },
  },
} as const;

Also this code doesn't show the enforcement of constraints that have been encoded into the table in Postgres.

CREATE TABLE "user" (
    id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
    email TEXT UNIQUE NOT NULL,
    password TEXT NOT NULL,
    CONSTRAINT email_length CHECK (length("email") >= 4 AND length("email") <= 128),
    CONSTRAINT email_lower CHECK (email = lower(email)),
    CONSTRAINT password_length CHECK (length(password) = 97)
);

Any violation of the constraints or schema get bubbled up to our centralized error handling meaning we don't have to write as much boilerplate. Its a nice QoL improvement and means we can keep route code mostly business logic focused. The error handler is a mapping of some the C style error codes from Postgres to a HTTP status code and message that correlates to the supplied error. Explicit use of ApiError which is a custom error that inherits from the Error base class passes through the top level error handling untouched.

This bubbling up also handles any other case that we have not accounted for too. Any exception that gets thrown and that is not mapped by the ApiError class gets a generic 500 HTTP response and message. Nothing important leaks and the full trace ends up in a log file. There are far too many possible errors just in Postgres to handle everything.

The password length may look weird there but the length of the string from our hash operation will always be that length and if not, something has gone very wrong. I see many folks writing app code for these constraints, just let Postgres do it for you.

Test Infrastructure

I believe when testing your application code that you should avoid mocking. Mocks are some weird parallel universe of your code that only exists in tests and do not in fact test your system. The goal should be to emulate the real world as close to 1:1 as possible.

However, if your system integrates with outside services, obviously you will need to mock. Complex workflows of interdependent systems are out of scope for us. We are looking specifically at code we run and control. Maybe I will write a follow up on effective mocking.

With that said, this is a good time to introduce testcontainers. This library allows us to spin up a database just for testing purposes (and a lot more). It's a docker control plane basically that makes setup and teardown wonderfully easy.

We have a migrations directory which holds our SQL files. In a setup file defined in our Vitest config for the globalSetup option we have the following:

import {
  PostgreSqlContainer,
  type StartedPostgreSqlContainer,
} from "@testcontainers/postgresql";
import path from "node:path";
import type { TestProject } from "vitest/node";

declare module "vitest" {
  export interface ProvidedContext {
    databaseUrl: string;
  }
}

let postgresContainer: StartedPostgreSqlContainer;

export async function setup(project: TestProject) {
  postgresContainer = await new PostgreSqlContainer("postgres:18-alpine")
    .withCopyDirectoriesToContainer([
      {
        source: path.resolve(import.meta.dirname, "../../db/migrations"),
        target: "/docker-entrypoint-initdb.d",
      },
    ])
    .start();

  project.provide("databaseUrl", postgresContainer.getConnectionUri());
}

export async function teardown() {
  await postgresContainer.stop();
}

By convention for the SQL based docker images I reviewed (Postgres, MySQL, Maria) - they look for this directory: /docker-entrypoint-initdb.d which on startup of the container will run our migrations for us since that is what is being copied. And then executed by psql -f <filename> so we have a real, working DB not much different than what production will look like.

Using the provide function we are able to inject the database URL into our test suite so that we can access the running container.

A few more odds and ends; I like signed session cookies, so I needed a way to validate that the cookie was being set when login was successful. Fetch-cookie handles this nicely. From their docs:

fetch-cookie wraps around a fetch function and intercepts request options and response objects to store received cookies and populate request with the appropriate cookies.

And that's exactly what we need. It also uses tough-cookie which handles all of the cookie jar related functionality.

Testing the User Endpoints

The setup code is a bit messy here but let's have a look and then walk through it.

import { expect, test, beforeAll, afterAll, inject } from "vitest";
import { user } from "../src/drizzle/schema.ts";
import { eq } from "drizzle-orm";
import makeFetchCookie from "fetch-cookie";

process.env["DATABASE_URL"] = inject("DATABASE_URL");

const { db } = await import("../src/db.ts");
const { setupServer } = await import("../src/server.ts");

let app: ReturnType<typeof setupServer>;
let client = makeFetchCookie(fetch);

function selectPort(min: number, max: number) {
  return Math.floor(Math.random() * (max - min) + min);
}

const randomPort = selectPort(4000, 7000);

beforeAll(() => {
  client = makeFetchCookie(fetch, new makeFetchCookie.toughCookie.CookieJar());
  app = setupServer();
  app.listen({ port: randomPort, host: "0.0.0.0" }, function (err) {
    if (err) {
      console.error(err);
      process.exit(1);
    }
  });
});

afterAll(async () => {
  await app.close();
});

async function fetcher(
  route: string,
  data?: Record<string, unknown>,
  method?: "POST" | "PATCH",
) {
  const res = await client(`http://localhost:${randomPort}${route}`, {
    method: method ? method : "GET",
    body: method === "POST" || method === "PATCH" ? JSON.stringify(data) : null,
    headers: {
      "Content-Type": "application/json",
    },
  });

  return res;
}

type Credentials = { email: string; password: string };

let userSeq = 0;

function makeUser(overrides: Partial<Credentials> = {}): Credentials {
  userSeq += 1;
  return {
    email: `user${userSeq}@test.com`,
    password: "n23j45io34io3j4io",
    ...overrides,
  };
}

async function createUser(creds: Credentials = makeUser()) {
  return fetcher("/user", creds, "POST");
}

async function login(creds: Credentials = makeUser()) {
  return fetcher("/user/login", creds, "POST");
}

test("can create a new user", async () => {
  const res = await createUser();
  const data = await res.json();

  expect(data).toStrictEqual({ message: "user created" });
});

test("email is lowercased before insert", async () => {
  await createUser(makeUser({ email: "USER@USER.COM" }));

  const [returnedUser] = await db
    .select()
    .from(user)
    .where(eq(user.email, "user@user.com"));
  if (!returnedUser) throw new Error("Could not insert user");
  expect(returnedUser.email).toEqual("user@user.com");
});

test("can login and create new session", async () => {
  const creds = makeUser();
  await createUser(creds);

  const res = await login(creds);

  const cookies = res.headers.getSetCookie();
  expect(cookies.some((c) => c.startsWith("sessionId="))).toBe(true);
});

test("unregistered user cannot log in", async () => {
  const res = await login(makeUser({ email: "notfound@email.com" }));

  expect(res.ok).toBe(false);

  const data = await res.json();
  expect(data).toStrictEqual({
    message: "user not found",
  });
});

The first few lines are normal imports. But then we use the DATABASE_URL injected from the global setup to set our database URL environment variables. Then, we dynamically import our db client and app server. We do this because import declarations are hoisted for ECMAScript (es6 and later) modules. And since the import for the server and the db client would be evaluated before vitest has made the DATABASE_URL available to us, we get an error. More about importing modules here.

A random port is also selected between 4000 and 7000 so that we can run tests in parallel if we want and each set of tests will get their own isolated instance so that all the running tests are clobbering the same instance. There is a bit of overhead to this approach. If that is an issue in your test environment you can skip the server initialization by using a testing strategy based around fastify's inject functionality.

Before all of these test run we also wrap the built-in fetch client with our fetch-cookie library and instantiate the API server. And of course, we clean up behind ourselves after all the tests have run by shutting down the server too. And then lastly, our teardown function runs which will kill the running db container so you don't end up with a bunch of orphaned, running containers.

And now with everything finally set up, you are able to assert all of your test cases with a fully running server and db. I set up a few helper functions to reduce the hard coding of user info and a reusable fetcher with the base URL defined. Just some nice to haves really and not required. You could also use the globalSetup to seed data as well if you like so you do not have to run your tests in a specific order like we did here.

The tests defined here are certainly not exhaustive but serve their purpose to show you how to get up and running.

See Also

We only used testcontainers for Postgres in this exercise but it can do a lot more. Like, a lot more. If you wanted to add caching with Redis to your server, they have an option for that. Memcached? Also, yes. They aren't paying me or anything, I was just glad to find out about them since it makes testing so much easier.

Thank you for making it this far. We did not cover anything new or novel here and that was by design. As I mentioned at the outset, I am filling in the gaps of my own knowledge. Engaging in the act of writing about testing helped me uncover some of the elements I still didn't fully understand even after setting up and writing those tests.

I hope you came away with something useful and that this may inspire you to test both more and better.