Created
December 10, 2014 19:22
-
-
Save partkyle/e6bcc8189f1891609724 to your computer and use it in GitHub Desktop.
golang setup closure example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main_test | |
| import ( | |
| "net/http/httptest" | |
| "testing" | |
| "time" | |
| ) | |
| type Bag struct { | |
| Holding int | |
| } | |
| var ( | |
| server *httptest.Server | |
| bag *Bag | |
| ) | |
| func setup() { | |
| // should actually be my http handler that I am testing | |
| server = httptest.NewServer(nil) | |
| bag = &Bag{} | |
| } | |
| func teardown() { | |
| server.Close() | |
| } | |
| func TestSomething(t *testing.T) { | |
| setup() | |
| defer teardown() | |
| t.Logf("after setup bag=%+v", bag) | |
| time.Sleep(500 * time.Millisecond) | |
| t.Logf("%+v", *server) | |
| t.Logf("before assign bag=%+v", bag) | |
| bag.Holding = 1 | |
| t.Logf("after assign bag=%+v", bag) | |
| t.Log(server.URL) | |
| } | |
| func TestSomethingElse(t *testing.T) { | |
| setup() | |
| defer teardown() | |
| t.Logf("after setup bag=%+v", bag) | |
| time.Sleep(1 * time.Second) | |
| t.Logf("%+v", *server) | |
| t.Logf("before assign bag=%+v", bag) | |
| bag.Holding = 5 | |
| t.Logf("after assign bag=%+v", bag) | |
| t.Log(server.URL) | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| [ `go test -parallel=2 -v -race my_test.go` | done: 6.875938401s ] | |
| === RUN TestSomething | |
| --- PASS: TestSomething (0.50 seconds) | |
| my_test.go:32: after setup bag=&{Holding:0} | |
| my_test.go:35: {URL:http://127.0.0.1:59272 Listener:0xc20800ebd0 TLS:<nil> Config:0xc208004360 wg:{m:{state:0 sema:0} counter:0 waiters:0 sema:<nil>}} | |
| my_test.go:37: before assign bag=&{Holding:0} | |
| my_test.go:39: after assign bag=&{Holding:1} | |
| my_test.go:41: http://127.0.0.1:59272 | |
| === RUN TestSomethingElse | |
| --- PASS: TestSomethingElse (1.01 seconds) | |
| my_test.go:48: after setup bag=&{Holding:0} | |
| my_test.go:51: {URL:http://127.0.0.1:59286 Listener:0xc20800ede0 TLS:<nil> Config:0xc208004420 wg:{m:{state:0 sema:0} counter:0 waiters:0 sema:<nil>}} | |
| my_test.go:53: before assign bag=&{Holding:0} | |
| my_test.go:55: after assign bag=&{Holding:5} | |
| my_test.go:57: http://127.0.0.1:59286 | |
| PASS | |
| ok command-line-arguments 2.523s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment