File size: 3,593 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
package harness

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"net/mail"
	"net/url"
	"os/exec"
	"path/filepath"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"testing"
	"time"

	"github.com/stretchr/testify/require"
)

type mailpit struct {
	t        *testing.T
	smtpAddr string
	apiAddr  string
	cleanup  func() error
}

var mailpitStartLock sync.Mutex

func newMailpit(t *testing.T) (mp *mailpit) {
	t.Helper()
	mailpitStartLock.Lock()
	defer mailpitStartLock.Unlock()

	addrs, err := findOpenPorts(2)
	require.NoError(t, err, "expected to find open ports for mailpit")
	_, file, _, ok := runtime.Caller(0)
	require.True(t, ok, "expected to find caller")

	var output bytes.Buffer
	cmdpath := filepath.Join(filepath.Dir(file), "../../../bin/tools/mailpit")

	cmd := exec.Command(cmdpath, "-s", addrs[0], "-l", addrs[1])
	cmd.Stdout, cmd.Stderr = &output, &output
	require.NoError(t, cmd.Start(), "expected to start mailpit")

	require.Eventually(t, func() bool {
		// check if the process is still running
		if cmd.ProcessState != nil && cmd.ProcessState.Exited() {
			t.Error(output.String())
			return false
		}
		return isListening(addrs[0]) && isListening(addrs[1])
	}, 30*time.Second, 100*time.Millisecond, "expected to find mailpit listening on ports")

	t.Cleanup(func() { _ = cmd.Process.Kill() })
	return &mailpit{
		t:        t,
		smtpAddr: addrs[0],
		apiAddr:  addrs[1],
		cleanup:  cmd.Process.Kill,
	}
}

func doJSON(t *testing.T, method, url string, reqBody, respBody any) {
	t.Helper()

	var data []byte
	if reqBody != nil {
		var err error
		data, err = json.Marshal(reqBody)
		require.NoError(t, err, "expected to marshal request")
	}

	req, err := http.NewRequest(method, url, bytes.NewReader(data))
	require.NoError(t, err, "expected to create request")

	resp, err := http.DefaultClient.Do(req)
	require.NoError(t, err, "expected to send request")
	data, err = io.ReadAll(resp.Body)
	require.NoError(t, err, "expected to read response")
	require.Equalf(t, http.StatusOK, resp.StatusCode, "expected status OK; data=\n%s", string(data))
	if respBody == nil {
		return
	}
	require.NoErrorf(t, json.Unmarshal(data, respBody), "expected to unmarshal response from:\n%s", string(data))
}

func (m *mailpit) UnreadMessages() []emailMessage {
	m.t.Helper()

	var body struct {
		Messages []struct {
			To      []mail.Address
			Snippet string
		}
	}
	doJSON(m.t, "GET", "http://"+m.apiAddr+"/api/v1/search?query=is:unread", nil, &body)

	var result []emailMessage
	for _, msg := range body.Messages {
		var addrs []string
		for _, p := range msg.To {
			addrs = append(addrs, p.Address)
		}
		result = append(result, emailMessage{address: addrs, body: msg.Snippet})
	}

	return result
}

// ReadMessage will return true if an unread message was found and matched the keywords, marking it as read in the process.
func (m *mailpit) ReadMessage(to string, keywords ...string) bool {
	quotedKeywords := make([]string, len(keywords))
	for i, k := range keywords {
		quotedKeywords[i] = strconv.Quote(k)
	}
	query := fmt.Sprintf("is:unread to:%s %s", strconv.Quote(to), strings.Join(quotedKeywords, " "))

	var body struct {
		Messages []struct{ ID string }
	}
	doJSON(m.t, "GET", "http://"+m.apiAddr+"/api/v1/search?query="+url.QueryEscape(query), nil, &body)

	if len(body.Messages) == 0 {
		return false
	}

	var reqBody struct {
		IDs  []string
		Read bool
	}
	reqBody.IDs = append(reqBody.IDs, body.Messages[0].ID) // only read the first message
	reqBody.Read = true

	doJSON(m.t, http.MethodPut, "http://"+m.apiAddr+"/api/v1/messages", reqBody, nil)

	return true
}