Type-safe assertion helpers for Go

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:

  • Type safety: it's impossible to compare values with different types.
  • Brevity: assertions usually print diffs rather than full values.
  • Minimalism: just a few assertions, not a whole DSL.
  • Natural ordering: every assertion uses got == want order.
  • Interoperability: assertions work with any cmp.Option.

An example

package main

import (
  "testing"
  "time"

  "github.com/akshayjshah/attest"
)

func TestExample(t *testing.T) {
  attest.Equal(t, 1, 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 and support

attest supports the two most recent major releases of Go, with a minimum of Go 1.18. It's currently unstable, but I hope to cut a stable 1.0 soon after the Go 1.19 release.

Legal

Offered under the Apache 2 license.

Owner
Akshay Shah
❤️ burritos, New Haven, histograms, and Go.
Akshay Shah
Comments
  • attest.StrContains

    attest.StrContains

    I find myself wanting to use attest.Contains but then I remember that what I have is a string and not a slice.

    So I end up doing; attest.True(t, strings.Contains("some-str", "some-other"))

    https://github.com/komuw/ong/blob/2a6145e85fc3227def1173610fe554bc54096270/log/log_test.go#L143-L144

  • display diff in reverse

    display diff in reverse

    If you have a program like (https://go.dev/play/p/6gWHICoz0xd):

    got := "hello"
    want := "hell"
    attest.Equal(t, got, want)
    

    and you run it, you get a diff like:

        prog.go:12: got != want
            diff (+got, -want):
              string(
            - 	"hell",
            + 	"hello",
              )
    

    In attest all the functions like Equal take got as the first argument and then want. So I would expect that when it comes to displaying the diff, it would follow the same order. ie, got is displayed first and then want.
    However the diff displays the want first(in the example above; - "hell",)

  • add attest.NotEqual

    add attest.NotEqual

    currently you have to do attest.True(t, a!=b) which does not work for all types. eg;

    type foo struct{ Name []string }
    

    the following works;

    attest.Equal(t, foo{Name: []string{"a"}}, foo{Name: []string{"a"}})
    

    whereas the following fails to compile(invalid operation: foo{…} != foo{…} (struct containing []string cannot be compared));

    attest.True(t, foo{Name: []string{"a"}} != foo{Name: []string{"b"}})
    

    That's why I think we need a NotEqual so that we can write;`

    attest.NotEqual(t, foo{Name: []string{"a"}}, foo{Name: []string{"b"}})
    
  • Bump github.com/google/go-cmp from 0.5.8 to 0.5.9

    Bump github.com/google/go-cmp from 0.5.8 to 0.5.9

    Bumps github.com/google/go-cmp from 0.5.8 to 0.5.9.

    Release notes

    Sourced from github.com/google/go-cmp's releases.

    v0.5.9

    Reporter changes:

    • (#299) Adjust heuristic for line-based versus byte-based diffing
    • (#306) Use value.TypeString in PathStep.String

    Code cleanup changes:

    • (#297) Use reflect.Value.IsZero
    • (#304) Format with Go 1.19 formatter
    • (#300 )Fix typo in Result documentation
    • (#302) Pre-declare global type variables
    • (#309) Run tests on Go 1.19
    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
  • Bump github.com/google/go-cmp from 0.5.7 to 0.5.8

    Bump github.com/google/go-cmp from 0.5.7 to 0.5.8

    Bumps github.com/google/go-cmp from 0.5.7 to 0.5.8.

    Release notes

    Sourced from github.com/google/go-cmp's releases.

    v0.5.8

    Reporter changes:

    • (#293) Fix printing of types in reporter output for interface and pointer types
    • (#294) Use string formatting for slice of bytes in more circumstances

    Dependency changes:

    • (#292) Update minimum supported version to go1.13 and remove xerrors dependency
    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
  • Trap panics from cmp

    Trap panics from cmp

    Because the cmp API doesn't take a testing.TB, they're forced to panic (or make their API very unpleasant) when they get invalid input. Panics are disconcerting for users, though - we should probably trap these panics and fail the test instead.

A Go test assertion library for verifying that two representations of JSON are semantically equal
A Go test assertion library for verifying that two representations of JSON are semantically equal

jsonassert is a Go test assertion library for verifying that two representations of JSON are semantically equal. Usage Create a new *jsonassert.Assert

Jan 4, 2023
A tool for generating self-contained, type-safe test doubles in go

counterfeiter When writing unit-tests for an object, it is often useful to have fake implementations of the object's collaborators. In go, such fake i

Jan 5, 2023
Package cdp provides type-safe bindings for the Chrome DevTools Protocol (CDP), written in the Go programming language.

cdp Package cdp provides type-safe bindings for the Chrome DevTools Protocol (CDP), written in the Go programming language. The bindings are generated

Jan 7, 2023
Completely type-safe compile-time mock generator for Go

Mockc Mockc is a completely type-safe compile-time mock generator for Go. You can use it just by writing the mock generators with mockc.Implement() or

Aug 25, 2022
Golang Server Helpers

go-server-helpers Package Changes NOTE: This package is a work in progress and subject to change. Before v1.0.0 will use minor version tags to mark if

Mar 8, 2022
Go concurrent-safe, goroutine-safe, thread-safe queue
Go concurrent-safe, goroutine-safe, thread-safe queue

goconcurrentqueue - Concurrent safe queues The package goconcurrentqueue offers a public interface Queue with methods for a queue. It comes with multi

Dec 31, 2022
May 8, 2022
:exclamation:Basic Assertion Library used along side native go testing, with building blocks for custom assertions

Package assert Package assert is a Basic Assertion library used along side native go testing Installation Use go get. go get github.com/go-playground/

Jan 6, 2023
A Go test assertion library for verifying that two representations of JSON are semantically equal
A Go test assertion library for verifying that two representations of JSON are semantically equal

jsonassert is a Go test assertion library for verifying that two representations of JSON are semantically equal. Usage Create a new *jsonassert.Assert

Jan 4, 2023
Supports the safe and convenient execution of asynchronous computations with goroutines and provides facilities for the safe retrieval of the computation results.

Rendezvous The Rendezvous library supports the safe and convenient execution of asynchronous computations with goroutines and provides facilities for

Dec 29, 2021
Null Types, Safe primitive type conversion and fetching value from complex structures.

Typ Typ is a library providing a powerful interface to impressive user experience with conversion and fetching data from built-in types in Golang Feat

Sep 26, 2022
Type safe SQL builder with code generation and automatic query result data mapping
Type safe SQL builder with code generation and automatic query result data mapping

Jet Jet is a complete solution for efficient and high performance database access, consisting of type-safe SQL builder with code generation and automa

Jan 6, 2023
Type safe SQL query builder and struct mapper for Go

sq (Structured Query) ?? ?? sq is a code-generated, type safe query builder and struct mapper for Go. ?? ?? Documentation • Reference • Examples This

Dec 19, 2022
Type-safe Redis client for Golang

Redis client for Golang ❤️ Uptrace.dev - distributed traces, logs, and errors in one place Join Discord to ask questions. Documentation Reference Exam

Jan 1, 2023
100% type-safe ORM for Go (Golang) with code generation and MySQL, PostgreSQL, Sqlite3, SQL Server support. GORM under the hood.

go-queryset 100% type-safe ORM for Go (Golang) with code generation and MySQL, PostgreSQL, Sqlite3, SQL Server support. GORM under the hood. Contents

Dec 30, 2022
Type-safe Redis client for Golang

Redis client for Golang ❤️ Uptrace.dev - distributed traces, logs, and errors in one place Join Discord to ask questions. Documentation Reference Exam

Jan 4, 2023
Type-safe Prometheus metrics builder library for golang

gotoprom A Prometheus metrics builder gotoprom offers an easy to use declarative API with type-safe labels for building and using Prometheus metrics.

Dec 5, 2022
A tool for generating self-contained, type-safe test doubles in go

counterfeiter When writing unit-tests for an object, it is often useful to have fake implementations of the object's collaborators. In go, such fake i

Jan 5, 2023
Package cdp provides type-safe bindings for the Chrome DevTools Protocol (CDP), written in the Go programming language.

cdp Package cdp provides type-safe bindings for the Chrome DevTools Protocol (CDP), written in the Go programming language. The bindings are generated

Jan 7, 2023
safe and easy casting from one type to another in Go

cast Easy and safe casting from one type to another in Go Don’t Panic! ... Cast What is Cast? Cast is a library to convert between different go types

Jan 7, 2023