...
1 package main
2
3 import (
4 "bytes"
5 "io/ioutil"
6 "os"
7 "runtime"
8 "strings"
9 "testing"
10 )
11
12 func expectBufferEquality(t *testing.T, name string, buffer *bytes.Buffer, expected string) {
13 output := buffer.String()
14 if output != expected {
15 t.Errorf("incorrect %s: \n%sexpected %s: \n%s", name, output, name, expected)
16 t.Log([]rune(output))
17 t.Log([]rune(expected))
18 }
19 }
20
21 func expectProcessMainResults(t *testing.T, input string, args []string, exitCode int, expectedOutput string, expectedError string) {
22 inputReader := strings.NewReader(input)
23
24 outputBuffer := new(bytes.Buffer)
25 errorBuffer := new(bytes.Buffer)
26
27 returnCode := processMain(args, inputReader, outputBuffer, errorBuffer)
28
29 expectBufferEquality(t, "output", outputBuffer, expectedOutput)
30 expectBufferEquality(t, "error", errorBuffer, expectedError)
31
32 if returnCode != exitCode {
33 t.Error("incorrect return code:", returnCode, "expected", exitCode)
34 }
35 }
36
37 func TestProcessMainReadFromStdin(t *testing.T) {
38 expectedOutput := `
39 [mytoml]
40 a = 42.0
41 `
42 input := `{
43 "mytoml": {
44 "a": 42
45 }
46 }
47 `
48 expectedError := ``
49 expectedExitCode := 0
50
51 expectProcessMainResults(t, input, []string{}, expectedExitCode, expectedOutput, expectedError)
52 }
53
54 func TestProcessMainReadFromFile(t *testing.T) {
55 input := `{
56 "mytoml": {
57 "a": 42
58 }
59 }
60 `
61 tmpfile, err := ioutil.TempFile("", "example.json")
62 if err != nil {
63 t.Fatal(err)
64 }
65 if _, err := tmpfile.Write([]byte(input)); err != nil {
66 t.Fatal(err)
67 }
68
69 defer os.Remove(tmpfile.Name())
70
71 expectedOutput := `
72 [mytoml]
73 a = 42.0
74 `
75 expectedError := ``
76 expectedExitCode := 0
77
78 expectProcessMainResults(t, ``, []string{tmpfile.Name()}, expectedExitCode, expectedOutput, expectedError)
79 }
80
81 func TestProcessMainReadFromMissingFile(t *testing.T) {
82 var expectedError string
83 if runtime.GOOS == "windows" {
84 expectedError = `open /this/file/does/not/exist: The system cannot find the path specified.
85 `
86 } else {
87 expectedError = `open /this/file/does/not/exist: no such file or directory
88 `
89 }
90
91 expectProcessMainResults(t, ``, []string{"/this/file/does/not/exist"}, -1, ``, expectedError)
92 }
93
View as plain text