import "github.com/tideland/golib/audit"
Package audit of the Tideland Go Library helps writing convenient and powerful unit tests. One part of it are assertions to compare expected and obtained values. Additional text output for failing tests can be added.
In the beginning of a test function a new assertion instance is created with:
assert := audit.NewTestingAssertion(t, shallFail)
Inside the test an assert looks like:
assert.Equal(obtained, expected, "obtained value has to be like expected")
If shallFail is set to true a failing assert also lets fail the Go test. Otherwise the failing is printed but the tests continue. Other functions help with temporary directories, environment variables, and the generating of test data.
Additional helpers support in generating test data or work with the environment, like temporary directories or environment variables, in a safe and convenient way.
asserts.go doc.go environments.go failer.go generators.go printer.go tester.go
const (
// MinWordLen is the length of the shortest word.
MinWordLen = 1
// MaxWordLen is the length of the longest word.
MaxWordLen = 14
)BuildEMail creates an e-mail address out of first and last name and the domain.
BuildTime returns the current time plus or minus the passed offset formatted as string and as Time. The returned time is the parsed formatted one to avoid parsing troubles in tests.
FixedRand returns a random number generator with a fixed source so that tests using the generate functions can be repeated with the same result.
func MakeSigChan() chan interface{}MakeSigChan is a simple one-liner to create the buffered signal channel for the wait assertion.
SimpleRand returns a random number generator with a source using the the current time as seed. It's not the best random, but ok to generate test data.
ToUpperFirst returns the passed string with the first rune converted to uppercase.
ValueDescription returns a description of a value as string.
type Assertion interface {
// SetFailable allows to change the failable possibly used inside
// a failer. This way a testing.T of a sub-test can be injected. A
// restore function is returned.
//
// t.Run(name, func(t *testing.T)) {
// defer assert.SetFailable(t)()
// ...
// })
//
// This way the returned restorer function will be called when
// leaving the sub-test.
SetFailable(f Failable) func()
// IncrCallstackOffset allows test libraries using the audit
// package internally to adjust the callstack offset. This
// way test output shows the correct location. Deferring
// the returned function restores the former offset.
IncrCallstackOffset() func()
// Logf can be used to display useful information during testing.
Logf(format string, args ...interface{})
// True tests if obtained is true.
True(obtained bool, msgs ...string) bool
// False tests if obtained is false.
False(obtained bool, msgs ...string) bool
// Nil tests if obtained is nil.
Nil(obtained interface{}, msgs ...string) bool
// NotNil tests if obtained is not nil.
NotNil(obtained interface{}, msgs ...string) bool
// Equal tests if obtained and expected are equal.
Equal(obtained, expected interface{}, msgs ...string) bool
// Different tests if obtained and expected are different.
Different(obtained, expected interface{}, msgs ...string) bool
// Contents tests if the obtained data is part of the expected
// string, array, or slice.
Contents(obtained, full interface{}, msgs ...string) bool
// About tests if obtained and expected are near to each other
// (within the given extent).
About(obtained, expected, extent float64, msgs ...string) bool
// Range tests if obtained is larger or equal low and lower or
// equal high. Allowed are byte, int and float64 for numbers, runes,
// strings, times, and duration. In case of obtained arrays,
// slices, and maps low and high have to be ints for testing
// the length.
Range(obtained, low, high interface{}, msgs ...string) bool
// Substring tests if obtained is a substring of the full string.
Substring(obtained, full string, msgs ...string) bool
// Case tests if obtained string is uppercase or lowercase.
Case(obtained string, upperCase bool, msgs ...string) bool
// Match tests if the obtained string matches a regular expression.
Match(obtained, regex string, msgs ...string) bool
// ErrorMatch tests if the obtained error as string matches a
// regular expression.
ErrorMatch(obtained error, regex string, msgs ...string) bool
// Implementor tests if obtained implements the expected
// interface variable pointer.
Implementor(obtained, expected interface{}, msgs ...string) bool
// Assignable tests if the types of expected and obtained are assignable.
Assignable(obtained, expected interface{}, msgs ...string) bool
// Unassignable tests if the types of expected and obtained are
// not assignable.
Unassignable(obtained, expected interface{}, msgs ...string) bool
// Empty tests if the len of the obtained string, array, slice
// map, or channel is 0.
Empty(obtained interface{}, msgs ...string) bool
// NotEmpty tests if the len of the obtained string, array, slice
// map, or channel is greater than 0.
NotEmpty(obtained interface{}, msgs ...string) bool
// Length tests if the len of the obtained string, array, slice
// map, or channel is equal to the expected one.
Length(obtained interface{}, expected int, msgs ...string) bool
// Panics checks if the passed function panics.
Panics(pf func(), msgs ...string) bool
// PathExists checks if the passed path or file exists.
PathExists(path string, msgs ...string) bool
// Wait until a received signal or a timeout. The signal has
// to be the expected value.
Wait(sigc <-chan interface{}, expected interface{}, timeout time.Duration, msgs ...string) bool
// WaitTested wait until a received signal or a timeout. The signal then
// is tested by the passed function which has to return nil for a successful
// assert.
WaitTested(sigc <-chan interface{}, tester func(interface{}) error, timeout time.Duration, msgs ...string) bool
// Retry calls the passed function and expects it to return true. Otherwise
// it pauses for the given duration and retries the call the defined number.
Retry(rf func() bool, retries int, pause time.Duration, msgs ...string) bool
// Fail always fails.
Fail(msgs ...string) bool
}Assertion defines the available test methods.
NewAssertion creates a new Assertion instance.
NewPanicAssertion creates a new Assertion instance which panics if a test fails.
NewTestingAssertion creates a new Assertion instance for use with the testing package. The *testing.T has to be passed as failable, the first argument. shallFail controls if a failing assertion also lets fail the Go test.
NewValidationAssertion creates a new Assertion instance which collections validation failures. The returned Failures instance allows to test an access them.
type EnvVars struct {
// contains filtered or unexported fields
}EnvVars allows to change and restore environment variables. The same variable can be set multiple times. Simply do
assert := audit.NewTestingAssertion(t, false)
ev := audit.NewEnvVars(assert)
defer ev.Restore()
ev.Set("MY_VAR", myValue)
...
ev.Set("MY_VAR", anotherValue)
The deferred Restore() resets to the original values.
NewEnvVars creates
Restore resets all changed environment variables
Set sets an environment variable to a new value.
Unset unsets an environment variable.
type Failable interface {
FailNow()
}Failable allows an assertion to signal a fail to an external instance like testing.T or testing.B.
type Failer interface {
// IncrCallstackOffset increases the callstack offset for
// the assertion output (see Assertion) and returns a function
// for restoring.
IncrCallstackOffset() func()
// Logf can be used to display useful information during testing.
Logf(format string, args ...interface{})
// Fail will be called if an assert fails.
Fail(test Test, obtained, expected interface{}, msgs ...string) bool
}Failer describes a type controlling how an assert reacts after a failure.
type FailureDetail interface {
// TImestamp tells when the failure has happened.
Timestamp() time.Time
// Locations returns file name, line number, and
// function name of the failure.
Location() (string, int, string)
// Test tells which kind of test has failed.
Test() Test
// Error returns the failure as error.
Error() error
// Message return the optional test message.
Message() string
}FailureDetail contains detailed information of a failure.
type Failures interface {
// HasErrors returns true, if assertion failures happened.
HasErrors() bool
// Details returns the collected details.
Details() []FailureDetail
// Errors returns the so far collected errors.
Errors() []error
// Error returns the collected errors as one error.
Error() error
}Failures collects the collected failures of a validation assertion.
type Generator struct {
// contains filtered or unexported fields
}Generator is responsible for generating different random data based on a random number generator.
NewGenerator returns a new generator using the passed random number generator.
Domain generates domain out of name and top level domain.
Duration generates a duration between lo and hi including those values.
EMail returns a random e-mail address.
FemaleName generates a female name consisting out of first, middle and last name.
FlipCoin returns true if the internal generated percentage is equal or greater than the passed percentage.
Int generates an int between lo and hi including those values.
Ints generates a slice of random ints.
LimitedWord generates a random word with a length between lo and hi.
MaleName generates a male name consisting out of first, middle and last name.
Name generates a male or female name consisting out of first, middle and last name.
OneByteOf returns one of the passed bytes.
OneDurationOf returns one of the passed durations.
OneIntOf returns one of the passed ints.
OneRuneOf returns one of the runes of the passed string.
OneStringOf returns one of the passed strings.
Paragraph generates a paragraph between 2 and 10 sentences.
Pattern generates a string based on a pattern. Here different escape chars are replaced by according random chars while all others are left as they are. Escape chars start with a caret (^) followed by specializer. Those are:
- ^ for a caret - 0 for a number between 0 and 9 - 1 for a number between 1 and 9 - o for an octal number - h for a hexadecimal number (lower-case) - H for a hexadecimal number (upper-case) - a for any char between a and z - A for any char between A and Z - c for a consonant (lower-case) - C for a consonant (upper-case) - v for a vowel (lower-case) - V for a vowel (upper-case)
Percent generates an int between 0 and 100.
Sentence generates a sentence between 2 and 15 words and possibly containing commas.
SleepOneOf chooses randomely one of the passed durations and lets the goroutine sleep for this time.
Time generates a time between the given one and that time plus the given duration. The result will have the passed location.
URL generates a http, https or ftp URL, some of the leading to a file.
Word generates a random word.
Words generates a slice of random words
type Printer interface {
// Printf prints a formatted information.
Printf(format string, args ...interface{})
}Printer allows to switch between different outputs.
SetPrinter sets a new global printer and returns the current one.
type TempDir struct {
// contains filtered or unexported fields
}TempDir represents a temporary directory and possible subdirectories for testing purposes. It simply is created with
assert := audit.NewTestingAssertion(t, false)
td := audit.NewTempDir(assert)
defer td.Restore()
tdName := td.String()
subName:= td.Mkdir("my", "sub", "directory")
The deferred Restore() removes the temporary directory with all contents.
NewTempDir creates a new temporary directory usable for direct usage or further subdirectories.
Mkdir creates a potentially nested directory inside the temporary directory.
Restore deletes the temporary directory and all contents.
String returns the temporary directory.
Test represents the test inside an assert.
const (
Invalid Test = iota + 1
True
False
Nil
NotNil
Equal
Different
Contents
About
Range
Substring
Case
Match
ErrorMatch
Implementor
Assignable
Unassignable
Empty
NotEmpty
Length
Panics
PathExists
Wait
WaitTested
Retry
Fail
)Tests provided by the assertion.
type Tester struct{}Tester is a helper which can be used in own Assertion implementations.
Contains checks if the part type is matching to the full type and if the full data contains the part data.
HasPanic checks if the passed function panics.
IsAbout checks if obtained and expected are to a given extent almost equal.
IsAssignable checks if the types of obtained and expected are assignable.
IsCase checks if the obtained string is uppercase or lowercase.
IsEqual checks if obtained and expected are equal.
IsImplementor checks if obtained implements the expected interface variable pointer.
IsInRange checks for range assertions
IsMatching checks if the obtained string matches a regular expression.
IsNil checks if obtained is nil in a safe way.
IsSubstring checks if obtained is a substring of the full string.
IsTrue checks if obtained is true.
IsValidPath checks if the given directory or file path exists.
Len checks the length of the obtained string, array, slice, map or channel.
Package audit imports 16 packages (graph) and is imported by 2 packages. Updated 2017-07-01. Refresh now. Tools for package owners.