File: util_test.go

package info (click to toggle)
golang-github-jarcoal-httpmock 1.0.8-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, sid
  • size: 220 kB
  • sloc: makefile: 2
file content (78 lines) | stat: -rw-r--r-- 1,359 bytes parent folder | download
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
package httpmock_test

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"testing"
)

func assertBody(t *testing.T, resp *http.Response, expected string) bool {
	defer resp.Body.Close()

	helper(t).Helper()

	data, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		t.Fatal(err)
	}

	got := string(data)

	if got != expected {
		t.Errorf("Got body: %#v, expected: %#v", got, expected)
		return false
	}
	return true
}

// Stolen from https://github.com/maxatome/go-testdeep
func catchPanic(fn func()) (panicked bool, ret string) {
	func() {
		defer func() {
			panicParam := recover()
			if panicked {
				ret = fmt.Sprint(panicParam)
			}
		}()
		panicked = true
		fn()
		panicked = false
	}()
	return
}

func tmpDir(t *testing.T) (string, func()) {
	dir, err := ioutil.TempDir("", "httpmock")
	if err != nil {
		helper(t).Helper()
		t.Fatal(err)
	}
	return dir, func() { os.RemoveAll(dir) }
}

func writeFile(t *testing.T, file string, content []byte) {
	err := ioutil.WriteFile(file, content, 0644)
	if err != nil {
		helper(t).Helper()
		t.Fatal(err)
	}
}

// fakeHelper allows to compensate the absence of
// (*testing.T).Helper() in go<1.9.
type fakeHelper struct{}

func (f fakeHelper) Helper() {}

type helperAble interface {
	Helper()
}

func helper(t interface{}) helperAble {
	if th, ok := t.(helperAble); ok {
		return th
	}
	return fakeHelper{}
}