testing: github.com/juju/testing Index | Examples | Files | Directories

package testing

import "github.com/juju/testing"

Code:

package main

import (
    "fmt"

    "log"

    "github.com/juju/loggo"
    "github.com/juju/testing"
)

type ExampleInterfaceToMock interface {
    Add(a, b int) int
    Div(a, b int) (int, error)
}

type fakeType struct {
    ExampleInterfaceToMock
    *testing.CallMocker
}

func (f *fakeType) Add(a, b int) int {
    results := f.MethodCall(f, "Add", a, b)
    return results[0].(int)
}

func (f *fakeType) Div(a, b int) (int, error) {
    results := f.MethodCall(f, "Div", a, b)
    return results[0].(int), testing.TypeAssertError(results[1])
}

type ExampleTypeWhichUsesInterface struct {
    calculator ExampleInterfaceToMock
}

func (e *ExampleTypeWhichUsesInterface) Add(nums ...int) int {
    var tally int
    for n := range nums {
        tally = e.calculator.Add(tally, n)
    }
    return tally
}

func (e *ExampleTypeWhichUsesInterface) Div(nums ...int) (int, error) {
    var tally int
    var err error
    for n := range nums {
        tally, err = e.calculator.Div(tally, n)
        if err != nil {
            break
        }
    }
    return tally, err
}

func main() {
    var logger loggo.Logger

    // Set a fake type which mocks out calls.
    mock := &fakeType{CallMocker: testing.NewCallMocker(logger)}
    mock.Call("Add", 1, 1).Returns(2)
    mock.Call("Div", 1, 1).Returns(1, nil)
    mock.Call("Div", 1, 0).Returns(0, fmt.Errorf("cannot divide by zero"))

    // Pass in the mock which satisifes a dependency of
    // ExampleTypeWhichUsesInterface. This allows us to inject mocked
    // calls.
    example := ExampleTypeWhichUsesInterface{calculator: mock}
    if example.Add(1, 1) != 2 {
        log.Fatal("unexpected result")
    }

    if result, err := example.Div(1, 1); err != nil {
        log.Fatalf("unexpected error: %v", err)
    } else if result != 1 {
        log.Fatal("unexpected result")
    }

    if _, err := example.Div(1, 0); err == nil {
        log.Fatal("did not receive expected divide by zero error")
    }
}

Index

Examples

Package Files

cleanup.go cmd.go constants.go goversion15.go home.go http.go imports.go isolation.go log.go mgo.go mgo_unix.go mocker.go norace.go osenv.go patch.go stub.go tcpproxy.go

Constants

const (
    EchoQuotedArgsUnix = `#!/bin/bash --norc
name=` + "`basename $0`" + "" /* 325 byte string literal not displayed */

    EchoQuotedArgsWindows = "" /* 562 byte string literal not displayed */

)
const (

    // The default password to use when connecting to the mongo database.
    DefaultMongoPassword = "conn-from-name-secret"
)
const GOVERSION = 1.5
const LongWait = 10 * time.Second

LongWait is used when something should have already happened, or happens quickly, but we want to make sure we just haven't missed it. As in, the test suite should proceed without sleeping at all, but just in case. It is long so that we don't have spurious failures without actually slowing down the test suite

const RaceEnabled = false
const ShortWait = 50 * time.Millisecond

ShortWait is a reasonable amount of time to block waiting for something that shouldn't actually happen. (as in, the test suite will *actually* wait this long before continuing)

Variables

var HookChannelSize = 10
var (
    // MgoServer is a shared mongo server used by tests.
    MgoServer = &MgoInstance{}
)
var Server = NewHTTPServer(5 * time.Second)

func AssertEchoArgs Uses

func AssertEchoArgs(c *gc.C, execName string, args ...string)

AssertEchoArgs is used to check the args from an execution of a command that has been patched using PatchExecutable containing EchoQuotedArgs.

func CaptureOutput Uses

func CaptureOutput(c *gc.C, f func()) (stdout []byte, stderr []byte)

CaptureOutput runs the given function and captures anything written to Stderr or Stdout during f's execution.

func FindImports Uses

func FindImports(packageName, prefix string) ([]string, error)

FindImports returns a sorted list of packages imported by the package with the given name that have the given prefix. The resulting list removes the common prefix, leaving just the short names.

func FindTCPPort Uses

func FindTCPPort() int

FindTCPPort finds an unused TCP port and returns it. Use of this function has an inherent race condition - another process may claim the port before we try to use it. We hope that the probability is small enough during testing to be negligible.

func HomePath Uses

func HomePath(names ...string) string

HomePath joins the specified path snippets and returns an absolute path under Juju home.

func HookCommandOutput Uses

func HookCommandOutput(
    outputFunc *func(cmd *exec.Cmd) ([]byte, error), output []byte, err error) (<-chan *exec.Cmd, func())

HookCommandOutput intercepts CommandOutput to a function that passes the actual command and it's output back via a channel, and returns the error passed into this function. It also returns a cleanup function so you can restore the original function

func JujuXDGDataHomePath Uses

func JujuXDGDataHomePath(names ...string) string

JujuXDGDataHomePath returns the test home path, it is just a convenience for tests, if extra path snippets are passed they will be joined to juju home. This tool assumes ~/.config/juju as the juju home.

func MgoDialInfo Uses

func MgoDialInfo(certs *Certs, addrs ...string) *mgo.DialInfo

MgoDialInfo returns a DialInfo suitable for dialling an MgoInstance at any of the given addresses, optionally using TLS.

func MgoTestPackage Uses

func MgoTestPackage(t *testing.T, certs *Certs)

MgoTestPackage should be called to register the tests for any package that requires a MongoDB server. If certs is non-nil, a secure SSL connection will be used from client to server.

func MongodVersion Uses

func MongodVersion() (version.Number, error)

func PatchExecutable Uses

func PatchExecutable(c *gc.C, patcher EnvironmentPatcher, execName, script string, exitCodes ...int)

PatchExecutable creates an executable called 'execName' in a new test directory and that directory is added to the path.

func PatchExecutableAsEchoArgs Uses

func PatchExecutableAsEchoArgs(c *gc.C, patcher EnvironmentPatcher, execName string, exitCodes ...int)

PatchExecutableAsEchoArgs creates an executable called 'execName' in a new test directory and that directory is added to the path. The content of the script is 'EchoQuotedArgs', and the args file is removed using a cleanup function.

func PatchExecutableThrowError Uses

func PatchExecutableThrowError(c *gc.C, patcher EnvironmentPatcher, execName string, exitCode int)

PatchExecutableThrowError is needed to test cases in which we expect exit codes from executables called from the system path

func ReadEchoArgs Uses

func ReadEchoArgs(c *gc.C, execName string) string

ReadEchoArgs is used to read the args from an execution of a command that has been patched using PatchExecutable containing EchoQuotedArgs.

func TypeAssertError Uses

func TypeAssertError(err interface{}) error

type CallMocker Uses

type CallMocker struct {
    Stub
    // contains filtered or unexported fields
}

CallMocker is a tool which allows tests to dynamically specify results for a given set of input parameters.

func NewCallMocker Uses

func NewCallMocker(logger loggo.Logger) *CallMocker

NewCallMocker returns a CallMocker which will log calls and results utilizing the given logger.

func (*CallMocker) Call Uses

func (m *CallMocker) Call(fnName string, args ...interface{}) *callMockReturner

Call is the first half a chained-predicate which registers that calls to a function named fnName with arguments args should return some value. The returned values are handled by the returned type, callMockReturner.

func (*CallMocker) MethodCall Uses

func (m *CallMocker) MethodCall(receiver interface{}, fnName string, args ...interface{}) []interface{}

MethodCall logs the call to a method and any results that will be returned. It returns the results previously specified by the Call function. If no results were specified, the returned slice will be nil.

func (*CallMocker) Results Uses

func (m *CallMocker) Results(fnName string, args ...interface{}) []interface{}

Results returns any results previously specified by calls to the Call method. If there are no results, the returned slice will be nil.

type Certs Uses

type Certs struct {
    // CACert holds the CA certificate. This must certify the private key that
    // was used to sign the server certificate.
    CACert *x509.Certificate
    // ServerCert holds the certificate that certifies the server's
    // private key.
    ServerCert *x509.Certificate
    // ServerKey holds the server's private key.
    ServerKey *rsa.PrivateKey
}

