Package truthy provides truthy condition testing with Go generics

Truthy

Truthiness

Truthy is a package which uses generics (Go 1.18+) to create useful boolean tests and helper functions.

Examples

// truthy.Value returns the truthiness of any argument.
// If the value's type has a Bool() bool method, the method is called and returned.
// If the type has an IsZero() bool method, the opposite value is returned.
// Slices and maps are truthy if they have a length greater than zero.
// All other types are truthy if they are not their zero value.

truthy.Value(0) // false
truthy.Value(1) // true

truthy.Value("") // false
truthy.Value(" ") // true

truthy.Value([]byte(``)) // false
truthy.Value([]byte(` `)) // true

truthy.Value([]int{}) // false
truthy.Value([]int{1, 2, 3}) // true

var err error
truthy.Value(err) // false
truthy.Value(errors.New("hi")) // true
if truthy.Value(err) {
	panic(err)
}


var p *int
truthy.Value(p) // false

p = new(int)
// truthy does not check value underlying pointer!
truthy.Value(p) // true

// Ever wish Go had ? : ternary operators?
// Now it has a ternary function.
x := truthy.Cond("", 1, 10) // x == 10

// truthy.Cond cannot lazily evaluate its arguments,
// but you can use a closure to fake it.
s := truthy.Cond([]string{""},
	func() string {
		// do some calculation
		return "foo"
	},
	func() string {
		// do some calculation
		return "bar"
	})()
// s == "foo"


// How about an equivalent of the nullish coalescing operator ?? 
// as seen in C#, JavaScript, PHP, etc.:
var s string
truthy.First(s, "default") // "default"
s = "something"
truthy.First(s, "default") // "something"
truthy.First(0, 0*1, 1-1, 0x10-10) // 6

// Easily set defaults
n := getUserInput()
truthy.SetDefault(&n, 42)

// Collection testing and filtering
truthy.Any(0, 1, 2) // true
truthy.All(0, 1, 2) // false

ss := []string{"", "a", "b", ""}
truthy.Filter(&ss) // ss == []string{"a", "b"}

// Logical operators
if truthy.Or("1", 0) {
	fmt.Println("yay") // prints yay
}

if truthy.And(300, "") {
	fmt.Println("boo") // not executed
}

Installation

As of October 2021, Go 1.18 is not released, but you can install Go tip with

$ go install golang.org/dl/gotip@latest
$ gotip download
$ gotip init me/myproject
$ gotip get github.com/carlmjohnson/truthy

FAQs

Oh god

This is the correct reaction.

Isn't this just using reflection? Does it even really require generics?

I tried to write a non-generic version of this package first, but you can’t reflect on an interface type. When you do reflect.Value(x), you lose the fact that x was, e.g. an error, because reflect.Value() only takes interface{} and the conversion loses the interface type. You’d end up saying whether the underlying concrete type was empty or not, which is typically not what you want. To work around that, you could require that everything is passed as a pointer, e.g. reflect.Value(&err), but truthy.Value(&err) sucks as an API. If you look at how truthy.Value() works, it accepts a value of type T, and then passes *T to reflect.Value() and calls value.Elem() to finally get the correct reflection type. So, on a technical level, you couldn’t quite make this API work without generics, although it could be close. However, truthy.Filter(), truthy.SetDefault(), truthy.Any(), and truthy.All() could be implemented with pure reflection, although the implementation would be a lot uglier.

Then there’s truthy.First(). To be honest, truthy.First() is the only part of the package that I consider actually useful, and even that, I mostly expect it to be used for picking a string or default. Anyhow, it requires generics to avoid the cast back from interface type to the concrete type.

Should I use this package?

Probably not. It's a little bit of a joke package, but the truthy.First() and truthy.SetDefault() functionality seem useful, especially for strings. Time will tell what best practices around the use of generics in Go turn out to be.

Owner
Carl Johnson
Carl M. Johnson is a philosopher and programmer, currently employed as the Technology Director for @spotlightpa.
Carl Johnson
Similar Resources

