GoCrest - Hamcrest-like matchers for Go

Overview

gocrest

A hamcrest-like assertion library for Go. GoCrest matchers are composable, self-describing and can be strung together in a more readable form to create flexible assertions.

Inspired by Hamcrest.

Build status Go Report Card GoDoc BCH compliance Coverage Status

Package import

import (
  "github.com/corbym/gocrest/then"
  "github.com/corbym/gocrest/is"
  "github.com/corbym/gocrest/has"
)

Example:

then.AssertThat(testing, "hi", is.EqualTo("bye").Reason("we are going"))

output:

we are going
Expected: value equal to <bye>
     but: <hi>

Composed with AllOf:

then.AssertThat(t, "abcdef", is.AllOf(is.ValueContaining("abc"), is.LessThan("ghi")))

Matchers so far..

  • is.EqualTo(x)
  • is.EqualToIgnoringWhitespace(string) - compares two strings without comparing their whitespace characters.
  • is.Nil() - value must be nil
  • is.ValueContaining(expected) -- acts like containsAll
  • is.Not(m *Matcher) -- logical not of matcher's result
  • is.MatchForPattern(regex string) -- a string regex expression
  • has.FunctionNamed(string x) - checks if an interface has a function (method)
  • has.FieldNamed(string x) - checks if a struct has a field named x
  • is.AllOf(... *Matcher) - returns true if all matchers match
  • is.AnyOf(... *Matcher) - return true if any matcher matches
  • is.GreaterThan(expected) - checks if actual > expected
  • is.LessThan(expected)
  • is.Empty() - matches if the actual is "", nil or len(actual)==0
  • is.LessThan(x)
  • is.LessThanOrEqualTo(x)
  • is.GreaterThan(x)
  • is.GreaterThanOrEqualTo(x)
  • has.Length(x) - matcher if given value (int or matcher) matches the len of the given
  • has.Prefix(x) - string starts with x
  • has.Suffix(x) - string ends with x
  • has.Key(x) - map has key x
  • has.AllKeys(T x, T y) (or has.AllKeys([]T{x,y})) - finds key of type T in map
  • has.EveryElement(x1...xn) - checks if actual[i] matches corresponding expectation (x[i])
  • has.StructWithValues(map[string]*gocrest.Matcher) - checks if actual[key] matches corresponding expectation (x[key])

For more comprehensive documentation see godoc.