Certs holds the certificates and keys required to make a secure SSL connection.

type CleanupSuite Uses

type CleanupSuite struct {
    // contains filtered or unexported fields
}

CleanupSuite adds the ability to add cleanup functions that are called during either test tear down or suite tear down depending on the method called.

func (*CleanupSuite) AddCleanup Uses

func (s *CleanupSuite) AddCleanup(cleanup func(*gc.C))

AddCleanup pushes the cleanup function onto the stack of functions to be called during TearDownTest or TearDownSuite. TearDownTest will be used if SetUpTest has already been called, else we will use TearDownSuite

func (*CleanupSuite) HookCommandOutput Uses

func (s *CleanupSuite) HookCommandOutput(
    outputFunc *func(cmd *exec.Cmd) ([]byte, error),
    output []byte,
    err error,
) <-chan *exec.Cmd

HookCommandOutput calls the package function of the same name to mock out the result of a particular comand execution, and will call the restore function on test teardown.

func (*CleanupSuite) PatchEnvPathPrepend Uses

func (s *CleanupSuite) PatchEnvPathPrepend(dir string)

PatchEnvPathPrepend prepends the given path to the environment $PATH and restores the original path on test teardown.

func (*CleanupSuite) PatchEnvironment Uses

func (s *CleanupSuite) PatchEnvironment(name, value string)

PatchEnvironment sets the environment variable 'name' the the value passed in. The old value is saved and returned to the original value at test tear down time using a cleanup function.

func (*CleanupSuite) PatchValue Uses

func (s *CleanupSuite) PatchValue(dest, value interface{})

PatchValue sets the 'dest' variable the the value passed in. The old value is saved and returned to the original value at test tear down time using a cleanup function. The value must be assignable to the element type of the destination.

func (*CleanupSuite) SetUpSuite Uses

func (s *CleanupSuite) SetUpSuite(c *gc.C)

func (*CleanupSuite) SetUpTest Uses

func (s *CleanupSuite) SetUpTest(c *gc.C)

func (*CleanupSuite) TearDownSuite Uses

func (s *CleanupSuite) TearDownSuite(c *gc.C)

func (*CleanupSuite) TearDownTest Uses

func (s *CleanupSuite) TearDownTest(c *gc.C)

type EnvironmentPatcher Uses

type EnvironmentPatcher interface {
    PatchEnvironment(name, value string)
}

EnvironmentPatcher is an interface that requires just one method: PatchEnvironment.

type FakeHome Uses

type FakeHome struct {
    // contains filtered or unexported fields
}

FakeHome stores information about the user's home environment so it can be cast aside for tests and restored afterwards.

func MakeFakeHome Uses

func MakeFakeHome(c *gc.C) *FakeHome

func (*FakeHome) AddFiles Uses

func (h *FakeHome) AddFiles(c *gc.C, files ...TestFile)

func (*FakeHome) FileContents Uses

func (h *FakeHome) FileContents(c *gc.C, path string) string

FileContents returns the test file contents for the given specified path (which may be relative, so we compare with the base filename only).

func (*FakeHome) FileExists Uses

func (h *FakeHome) FileExists(path string) bool

FileExists returns if the given relative file path exists in the fake home.

type FakeHomeSuite Uses

type FakeHomeSuite struct {
    CleanupSuite
    LoggingSuite
    Home *FakeHome
}

FakeHomeSuite sets up a fake home directory before running tests.

func (*FakeHomeSuite) SetUpSuite Uses

func (s *FakeHomeSuite) SetUpSuite(c *gc.C)

func (*FakeHomeSuite) SetUpTest Uses

func (s *FakeHomeSuite) SetUpTest(c *gc.C)

func (*FakeHomeSuite) TearDownSuite Uses

func (s *FakeHomeSuite) TearDownSuite(c *gc.C)

func (*FakeHomeSuite) TearDownTest Uses

func (s *FakeHomeSuite) TearDownTest(c *gc.C)

type HTTPServer Uses

type HTTPServer struct {
    URL     string
    Timeout time.Duration
    // contains filtered or unexported fields
}

