Debian Codegraph @

testing/integration/xmpp/utils_test.go

raw
1 package xmpp_test
2
3 import (
4 "context"
5 "io"
6 "net"
7 "net/url"
8 "testing"
9
10 "github.com/stretchr/testify/require"
11
12 "github.com/nicholas-fedor/shoutrrr/pkg/services/chat/xmpp"
13 "github.com/nicholas-fedor/shoutrrr/pkg/types"
14 )
15
16 type mockLogger struct{}
17
18 type mockSession struct {
19 chats [][2]string
20 rooms [][4]string
21 err error
22 chatErr error
23 roomErr error
24 }
25
26 const (
27 chatURL = "xmpp://alice:[email protected]/[email protected]"
28 mucURL = "xmpp://alice:[email protected]/[email protected]"
29 bothURL = "xmpp://alice:[email protected]/[email protected]&[email protected]&nick=bot&roompassword=pw"
30 )
31
32 func (*mockLogger) Print(...any) {}
33 func (*mockLogger) Printf(string, ...any) {}
34 func (*mockLogger) Println(...any) {}
35
36 func (*mockSession) Close() error {
37 return nil
38 }
39
40 func (m *mockSession) SendChat(_ context.Context, to, body string) error {
41 m.chats = append(m.chats, [2]string{to, body})
42 if m.chatErr != nil {
43 return m.chatErr
44 }
45
46 return m.err
47 }
48
49 func (m *mockSession) SendToRoom(_ context.Context, room, nick, password, body string) error {
50 m.rooms = append(m.rooms, [4]string{room, nick, password, body})
51 if m.roomErr != nil {
52 return m.roomErr
53 }
54
55 return m.err
56 }
57
58 func pipeDialer() types.DialContextFunc {
59 return func(context.Context, string, string) (net.Conn, error) {
60 client, server := net.Pipe()
61 go func() {
62 _, _ = io.Copy(io.Discard, server)
63 _ = server.Close()
64 }()
65
66 return client, nil
67 }
68 }
69
70 func createTestService(t *testing.T, rawURL string, session xmpp.Session) *xmpp.Service {
71 t.Helper()
72
73 parsed, err := url.Parse(rawURL)
74 require.NoError(t, err)
75
76 service := &xmpp.Service{}
77 require.NoError(t, service.Initialize(parsed, &mockLogger{}))
78 service.SetDialContext(pipeDialer())
79 service.SetSessionFactory(func(context.Context, *xmpp.Config, net.Conn) (xmpp.Session, error) {
80 return session, nil
81 })
82
83 return service
84 }
85
86 func mustParse(t *testing.T, raw string) *url.URL {
87 t.Helper()
88
89 parsed, err := url.Parse(raw)
90 require.NoError(t, err)
91
92 return parsed
93 }