github.com/oinume/lekcije@v0.0.0-20231017100347-5b4c5eb6ab24/backend/interface/http/index_test.go (about)

     1  package http
     2  
     3  import (
     4  	"bytes"
     5  	"net/http"
     6  	"net/http/httptest"
     7  	"testing"
     8  
     9  	"github.com/stretchr/testify/assert"
    10  	"github.com/stretchr/testify/require"
    11  
    12  	"github.com/oinume/lekcije/backend/context_data"
    13  )
    14  
    15  func TestIndex(t *testing.T) {
    16  	t.Parallel()
    17  	a := assert.New(t)
    18  	r := require.New(t)
    19  
    20  	var accessLog, appLog bytes.Buffer
    21  	s := newTestServer(t, &accessLog, &appLog)
    22  	testCases := []struct {
    23  		path     string
    24  		handler  http.HandlerFunc
    25  		code     int
    26  		keywords []string
    27  	}{
    28  		{
    29  			path:    "/",
    30  			handler: s.indexHandler(),
    31  			code:    http.StatusOK,
    32  			keywords: []string{
    33  				`<title>lekcije - DMM英会話のお気に入り講師をフォローしよう</title>`,
    34  			},
    35  		},
    36  		{
    37  			path:     "/robots.txt",
    38  			handler:  s.robotsTxtHandler(),
    39  			code:     http.StatusOK,
    40  			keywords: []string{`Allow: /`},
    41  		},
    42  		{
    43  			path:    "/signup",
    44  			handler: s.signupHandler(),
    45  			code:    http.StatusOK,
    46  			keywords: []string{
    47  				`<title>新規登録 | lekcije</title>`,
    48  			},
    49  		},
    50  		{
    51  			path:    "/sitemap.xml",
    52  			handler: s.sitemapXMLHandler(),
    53  			code:    http.StatusOK,
    54  			keywords: []string{
    55  				`<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">`,
    56  				"/signup",
    57  				"/terms",
    58  			},
    59  		},
    60  		{
    61  			path:    "/terms",
    62  			handler: s.termsHandler(),
    63  			code:    http.StatusOK,
    64  			keywords: []string{
    65  				`<title>利用規約 | lekcije</title>`,
    66  			},
    67  		},
    68  	}
    69  
    70  	for _, tc := range testCases {
    71  		req, err := http.NewRequest("GET", tc.path, nil)
    72  		r.NoError(err)
    73  
    74  		ctx := context_data.SetTrackingID(req.Context(), "a")
    75  		req = req.WithContext(ctx)
    76  
    77  		w := httptest.NewRecorder()
    78  		tc.handler.ServeHTTP(w, req)
    79  
    80  		a.Equal(tc.code, w.Code)
    81  		for _, keyword := range tc.keywords {
    82  			a.Contains(w.Body.String(), keyword)
    83  		}
    84  	}
    85  }