TempFile is a test helper that creates a temporary file, returns its name and a function which when called removes that file. This is useful to be called as follows at the top of a test or benchmark requiring a temporary file: func TestFoo(t *testing.T) { name, rmfile := testutil.TempFile(t) defer
(tb testing.TB)
| 48 | // ... |
| 49 | // } |
| 50 | func TempFile(tb testing.TB) (file string, rmfile func()) { |
| 51 | tb.Helper() |
| 52 | |
| 53 | f, err := os.CreateTemp("", tb.Name()) |
| 54 | if err != nil { |
| 55 | tb.Fatalf("can't create temp file: %v", err) |
| 56 | } |
| 57 | |
| 58 | if err = f.Close(); err != nil { |
| 59 | tb.Fatalf("can't create temp file: %v", err) |
| 60 | } |
| 61 | |
| 62 | rmfile = func() { |
| 63 | if err = os.Remove(f.Name()); err != nil { |
| 64 | tb.Fatalf("can't remove temp file: %v", err) |
| 65 | } |
| 66 | } |
| 67 | return f.Name(), rmfile |
| 68 | } |
| 69 | |
| 70 | // DisableLogging is a test helper that disable logging (in fact it sets its |
| 71 | // level to panic). It returns a function which when called, resets it to its |