func NewHTTPServer Uses

func NewHTTPServer(timeout time.Duration) *HTTPServer

func (*HTTPServer) Flush Uses

func (s *HTTPServer) Flush()

Flush discards all pending requests and responses.

func (*HTTPServer) Response Uses

func (s *HTTPServer) Response(status int, headers map[string]string, body []byte)

Response prepares the test server to respond the following request using the provided response parameters.

func (*HTTPServer) ResponseFunc Uses

func (s *HTTPServer) ResponseFunc(n int, f ResponseFunc)

ResponseFunc prepares the test server to respond the following n requests using f to build each response.

func (*HTTPServer) ResponseMap Uses

func (s *HTTPServer) ResponseMap(n int, m ResponseMap)

ResponseMap prepares the test server to respond the following n requests using the m to obtain the responses.

func (*HTTPServer) Responses Uses

func (s *HTTPServer) Responses(n int, status int, headers map[string]string, body []byte)

Responses prepares the test server to respond the following n requests using the provided response parameters.

func (*HTTPServer) ServeHTTP Uses

func (s *HTTPServer) ServeHTTP(w http.ResponseWriter, req *http.Request)

func (*HTTPServer) Start Uses

func (s *HTTPServer) Start()

func (*HTTPServer) WaitRequest Uses

func (s *HTTPServer) WaitRequest() *http.Request

WaitRequest returns the next request made to the http server from the queue. If no requests were previously made, it waits until the timeout value for one to be made.

func (*HTTPServer) WaitRequests Uses

func (s *HTTPServer) WaitRequests(n int) []*http.Request

WaitRequests returns the next n requests made to the http server from the queue. If not enough requests were previously made, it waits until the timeout value for them to be made.

type HTTPSuite Uses

type HTTPSuite struct{}

func (*HTTPSuite) SetUpSuite Uses

func (s *HTTPSuite) SetUpSuite(c *gc.C)

func (*HTTPSuite) SetUpTest Uses

func (s *HTTPSuite) SetUpTest(c *gc.C)

func (*HTTPSuite) TearDownSuite Uses

func (s *HTTPSuite) TearDownSuite(c *gc.C)

func (*HTTPSuite) TearDownTest Uses

func (s *HTTPSuite) TearDownTest(c *gc.C)

func (*HTTPSuite) URL Uses

func (s *HTTPSuite) URL(path string) string

type IsolatedMgoSuite Uses

type IsolatedMgoSuite struct {
    IsolationSuite
    MgoSuite
}

IsolatedMgoSuite is a convenience type that combines the functionality IsolationSuite and MgoSuite.

func (*IsolatedMgoSuite) SetUpSuite Uses

func (s *IsolatedMgoSuite) SetUpSuite(c *gc.C)

func (*IsolatedMgoSuite) SetUpTest Uses

func (s *IsolatedMgoSuite) SetUpTest(c *gc.C)

func (*IsolatedMgoSuite) TearDownSuite Uses

func (s *IsolatedMgoSuite) TearDownSuite(c *gc.C)

func (*IsolatedMgoSuite) TearDownTest Uses

func (s *IsolatedMgoSuite) TearDownTest(c *gc.C)

type IsolationSuite Uses

type IsolationSuite struct {
    OsEnvSuite
    CleanupSuite
    LoggingSuite
}

IsolationSuite isolates the tests from the underlaying system environment, sets up test logging and exposes cleanup facilities.

func (*IsolationSuite) SetUpSuite Uses

func (s *IsolationSuite) SetUpSuite(c *gc.C)

func (*IsolationSuite) SetUpTest Uses

func (s *IsolationSuite) SetUpTest(c *gc.C)

func (*IsolationSuite) TearDownSuite Uses

func (s *IsolationSuite) TearDownSuite(c *gc.C)

func (*IsolationSuite) TearDownTest Uses

func (s *IsolationSuite) TearDownTest(c *gc.C)

type LoggingCleanupSuite Uses

type LoggingCleanupSuite struct {
    LoggingSuite
    CleanupSuite
}

LoggingCleanupSuite is defined for backward compatibility. Do not use this suite in new tests.

func (*LoggingCleanupSuite) SetUpSuite Uses

