-
Notifications
You must be signed in to change notification settings - Fork 0
/
main_test.go
129 lines (114 loc) · 2.41 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package main
import (
"bytes"
"flag"
"fmt"
"io"
"os"
"testing"
)
func TestMain(t *testing.T) {
os.Args = []string{"qr", "chey"}
main()
}
func TestMainDefaults(t *testing.T) {
var buf bytes.Buffer
os.Args = []string{"qr", "chey"}
flag.Parse()
if err := execute(&buf); err != nil {
t.Error(err)
}
}
func TestMainBig(t *testing.T) {
var buf bytes.Buffer
os.Args = []string{"qr", "-big", "chey"}
flag.Parse()
if err := execute(&buf); err != nil {
t.Error(err)
}
}
func TestMainLevel(t *testing.T) {
var buf bytes.Buffer
os.Args = []string{"qr", "-level", "3", "chey"}
flag.Parse()
if err := execute(&buf); err != nil {
t.Error(err)
}
}
func TestMainErrors(t *testing.T) {
var buf bytes.Buffer
cases := []struct {
args []string
expected error
}{
{[]string{"qr"}, ErrMissingText},
{[]string{"qr", "chey", "wuz", "here"}, ErrToManyArgs},
{[]string{"qr", "-level", "5", "chey"}, ErrInvalidLevel},
}
for _, c := range cases {
os.Args = c.args
flag.Parse()
if err := execute(&buf); err == nil {
t.Errorf("expected = %#v", c.expected)
}
}
}
func TestMainPng(t *testing.T) {
var buf bytes.Buffer
file := fmt.Sprintf("%s%c%s", t.TempDir(), os.PathSeparator, "qrcode.png")
os.Args = []string{"qr", "-png", "-file", file, "-level", "0", "chey"}
flag.Parse()
if err := execute(&buf); err != nil {
t.Error(err)
}
}
func TestMainPngStdout(t *testing.T) {
var buf bytes.Buffer
os.Args = []string{"qr", "-png", "-file", "-", "-level", "0", "chey"}
flag.Parse()
rc := capture()
if err := execute(&buf); err != nil {
t.Error(err)
}
out := <-rc()
if out == "" {
t.Error("cannot send PNG to stdout")
}
}
func TestMainHelp(t *testing.T) {
fs := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
fs.Usage = usage
err := fs.Parse([]string{"-h"})
if err != flag.ErrHelp {
t.Error("expected = flag.ErrHelp")
}
}
func TestMainVersionFlag(t *testing.T) {
var buf bytes.Buffer
os.Args = []string{"qr", "-version"}
flag.Parse()
if err := execute(&buf); err != nil {
t.Error(err)
}
}
func capture() func() <-chan string {
stdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
c := make(chan string)
// this copies stdout to the buffer without blocking
go func() {
var buf bytes.Buffer
if _, err := io.Copy(&buf, r); err != nil {
panic(err)
}
c <- buf.String()
}()
return func() <-chan string {
defer func() {
w.Close()
os.Stdout = stdout
}()
return c
}
}