...

Source file src/github.com/letsencrypt/boulder/test/mail-test-srv/http_test.go

Documentation: github.com/letsencrypt/boulder/test/mail-test-srv

     1  package main
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"io"
     7  	"net/http"
     8  	"net/http/httptest"
     9  	"strconv"
    10  	"strings"
    11  	"testing"
    12  )
    13  
    14  func reqAndRecorder(t testing.TB, method, relativeUrl string, body io.Reader) (*httptest.ResponseRecorder, *http.Request) {
    15  	endURL := fmt.Sprintf("http://localhost:9381%s", relativeUrl)
    16  	r, err := http.NewRequest(method, endURL, body)
    17  	if err != nil {
    18  		t.Fatalf("could not construct request: %v", err)
    19  	}
    20  	return httptest.NewRecorder(), r
    21  }
    22  
    23  func TestHTTPClear(t *testing.T) {
    24  	srv := mailSrv{}
    25  	w, r := reqAndRecorder(t, "POST", "/clear", nil)
    26  	srv.allReceivedMail = []rcvdMail{{}}
    27  	srv.httpClear(w, r)
    28  	if w.Code != 200 {
    29  		t.Errorf("expected 200, got %d", w.Code)
    30  	}
    31  	if len(srv.allReceivedMail) != 0 {
    32  		t.Error("/clear failed to clear mail buffer")
    33  	}
    34  
    35  	w, r = reqAndRecorder(t, "GET", "/clear", nil)
    36  	srv.allReceivedMail = []rcvdMail{{}}
    37  	srv.httpClear(w, r)
    38  	if w.Code != 405 {
    39  		t.Errorf("expected 405, got %d", w.Code)
    40  	}
    41  	if len(srv.allReceivedMail) != 1 {
    42  		t.Error("GET /clear cleared the mail buffer")
    43  	}
    44  }
    45  
    46  func TestHTTPCount(t *testing.T) {
    47  	srv := mailSrv{}
    48  	srv.allReceivedMail = []rcvdMail{
    49  		{From: "a", To: "b"},
    50  		{From: "a", To: "b"},
    51  		{From: "a", To: "c"},
    52  		{From: "c", To: "a"},
    53  		{From: "c", To: "b"},
    54  	}
    55  
    56  	tests := []struct {
    57  		URL   string
    58  		Count int
    59  	}{
    60  		{URL: "/count", Count: 5},
    61  		{URL: "/count?to=b", Count: 3},
    62  		{URL: "/count?to=c", Count: 1},
    63  	}
    64  
    65  	var buf bytes.Buffer
    66  	for _, test := range tests {
    67  		w, r := reqAndRecorder(t, "GET", test.URL, nil)
    68  		buf.Reset()
    69  		w.Body = &buf
    70  
    71  		srv.httpCount(w, r)
    72  		if w.Code != 200 {
    73  			t.Errorf("%s: expected 200, got %d", test.URL, w.Code)
    74  		}
    75  		n, err := strconv.Atoi(strings.TrimSpace(buf.String()))
    76  		if err != nil {
    77  			t.Errorf("%s: expected a number, got '%s'", test.URL, buf.String())
    78  		} else if n != test.Count {
    79  			t.Errorf("%s: expected %d, got %d", test.URL, test.Count, n)
    80  		}
    81  	}
    82  }
    83  

View as plain text