Comments
  • Matchers: has.ElementsWith and has.StructWithValues

    Matchers: has.ElementsWith and has.StructWithValues

    I implemented two new matchers:

    has.ElementsWith: Checks wether each element of an array/slice matches all expectations has.StructWithValues: Allows to check single struct fields

    Can be combined in a way that now we can check if f.e.:

    [
      {
        "id": "someId1",
        "someOmittedField": true
      },
      {
        "id": "someId2",
        "someOmittedField": false
      }
    ]
    

    has structs that have an id field with the prefix someId

    opened by jpolack 6
  • Implement the gomock.Matcher interface

    Implement the gomock.Matcher interface

    I was using gomock and wanted to use our matchers. Sadly it didn't work out because our matchers don't implement the gomock.Matcher interface:

    type Matcher interface {
      // Matches returns whether x is a match.
      Matches(x interface{}) bool
    
      // String describes what the matcher matches.
      String() string
    }
    

    To implement the gomock.Matcher interface we would have to:

    1. implement a .Matches method as a struct method, not only as a field
    2. implement the Stringer interface

    The Stringer interface should be fairly easy. But the Matches method would cause trouble, because Matcher already has a field called Matches of type func(actual interface{}) bool.

    At this point I see two options:

    1. add a mapping method from gocrest.Matcher to gomock.Matcher:

    A quick win, but kind of dirty because it doesn't really take advantage of go's interface system. Additionally it kind of breaks gomocks syntax:

    m.
      EXPECT().
      Bar(is.Equalto(99).toGomockMatcher()).
      Return(101)
    

    2. rename the Matches method on the Matcher struct:

    Seems like the cleaner way to me, but would cause a breaking change in how matchers are written. Would result in the following gomock syntax:

    m.
      EXPECT().
      Bar(is.Equalto(99)).
      Return(101)
    

    I would love to discuss this and find a way that suites us best!

    opened by jpolack 2
  • does a NoError() matcher make sense?

    does a NoError() matcher make sense?

    Hi,

    since foo, err := bar() is a typical go style, I wonder, if a NoError() matcher would make sense to add?

    Example

    foo, err := bar()
    then.assertThat(t, err, is.NoError())
    

    What do you think? I would be open to create a PR ... but would like to get your view first :)

    opened by nitram509 1
  • Implement Testify custom matchers via mock.MatchedBy

    Implement Testify custom matchers via mock.MatchedBy

    Hi, I saw the recent gomock discussion and would love documentation on how to Implement Testify's custom matchers via mock.MatchedBy using this library.

    // Anything and AnythingOfType matchers
    mockDoer.
        On("Do", mock.Anything, mock.AnythingOfType("string"))
    
    // Custom matcher
    mockDoer.
        On("Do", 1, mock.MatchedBy(func(x string) bool {
            return strings.HasPrefix(x, "abc")
        })
    
    opened by StevenACoffman 2
  • Describe only failed matchers in AnyOf

    Describe only failed matchers in AnyOf

    AnyOf reports all matcher's descriptions when it fails.

    Given a number of matchers, when less than all of them fail, we should only report the description of the failing matchers.

    opened by corbym 1
Releases(v1.0.5)
  • v1.0.5(Dec 21, 2020)

    Two more matchers added:

    • has.EveryElement(x1...xn) - checks if actual[i] matches corresponding expectation (x[i])
    • has.StructWithValues(map[string]*gocrest.Matcher) - checks if actual[key] matches corresponding expectation (x[key])

    Bugs fixed:

    https://github.com/corbym/gocrest/issues/2

    Source code(tar.gz)
    Source code(zip)
  • v1.0.4(Nov 26, 2020)

  • v1.0.3(Feb 1, 2018)

    Added matchers:

    • has.TypeName - checks if an instance has the struct name x where x is a string or a matcher
    • shortcut matchers is.True and is.False
    Source code(tar.gz)
    Source code(zip)
  • v1.0.2(Jan 21, 2018)

    Includes:

    • has length panicked with nil actual Matt Corby 21/01/2018 20:48
    • godoc for AppendActual Matt Corby 21/01/2018 16:40
    • anyof and all of now carry actuals over Matt Corby 21/01/2018 16:36
    • Length matcher actual was only useful if you know the length of actual
    • not now carries the actual over.
    Source code(tar.gz)
    Source code(zip)
  • v1.0.1(Jan 17, 2018)

Owner
Matt
Java Dev, 20 years industry experience. Full stack developer (Team Lead) at eBay
Matt
Ruby on Rails like test fixtures for Go. Write tests against a real database

testfixtures Warning: this package will wipe the database data before loading the fixtures! It is supposed to be used on a test database. Please, doub

null 873 Nov 21, 2022
🏳️ Go package that provides function like assert of Python or C++.

gassert gassert is Go package that provides function like assert of Python or C++. With gassert, you can check validation of parameters or values more

KyuSik Kim 4 Aug 5, 2022
An assert function for Go that works like the one in C.

Assert This package provides an assert function for Go. It's designed to work like assert in C.

Josh 20 Nov 16, 2022
go-test-trace is like go test but it also generates distributed traces.

go-test-trace go-test-trace is like go test but it also generates distributed traces. Generated traces are exported in OTLP to a OpenTelemetry collect

JBD 376 Nov 21, 2022
Rest API to receive solana tokens in testnet just like a faucet

solana-example Rest API to receive solana tokens in testnet just like a faucet Running go run main.go Test Request airdrop curl --header "Content-Type

Rafael Escrich 0 Oct 14, 2021
Generate a test coverage badge like this one for your go projects.

coverage-badge-go ?? Generate a test coverage badge like this one for your go projects. Usage on: pull_request: branches: -

tj-actions 28 Nov 11, 2022
Hamcrest matchers for the Go programming language

Note: This has not been maintained and/or updated since 2011. Perhaps consider corbym/gocrest, instead. Introduction Hamcrest is a fluent framework fo

null 28 Sep 27, 2022
Just some random matchers

The package provides a matcher interface to match a given value of any types.

Nhat 2 Nov 3, 2022
Generate random, pronounceable, sometimes even memorable, "superhero like" codenames - just like Docker does with container names.

Codename an RFC1178 implementation to generate pronounceable, sometimes even memorable, "superheroe like" codenames, consisting of a random combinatio

Luca Sepe 83 Oct 23, 2022
A plugin for argo which behaves like I'd like

argocd-lovely-plugin An ArgoCD plugin to perform various manipulations in a sensible order to ultimately output YAML for Argo CD to put into your clus

null 109 Nov 20, 2022
I like reading news but I also like the terminal. I am leaning and practicing my go.

I made an api and didn't know how to use it. Screenshots The initial screen when you first run the app. The screen after you specify an id. This app u

Daniel M. Matongo 2 Jan 14, 2022
An authorization library that supports access control models like ACL, RBAC, ABAC in Golang

Casbin News: still worry about how to write the correct Casbin policy? Casbin online editor is coming to help! Try it at: https://casbin.org/editor/ C

Casbin 13.2k Nov 19, 2022
Herbert Fischer 198 Oct 8, 2022
Various tools for usage with Golang like installer, github tool and cloud features.

Gopei2 (Go Programming Environment Installer) Gopei shell install Go compiler, LiteIDE and configure for you the entire environment, variables, paths,

George Calianu 100 Nov 9, 2022
lsp is like ls command but more human-friendly

lsp: list files in a mildly human-frendlier manner lsp lists files, like ls command, but it does not attempt to meet that archaic POSIX specification,

Dmitry Borzov 510 Nov 13, 2022
A tree like tool help you to explore data structures in your redis server

Redis-view is a tree like tool help you explore data structures in your redis server

dreamersdw 19 Mar 17, 2022
getopt-like flags package for golang,

goopt A getopt-like processor of command-line flags. It works much like the "flag" package, only it processes arguments in a way that is compatible wi

David Roundy 84 Oct 5, 2022
:jeans:Multi-Package go project coverprofile for tools like goveralls

Package overalls Package overalls takes multi-package go projects, runs test coverage tests on all packages in each directory and finally concatenates

Go Playgound 112 Sep 26, 2022
pongo2 is a Django-syntax like templating-language

Django-syntax like template-engine for Go

Florian Schlachter 2.4k Nov 25, 2022
Python-like dictionaries for Go

Dict Python dictionary data type (dict) in Go Package dict is a Go implementation of Python dict, which are hashable object maps. Dictionaries complem

Mr. Gus 34 Nov 1, 2022