1
// Copyright 2013 Canonical Ltd.
2
// Licensed under the AGPLv3, see LICENCE file for details.
9
gc "launchpad.net/gocheck"
12
type CleanupFunc func(*gc.C)
13
type cleanupStack []CleanupFunc
15
// CleanupSuite adds the ability to add cleanup functions that are called
16
// during either test tear down or suite tear down depending on the method
18
type CleanupSuite struct {
19
testStack cleanupStack
20
suiteStack cleanupStack
23
func (s *CleanupSuite) SetUpSuite(c *gc.C) {
27
func (s *CleanupSuite) TearDownSuite(c *gc.C) {
28
s.callStack(c, s.suiteStack)
31
func (s *CleanupSuite) SetUpTest(c *gc.C) {
35
func (s *CleanupSuite) TearDownTest(c *gc.C) {
36
s.callStack(c, s.testStack)
39
func (s *CleanupSuite) callStack(c *gc.C, stack cleanupStack) {
40
for i := len(stack) - 1; i >= 0; i-- {
45
// AddCleanup pushes the cleanup function onto the stack of functions to be
46
// called during TearDownTest.
47
func (s *CleanupSuite) AddCleanup(cleanup CleanupFunc) {
48
s.testStack = append(s.testStack, cleanup)
51
// AddSuiteCleanup pushes the cleanup function onto the stack of functions to
52
// be called during TearDownSuite.
53
func (s *CleanupSuite) AddSuiteCleanup(cleanup CleanupFunc) {
54
s.suiteStack = append(s.suiteStack, cleanup)
57
// PatchEnvironment sets the environment variable 'name' the the value passed
58
// in. The old value is saved and returned to the original value at test tear
59
// down time using a cleanup function.
60
func (s *CleanupSuite) PatchEnvironment(name, value string) {
61
restore := PatchEnvironment(name, value)
62
s.AddCleanup(func(*gc.C) { restore() })
65
// PatchEnvPathPrepend prepends the given path to the environment $PATH and restores the
66
// original path on test teardown.
67
func (s *CleanupSuite) PatchEnvPathPrepend(dir string) {
68
restore := PatchEnvPathPrepend(dir)
69
s.AddCleanup(func(*gc.C) { restore() })
72
// PatchValue sets the 'dest' variable the the value passed in. The old value
73
// is saved and returned to the original value at test tear down time using a
74
// cleanup function. The value must be assignable to the element type of the
76
func (s *CleanupSuite) PatchValue(dest, value interface{}) {
77
restore := PatchValue(dest, value)
78
s.AddCleanup(func(*gc.C) { restore() })
81
// HookCommandOutput calls the package function of the same name to mock out
82
// the result of a particular comand execution, and will call the restore
83
// function on test teardown.
84
func (s *CleanupSuite) HookCommandOutput(
85
outputFunc *func(cmd *exec.Cmd) ([]byte, error),
89
result, restore := HookCommandOutput(outputFunc, output, err)
90
s.AddCleanup(func(*gc.C) { restore() })