func (s *LoggingCleanupSuite) SetUpSuite(c *gc.C)

func (*LoggingCleanupSuite) SetUpTest Uses

func (s *LoggingCleanupSuite) SetUpTest(c *gc.C)

func (*LoggingCleanupSuite) TearDownSuite Uses

func (s *LoggingCleanupSuite) TearDownSuite(c *gc.C)

func (*LoggingCleanupSuite) TearDownTest Uses

func (s *LoggingCleanupSuite) TearDownTest(c *gc.C)

type LoggingSuite Uses

type LoggingSuite struct{}

LoggingSuite redirects the juju logger to the test logger when embedded in a gocheck suite type.

func (*LoggingSuite) SetUpSuite Uses

func (s *LoggingSuite) SetUpSuite(c *gc.C)

func (*LoggingSuite) SetUpTest Uses

func (s *LoggingSuite) SetUpTest(c *gc.C)

func (*LoggingSuite) TearDownSuite Uses

func (s *LoggingSuite) TearDownSuite(c *gc.C)

func (*LoggingSuite) TearDownTest Uses

func (s *LoggingSuite) TearDownTest(c *gc.C)

type MgoInstance Uses

type MgoInstance struct {

    // Params is a list of additional parameters that will be passed to
    // the mongod application
    Params []string

    // EnableReplicaSet will pass the right parameters to --replSet and call
    // replSetInitiate when appropriate.
    EnableReplicaSet bool

    // EnableAuth enables authentication/authorization.
    EnableAuth bool

    // WithoutV8 is true if we believe this Mongo doesn't actually have the
    // V8 engine
    WithoutV8 bool
    // contains filtered or unexported fields
}

func (*MgoInstance) Addr Uses

func (m *MgoInstance) Addr() string

Addr returns the address of the MongoDB server.

func (*MgoInstance) Destroy Uses

func (inst *MgoInstance) Destroy()

Destroy kills mongod and cleans up its data directory.

func (*MgoInstance) DestroyWithLog Uses

func (inst *MgoInstance) DestroyWithLog()

DestroyWithLog causes mongod to exit, cleans up its data directory, and captures the last N lines of mongod's log output.

func (*MgoInstance) Dial Uses

func (inst *MgoInstance) Dial() (*mgo.Session, error)

Dial returns a new connection to the MongoDB server.

func (*MgoInstance) DialDirect Uses

func (inst *MgoInstance) DialDirect() (*mgo.Session, error)

DialDirect returns a new direct connection to the shared MongoDB server. This must be used if you're connecting to a replicaset that hasn't been initiated yet.

func (*MgoInstance) DialInfo Uses

func (inst *MgoInstance) DialInfo() *mgo.DialInfo

DialInfo returns information suitable for dialling the receiving MongoDB instance.

func (*MgoInstance) EnsureRunning Uses

func (inst *MgoInstance) EnsureRunning() error

func (*MgoInstance) MustDial Uses

func (inst *MgoInstance) MustDial() *mgo.Session

MustDial returns a new connection to the MongoDB server, and panics on errors.

func (*MgoInstance) MustDialDirect Uses

func (inst *MgoInstance) MustDialDirect() *mgo.Session

MustDialDirect works like DialDirect, but panics on errors.

func (*MgoInstance) Port Uses

func (m *MgoInstance) Port() int

Port returns the port of the MongoDB server.

func (*MgoInstance) Reset Uses

func (inst *MgoInstance) Reset() error

Reset deletes all content from the MongoDB server.

func (*MgoInstance) Restart Uses

func (inst *MgoInstance) Restart()

Restart restarts the mongo server, useful for testing what happens when a state server goes down.

func (*MgoInstance) SSLEnabled Uses

func (m *MgoInstance) SSLEnabled() bool

SSLEnabled reports whether or not SSL is enabled for the MongoDB server.

func (*MgoInstance) Start Uses

func (inst *MgoInstance) Start(certs *Certs) error

Start starts a MongoDB server in a temporary directory.

type MgoSuite Uses

type MgoSuite struct {
    Session *mgo.Session

    // DebugMgo controls whether SetUpSuite enables mgo logging and
    // debugging. Set this before calling SetUpSuite. Enabling either
    // logging or debugging in mgo adds a significant overhead to the
    // Juju tests, so they are disabled by default.
    DebugMgo bool
}

