mirror of
https://github.com/jhillyerd/inbucket.git
synced 2025-12-17 17:47:03 +00:00
Remove old REST API, closes #28
This commit is contained in:
@@ -7,13 +7,13 @@ import (
|
||||
"net/mail"
|
||||
"time"
|
||||
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"github.com/jhillyerd/inbucket/httpd"
|
||||
"github.com/jhillyerd/inbucket/log"
|
||||
"github.com/jhillyerd/inbucket/smtpd"
|
||||
"strconv"
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"io/ioutil"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// JSONMessageHeaderV1 contains the basic header data for a message
|
||||
@@ -29,24 +29,24 @@ type JSONMessageHeaderV1 struct {
|
||||
|
||||
// JSONMessageV1 contains the same data as the header plus a JSONMessageBody
|
||||
type JSONMessageV1 struct {
|
||||
Mailbox string `json:"mailbox"`
|
||||
ID string `json:"id"`
|
||||
From string `json:"from"`
|
||||
To []string `json:"to"`
|
||||
Subject string `json:"subject"`
|
||||
Date time.Time `json:"date"`
|
||||
Size int64 `json:"size"`
|
||||
Body *JSONMessageBodyV1 `json:"body"`
|
||||
Header mail.Header `json:"header"`
|
||||
Mailbox string `json:"mailbox"`
|
||||
ID string `json:"id"`
|
||||
From string `json:"from"`
|
||||
To []string `json:"to"`
|
||||
Subject string `json:"subject"`
|
||||
Date time.Time `json:"date"`
|
||||
Size int64 `json:"size"`
|
||||
Body *JSONMessageBodyV1 `json:"body"`
|
||||
Header mail.Header `json:"header"`
|
||||
Attachments []*JSONMessageAttachmentV1 `json:"attachments"`
|
||||
}
|
||||
|
||||
type JSONMessageAttachmentV1 struct {
|
||||
FileName string `json:"filename"`
|
||||
ContentType string `json:"content-type"`
|
||||
DownloadLink string `json:"download-link"`
|
||||
ViewLink string `json:"view-link"`
|
||||
MD5 string `json:"md5"`
|
||||
FileName string `json:"filename"`
|
||||
ContentType string `json:"content-type"`
|
||||
DownloadLink string `json:"download-link"`
|
||||
ViewLink string `json:"view-link"`
|
||||
MD5 string `json:"md5"`
|
||||
}
|
||||
|
||||
// JSONMessageBodyV1 contains the Text and HTML versions of the message body
|
||||
@@ -126,11 +126,11 @@ func MailboxShowV1(w http.ResponseWriter, req *http.Request, ctx *httpd.Context)
|
||||
content, err = ioutil.ReadAll(att)
|
||||
var checksum = md5.Sum(content)
|
||||
attachments[i] = &JSONMessageAttachmentV1{
|
||||
ContentType: att.ContentType,
|
||||
FileName: att.FileName,
|
||||
DownloadLink: "http://" + req.Host + "/mailbox/dattach/" + name + "/" + id + "/" + strconv.Itoa(i) + "/" + att.FileName,
|
||||
ViewLink: "http://" + req.Host + "/mailbox/vattach/" + name + "/" + id + "/" + strconv.Itoa(i) + "/" + att.FileName,
|
||||
MD5: hex.EncodeToString(checksum[:]),
|
||||
ContentType: att.ContentType,
|
||||
FileName: att.FileName,
|
||||
DownloadLink: "http://" + req.Host + "/mailbox/dattach/" + name + "/" + id + "/" + strconv.Itoa(i) + "/" + att.FileName,
|
||||
ViewLink: "http://" + req.Host + "/mailbox/vattach/" + name + "/" + id + "/" + strconv.Itoa(i) + "/" + att.FileName,
|
||||
MD5: hex.EncodeToString(checksum[:]),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -208,7 +208,7 @@ func MailboxSourceV1(w http.ResponseWriter, req *http.Request, ctx *httpd.Contex
|
||||
return nil
|
||||
}
|
||||
|
||||
// MailboxDeleteV1 removes a particular message from a mailbox. Renders JSON or plain/text OK
|
||||
// MailboxDeleteV1 removes a particular message from a mailbox
|
||||
func MailboxDeleteV1(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (err error) {
|
||||
// Don't have to validate these aren't empty, Gorilla returns 404
|
||||
id := ctx.Vars["id"]
|
||||
|
||||
@@ -17,7 +17,7 @@ function deleteMessage(id) {
|
||||
$('#message-content').empty();
|
||||
$.ajax({
|
||||
type: 'DELETE',
|
||||
url: '/mailbox/' + mailbox + '/' + id,
|
||||
url: '/api/v1/mailbox/' + mailbox + '/' + id,
|
||||
success: loadList
|
||||
})
|
||||
}
|
||||
|
||||
@@ -5,43 +5,13 @@ import (
|
||||
"html/template"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/mail"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/jhillyerd/inbucket/httpd"
|
||||
"github.com/jhillyerd/inbucket/log"
|
||||
"github.com/jhillyerd/inbucket/smtpd"
|
||||
)
|
||||
|
||||
// JSONMessageHeader contains the basic header data for a message
|
||||
type JSONMessageHeader struct {
|
||||
Mailbox string
|
||||
ID string `json:"Id"`
|
||||
From string
|
||||
Subject string
|
||||
Date time.Time
|
||||
Size int64
|
||||
}
|
||||
|
||||
// JSONMessage contains the same data as the header plus a JSONMessageBody
|
||||
type JSONMessage struct {
|
||||
Mailbox string
|
||||
ID string `json:"Id"`
|
||||
From string
|
||||
Subject string
|
||||
Date time.Time
|
||||
Size int64
|
||||
Body *JSONMessageBody
|
||||
Header mail.Header
|
||||
}
|
||||
|
||||
// JSONMessageBody contains the Text and HTML versions of the message body
|
||||
type JSONMessageBody struct {
|
||||
Text string
|
||||
HTML string `json:"Html"`
|
||||
}
|
||||
|
||||
// MailboxIndex renders the index page for a particular mailbox
|
||||
func MailboxIndex(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (err error) {
|
||||
// Form values must be validated manually
|
||||
@@ -106,21 +76,6 @@ func MailboxList(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (
|
||||
}
|
||||
log.Tracef("Got %v messsages", len(messages))
|
||||
|
||||
if ctx.IsJSON {
|
||||
jmessages := make([]*JSONMessageHeader, len(messages))
|
||||
for i, msg := range messages {
|
||||
jmessages[i] = &JSONMessageHeader{
|
||||
Mailbox: name,
|
||||
ID: msg.ID(),
|
||||
From: msg.From(),
|
||||
Subject: msg.Subject(),
|
||||
Date: msg.Date(),
|
||||
Size: msg.Size(),
|
||||
}
|
||||
}
|
||||
return httpd.RenderJSON(w, jmessages)
|
||||
}
|
||||
|
||||
return httpd.RenderPartial("mailbox/_list.html", w, map[string]interface{}{
|
||||
"ctx": ctx,
|
||||
"name": name,
|
||||
@@ -128,7 +83,7 @@ func MailboxList(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (
|
||||
})
|
||||
}
|
||||
|
||||
// MailboxShow renders a particular message from a mailbox. Renders JSON or a partial
|
||||
// MailboxShow renders a particular message from a mailbox. Renders an HTML partial
|
||||
func MailboxShow(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (err error) {
|
||||
// Don't have to validate these aren't empty, Gorilla returns 404
|
||||
id := ctx.Vars["id"]
|
||||
@@ -150,32 +105,11 @@ func MailboxShow(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (
|
||||
// This doesn't indicate empty, likely an IO error
|
||||
return fmt.Errorf("GetMessage(%q) failed: %v", id, err)
|
||||
}
|
||||
header, err := msg.ReadHeader()
|
||||
if err != nil {
|
||||
return fmt.Errorf("ReadHeader(%q) failed: %v", id, err)
|
||||
}
|
||||
mime, err := msg.ReadBody()
|
||||
if err != nil {
|
||||
return fmt.Errorf("ReadBody(%q) failed: %v", id, err)
|
||||
}
|
||||
|
||||
if ctx.IsJSON {
|
||||
return httpd.RenderJSON(w,
|
||||
&JSONMessage{
|
||||
Mailbox: name,
|
||||
ID: msg.ID(),
|
||||
From: msg.From(),
|
||||
Subject: msg.Subject(),
|
||||
Date: msg.Date(),
|
||||
Size: msg.Size(),
|
||||
Header: header.Header,
|
||||
Body: &JSONMessageBody{
|
||||
Text: mime.Text,
|
||||
HTML: mime.HTML,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
body := template.HTML(httpd.TextToHTML(mime.Text))
|
||||
htmlAvailable := mime.HTML != ""
|
||||
|
||||
@@ -190,36 +124,6 @@ func MailboxShow(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (
|
||||
})
|
||||
}
|
||||
|
||||
// MailboxPurge deletes all messages from a mailbox. Renders JSON or text/plain OK
|
||||
func MailboxPurge(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (err error) {
|
||||
// Don't have to validate these aren't empty, Gorilla returns 404
|
||||
name, err := smtpd.ParseMailboxName(ctx.Vars["name"])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mb, err := ctx.DataStore.MailboxFor(name)
|
||||
if err != nil {
|
||||
// This doesn't indicate not found, likely an IO error
|
||||
return fmt.Errorf("Failed to get mailbox for %q: %v", name, err)
|
||||
}
|
||||
// Delete all messages
|
||||
err = mb.Purge()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Mailbox(%q) purge failed: %v", name, err)
|
||||
}
|
||||
log.Tracef("HTTP purged mailbox for %q", name)
|
||||
|
||||
if ctx.IsJSON {
|
||||
return httpd.RenderJSON(w, "OK")
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
if _, err := io.WriteString(w, "OK"); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MailboxHTML displays the HTML content of a message. Renders a partial
|
||||
func MailboxHTML(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (err error) {
|
||||
// Don't have to validate these aren't empty, Gorilla returns 404
|
||||
@@ -392,41 +296,3 @@ func MailboxViewAttach(w http.ResponseWriter, req *http.Request, ctx *httpd.Cont
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// MailboxDelete removes a particular message from a mailbox. Renders JSON or plain/text OK
|
||||
func MailboxDelete(w http.ResponseWriter, req *http.Request, ctx *httpd.Context) (err error) {
|
||||
// Don't have to validate these aren't empty, Gorilla returns 404
|
||||
id := ctx.Vars["id"]
|
||||
name, err := smtpd.ParseMailboxName(ctx.Vars["name"])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mb, err := ctx.DataStore.MailboxFor(name)
|
||||
if err != nil {
|
||||
// This doesn't indicate not found, likely an IO error
|
||||
return fmt.Errorf("Failed to get mailbox for %q: %v", name, err)
|
||||
}
|
||||
message, err := mb.GetMessage(id)
|
||||
if err == smtpd.ErrNotExist {
|
||||
http.NotFound(w, req)
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
// This doesn't indicate missing, likely an IO error
|
||||
return fmt.Errorf("GetMessage(%q) failed: %v", id, err)
|
||||
}
|
||||
err = message.Delete()
|
||||
if err != nil {
|
||||
return fmt.Errorf("Delete(%q) failed: %v", id, err)
|
||||
}
|
||||
|
||||
if ctx.IsJSON {
|
||||
return httpd.RenderJSON(w, "OK")
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/plain")
|
||||
if _, err := io.WriteString(w, "OK"); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1,539 +0,0 @@
|
||||
package webui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/mail"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jhillyerd/enmime"
|
||||
"github.com/jhillyerd/inbucket/config"
|
||||
"github.com/jhillyerd/inbucket/httpd"
|
||||
"github.com/jhillyerd/inbucket/smtpd"
|
||||
"github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// OutputJSONHeader holds the received Header
|
||||
type OutputJSONHeader struct {
|
||||
Mailbox string
|
||||
ID string `json:"Id"`
|
||||
From, Subject, Date string
|
||||
Size int
|
||||
}
|
||||
|
||||
// OutputJSONMessage holds the received Message
|
||||
type OutputJSONMessage struct {
|
||||
Mailbox string
|
||||
ID string `json:"Id"`
|
||||
From, Subject, Date string
|
||||
Size int
|
||||
Header map[string][]string
|
||||
Body struct {
|
||||
Text string
|
||||
HTML string `json:"Html"`
|
||||
}
|
||||
}
|
||||
|
||||
// InputMessageData holds the message we want to test
|
||||
type InputMessageData struct {
|
||||
Mailbox string
|
||||
ID string `json:"Id"`
|
||||
From, Subject string
|
||||
Date time.Time
|
||||
Size int
|
||||
Header mail.Header
|
||||
HTML string `json:"Html"`
|
||||
Text string
|
||||
}
|
||||
|
||||
func (d *InputMessageData) MockMessage() *MockMessage {
|
||||
msg := &MockMessage{}
|
||||
msg.On("ID").Return(d.ID)
|
||||
msg.On("From").Return(d.From)
|
||||
msg.On("Subject").Return(d.Subject)
|
||||
msg.On("Date").Return(d.Date)
|
||||
msg.On("Size").Return(d.Size)
|
||||
gomsg := &mail.Message{
|
||||
Header: d.Header,
|
||||
}
|
||||
msg.On("ReadHeader").Return(gomsg, nil)
|
||||
body := &enmime.Envelope{
|
||||
Text: d.Text,
|
||||
HTML: d.HTML,
|
||||
}
|
||||
msg.On("ReadBody").Return(body, nil)
|
||||
return msg
|
||||
}
|
||||
|
||||
func (d *InputMessageData) CompareToJSONHeader(j *OutputJSONHeader) (errors []string) {
|
||||
if d.Mailbox != j.Mailbox {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Mailbox=%q, got %q", d.Mailbox,
|
||||
j.Mailbox))
|
||||
}
|
||||
if d.ID != j.ID {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Id=%q, got %q", d.ID,
|
||||
j.ID))
|
||||
}
|
||||
if d.From != j.From {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.From=%q, got %q", d.From,
|
||||
j.From))
|
||||
}
|
||||
if d.Subject != j.Subject {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Subject=%q, got %q", d.Subject,
|
||||
j.Subject))
|
||||
}
|
||||
exDate := d.Date.Format("2006-01-02T15:04:05.999999999-07:00")
|
||||
if exDate != j.Date {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Date=%q, got %q", exDate,
|
||||
j.Date))
|
||||
}
|
||||
if d.Size != j.Size {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Size=%v, got %v", d.Size,
|
||||
j.Size))
|
||||
}
|
||||
|
||||
return errors
|
||||
}
|
||||
|
||||
func (d *InputMessageData) CompareToJSONMessage(j *OutputJSONMessage) (errors []string) {
|
||||
if d.Mailbox != j.Mailbox {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Mailbox=%q, got %q", d.Mailbox,
|
||||
j.Mailbox))
|
||||
}
|
||||
if d.ID != j.ID {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Id=%q, got %q", d.ID,
|
||||
j.ID))
|
||||
}
|
||||
if d.From != j.From {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.From=%q, got %q", d.From,
|
||||
j.From))
|
||||
}
|
||||
if d.Subject != j.Subject {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Subject=%q, got %q", d.Subject,
|
||||
j.Subject))
|
||||
}
|
||||
exDate := d.Date.Format("2006-01-02T15:04:05.999999999-07:00")
|
||||
if exDate != j.Date {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Date=%q, got %q", exDate,
|
||||
j.Date))
|
||||
}
|
||||
if d.Size != j.Size {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Size=%v, got %v", d.Size,
|
||||
j.Size))
|
||||
}
|
||||
if d.Text != j.Body.Text {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Text=%q, got %q", d.Text,
|
||||
j.Body.Text))
|
||||
}
|
||||
if d.HTML != j.Body.HTML {
|
||||
errors = append(errors, fmt.Sprintf("Expected JSON.Html=%q, got %q", d.HTML,
|
||||
j.Body.HTML))
|
||||
}
|
||||
for k, vals := range d.Header {
|
||||
jvals, ok := j.Header[k]
|
||||
if ok {
|
||||
for _, v := range vals {
|
||||
hasValue := false
|
||||
for _, jv := range jvals {
|
||||
if v == jv {
|
||||
hasValue = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasValue {
|
||||
errors = append(errors, fmt.Sprintf("JSON.Header[%q] missing value %q", k, v))
|
||||
}
|
||||
}
|
||||
} else {
|
||||
errors = append(errors, fmt.Sprintf("JSON.Header missing key %q", k))
|
||||
}
|
||||
}
|
||||
|
||||
return errors
|
||||
}
|
||||
|
||||
func TestRestMailboxList(t *testing.T) {
|
||||
// Setup
|
||||
ds := &MockDataStore{}
|
||||
logbuf := setupWebServer(ds)
|
||||
|
||||
// Test invalid mailbox name
|
||||
w, err := testRestGet("http://localhost/mailbox/foo@bar")
|
||||
expectCode := 500
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.Code != expectCode {
|
||||
t.Errorf("Expected code %v, got %v", expectCode, w.Code)
|
||||
}
|
||||
|
||||
// Test empty mailbox
|
||||
emptybox := &MockMailbox{}
|
||||
ds.On("MailboxFor", "empty").Return(emptybox, nil)
|
||||
emptybox.On("GetMessages").Return([]smtpd.Message{}, nil)
|
||||
|
||||
w, err = testRestGet("http://localhost/mailbox/empty")
|
||||
expectCode = 200
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.Code != expectCode {
|
||||
t.Errorf("Expected code %v, got %v", expectCode, w.Code)
|
||||
}
|
||||
|
||||
// Test MailboxFor error
|
||||
ds.On("MailboxFor", "error").Return(&MockMailbox{}, fmt.Errorf("Internal error"))
|
||||
w, err = testRestGet("http://localhost/mailbox/error")
|
||||
expectCode = 500
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.Code != expectCode {
|
||||
t.Errorf("Expected code %v, got %v", expectCode, w.Code)
|
||||
}
|
||||
|
||||
if t.Failed() {
|
||||
// Wait for handler to finish logging
|
||||
time.Sleep(2 * time.Second)
|
||||
// Dump buffered log data if there was a failure
|
||||
_, _ = io.Copy(os.Stderr, logbuf)
|
||||
}
|
||||
|
||||
// Test MailboxFor error
|
||||
error2box := &MockMailbox{}
|
||||
ds.On("MailboxFor", "error2").Return(error2box, nil)
|
||||
error2box.On("GetMessages").Return([]smtpd.Message{}, fmt.Errorf("Internal error 2"))
|
||||
|
||||
w, err = testRestGet("http://localhost/mailbox/error2")
|
||||
expectCode = 500
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.Code != expectCode {
|
||||
t.Errorf("Expected code %v, got %v", expectCode, w.Code)
|
||||
}
|
||||
|
||||
// Test JSON message headers
|
||||
data1 := &InputMessageData{
|
||||
Mailbox: "good",
|
||||
ID: "0001",
|
||||
From: "from1",
|
||||
Subject: "subject 1",
|
||||
Date: time.Date(2012, 2, 1, 10, 11, 12, 253, time.FixedZone("PST", -800)),
|
||||
}
|
||||
data2 := &InputMessageData{
|
||||
Mailbox: "good",
|
||||
ID: "0002",
|
||||
From: "from2",
|
||||
Subject: "subject 2",
|
||||
Date: time.Date(2012, 7, 1, 10, 11, 12, 253, time.FixedZone("PDT", -700)),
|
||||
}
|
||||
goodbox := &MockMailbox{}
|
||||
ds.On("MailboxFor", "good").Return(goodbox, nil)
|
||||
msg1 := data1.MockMessage()
|
||||
msg2 := data2.MockMessage()
|
||||
goodbox.On("GetMessages").Return([]smtpd.Message{msg1, msg2}, nil)
|
||||
|
||||
// Check return code
|
||||
w, err = testRestGet("http://localhost/mailbox/good")
|
||||
expectCode = 200
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.Code != expectCode {
|
||||
t.Fatalf("Expected code %v, got %v", expectCode, w.Code)
|
||||
}
|
||||
|
||||
// Check JSON
|
||||
dec := json.NewDecoder(w.Body)
|
||||
var result []OutputJSONHeader
|
||||
if err := dec.Decode(&result); err != nil {
|
||||
t.Errorf("Failed to decode JSON: %v", err)
|
||||
}
|
||||
if len(result) != 2 {
|
||||
t.Errorf("Expected 2 results, got %v", len(result))
|
||||
}
|
||||
if errors := data1.CompareToJSONHeader(&result[0]); len(errors) > 0 {
|
||||
for _, e := range errors {
|
||||
t.Error(e)
|
||||
}
|
||||
}
|
||||
if errors := data2.CompareToJSONHeader(&result[1]); len(errors) > 0 {
|
||||
for _, e := range errors {
|
||||
t.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
if t.Failed() {
|
||||
// Wait for handler to finish logging
|
||||
time.Sleep(2 * time.Second)
|
||||
// Dump buffered log data if there was a failure
|
||||
_, _ = io.Copy(os.Stderr, logbuf)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRestMessage(t *testing.T) {
|
||||
// Setup
|
||||
ds := &MockDataStore{}
|
||||
logbuf := setupWebServer(ds)
|
||||
|
||||
// Test invalid mailbox name
|
||||
w, err := testRestGet("http://localhost/mailbox/foo@bar/0001")
|
||||
expectCode := 500
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.Code != expectCode {
|
||||
t.Errorf("Expected code %v, got %v", expectCode, w.Code)
|
||||
}
|
||||
|
||||
// Test requesting a message that does not exist
|
||||
emptybox := &MockMailbox{}
|
||||
ds.On("MailboxFor", "empty").Return(emptybox, nil)
|
||||
emptybox.On("GetMessage", "0001").Return(&MockMessage{}, smtpd.ErrNotExist)
|
||||
|
||||
w, err = testRestGet("http://localhost/mailbox/empty/0001")
|
||||
expectCode = 404
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.Code != expectCode {
|
||||
t.Errorf("Expected code %v, got %v", expectCode, w.Code)
|
||||
}
|
||||
|
||||
// Test MailboxFor error
|
||||
ds.On("MailboxFor", "error").Return(&MockMailbox{}, fmt.Errorf("Internal error"))
|
||||
w, err = testRestGet("http://localhost/mailbox/error/0001")
|
||||
expectCode = 500
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.Code != expectCode {
|
||||
t.Errorf("Expected code %v, got %v", expectCode, w.Code)
|
||||
}
|
||||
|
||||
if t.Failed() {
|
||||
// Wait for handler to finish logging
|
||||
time.Sleep(2 * time.Second)
|
||||
// Dump buffered log data if there was a failure
|
||||
_, _ = io.Copy(os.Stderr, logbuf)
|
||||
}
|
||||
|
||||
// Test GetMessage error
|
||||
error2box := &MockMailbox{}
|
||||
ds.On("MailboxFor", "error2").Return(error2box, nil)
|
||||
error2box.On("GetMessage", "0001").Return(&MockMessage{}, fmt.Errorf("Internal error 2"))
|
||||
|
||||
w, err = testRestGet("http://localhost/mailbox/error2/0001")
|
||||
expectCode = 500
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.Code != expectCode {
|
||||
t.Errorf("Expected code %v, got %v", expectCode, w.Code)
|
||||
}
|
||||
|
||||
// Test JSON message headers
|
||||
data1 := &InputMessageData{
|
||||
Mailbox: "good",
|
||||
ID: "0001",
|
||||
From: "from1",
|
||||
Subject: "subject 1",
|
||||
Date: time.Date(2012, 2, 1, 10, 11, 12, 253, time.FixedZone("PST", -800)),
|
||||
Header: mail.Header{
|
||||
"To": []string{"fred@fish.com", "keyword@nsa.gov"},
|
||||
},
|
||||
Text: "This is some text",
|
||||
HTML: "This is some HTML",
|
||||
}
|
||||
goodbox := &MockMailbox{}
|
||||
ds.On("MailboxFor", "good").Return(goodbox, nil)
|
||||
msg1 := data1.MockMessage()
|
||||
goodbox.On("GetMessage", "0001").Return(msg1, nil)
|
||||
|
||||
// Check return code
|
||||
w, err = testRestGet("http://localhost/mailbox/good/0001")
|
||||
expectCode = 200
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w.Code != expectCode {
|
||||
t.Fatalf("Expected code %v, got %v", expectCode, w.Code)
|
||||
}
|
||||
|
||||
// Check JSON
|
||||
dec := json.NewDecoder(w.Body)
|
||||
var result OutputJSONMessage
|
||||
if err := dec.Decode(&result); err != nil {
|
||||
t.Errorf("Failed to decode JSON: %v", err)
|
||||
}
|
||||
if errors := data1.CompareToJSONMessage(&result); len(errors) > 0 {
|
||||
for _, e := range errors {
|
||||
t.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
if t.Failed() {
|
||||
// Wait for handler to finish logging
|
||||
time.Sleep(2 * time.Second)
|
||||
// Dump buffered log data if there was a failure
|
||||
_, _ = io.Copy(os.Stderr, logbuf)
|
||||
}
|
||||
}
|
||||
|
||||
func testRestGet(url string) (*httptest.ResponseRecorder, error) {
|
||||
req, err := http.NewRequest("GET", url, nil)
|
||||
req.Header.Add("Accept", "application/json")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
httpd.Router.ServeHTTP(w, req)
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func setupWebServer(ds smtpd.DataStore) *bytes.Buffer {
|
||||
// Capture log output
|
||||
buf := new(bytes.Buffer)
|
||||
log.SetOutput(buf)
|
||||
|
||||
// Have to reset default mux to prevent duplicate routes
|
||||
http.DefaultServeMux = http.NewServeMux()
|
||||
cfg := config.WebConfig{
|
||||
TemplateDir: "../themes/bootstrap/templates",
|
||||
PublicDir: "../themes/bootstrap/public",
|
||||
}
|
||||
shutdownChan := make(chan bool)
|
||||
httpd.Initialize(cfg, ds, shutdownChan)
|
||||
SetupRoutes(httpd.Router)
|
||||
|
||||
return buf
|
||||
}
|
||||
|
||||
// MockDataStore used to mock DataStore interface
|
||||
type MockDataStore struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *MockDataStore) MailboxFor(name string) (smtpd.Mailbox, error) {
|
||||
args := m.Called(name)
|
||||
return args.Get(0).(smtpd.Mailbox), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockDataStore) AllMailboxes() ([]smtpd.Mailbox, error) {
|
||||
args := m.Called()
|
||||
return args.Get(0).([]smtpd.Mailbox), args.Error(1)
|
||||
}
|
||||
|
||||
// MockMailbox used to mock Mailbox interface
|
||||
type MockMailbox struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *MockMailbox) GetMessages() ([]smtpd.Message, error) {
|
||||
args := m.Called()
|
||||
return args.Get(0).([]smtpd.Message), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockMailbox) GetMessage(id string) (smtpd.Message, error) {
|
||||
args := m.Called(id)
|
||||
return args.Get(0).(smtpd.Message), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockMailbox) Purge() error {
|
||||
args := m.Called()
|
||||
return args.Error(0)
|
||||
}
|
||||
|
||||
func (m *MockMailbox) NewMessage() (smtpd.Message, error) {
|
||||
args := m.Called()
|
||||
return args.Get(0).(smtpd.Message), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockMailbox) String() string {
|
||||
args := m.Called()
|
||||
return args.String(0)
|
||||
}
|
||||
|
||||
// Mock Message object
|
||||
type MockMessage struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *MockMessage) ID() string {
|
||||
args := m.Called()
|
||||
return args.String(0)
|
||||
}
|
||||
|
||||
func (m *MockMessage) From() string {
|
||||
args := m.Called()
|
||||
return args.String(0)
|
||||
}
|
||||
|
||||
func (m *MockMessage) To() []string {
|
||||
args := m.Called()
|
||||
return args.Get(0).([]string)
|
||||
}
|
||||
|
||||
func (m *MockMessage) Date() time.Time {
|
||||
args := m.Called()
|
||||
return args.Get(0).(time.Time)
|
||||
}
|
||||
|
||||
func (m *MockMessage) Subject() string {
|
||||
args := m.Called()
|
||||
return args.String(0)
|
||||
}
|
||||
|
||||
func (m *MockMessage) ReadHeader() (msg *mail.Message, err error) {
|
||||
args := m.Called()
|
||||
return args.Get(0).(*mail.Message), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockMessage) ReadBody() (body *enmime.Envelope, err error) {
|
||||
args := m.Called()
|
||||
return args.Get(0).(*enmime.Envelope), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockMessage) ReadRaw() (raw *string, err error) {
|
||||
args := m.Called()
|
||||
return args.Get(0).(*string), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockMessage) RawReader() (reader io.ReadCloser, err error) {
|
||||
args := m.Called()
|
||||
return args.Get(0).(io.ReadCloser), args.Error(1)
|
||||
}
|
||||
|
||||
func (m *MockMessage) Size() int64 {
|
||||
args := m.Called()
|
||||
return int64(args.Int(0))
|
||||
}
|
||||
|
||||
func (m *MockMessage) Append(data []byte) error {
|
||||
// []byte arg seems to mess up testify/mock
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MockMessage) Close() error {
|
||||
args := m.Called()
|
||||
return args.Error(0)
|
||||
}
|
||||
|
||||
func (m *MockMessage) Delete() error {
|
||||
args := m.Called()
|
||||
return args.Error(0)
|
||||
}
|
||||
|
||||
func (m *MockMessage) String() string {
|
||||
args := m.Called()
|
||||
return args.String(0)
|
||||
}
|
||||
@@ -13,11 +13,9 @@ func SetupRoutes(r *mux.Router) {
|
||||
r.Path("/link/{name}/{id}").Handler(httpd.Handler(MailboxLink)).Name("MailboxLink").Methods("GET")
|
||||
r.Path("/mailbox").Handler(httpd.Handler(MailboxIndex)).Name("MailboxIndex").Methods("GET")
|
||||
r.Path("/mailbox/{name}").Handler(httpd.Handler(MailboxList)).Name("MailboxList").Methods("GET")
|
||||
r.Path("/mailbox/{name}").Handler(httpd.Handler(MailboxPurge)).Name("MailboxPurge").Methods("DELETE")
|
||||
r.Path("/mailbox/{name}/{id}").Handler(httpd.Handler(MailboxShow)).Name("MailboxShow").Methods("GET")
|
||||
r.Path("/mailbox/{name}/{id}/html").Handler(httpd.Handler(MailboxHTML)).Name("MailboxHtml").Methods("GET")
|
||||
r.Path("/mailbox/{name}/{id}/source").Handler(httpd.Handler(MailboxSource)).Name("MailboxSource").Methods("GET")
|
||||
r.Path("/mailbox/{name}/{id}").Handler(httpd.Handler(MailboxDelete)).Name("MailboxDelete").Methods("DELETE")
|
||||
r.Path("/mailbox/dattach/{name}/{id}/{num}/{file}").Handler(httpd.Handler(MailboxDownloadAttach)).Name("MailboxDownloadAttach").Methods("GET")
|
||||
r.Path("/mailbox/vattach/{name}/{id}/{num}/{file}").Handler(httpd.Handler(MailboxViewAttach)).Name("MailboxViewAttach").Methods("GET")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user