Expressive end-to-end HTTP API testing made easy in Go

baloo Expressive and versatile end-to-end HTTP API testing made easy in Go (golang), built on top of gentleman HTTP client toolkit. Take a look to the

Dec 13, 2022

Simple Go snapshot testing

Simple Go snapshot testing

Incredibly simple Go snapshot testing: cupaloy takes a snapshot of your test output and compares it to a snapshot committed alongside your tests. If t

Jan 5, 2023

Clean database for testing, inspired by database_cleaner for Ruby

DbCleaner Clean database for testing, inspired by database_cleaner for Ruby. It uses flock syscall under the hood to make sure the test can runs in pa

Nov 17, 2022

Golang HTTP client testing framework

flute Golang HTTP client testing framework Presentation https://speakerdeck.com/szksh/flute-golang-http-client-testing-framework Overview flute is the

Sep 27, 2022

API testing framework inspired by frisby-js

API testing framework inspired by frisby-js

frisby REST API testing framework inspired by frisby-js, written in Go Proposals I'm starting to work on frisby again with the following ideas: Read s

Sep 27, 2022

Mutation testing for Go source code

go-mutesting go-mutesting is a framework for performing mutation testing on Go source code. Its main purpose is to find source code, which is not cove

Dec 28, 2022

Minimal and Beautiful Go testing framework

Minimal and Beautiful Go testing framework

Goblin A Mocha like BDD testing framework written in Go that requires no additional dependencies. Requires no extensive documentation nor complicated

Dec 25, 2022

A Comprehensive Coverage Testing System for The Go Programming Language

A Comprehensive Coverage Testing System for The Go Programming Language

goc 中文页 | goc is a comprehensive coverage testing system for The Go Programming Language, especially for some complex scenarios, like system testing c

Jan 8, 2023

Go testing in the browser. Integrates with `go test`. Write behavioral tests in Go.

Go testing in the browser. Integrates with `go test`. Write behavioral tests in Go.

GoConvey is awesome Go testing Welcome to GoConvey, a yummy Go testing tool for gophers. Works with go test. Use it in the terminal or browser accordi

Dec 30, 2022
A next-generation testing tool. Orion provides a powerful DSL to write and automate your acceptance tests

Orion is born to change the way we implement our acceptance tests. It takes advantage of HCL from Hashicorp t o provide a simple DSL to write the acceptance tests.

Aug 31, 2022
testtime provides time.Now for testing.

testtime provides time.Now for testing.

Dec 21, 2022
This is just a repository to play around with Generics and Fuzzing, two big things coming with go 1.18!

This is just a repository to play around with Generics and Fuzzing, two big things coming with go 1.18!

Feb 6, 2022
Extremely flexible golang deep comparison, extends the go testing package and tests HTTP APIs
Extremely flexible golang deep comparison, extends the go testing package and tests HTTP APIs

go-testdeep Extremely flexible golang deep comparison, extends the go testing package. Latest news Synopsis Description Installation Functions Availab

Dec 22, 2022
A collection of packages to augment the go testing package and support common patterns.

gotest.tools A collection of packages to augment testing and support common patterns. Usage With Go modules enabled (go1.11+) $ go get gotest.tools/v3

Jan 4, 2023
A mock of Go's net package for unit/integration testing

netmock: Simulate Go network connections netmock is a Go package for simulating net connections, including delays and disconnects. This is work in pro

Oct 27, 2021
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
🏳️ 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

Aug 5, 2022
Fortio load testing library, command line tool, advanced echo server and web UI in go (golang). Allows to specify a set query-per-second load and record latency histograms and other useful stats.
Fortio load testing library, command line tool, advanced echo server and web UI in go (golang). Allows to specify a set query-per-second load and record latency histograms and other useful stats.

Fortio Fortio (Φορτίο) started as, and is, Istio's load testing tool and now graduated to be its own project. Fortio is also used by, among others, Me

Jan 2, 2023
: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