akshayjshah / attest

Type-safe assertion helpers for Go
https://pkg.go.dev/go.akshayshah.org/attest
MIT License
15 stars 2 forks source link
assert generics go testing

attest

Build Report Card GoDoc

attest is a small package of type-safe assertion helpers. Under the hood, it uses cmp for equality testing and diffing. You may enjoy attest if you prefer:

Installation

go get go.akshayshah.org/attest

Usage

package main

import (
  "testing"
  "time"

  "go.akshayshah.org/attest"
)

func TestExample(t *testing.T) {
  attest.Equal(t, 1, 1)
  attest.NotEqual(t, 2, 1)
  attest.Approximately(
    t,
    time.Minute - 1, // got
    time.Minute,     // want
    time.Second,     // tolerance
  )
  attest.Zero(t, "")
  attest.Contains(t, []int{0, 1, 2}, 2)

  var err error
  attest.Ok(t, err)
  err = fmt.Errorf("read config: %w", io.EOF)
  attest.Error(t, err)
  attest.ErrorIs(t, err, io.EOF)

  // You can enrich the default failure message.
  attest.Equal(t, 1, 2, attest.Sprintf("integer %s", "addition"))

  // The next two assertions won't compile.
  attest.Equal(t, int64(1), int(1))
  attest.Approximately(t, 9, 10, 0.5)
}

Failed assertions usually print a diff. Here's an example using attest.Equal:

--- FAIL: TestEqual (0.00s)
    attest_test.go:58: got != want
        diff (+got, -want):
          attest.Point{
                X: 1,
        -       Y: 4.2,
        +       Y: 3.5,
          }

Status: Stable

This module is stable. It supports the two most recent major releases of Go.

Within those parameters, attest follows semantic versioning. No breaking changes will be made without incrementing the major version.

Legal

Offered under the MIT license.