MgoSuite is a suite that deletes all content from the shared MongoDB server at the end of every test and supplies a connection to the shared MongoDB server.

func (*MgoSuite) SetUpSuite Uses

func (s *MgoSuite) SetUpSuite(c *gc.C)

func (*MgoSuite) SetUpTest Uses

func (s *MgoSuite) SetUpTest(c *gc.C)

func (*MgoSuite) TearDownSuite Uses

func (s *MgoSuite) TearDownSuite(c *gc.C)

func (*MgoSuite) TearDownTest Uses

func (s *MgoSuite) TearDownTest(c *gc.C)

type OsEnvSuite Uses

type OsEnvSuite struct {
    // contains filtered or unexported fields
}

OsEnvSuite isolates the tests from the underlaying system environment. Environment variables are reset in SetUpTest and restored in TearDownTest.

func (*OsEnvSuite) SetUpSuite Uses

func (s *OsEnvSuite) SetUpSuite(c *gc.C)

func (*OsEnvSuite) SetUpTest Uses

func (s *OsEnvSuite) SetUpTest(c *gc.C)

func (*OsEnvSuite) TearDownSuite Uses

func (s *OsEnvSuite) TearDownSuite(c *gc.C)

func (*OsEnvSuite) TearDownTest Uses

func (s *OsEnvSuite) TearDownTest(c *gc.C)

type PatchExecConfig Uses

type PatchExecConfig struct {
    // Stderr is the value you'd like written to stderr.
    Stderr string
    // Stdout is the value you'd like written to stdout.
    Stdout string
    // ExitCode controls the exit code of the patched executable.
    ExitCode int
    // Args is a channel that will be sent the args passed to the patched
    // execCommand function.  It should be a channel with a buffer equal to the
    // number of executions you expect to be run (often just 1).  Do not use an
    // unbuffered channel unless you're reading the channel from another
    // goroutine, or you will almost certainly block your tests indefinitely.
    Args chan<- []string
}

PatchExecConfig holds the arguments for PatchExecHelper.GetExecCommand.

type PatchExecHelper Uses

type PatchExecHelper struct{}

PatchExecHelper is a type that helps you patch out calls to executables by patching out the exec.Command function that creates the exec.Cmd to call them. This is very similar to PatchExecutable above, except it works on windows exe files, is a lot easier to control stderr and stdout, doesn't require arcane bash and batch scripting, and lets you control both the output *and* test the arguments, all without requiring writing any garbage files to disk.

PatchExecHelper *must* be embedded in your test suite in order to function. It adds a test to your testsuite which by default simply does nothing. When the patched exec.Command function is called (returned by GetExecCommand), instead of running the requested executable, we call the test executable with -check.f to rnu only TestExecSuiteHelperProcess, which acts as a configurable main function.

func (PatchExecHelper) GetExecCommand Uses

func (PatchExecHelper) GetExecCommand(cfg PatchExecConfig) func(string, ...string) *exec.Cmd

GetExecCommand returns a function that can be used to patch out a use of exec.Command. See PatchExecConfig for details about the arguments.

func (PatchExecHelper) TestExecSuiteHelperProcess Uses

func (PatchExecHelper) TestExecSuiteHelperProcess(c *gc.C)

TestExecSuiteHelperProcess is a fake test which is added to your test suite (because you remembered to embed PatchExecHelper in your suite, right?). It allows us to use the test executable as a helper process to get expected output for tests. When run normally during tests, this test simply does nothing (and passes). The above patched exec.Command runs the test executable with -check.f, it runs this test and enables the configurable behavior. Because the test exits with os.Exit, no additional test output is written.

type ProxiedSession Uses

type ProxiedSession struct {
    *mgo.Session
    *TCPProxy
}

ProxiedSession represents a mongo session that's proxied through a TCPProxy instance.

func NewProxiedSession Uses

func NewProxiedSession(c *gc.C) *ProxiedSession

NewProxiedSession returns a ProxiedSession instance that holds a mgo.Session that directs through a TCPProxy instance to the testing mongoDB server, and the proxy instance itself. This allows tests to check what happens when mongo connections are broken.

