...
1 package httpmock_test
2
3 import (
4 "encoding/json"
5 "path/filepath"
6 "testing"
7
8 "github.com/maxatome/go-testdeep/td"
9
10 "github.com/jarcoal/httpmock"
11 )
12
13 var _ json.Marshaler = httpmock.File("test.json")
14
15 func TestFile(t *testing.T) {
16 assert := td.Assert(t)
17
18 dir, cleanup := tmpDir(assert)
19 defer cleanup()
20
21 assert.Run("Valid JSON file", func(assert *td.T) {
22 okFile := filepath.Join(dir, "ok.json")
23 writeFile(assert, okFile, []byte(`{ "test": true }`))
24
25 encoded, err := json.Marshal(httpmock.File(okFile))
26 if !assert.CmpNoError(err, "json.Marshal(%s)", okFile) {
27 return
28 }
29 assert.String(encoded, `{"test":true}`)
30 })
31
32 assert.Run("Nonexistent JSON file", func(assert *td.T) {
33 nonexistentFile := filepath.Join(dir, "nonexistent.json")
34 _, err := json.Marshal(httpmock.File(nonexistentFile))
35 assert.CmpError(err, "json.Marshal(%s), error expected", nonexistentFile)
36 })
37
38 assert.Run("Invalid JSON file", func(assert *td.T) {
39 badFile := filepath.Join(dir, "bad.json")
40 writeFile(assert, badFile, []byte(`[123`))
41
42 _, err := json.Marshal(httpmock.File(badFile))
43 assert.CmpError(err, "json.Marshal(%s), error expected", badFile)
44 })
45
46 assert.Run("Bytes", func(assert *td.T) {
47 file := filepath.Join(dir, "ok.raw")
48 content := []byte(`abc123`)
49 writeFile(assert, file, content)
50
51 assert.Cmp(httpmock.File(file).Bytes(), content)
52 })
53
54 assert.Run("Bytes panic", func(assert *td.T) {
55 nonexistentFile := filepath.Join(dir, "nonexistent.raw")
56 assert.CmpPanic(func() { httpmock.File(nonexistentFile).Bytes() },
57 td.HasPrefix("Cannot read "+nonexistentFile))
58 })
59
60 assert.Run("String", func(assert *td.T) {
61 file := filepath.Join(dir, "ok.txt")
62 content := `abc123`
63 writeFile(assert, file, []byte(content))
64
65 assert.Cmp(httpmock.File(file).String(), content)
66 })
67
68 assert.Run("String panic", func(assert *td.T) {
69 nonexistentFile := filepath.Join(dir, "nonexistent.txt")
70 assert.CmpPanic(
71 func() {
72 httpmock.File(nonexistentFile).String()
73 },
74 td.HasPrefix("Cannot read "+nonexistentFile))
75 })
76 }
77
View as plain text