summaryrefslogtreecommitdiff
path: root/vendor/github.com/playwright-community/playwright-go/apiresponse_assertions.go
blob: 187618e289c0150fb8d49de0dbc06be07b4d6190 (plain)
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
package playwright

import (
	"errors"
	"fmt"
	"regexp"
	"strings"
)

type apiResponseAssertionsImpl struct {
	actual APIResponse
	isNot  bool
}

func newAPIResponseAssertions(actual APIResponse, isNot bool) *apiResponseAssertionsImpl {
	return &apiResponseAssertionsImpl{
		actual: actual,
		isNot:  isNot,
	}
}

func (ar *apiResponseAssertionsImpl) Not() APIResponseAssertions {
	return newAPIResponseAssertions(ar.actual, true)
}

func (ar *apiResponseAssertionsImpl) ToBeOK() error {
	if ar.isNot != ar.actual.Ok() {
		return nil
	}
	message := fmt.Sprintf(`Response status expected to be within [200..299] range, was %v`, ar.actual.Status())
	if ar.isNot {
		message = strings.ReplaceAll(message, "expected to", "expected not to")
	}
	logList, err := ar.actual.(*apiResponseImpl).fetchLog()
	if err != nil {
		return err
	}
	log := strings.Join(logList, "\n")
	if log != "" {
		message += "\nCall log:\n" + log
	}

	isTextEncoding := false
	contentType, ok := ar.actual.Headers()["content-type"]
	if ok {
		isTextEncoding = isTexualMimeType(contentType)
	}
	if isTextEncoding {
		text, err := ar.actual.Text()
		if err == nil {
			message += fmt.Sprintf(`\n Response Text:\n %s`, subString(text, 0, 1000))
		}
	}
	return errors.New(message)
}

func isTexualMimeType(mimeType string) bool {
	re := regexp.MustCompile(`^(text\/.*?|application\/(json|(x-)?javascript|xml.*?|ecmascript|graphql|x-www-form-urlencoded)|image\/svg(\+xml)?|application\/.*?(\+json|\+xml))(;\s*charset=.*)?$`)
	return re.MatchString(mimeType)
}

func subString(s string, start, length int) string {
	if start < 0 {
		start = 0
	}
	if length < 0 {
		length = 0
	}
	rs := []rune(s)
	end := start + length
	if end > len(rs) {
		end = len(rs)
	}
	return string(rs[start:end])
}