forked from maruel/subcommands
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain_test.go
63 lines (52 loc) · 1.6 KB
/
main_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
// Copyright 2014 Marc-Antoine Ruel. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.
package main
import (
"io"
"log"
"os"
"testing"
"github.com/maruel/subcommands"
"github.com/maruel/ut"
)
// t.Parallel() cannot be used here, see main.go for rationale.
// In addition, logging must be zapped out.
// TODO(maruel): Create an in-memory os.File, couldn't quickly find a ready
// made fake only.
func newTempFile(t testing.TB) *os.File {
f, err := os.CreateTemp("", "sample-simple")
ut.AssertEqual(t, nil, err)
return f
}
// mockStdout mocks os.Stdout manually. To have it mocked automatically, see
// sample-complex.
func mockStdout(t testing.TB) func() {
oldStdout := os.Stdout
os.Stdout = newTempFile(t)
return func() {
os.Stdout.Close()
os.Stdout = oldStdout
}
}
func assertStdout(t testing.TB, expected string) {
_, _ = os.Stdout.Seek(0, 0)
actual, err := io.ReadAll(os.Stdout)
ut.AssertEqual(t, nil, err)
ut.AssertEqual(t, expected, string(actual))
}
func TestGreet(t *testing.T) {
defer mockStdout(t)()
ut.AssertEqual(t, 0, subcommands.Run(application, []string{"greet", "active tester"}))
assertStdout(t, "Hi active tester!\n")
}
func TestSleep(t *testing.T) {
defer mockStdout(t)()
// If running with "go test -v", the following log entry will be printed:
// utiltest.go:132: 2010/01/02 03:04:05 Simulating sleeping for 1s.
out := ut.NewWriter(t)
defer out.Close()
log.SetOutput(out)
ut.AssertEqual(t, 0, subcommands.Run(application, []string{"sleep", "-duration", "1"}))
assertStdout(t, "")
}