Documentation ¶
Overview ¶
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.
Index ¶
- Constants
- func BuildEMail(first, last, domain string) string
- func BuildTime(layout string, offset time.Duration) (string, time.Time)
- func FixedRand() *rand.Rand
- func MakeSigChan() chan interface{}
- func NewValidationAssertion() (Assertion, Failures)
- func SimpleRand() *rand.Rand
- func ToUpperFirst(s string) string
- func ValueDescription(value interface{}) string
- type Assertion
- type EnvVars
- type Failable
- type Failer
- type FailureDetail
- type Failures
- type Generator
- func (g *Generator) Domain() string
- func (g *Generator) Duration(lo, hi time.Duration) time.Duration
- func (g *Generator) EMail() string
- func (g *Generator) FemaleName() (first, middle, last string)
- func (g *Generator) FlipCoin(percent int) bool
- func (g *Generator) Int(lo, hi int) int
- func (g *Generator) Ints(lo, hi, count int) []int
- func (g *Generator) LimitedWord(lo, hi int) string
- func (g *Generator) MaleName() (first, middle, last string)
- func (g *Generator) Name() (first, middle, last string)
- func (g *Generator) OneByteOf(values ...byte) byte
- func (g *Generator) OneDurationOf(values ...time.Duration) time.Duration
- func (g *Generator) OneIntOf(values ...int) int
- func (g *Generator) OneRuneOf(values string) rune
- func (g *Generator) OneStringOf(values ...string) string
- func (g *Generator) Paragraph() string
- func (g *Generator) Pattern(pattern string) string
- func (g *Generator) Percent() int
- func (g *Generator) Sentence() string
- func (g *Generator) SleepOneOf(sleeps ...time.Duration) time.Duration
- func (g *Generator) Time(loc *time.Location, base time.Time, dur time.Duration) time.Time
- func (g *Generator) URL() string
- func (g *Generator) Word() string
- func (g *Generator) Words(count int) []string
- type Printer
- type TempDir
- type Test
- type Tester
- func (t Tester) Contains(part, full interface{}) (bool, error)
- func (t Tester) HasPanic(pf func()) (ok bool)
- func (t Tester) IsAbout(obtained, expected, extent float64) bool
- func (t Tester) IsAssignable(obtained, expected interface{}) bool
- func (t Tester) IsCase(obtained string, upperCase bool) bool
- func (t Tester) IsEqual(obtained, expected interface{}) bool
- func (t Tester) IsImplementor(obtained, expected interface{}) (bool, error)
- func (t Tester) IsInRange(obtained, low, high interface{}) (bool, error)
- func (t Tester) IsMatching(obtained, regex string) (bool, error)
- func (t Tester) IsNil(obtained interface{}) bool
- func (t Tester) IsSubstring(obtained, full string) bool
- func (t Tester) IsTrue(obtained bool) bool
- func (t Tester) IsValidPath(path string) (bool, error)
- func (t Tester) Len(obtained interface{}) (int, error)
Constants ¶
const ( // MinWordLen is the length of the shortest word. MinWordLen = 1 // MaxWordLen is the length of the longest word. MaxWordLen = 14 )
Variables ¶
This section is empty.
Functions ¶
func BuildEMail ¶
BuildEMail creates an e-mail address out of first and last name and the domain.
func BuildTime ¶
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.
func FixedRand ¶
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 ¶
func MakeSigChan() chan interface{}
MakeSigChan is a simple one-liner to create the buffered signal channel for the wait assertion.
func NewValidationAssertion ¶
NewValidationAssertion creates a new Assertion instance which collections validation failures. The returned Failures instance allows to test an access them.
func SimpleRand ¶
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.
func ToUpperFirst ¶
ToUpperFirst returns the passed string with the first rune converted to uppercase.
func ValueDescription ¶
func ValueDescription(value interface{}) string
ValueDescription returns a description of a value as string.
Types ¶
type Assertion ¶
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.
func NewAssertion ¶
NewAssertion creates a new Assertion instance.
func NewPanicAssertion ¶
func NewPanicAssertion() Assertion
NewPanicAssertion creates a new Assertion instance which panics if a test fails.
func NewTestingAssertion ¶
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.
type EnvVars ¶
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.
func (*EnvVars) Restore ¶
func (ev *EnvVars) Restore()
Restore resets all changed environment variables
type Failable ¶
type Failable interface {
FailNow()
}
Failable allows an assertion to signal a fail to an external instance like testing.T or testing.B.
type Failer ¶
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 ¶
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 ¶
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 ¶
type Generator struct {
// contains filtered or unexported fields
}
Generator is responsible for generating different random data based on a random number generator.
func NewGenerator ¶
NewGenerator returns a new generator using the passed random number generator.
func (*Generator) Duration ¶
Duration generates a duration between lo and hi including those values.
func (*Generator) FemaleName ¶
FemaleName generates a female name consisting out of first, middle and last name.
func (*Generator) FlipCoin ¶
FlipCoin returns true if the internal generated percentage is equal or greater than the passed percentage.
func (*Generator) LimitedWord ¶
LimitedWord generates a random word with a length between lo and hi.
func (*Generator) MaleName ¶
MaleName generates a male name consisting out of first, middle and last name.
func (*Generator) Name ¶
Name generates a male or female name consisting out of first, middle and last name.
func (*Generator) OneDurationOf ¶
OneDurationOf returns one of the passed durations.
func (*Generator) OneStringOf ¶
OneStringOf returns one of the passed strings.
func (*Generator) Pattern ¶
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)
func (*Generator) Sentence ¶
Sentence generates a sentence between 2 and 15 words and possibly containing commas.
func (*Generator) SleepOneOf ¶
SleepOneOf chooses randomely one of the passed durations and lets the goroutine sleep for this time.
func (*Generator) Time ¶
Time generates a time between the given one and that time plus the given duration. The result will have the passed location.
type Printer ¶
type Printer interface { // Printf prints a formatted information. Printf(format string, args ...interface{}) }
Printer allows to switch between different outputs.
func SetPrinter ¶
SetPrinter sets a new global printer and returns the current one.
type TempDir ¶
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.
func NewTempDir ¶
NewTempDir creates a new temporary directory usable for direct usage or further subdirectories.
func (*TempDir) Mkdir ¶
Mkdir creates a potentially nested directory inside the temporary directory.
type Test ¶
type Test uint
Test represents the test inside an assert.
type Tester ¶
type Tester struct{}
Tester is a helper which can be used in own Assertion implementations.
func (Tester) Contains ¶
Contains checks if the part type is matching to the full type and if the full data contains the part data.
func (Tester) IsAssignable ¶
IsAssignable checks if the types of obtained and expected are assignable.
func (Tester) IsImplementor ¶
IsImplementor checks if obtained implements the expected interface variable pointer.
func (Tester) IsMatching ¶
IsMatching checks if the obtained string matches a regular expression.
func (Tester) IsSubstring ¶
IsSubstring checks if obtained is a substring of the full string.
func (Tester) IsValidPath ¶
IsValidPath checks if the given directory or file path exists.