The returned value should be closed after use.

func (*ProxiedSession) Close Uses

func (s *ProxiedSession) Close()

Close closes s.Session and s.TCPProxy.

type Response Uses

type Response struct {
    Status  int
    Headers map[string]string
    Body    []byte
}

type ResponseFunc Uses

type ResponseFunc func(path string) Response

type ResponseMap Uses

type ResponseMap map[string]Response

ResponseMap maps request paths to responses.

type Restorer Uses

type Restorer func()

Restorer holds a function that can be used to restore some previous state.

func PatchEnvPathPrepend Uses

func PatchEnvPathPrepend(dir string) Restorer

PatchEnvPathPrepend provides a simple way to prepend path to the start of the PATH environment variable. Returns a function that restores the environment to what it was before.

func PatchEnvironment Uses

func PatchEnvironment(name, value string) Restorer

PatchEnvironment provides a test a simple way to override a single environment variable. A function is returned that will return the environment to what it was before.

func PatchValue Uses

func PatchValue(dest, value interface{}) Restorer

PatchValue sets the value pointed to by the given destination to the given value, and returns a function to restore it to its original value. The value must be assignable to the element type of the destination.

func (Restorer) Add Uses

func (f Restorer) Add(f1 Restorer) Restorer

Add returns a Restorer that restores first f1 and then f. It is valid to call this on a nil Restorer.

func (Restorer) Restore Uses

func (r Restorer) Restore()

Restore restores some previous state.

type Stub Uses

type Stub struct {
    // contains filtered or unexported fields
}

Stub is used in testing to stand in for some other value, to record all calls to stubbed methods/functions, and to allow users to set the values that are returned from those calls. Stub is intended to be embedded in another struct that will define the methods to track:

type stubConn struct {
    *testing.Stub
    Response []byte
}

func newStubConn() *stubConn {
    return &stubConn{
        Stub: &testing.Stub{},
    }
}

// Send implements Connection.
func (fc *stubConn) Send(request string) []byte {
    fc.MethodCall(fc, "Send", request)
    return fc.Response, fc.NextErr()
}

As demonstrated in the example, embed a pointer to testing.Stub. This allows a single testing.Stub to be shared between multiple stubs.

Error return values are set through Stub.Errors. Set it to the errors you want returned (or use the convenience method `SetErrors`). The `NextErr` method returns the errors from Stub.Errors in sequence, falling back to `DefaultError` when the sequence is exhausted. Thus each stubbed method should call `NextErr` to get its error return value.

To validate calls made to the stub in a test call the CheckCalls (or CheckCall) method:

s.stub.CheckCalls(c, []StubCall{{
    FuncName: "Send",
    Args: []interface{}{
        expected,
    },
}})

s.stub.CheckCall(c, 0, "Send", expected)

Not only is Stub useful for building a interface implementation to use in testing (e.g. a network API client), it is also useful in regular function patching situations:

type myStub struct {
    *testing.Stub
}

func (f *myStub) SomeFunc(arg interface{}) error {
    f.AddCall("SomeFunc", arg)
    return f.NextErr()
}

s.PatchValue(&somefunc, s.myStub.SomeFunc)

This allows for easily monitoring the args passed to the patched func, as well as controlling the return value from the func in a clean manner (by simply setting the correct field on the stub).

func (*Stub) AddCall Uses

func (f *Stub) AddCall(funcName string, args ...interface{})

AddCall records a stubbed function call for later inspection using the CheckCalls method. A nil receiver is recorded. Thus for methods use MethodCall. All stubbed functions should call AddCall.

func (*Stub) Calls Uses

func (f *Stub) Calls() []StubCall

