You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

mail_test.go 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  1. // Copyright 2019 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package mailer
  4. import (
  5. "bytes"
  6. "context"
  7. "fmt"
  8. "html/template"
  9. "regexp"
  10. "strings"
  11. "testing"
  12. texttmpl "text/template"
  13. activities_model "code.gitea.io/gitea/models/activities"
  14. "code.gitea.io/gitea/models/db"
  15. issues_model "code.gitea.io/gitea/models/issues"
  16. repo_model "code.gitea.io/gitea/models/repo"
  17. "code.gitea.io/gitea/models/unittest"
  18. user_model "code.gitea.io/gitea/models/user"
  19. "code.gitea.io/gitea/modules/setting"
  20. "github.com/stretchr/testify/assert"
  21. )
  22. const subjectTpl = `
  23. {{.SubjectPrefix}}[{{.Repo}}] @{{.Doer.Name}} #{{.Issue.Index}} - {{.Issue.Title}}
  24. `
  25. const bodyTpl = `
  26. <!DOCTYPE html>
  27. <html>
  28. <head>
  29. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  30. <title>{{.Subject}}</title>
  31. </head>
  32. <body>
  33. <p>{{.Body}}</p>
  34. <p>
  35. ---
  36. <br>
  37. <a href="{{.Link}}">View it on Gitea</a>.
  38. </p>
  39. </body>
  40. </html>
  41. `
  42. func prepareMailerTest(t *testing.T) (doer *user_model.User, repo *repo_model.Repository, issue *issues_model.Issue, comment *issues_model.Comment) {
  43. assert.NoError(t, unittest.PrepareTestDatabase())
  44. mailService := setting.Mailer{
  45. From: "test@gitea.com",
  46. }
  47. setting.MailService = &mailService
  48. setting.Domain = "localhost"
  49. doer = unittest.AssertExistsAndLoadBean(t, &user_model.User{ID: 2})
  50. repo = unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1, Owner: doer})
  51. issue = unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 1, Repo: repo, Poster: doer})
  52. assert.NoError(t, issue.LoadRepo(db.DefaultContext))
  53. comment = unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: 2, Issue: issue})
  54. return doer, repo, issue, comment
  55. }
  56. func TestComposeIssueCommentMessage(t *testing.T) {
  57. doer, _, issue, comment := prepareMailerTest(t)
  58. setting.IncomingEmail.Enabled = true
  59. defer func() { setting.IncomingEmail.Enabled = false }()
  60. subjectTemplates = texttmpl.Must(texttmpl.New("issue/comment").Parse(subjectTpl))
  61. bodyTemplates = template.Must(template.New("issue/comment").Parse(bodyTpl))
  62. recipients := []*user_model.User{{Name: "Test", Email: "test@gitea.com"}, {Name: "Test2", Email: "test2@gitea.com"}}
  63. msgs, err := composeIssueCommentMessages(&mailCommentContext{
  64. Context: context.TODO(), // TODO: use a correct context
  65. Issue: issue, Doer: doer, ActionType: activities_model.ActionCommentIssue,
  66. Content: "test body", Comment: comment,
  67. }, "en-US", recipients, false, "issue comment")
  68. assert.NoError(t, err)
  69. assert.Len(t, msgs, 2)
  70. gomailMsg := msgs[0].ToMessage()
  71. replyTo := gomailMsg.GetHeader("Reply-To")[0]
  72. subject := gomailMsg.GetHeader("Subject")[0]
  73. assert.Len(t, gomailMsg.GetHeader("To"), 1, "exactly one recipient is expected in the To field")
  74. tokenRegex := regexp.MustCompile(`\Aincoming\+(.+)@localhost\z`)
  75. assert.Regexp(t, tokenRegex, replyTo)
  76. token := tokenRegex.FindAllStringSubmatch(replyTo, 1)[0][1]
  77. assert.Equal(t, "Re: ", subject[:4], "Comment reply subject should contain Re:")
  78. assert.Equal(t, "Re: [user2/repo1] @user2 #1 - issue1", subject)
  79. assert.Equal(t, "<user2/repo1/issues/1@localhost>", gomailMsg.GetHeader("In-Reply-To")[0], "In-Reply-To header doesn't match")
  80. assert.ElementsMatch(t, []string{"<user2/repo1/issues/1@localhost>", "<reply-" + token + "@localhost>"}, gomailMsg.GetHeader("References"), "References header doesn't match")
  81. assert.Equal(t, "<user2/repo1/issues/1/comment/2@localhost>", gomailMsg.GetHeader("Message-ID")[0], "Message-ID header doesn't match")
  82. assert.Equal(t, "<mailto:"+replyTo+">", gomailMsg.GetHeader("List-Post")[0])
  83. assert.Len(t, gomailMsg.GetHeader("List-Unsubscribe"), 2) // url + mailto
  84. }
  85. func TestComposeIssueMessage(t *testing.T) {
  86. doer, _, issue, _ := prepareMailerTest(t)
  87. subjectTemplates = texttmpl.Must(texttmpl.New("issue/new").Parse(subjectTpl))
  88. bodyTemplates = template.Must(template.New("issue/new").Parse(bodyTpl))
  89. recipients := []*user_model.User{{Name: "Test", Email: "test@gitea.com"}, {Name: "Test2", Email: "test2@gitea.com"}}
  90. msgs, err := composeIssueCommentMessages(&mailCommentContext{
  91. Context: context.TODO(), // TODO: use a correct context
  92. Issue: issue, Doer: doer, ActionType: activities_model.ActionCreateIssue,
  93. Content: "test body",
  94. }, "en-US", recipients, false, "issue create")
  95. assert.NoError(t, err)
  96. assert.Len(t, msgs, 2)
  97. gomailMsg := msgs[0].ToMessage()
  98. mailto := gomailMsg.GetHeader("To")
  99. subject := gomailMsg.GetHeader("Subject")
  100. messageID := gomailMsg.GetHeader("Message-ID")
  101. inReplyTo := gomailMsg.GetHeader("In-Reply-To")
  102. references := gomailMsg.GetHeader("References")
  103. assert.Len(t, mailto, 1, "exactly one recipient is expected in the To field")
  104. assert.Equal(t, "[user2/repo1] @user2 #1 - issue1", subject[0])
  105. assert.Equal(t, "<user2/repo1/issues/1@localhost>", inReplyTo[0], "In-Reply-To header doesn't match")
  106. assert.Equal(t, "<user2/repo1/issues/1@localhost>", references[0], "References header doesn't match")
  107. assert.Equal(t, "<user2/repo1/issues/1@localhost>", messageID[0], "Message-ID header doesn't match")
  108. assert.Empty(t, gomailMsg.GetHeader("List-Post")) // incoming mail feature disabled
  109. assert.Len(t, gomailMsg.GetHeader("List-Unsubscribe"), 1) // url without mailto
  110. }
  111. func TestTemplateSelection(t *testing.T) {
  112. doer, repo, issue, comment := prepareMailerTest(t)
  113. recipients := []*user_model.User{{Name: "Test", Email: "test@gitea.com"}}
  114. subjectTemplates = texttmpl.Must(texttmpl.New("issue/default").Parse("issue/default/subject"))
  115. texttmpl.Must(subjectTemplates.New("issue/new").Parse("issue/new/subject"))
  116. texttmpl.Must(subjectTemplates.New("pull/comment").Parse("pull/comment/subject"))
  117. texttmpl.Must(subjectTemplates.New("issue/close").Parse("")) // Must default to fallback subject
  118. bodyTemplates = template.Must(template.New("issue/default").Parse("issue/default/body"))
  119. template.Must(bodyTemplates.New("issue/new").Parse("issue/new/body"))
  120. template.Must(bodyTemplates.New("pull/comment").Parse("pull/comment/body"))
  121. template.Must(bodyTemplates.New("issue/close").Parse("issue/close/body"))
  122. expect := func(t *testing.T, msg *Message, expSubject, expBody string) {
  123. subject := msg.ToMessage().GetHeader("Subject")
  124. msgbuf := new(bytes.Buffer)
  125. _, _ = msg.ToMessage().WriteTo(msgbuf)
  126. wholemsg := msgbuf.String()
  127. assert.Equal(t, []string{expSubject}, subject)
  128. assert.Contains(t, wholemsg, expBody)
  129. }
  130. msg := testComposeIssueCommentMessage(t, &mailCommentContext{
  131. Context: context.TODO(), // TODO: use a correct context
  132. Issue: issue, Doer: doer, ActionType: activities_model.ActionCreateIssue,
  133. Content: "test body",
  134. }, recipients, false, "TestTemplateSelection")
  135. expect(t, msg, "issue/new/subject", "issue/new/body")
  136. msg = testComposeIssueCommentMessage(t, &mailCommentContext{
  137. Context: context.TODO(), // TODO: use a correct context
  138. Issue: issue, Doer: doer, ActionType: activities_model.ActionCommentIssue,
  139. Content: "test body", Comment: comment,
  140. }, recipients, false, "TestTemplateSelection")
  141. expect(t, msg, "issue/default/subject", "issue/default/body")
  142. pull := unittest.AssertExistsAndLoadBean(t, &issues_model.Issue{ID: 2, Repo: repo, Poster: doer})
  143. comment = unittest.AssertExistsAndLoadBean(t, &issues_model.Comment{ID: 4, Issue: pull})
  144. msg = testComposeIssueCommentMessage(t, &mailCommentContext{
  145. Context: context.TODO(), // TODO: use a correct context
  146. Issue: pull, Doer: doer, ActionType: activities_model.ActionCommentPull,
  147. Content: "test body", Comment: comment,
  148. }, recipients, false, "TestTemplateSelection")
  149. expect(t, msg, "pull/comment/subject", "pull/comment/body")
  150. msg = testComposeIssueCommentMessage(t, &mailCommentContext{
  151. Context: context.TODO(), // TODO: use a correct context
  152. Issue: issue, Doer: doer, ActionType: activities_model.ActionCloseIssue,
  153. Content: "test body", Comment: comment,
  154. }, recipients, false, "TestTemplateSelection")
  155. expect(t, msg, "Re: [user2/repo1] issue1 (#1)", "issue/close/body")
  156. }
  157. func TestTemplateServices(t *testing.T) {
  158. doer, _, issue, comment := prepareMailerTest(t)
  159. assert.NoError(t, issue.LoadRepo(db.DefaultContext))
  160. expect := func(t *testing.T, issue *issues_model.Issue, comment *issues_model.Comment, doer *user_model.User,
  161. actionType activities_model.ActionType, fromMention bool, tplSubject, tplBody, expSubject, expBody string,
  162. ) {
  163. subjectTemplates = texttmpl.Must(texttmpl.New("issue/default").Parse(tplSubject))
  164. bodyTemplates = template.Must(template.New("issue/default").Parse(tplBody))
  165. recipients := []*user_model.User{{Name: "Test", Email: "test@gitea.com"}}
  166. msg := testComposeIssueCommentMessage(t, &mailCommentContext{
  167. Context: context.TODO(), // TODO: use a correct context
  168. Issue: issue, Doer: doer, ActionType: actionType,
  169. Content: "test body", Comment: comment,
  170. }, recipients, fromMention, "TestTemplateServices")
  171. subject := msg.ToMessage().GetHeader("Subject")
  172. msgbuf := new(bytes.Buffer)
  173. _, _ = msg.ToMessage().WriteTo(msgbuf)
  174. wholemsg := msgbuf.String()
  175. assert.Equal(t, []string{expSubject}, subject)
  176. assert.Contains(t, wholemsg, "\r\n"+expBody+"\r\n")
  177. }
  178. expect(t, issue, comment, doer, activities_model.ActionCommentIssue, false,
  179. "{{.SubjectPrefix}}[{{.Repo}}]: @{{.Doer.Name}} commented on #{{.Issue.Index}} - {{.Issue.Title}}",
  180. "//{{.ActionType}},{{.ActionName}},{{if .IsMention}}norender{{end}}//",
  181. "Re: [user2/repo1]: @user2 commented on #1 - issue1",
  182. "//issue,comment,//")
  183. expect(t, issue, comment, doer, activities_model.ActionCommentIssue, true,
  184. "{{if .IsMention}}must render{{end}}",
  185. "//subject is: {{.Subject}}//",
  186. "must render",
  187. "//subject is: must render//")
  188. expect(t, issue, comment, doer, activities_model.ActionCommentIssue, true,
  189. "{{.FallbackSubject}}",
  190. "//{{.SubjectPrefix}}//",
  191. "Re: [user2/repo1] issue1 (#1)",
  192. "//Re: //")
  193. }
  194. func testComposeIssueCommentMessage(t *testing.T, ctx *mailCommentContext, recipients []*user_model.User, fromMention bool, info string) *Message {
  195. msgs, err := composeIssueCommentMessages(ctx, "en-US", recipients, fromMention, info)
  196. assert.NoError(t, err)
  197. assert.Len(t, msgs, 1)
  198. return msgs[0]
  199. }
  200. func TestGenerateAdditionalHeaders(t *testing.T) {
  201. doer, _, issue, _ := prepareMailerTest(t)
  202. ctx := &mailCommentContext{Context: context.TODO() /* TODO: use a correct context */, Issue: issue, Doer: doer}
  203. recipient := &user_model.User{Name: "Test", Email: "test@gitea.com"}
  204. headers := generateAdditionalHeaders(ctx, "dummy-reason", recipient)
  205. expected := map[string]string{
  206. "List-ID": "user2/repo1 <repo1.user2.localhost>",
  207. "List-Archive": "<https://try.gitea.io/user2/repo1>",
  208. "X-Gitea-Reason": "dummy-reason",
  209. "X-Gitea-Sender": "< U<se>r Tw<o > ><",
  210. "X-Gitea-Recipient": "Test",
  211. "X-Gitea-Recipient-Address": "test@gitea.com",
  212. "X-Gitea-Repository": "repo1",
  213. "X-Gitea-Repository-Path": "user2/repo1",
  214. "X-Gitea-Repository-Link": "https://try.gitea.io/user2/repo1",
  215. "X-Gitea-Issue-ID": "1",
  216. "X-Gitea-Issue-Link": "https://try.gitea.io/user2/repo1/issues/1",
  217. }
  218. for key, value := range expected {
  219. if assert.Contains(t, headers, key) {
  220. assert.Equal(t, value, headers[key])
  221. }
  222. }
  223. }
  224. func Test_createReference(t *testing.T) {
  225. _, _, issue, comment := prepareMailerTest(t)
  226. _, _, pullIssue, _ := prepareMailerTest(t)
  227. pullIssue.IsPull = true
  228. type args struct {
  229. issue *issues_model.Issue
  230. comment *issues_model.Comment
  231. actionType activities_model.ActionType
  232. }
  233. tests := []struct {
  234. name string
  235. args args
  236. prefix string
  237. }{
  238. {
  239. name: "Open Issue",
  240. args: args{
  241. issue: issue,
  242. actionType: activities_model.ActionCreateIssue,
  243. },
  244. prefix: fmt.Sprintf("<%s/issues/%d@%s>", issue.Repo.FullName(), issue.Index, setting.Domain),
  245. },
  246. {
  247. name: "Open Pull",
  248. args: args{
  249. issue: pullIssue,
  250. actionType: activities_model.ActionCreatePullRequest,
  251. },
  252. prefix: fmt.Sprintf("<%s/pulls/%d@%s>", issue.Repo.FullName(), issue.Index, setting.Domain),
  253. },
  254. {
  255. name: "Comment Issue",
  256. args: args{
  257. issue: issue,
  258. comment: comment,
  259. actionType: activities_model.ActionCommentIssue,
  260. },
  261. prefix: fmt.Sprintf("<%s/issues/%d/comment/%d@%s>", issue.Repo.FullName(), issue.Index, comment.ID, setting.Domain),
  262. },
  263. {
  264. name: "Comment Pull",
  265. args: args{
  266. issue: pullIssue,
  267. comment: comment,
  268. actionType: activities_model.ActionCommentPull,
  269. },
  270. prefix: fmt.Sprintf("<%s/pulls/%d/comment/%d@%s>", issue.Repo.FullName(), issue.Index, comment.ID, setting.Domain),
  271. },
  272. {
  273. name: "Close Issue",
  274. args: args{
  275. issue: issue,
  276. actionType: activities_model.ActionCloseIssue,
  277. },
  278. prefix: fmt.Sprintf("<%s/issues/%d/close/", issue.Repo.FullName(), issue.Index),
  279. },
  280. {
  281. name: "Close Pull",
  282. args: args{
  283. issue: pullIssue,
  284. actionType: activities_model.ActionClosePullRequest,
  285. },
  286. prefix: fmt.Sprintf("<%s/pulls/%d/close/", issue.Repo.FullName(), issue.Index),
  287. },
  288. {
  289. name: "Reopen Issue",
  290. args: args{
  291. issue: issue,
  292. actionType: activities_model.ActionReopenIssue,
  293. },
  294. prefix: fmt.Sprintf("<%s/issues/%d/reopen/", issue.Repo.FullName(), issue.Index),
  295. },
  296. {
  297. name: "Reopen Pull",
  298. args: args{
  299. issue: pullIssue,
  300. actionType: activities_model.ActionReopenPullRequest,
  301. },
  302. prefix: fmt.Sprintf("<%s/pulls/%d/reopen/", issue.Repo.FullName(), issue.Index),
  303. },
  304. {
  305. name: "Merge Pull",
  306. args: args{
  307. issue: pullIssue,
  308. actionType: activities_model.ActionMergePullRequest,
  309. },
  310. prefix: fmt.Sprintf("<%s/pulls/%d/merge/", issue.Repo.FullName(), issue.Index),
  311. },
  312. {
  313. name: "Ready Pull",
  314. args: args{
  315. issue: pullIssue,
  316. actionType: activities_model.ActionPullRequestReadyForReview,
  317. },
  318. prefix: fmt.Sprintf("<%s/pulls/%d/ready/", issue.Repo.FullName(), issue.Index),
  319. },
  320. }
  321. for _, tt := range tests {
  322. t.Run(tt.name, func(t *testing.T) {
  323. got := createReference(tt.args.issue, tt.args.comment, tt.args.actionType)
  324. if !strings.HasPrefix(got, tt.prefix) {
  325. t.Errorf("createReference() = %v, want %v", got, tt.prefix)
  326. }
  327. })
  328. }
  329. }