| // Copyright 2019 The Fuchsia Authors. All rights reserved. |
| // Use of this source code is governed by a BSD-style license that can be |
| // found in the LICENSE file. |
| |
| package testbed |
| |
| import ( |
| "io/ioutil" |
| "os" |
| "testing" |
| ) |
| |
| // TestBed is an integration test helper that encapsulates setup and teardown. It ensures that tests |
| // are run in isolated directories. Always `defer teardown` to ensure teardown even if the |
| // current go-routine panics. |
| // |
| // Example: |
| // |
| // func TestFoo(t *testing.T) { |
| // tb := New(t) |
| // tb.Setup() |
| // defer tb.Teardown() |
| // ... test code ... |
| // } |
| // |
| type TestBed struct { |
| t *testing.T |
| dir string |
| } |
| |
| // New creates a new TestBed. |
| func New(t *testing.T) *TestBed { |
| return &TestBed{t: t} |
| } |
| |
| func (tb *TestBed) Setup() { |
| if testing.Short() { |
| tb.t.Skip("skipping integration tests when -test.short is set") |
| } |
| tmpdir, err := ioutil.TempDir("", "") |
| if err != nil { |
| tb.t.Fatal(err) |
| } |
| if err := os.Chdir(tmpdir); err != nil { |
| tb.t.Fatal(err) |
| } |
| tb.dir = tmpdir |
| } |
| |
| func (tb *TestBed) Teardown() { |
| if err := os.RemoveAll(tb.dir); err != nil { |
| tb.t.Fatalf("failed to teardown: %v", err) |
| } |
| } |