Calls returns the list of calls that have been registered on the stub (i.e. made on the stub's methods), in the order that they were made.

func (*Stub) CheckCall Uses

func (f *Stub) CheckCall(c *gc.C, index int, funcName string, args ...interface{})

CheckCall checks the recorded call at the given index against the provided values. If the index is out of bounds then the check fails. The receiver is not checked. If it is significant for a test then it can be checked separately:

c.Check(mystub.Receivers[index], gc.Equals, expected)

func (*Stub) CheckCallNames Uses

func (f *Stub) CheckCallNames(c *gc.C, expected ...string) bool

CheckCallNames verifies that the in-order list of called method names matches the expected calls.

func (*Stub) CheckCalls Uses

func (f *Stub) CheckCalls(c *gc.C, expected []StubCall)

CheckCalls verifies that the history of calls on the stub's methods matches the expected calls. The receivers are not checked. If they are significant then check Stub.Receivers separately.

func (*Stub) CheckCallsUnordered Uses

func (f *Stub) CheckCallsUnordered(c *gc.C, expected []StubCall)

CheckCallsUnordered verifies that the history of calls on the stub's methods contains the expected calls. The receivers are not checked. If they are significant then check Stub.Receivers separately. This method explicitly does not check if the calls were made in order, just whether they have been made.

func (*Stub) CheckErrors Uses

func (f *Stub) CheckErrors(c *gc.C, expected ...error) bool

CheckErrors verifies that the list of errors is matches the expected list.

func (*Stub) CheckNoCalls Uses

func (f *Stub) CheckNoCalls(c *gc.C)

CheckNoCalls verifies that none of the stub's methods have been called.

func (*Stub) CheckReceivers Uses

func (f *Stub) CheckReceivers(c *gc.C, expected ...interface{}) bool

CheckReceivers verifies that the list of errors is matches the expected list.

func (*Stub) MethodCall Uses

func (f *Stub) MethodCall(receiver interface{}, funcName string, args ...interface{})

MethodCall records a stubbed method call for later inspection using the CheckCalls method. The receiver is added to Stub.Receivers.

func (*Stub) NextErr Uses

func (f *Stub) NextErr() error

NextErr returns the error that should be returned on the nth call to any method on the stub. It should be called for the error return in all stubbed methods.

func (*Stub) PopNoErr Uses

func (f *Stub) PopNoErr()

PopNoErr pops off the next error without returning it. If the error is not nil then PopNoErr will panic.

PopNoErr is useful in stub methods that do not return an error.

func (*Stub) ResetCalls Uses

func (f *Stub) ResetCalls()

ResetCalls erases the calls recorded by this Stub.

func (*Stub) SetErrors Uses

func (f *Stub) SetErrors(errors ...error)

SetErrors sets the sequence of error returns for the stub. Each call to Err (thus each stub method call) pops an error off the front. So frontloading nil here will allow calls to pass, followed by a failure.

type StubCall Uses

type StubCall struct {
    // Funcname is the name of the function that was called.
    FuncName string

    // Args is the set of arguments passed to the function. They are
    // in the same order as the function's parameters
    Args []interface{}
}

StubCall records the name of a called function and the passed args.

type TCPProxy Uses

type TCPProxy struct {
    // contains filtered or unexported fields
}

TCPProxy is a simple TCP proxy that can be used to deliberately break TCP connections.

func NewTCPProxy Uses

func NewTCPProxy(c *gc.C, remoteAddr string) *TCPProxy

NewTCPProxy runs a proxy that copies to and from the given remote TCP address. When the proxy is closed, its listener and all connections will be closed.

func (*TCPProxy) Addr Uses

func (p *TCPProxy) Addr() string

Addr returns the TCP address of the proxy. Dialing this address will cause a connection to be made to the remote address; any data written will be written there, and any data read from the remote address will be available to read locally.

func (*TCPProxy) Close Uses

func (p *TCPProxy) Close() error

Close closes the TCPProxy and any connections that are currently active.

func (*TCPProxy) CloseConns Uses

func (p *TCPProxy) CloseConns()

CloseConns closes all the connections that are currently active. The proxy itself remains active.

func (*TCPProxy) PauseConns Uses

func (p *TCPProxy) PauseConns()

PauseConns stops all traffic flowing through the proxy.

func (*TCPProxy) ResumeConns Uses

func (p *TCPProxy) ResumeConns()

ResumeConns resumes sending traffic through the proxy.

type TestFile Uses

type TestFile struct {
    Name, Data string
}

Directories

PathSynopsis
checkers
filetesting
httptesting

Package testing imports 35 packages (graph) and is imported by 749 packages. Updated 2019-10-02. Refresh now. Tools for package owners.