Debian Codegraph @

attachment_test.go

raw
1 package proton_test
2
3 import (
4 "context"
5 "errors"
6 "net/http"
7 "sync"
8 "testing"
9
10 "github.com/henrybear327/go-proton-api"
11 "github.com/henrybear327/go-proton-api/server"
12 "github.com/stretchr/testify/require"
13 )
14
15 func TestAttachment_429Response(t *testing.T) {
16 ctx, cancel := context.WithCancel(context.Background())
17 defer cancel()
18
19 s := server.New()
20 defer s.Close()
21
22 m := proton.New(
23 proton.WithHostURL(s.GetHostURL()),
24 proton.WithTransport(proton.InsecureTransport()),
25 )
26
27 _, _, err := s.CreateUser("user", []byte("pass"))
28 require.NoError(t, err)
29
30 c, _, err := m.NewClientWithLogin(ctx, "user", []byte("pass"))
31 require.NoError(t, err)
32
33 s.AddStatusHook(func(r *http.Request) (int, bool) {
34 return http.StatusTooManyRequests, true
35 })
36
37 _, err = c.GetAttachment(ctx, "someID")
38 require.Error(t, err)
39
40 apiErr := new(proton.APIError)
41 require.True(t, errors.As(err, &apiErr), "expected to be API error")
42 require.Equal(t, 429, apiErr.Status)
43 require.Equal(t, proton.InvalidValue, apiErr.Code)
44 require.Equal(t, "Request failed with status 429", apiErr.Message)
45 }
46
47 func TestAttachment_ContextCancelled(t *testing.T) {
48 ctx, cancel := context.WithCancel(context.Background())
49
50 s := server.New()
51 defer s.Close()
52
53 m := proton.New(
54 proton.WithHostURL(s.GetHostURL()),
55 proton.WithTransport(proton.InsecureTransport()),
56 )
57
58 _, _, err := s.CreateUser("user", []byte("pass"))
59 require.NoError(t, err)
60
61 c, _, err := m.NewClientWithLogin(ctx, "user", []byte("pass"))
62 require.NoError(t, err)
63
64 wg := sync.WaitGroup{}
65 wg.Add(1)
66
67 s.AddStatusHook(func(r *http.Request) (int, bool) {
68 wg.Wait()
69 return http.StatusTooManyRequests, true
70 })
71
72 go func() {
73 _, err = c.GetAttachment(ctx, "someID")
74 wg.Done()
75 }()
76
77 cancel()
78
79 wg.Wait()
80 require.Error(t, err)
81 require.True(t, errors.Is(err, context.Canceled))
82 }