audit

package
v4.24.2+incompatible Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 9, 2017 License: BSD-3-Clause Imports: 16 Imported by: 6

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

View Source
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

func BuildEMail(first, last, domain string) string

BuildEMail creates an e-mail address out of first and last name and the domain.

func BuildTime

func BuildTime(layout string, offset time.Duration) (string, time.Time)

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

func FixedRand() *rand.Rand

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

func NewValidationAssertion() (Assertion, Failures)

NewValidationAssertion creates a new Assertion instance which collections validation failures. The returned Failures instance allows to test an access them.

func SimpleRand

func SimpleRand() *rand.Rand

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

func ToUpperFirst(s string) string

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

func NewAssertion(f Failer) Assertion

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

func NewTestingAssertion(f Failable, shallFail bool) Assertion

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 NewEnvVars

func NewEnvVars(assert Assertion) *EnvVars

NewEnvVars creates

func (*EnvVars) Restore

func (ev *EnvVars) Restore()

Restore resets all changed environment variables

func (*EnvVars) Set

func (ev *EnvVars) Set(key, value string)

Set sets an environment variable to a new value.

func (*EnvVars) Unset

func (ev *EnvVars) Unset(key string)

Unset unsets an environment variable.

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

func NewGenerator(rand *rand.Rand) *Generator

NewGenerator returns a new generator using the passed random number generator.

func (*Generator) Domain

func (g *Generator) Domain() string

Domain generates domain out of name and top level domain.

func (*Generator) Duration

func (g *Generator) Duration(lo, hi time.Duration) time.Duration

Duration generates a duration between lo and hi including those values.

func (*Generator) EMail

func (g *Generator) EMail() string

EMail returns a random e-mail address.

func (*Generator) FemaleName

func (g *Generator) FemaleName() (first, middle, last string)

FemaleName generates a female name consisting out of first, middle and last name.

func (*Generator) FlipCoin

func (g *Generator) FlipCoin(percent int) bool

FlipCoin returns true if the internal generated percentage is equal or greater than the passed percentage.

func (*Generator) Int

func (g *Generator) Int(lo, hi int) int

Int generates an int between lo and hi including those values.

func (*Generator) Ints

func (g *Generator) Ints(lo, hi, count int) []int

Ints generates a slice of random ints.

func (*Generator) LimitedWord

func (g *Generator) LimitedWord(lo, hi int) string

LimitedWord generates a random word with a length between lo and hi.

func (*Generator) MaleName

func (g *Generator) MaleName() (first, middle, last string)

MaleName generates a male name consisting out of first, middle and last name.

func (*Generator) Name

func (g *Generator) Name() (first, middle, last string)

Name generates a male or female name consisting out of first, middle and last name.

func (*Generator) OneByteOf

func (g *Generator) OneByteOf(values ...byte) byte

OneByteOf returns one of the passed bytes.

func (*Generator) OneDurationOf

func (g *Generator) OneDurationOf(values ...time.Duration) time.Duration

OneDurationOf returns one of the passed durations.

func (*Generator) OneIntOf

func (g *Generator) OneIntOf(values ...int) int

OneIntOf returns one of the passed ints.

func (*Generator) OneRuneOf

func (g *Generator) OneRuneOf(values string) rune

OneRuneOf returns one of the runes of the passed string.

func (*Generator) OneStringOf

func (g *Generator) OneStringOf(values ...string) string

OneStringOf returns one of the passed strings.

func (*Generator) Paragraph

func (g *Generator) Paragraph() string

Paragraph generates a paragraph between 2 and 10 sentences.

func (*Generator) Pattern

func (g *Generator) Pattern(pattern string) string

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) Percent

func (g *Generator) Percent() int

Percent generates an int between 0 and 100.

func (*Generator) Sentence

func (g *Generator) Sentence() string

Sentence generates a sentence between 2 and 15 words and possibly containing commas.

func (*Generator) SleepOneOf

func (g *Generator) SleepOneOf(sleeps ...time.Duration) time.Duration

SleepOneOf chooses randomely one of the passed durations and lets the goroutine sleep for this time.

func (*Generator) Time

func (g *Generator) Time(loc *time.Location, base time.Time, dur time.Duration) time.Time

Time generates a time between the given one and that time plus the given duration. The result will have the passed location.

func (*Generator) URL

func (g *Generator) URL() string

URL generates a http, https or ftp URL, some of the leading to a file.

func (*Generator) Word

func (g *Generator) Word() string

Word generates a random word.

func (*Generator) Words

func (g *Generator) Words(count int) []string

Words generates a slice of random words

type Printer

type Printer interface {
	// Printf prints a formatted information.
	Printf(format string, args ...interface{})
}

Printer allows to switch between different outputs.

func SetPrinter

func SetPrinter(p Printer) Printer

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

func NewTempDir(assert Assertion) *TempDir

NewTempDir creates a new temporary directory usable for direct usage or further subdirectories.

func (*TempDir) Mkdir

func (td *TempDir) Mkdir(name ...string) string

Mkdir creates a potentially nested directory inside the temporary directory.

func (*TempDir) Restore

func (td *TempDir) Restore()

Restore deletes the temporary directory and all contents.

func (*TempDir) String

func (td *TempDir) String() string

String returns the temporary directory.

type Test

type Test uint

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.

func (Test) String

func (t Test) String() string

type Tester

type Tester struct{}

Tester is a helper which can be used in own Assertion implementations.

func (Tester) Contains

func (t Tester) Contains(part, full interface{}) (bool, error)

Contains checks if the part type is matching to the full type and if the full data contains the part data.

func (Tester) HasPanic

func (t Tester) HasPanic(pf func()) (ok bool)

HasPanic checks if the passed function panics.

func (Tester) IsAbout

func (t Tester) IsAbout(obtained, expected, extent float64) bool

IsAbout checks if obtained and expected are to a given extent almost equal.

func (Tester) IsAssignable

func (t Tester) IsAssignable(obtained, expected interface{}) bool

IsAssignable checks if the types of obtained and expected are assignable.

func (Tester) IsCase

func (t Tester) IsCase(obtained string, upperCase bool) bool

IsCase checks if the obtained string is uppercase or lowercase.

func (Tester) IsEqual

func (t Tester) IsEqual(obtained, expected interface{}) bool

IsEqual checks if obtained and expected are equal.

func (Tester) IsImplementor

func (t Tester) IsImplementor(obtained, expected interface{}) (bool, error)

IsImplementor checks if obtained implements the expected interface variable pointer.

func (Tester) IsInRange

func (t Tester) IsInRange(obtained, low, high interface{}) (bool, error)

IsInRange checks for range assertions

func (Tester) IsMatching

func (t Tester) IsMatching(obtained, regex string) (bool, error)

IsMatching checks if the obtained string matches a regular expression.

func (Tester) IsNil

func (t Tester) IsNil(obtained interface{}) bool

IsNil checks if obtained is nil in a safe way.

func (Tester) IsSubstring

func (t Tester) IsSubstring(obtained, full string) bool

IsSubstring checks if obtained is a substring of the full string.

func (Tester) IsTrue

func (t Tester) IsTrue(obtained bool) bool

IsTrue checks if obtained is true.

func (Tester) IsValidPath

func (t Tester) IsValidPath(path string) (bool, error)

IsValidPath checks if the given directory or file path exists.

func (Tester) Len

func (t Tester) Len(obtained interface{}) (int, error)

Len checks the length of the obtained string, array, slice, map or channel.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL