| 1 |
# Expect |
| 2 |
|
| 3 |
A library to help you write tests in Go. |
| 4 |
|
| 5 |
What's wrong with Go's built-in testing package? Not much, except it tends to lead to verbose code. `Expect` runs within `go test` but provides a different syntax for specifying expectations. |
| 6 |
|
| 7 |
## Example |
| 8 |
|
| 9 |
```go |
| 10 |
import ( |
| 11 |
"testing" |
| 12 |
. "github.com/karlseguin/expect" |
| 13 |
) |
| 14 |
|
| 15 |
type CalculatorTests struct{} |
| 16 |
|
| 17 |
func Test_Caculator(t *testing.T) { |
| 18 |
Expectify(new(CalculatorTests), t) |
| 19 |
} |
| 20 |
|
| 21 |
func (_ CalculatorTests) AddsTwoNumbers() { |
| 22 |
c := new(Calculator) |
| 23 |
Expect(c.Add(4, 8)).To.Equal(12) |
| 24 |
Expect(c.Add(10, 2)).Greater.Than(11) |
| 25 |
Expect(c.Add(10, 2)).LessOrEqual.To(12) |
| 26 |
Expect(c.Add(10, 2)).Not.Greater.Than(9000) |
| 27 |
Expect(c.Add(1, 1)).Not.To.Equal(3) |
| 28 |
|
| 29 |
//OR |
| 30 |
|
| 31 |
Expect(c.Add(4.8)).ToEqual(12) |
| 32 |
Expect(c.Add(10, 2)).GreaterThan(11) |
| 33 |
Expect(c.Add(10, 2)).LessOrEqualTo(12) |
| 34 |
Expect(c.Add(10, 2)).Not.GreaterThan(9000) |
| 35 |
Expect(c.Add(1, 1)).Not.ToEqual(3) |
| 36 |
} |
| 37 |
``` |
| 38 |
|
| 39 |
You can also use `Skip(format, args...)` and `Fail(format, args...)` to either skip a test or cause a test to fail. |
| 40 |
|
| 41 |
## Running |
| 42 |
|
| 43 |
Run tests as you normally would via `go test`. However, to run specific tests, use the -m flag, which will do a case-insensitive regular expression match. |
| 44 |
|
| 45 |
go test -m AddsTwo |
| 46 |
|
| 47 |
## Expectations |
| 48 |
|
| 49 |
Two similar syntaxes of expectations are supported |
| 50 |
|
| 51 |
* `To.Equal(x)` or `ToEqual(x)` |
| 52 |
* `Greater.Than(x)` or `GreaterThan(x)` |
| 53 |
* `GreaterOrEqual.To(x)` or `GreaterOrEqualTo(x)` |
| 54 |
* `Less.Than(x)` or `LessThan(x)` |
| 55 |
* `LessOrEqual.To(x)` or `LessOrEqualTo(x)` |
| 56 |
|
| 57 |
All expectations can be reversed by starting the chain with `Not.`: |
| 58 |
|
| 59 |
* `Not.To.Equal(x)` or `Not.ToEqual(x)` |
| 60 |
* `Not.Greater.Than(x)` or `Not.GreaterThan(x)` |
| 61 |
* `Not.GreaterOrEqual.To(x)` or `Not.GreaterOrEqualTo(x)` |
| 62 |
* `Not.Less.Than(x)` or `Not.LessThan(x)` |
| 63 |
* `Not.LessOrEqual.To(x)` or `Not.LessOrEqualTo(x)` |
| 64 |
|
| 65 |
### Eql |
| 66 |
|
| 67 |
The `Equal` method is strict. This will fail: |
| 68 |
|
| 69 |
```go |
| 70 |
//fails |
| 71 |
Expect(uint32(449)).To.Equal(449) |
| 72 |
``` |
| 73 |
|
| 74 |
`Eql` can be used to do implicit type conversion for common types (notably between the various integer types, as well as []byte <-> string). |
| 75 |
|
| 76 |
```go |
| 77 |
//passes |
| 78 |
Expect(uint32(449)).To.Eql(449) |
| 79 |
Expect([]byte{65, 66}).To.Eql("AB") |
| 80 |
``` |
| 81 |
|
| 82 |
### JSON |
| 83 |
|
| 84 |
`Expect` exposes a `JSON` helper: |
| 85 |
|
| 86 |
```go |
| 87 |
Expect(`{"spice":"must flow"}`).To.Equal(JSON(` |
| 88 |
{ |
| 89 |
"spice": "must flow" |
| 90 |
}`)) |
| 91 |
``` |
| 92 |
|
| 93 |
The helper makes it possible to write a expectations which ignore white spaces and are thus easier to write, read and maintain. Internally, when the `JSON` helper is used, both values (actual and expected) are unmarshalled using the encoding/json library (essentially converted to an map[string]interface{}) and a then compared in this form. |
| 94 |
|
| 95 |
### Contains |
| 96 |
|
| 97 |
`To.Contain` works with strings, arrays, slices and maps. For arrays and slices, only individual values are matched. For example: |
| 98 |
|
| 99 |
```go |
| 100 |
Expect([]int{1,2,3}).To.Contain([]int{1,2}) |
| 101 |
``` |
| 102 |
|
| 103 |
will, sadly, not work. |
| 104 |
|
| 105 |
The exception to this is for strings and `[]byte`. These work with either a single value or an array (they use the stdlib's `strings.Contains` and `bytes.Contains`). |
| 106 |
|
| 107 |
## Additional Information |
| 108 |
|
| 109 |
You can add extra information to an error by using the `Message(format string, args ...interface{})` function on an expectation: |
| 110 |
|
| 111 |
```go |
| 112 |
Expect(res.Code).To.Equal(404).Message("path: %s", path) |
| 113 |
``` |
| 114 |
|
| 115 |
This can be useful when you're testing the same code against different inputs (probably in a `for` loop). |
| 116 |
|
| 117 |
Given a message with a layout but not arguments, `Message` will inject the actual |
| 118 |
and expected values. |
| 119 |
|
| 120 |
```go |
| 121 |
Expect(res.Code).To.Equal(404).Message("Expected %d got %d") |
| 122 |
``` |
| 123 |
|
| 124 |
## Multiple Values |
| 125 |
|
| 126 |
`Expect` throws away all but the first value. This is convenient when a method returns an error which you don't care to test: |
| 127 |
|
| 128 |
```go |
| 129 |
Expect(ioutil.ReadFile("blah")).To.Equal([]byte{1, 2, 3, 4}) |
| 130 |
``` |
| 131 |
|
| 132 |
However, using `To.Equal` multiple values can be provided: |
| 133 |
|
| 134 |
```go |
| 135 |
Expect(1, true, "a").To.Equal(1, true, "a") |
| 136 |
``` |
| 137 |
|
| 138 |
## stdout |
| 139 |
|
| 140 |
Go's testing package has no hooks into its reporting. `Expect` takes the drastic step of occasionally silencing `os.Stdout`, which many packages uses (such as `fmt.Print`). However, within your test, `os.Stdout` **will** work. |
| 141 |
|
| 142 |
If you print anything outside of your test, say during `init`, it'll likely be silenced by `Expect`. You can disable this behavior with the `-vv` flag (use `-v` and `-vv` in combination to change the behavior of both `Expect` and Go's library) |
| 143 |
|
| 144 |
## Mixing with *testing.T |
| 145 |
|
| 146 |
Since `Expect` runs within `go test`, you can mix `Expect` style tests with traditional Go tests. To do this, you'll probably want to run your tests with `-vv` (see *stdout* section above). Even without `-vv`, you *will* get the proper return code (!= 0 on failure). |
| 147 |
|
| 148 |
This also means that `go test` features, such as `-cover`, work with `Expect`. However, `Expect` tests cannot be run in parallel. |
| 149 |
|
| 150 |
## Advanced Patterns |
| 151 |
|
| 152 |
Since tests are organized within a class, there are patterns you can used for tests which require special care. For example, unexported methods can be used for helpers without conflicting with other helpers: |
| 153 |
|
| 154 |
```go |
| 155 |
func (ct *CalculatorTests) AddsTwoNumbers() { |
| 156 |
c := ct.n() |
| 157 |
// ... |
| 158 |
} |
| 159 |
|
| 160 |
func (ct *CalculatorTests) n() *Calculator { |
| 161 |
return &Calculator{...} |
| 162 |
} |
| 163 |
``` |
| 164 |
|
| 165 |
Futhermore, when you setup the runner, you can setup code to before or after running tests (once for all tests, not once per test): |
| 166 |
|
| 167 |
```go |
| 168 |
func Test_Caculator(t *testing.T) { |
| 169 |
// before all tests |
| 170 |
Expectify(new(CalculatorTests), t) |
| 171 |
// after all tests |
| 172 |
} |
| 173 |
``` |
| 174 |
|
| 175 |
### Before / After Each |
| 176 |
|
| 177 |
You can intercept each run test by creating a method named `Each` which takes a single parameter of type `func()`: |
| 178 |
|
| 179 |
```go |
| 180 |
func (_ *CalculatorTests) Each(f func()) { |
| 181 |
//run code before each test |
| 182 |
f() |
| 183 |
//run code after each test |
| 184 |
} |
| 185 |
``` |
| 186 |
|
| 187 |
|
| 188 |
### Global Before Each |
| 189 |
A before each can be registered for all suites. This function will be called before any suite-specific Each. |
| 190 |
|
| 191 |
```go |
| 192 |
func init() { |
| 193 |
BeforeEach(func() { |
| 194 |
//do something |
| 195 |
}) |
| 196 |
} |
| 197 |
``` |
| 198 |
|
| 199 |
## Summary File |
| 200 |
If you have many tests, you may find it cumbersome to run with -v and/or -vv, yet still want |
| 201 |
a brief summary beyond what Go's test runner provides (I always worry that everything passed because nothing ran). However, because of the way that Go's running takes over stdout and the fact that it potentially launches multiple processes, writing a final summary is not something we can do as easily as we'd like. |
| 202 |
|
| 203 |
What we can do is use the `-summary <PATH>` flag and provide a path where summary data will be stored / updated. Therefore, even if multiple processes are launched, and even if we can't output to stdout, with a bit of work invoking the tests, we can get a summary. For example, I recommend a simple Makefile: |
| 204 |
|
| 205 |
```Makefile |
| 206 |
TEMPFILE := $(shell mktemp -u -t testsummary) |
| 207 |
|
| 208 |
test: |
| 209 |
go test ./... -summary $(TEMPFILE) |
| 210 |
@if [ -a $(TEMPFILE) ] ; \ |
| 211 |
then \ |
| 212 |
awk '{s+=$$1} END {print "\033[1;32m", s, "passed"}' $(TEMPFILE); rm $(TEMPFILE) ;\ |
| 213 |
fi; |
| 214 |
|
| 215 |
# Mocks |
| 216 |
|
| 217 |
The `mock` sub-package provides mock objects and buiders for common standard library components. |
| 218 |
|
| 219 |
**Work in progress** |
| 220 |
|
| 221 |
## net.Conn |
| 222 |
|
| 223 |
The `MockConn` lets you test both the reading and writing to a `net.Conn` object. |
| 224 |
|
| 225 |
### Writes |
| 226 |
Writes sent to the mock object are captured in the `Written` field. Note that this is a `[][]byte` - it captures each write individually. |
| 227 |
|
| 228 |
### Reads |
| 229 |
You can `Read` from the mock object by first priming it with data via the `Reading` function: |
| 230 |
|
| 231 |
```go |
| 232 |
conn := mock.Conn().Reading([]byte("hello"), []byte("world")) |
| 233 |
``` |
| 234 |
|
| 235 |
To drain this connection `Read` will have to be called twice provided a large enough buffer is provided. If the supplied buffer is too small, the mock object will behave as expected, reading what it can, returning the length read and properly handling subsequent requests to `Read`. |
| 236 |
|
| 237 |
Rather than reading data, the mock object can be primed to return an error: |
| 238 |
|
| 239 |
```go |
| 240 |
conn := mock.Conn().Error(errors.New("some error")) |
| 241 |
``` |
| 242 |
|
| 243 |
This will cause the first call to `Read` to return an error |
| 244 |
|
| 245 |
# Builders |
| 246 |
|
| 247 |
The `build` sub-package provides build helpers for common standard library components. Builders expose a fluent interface for setting various properties. The default object returned from a builder should be safe to use as-is. |
| 248 |
|
| 249 |
**Work in progress** |
| 250 |
|
| 251 |
## *http.Request |
| 252 |
|
| 253 |
```go |
| 254 |
req := build.Request(). |
| 255 |
Method("GET"). |
| 256 |
URLString("http://openmymind.net/test"). |
| 257 |
Request |
| 258 |
``` |
| 259 |
|
| 260 |
* `Method(method string)` |
| 261 |
* `Proto(major, minor int)` |
| 262 |
* `URL(u *url.URL)` |
| 263 |
* `URLString(url string)` - panics if `url` isn't a valid URL |
| 264 |
* `Path(path string)` - changes the `path` component of the URL only |
| 265 |
* `RawQuery(query string)` - changes the `rawquery` component of the URL only |
| 266 |
* `Host(host string)` - changes the `host` component of the URL only |
| 267 |
* `Header(key, value string)` - set the specified header |
| 268 |
* `Body(body string)` - set's the request's body |