-
Notifications
You must be signed in to change notification settings - Fork 0
/
option_test.go
67 lines (56 loc) · 1.38 KB
/
option_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
package option
import (
"errors"
"net/url"
"testing"
)
type Client struct {
APIKey string
BaseURL *url.URL
}
func OptionAPIKey(apiKey string) Func[Client] {
return func(client Client) (Client, error) {
client.APIKey = apiKey
return client, nil
}
}
func OptionBaseURL(baseURL string) Func[Client] {
return func(client Client) (Client, error) {
parsed, err := url.Parse(baseURL)
if err != nil {
return Client{}, err
}
client.BaseURL = parsed
return client, nil
}
}
func TestApply(t *testing.T) {
t.Run("applies options", func(t *testing.T) {
apiKey := "foo-api-key"
baseURL, err := url.Parse("https://example.com")
requireNoError(t, err)
got, err := Apply[Client](Client{},
OptionAPIKey(apiKey),
OptionBaseURL(baseURL.String()),
)
requireNoError(t, err)
want := Client{APIKey: apiKey, BaseURL: baseURL}
if got.APIKey != want.APIKey || got.BaseURL.String() != want.BaseURL.String() {
t.Errorf("got: %v, want: %v", got, want)
}
})
t.Run("fails on error", func(t *testing.T) {
_, got := Apply[Client](Client{},
Func[Client](func(Client) (Client, error) { return Client{}, errors.New("foo error") }),
)
want := "failed to apply option 0: foo error"
if got.Error() != want {
t.Errorf("got: %v, want: %v", got, want)
}
})
}
func requireNoError(t *testing.T, err error) {
if err != nil {
t.Fatalf("error when none expected: %v", err)
}
}