| 1 |
// Licensed under the MIT license, see LICENSE file for details. |
| 2 |
|
| 3 |
package quicktest |
| 4 |
|
| 5 |
import ( |
| 6 |
"io/ioutil" |
| 7 |
"os" |
| 8 |
"reflect" |
| 9 |
) |
| 10 |
|
| 11 |
// Patch sets a variable to a temporary value for the duration of the test. |
| 12 |
// |
| 13 |
// It sets the value pointed to by the given destination to the given |
| 14 |
// value, which must be assignable to the element type of the destination. |
| 15 |
// |
| 16 |
// At the end of the test (see "Deferred execution" in the package docs), the |
| 17 |
// destination is set back to its original value. |
| 18 |
func (c *C) Patch(dest, value interface{}) { |
| 19 |
destv := reflect.ValueOf(dest).Elem() |
| 20 |
oldv := reflect.New(destv.Type()).Elem() |
| 21 |
oldv.Set(destv) |
| 22 |
valuev := reflect.ValueOf(value) |
| 23 |
if !valuev.IsValid() { |
| 24 |
// This isn't quite right when the destination type is not |
| 25 |
// nilable, but it's better than the complex alternative. |
| 26 |
valuev = reflect.Zero(destv.Type()) |
| 27 |
} |
| 28 |
destv.Set(valuev) |
| 29 |
c.cleanup(func() { |
| 30 |
destv.Set(oldv) |
| 31 |
}) |
| 32 |
} |
| 33 |
|
| 34 |
// Unsetenv unsets an environment variable for the duration of a test. |
| 35 |
func (c *C) Unsetenv(name string) { |
| 36 |
c.Setenv(name, "") |
| 37 |
os.Unsetenv(name) |
| 38 |
} |
| 39 |
|
| 40 |
// Mkdir makes a temporary directory and returns its name. |
| 41 |
// |
| 42 |
// At the end of the test (see "Deferred execution" in the package docs), the |
| 43 |
// directory and its contents are removed. |
| 44 |
// |
| 45 |
// Deprecated: in Go >= 1.15 use testing.TB.TempDir instead. |
| 46 |
func (c *C) Mkdir() string { |
| 47 |
td, ok := c.TB.(interface { |
| 48 |
TempDir() string |
| 49 |
}) |
| 50 |
if ok { |
| 51 |
return td.TempDir() |
| 52 |
} |
| 53 |
name, err := ioutil.TempDir("", "quicktest-") |
| 54 |
c.Assert(err, Equals, nil) |
| 55 |
c.cleanup(func() { |
| 56 |
if err := os.RemoveAll(name); err != nil { |
| 57 |
// Don't call c.Check because the stack traverse logic won't |
| 58 |
// print the source location, so just log instead. |
| 59 |
c.Errorf("quicktest cannot remove temporary testing directory: %v", err) |
| 60 |
} |
| 61 |
}) |
| 62 |
return name |
| 63 |
} |
| 64 |
|
| 65 |
// cleanup uses Cleanup when it can, falling back to using Defer. |
| 66 |
func (c *C) cleanup(f func()) { |
| 67 |
if tb, ok := c.TB.(cleaner); ok { |
| 68 |
tb.Cleanup(f) |
| 69 |
} else { |
| 70 |
c.Defer(f) |
| 71 |
} |
| 72 |
} |