github.com/hellofresh/janus@v0.0.0-20230925145208-ce8de8183c67/pkg/middleware/host_matcher_test.go (about)

     1  package middleware
     2  
     3  import (
     4  	"io/ioutil"
     5  	"net/http"
     6  	"os"
     7  	"testing"
     8  
     9  	"github.com/hellofresh/janus/pkg/test"
    10  	log "github.com/sirupsen/logrus"
    11  	"github.com/stretchr/testify/assert"
    12  )
    13  
    14  func TestMain(m *testing.M) {
    15  	log.SetOutput(ioutil.Discard)
    16  	os.Exit(m.Run())
    17  }
    18  
    19  func TestMatchSimpleHeader(t *testing.T) {
    20  	mw := NewHostMatcher([]string{"hellofresh.com"})
    21  	w, err := test.Record(
    22  		"GET",
    23  		"/",
    24  		map[string]string{
    25  			"Content-Type": "application/json",
    26  			"Host":         "hellofresh.com",
    27  		},
    28  		mw.Handler(http.HandlerFunc(test.Ping)),
    29  	)
    30  	assert.NoError(t, err)
    31  
    32  	assert.Equal(t, http.StatusOK, w.Code)
    33  	assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
    34  }
    35  
    36  func TestNotMatchSimpleHeader(t *testing.T) {
    37  	mw := NewHostMatcher([]string{"hellofresh.com"})
    38  	w, err := test.Record(
    39  		"GET",
    40  		"/",
    41  		map[string]string{
    42  			"Content-Type": "application/json",
    43  			"Host":         "hellofresh.de",
    44  		},
    45  		mw.Handler(http.HandlerFunc(test.Ping)),
    46  	)
    47  	assert.NoError(t, err)
    48  
    49  	assert.Equal(t, http.StatusNotFound, w.Code)
    50  	assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
    51  }
    52  
    53  func TestMatchRegexHeader(t *testing.T) {
    54  	mw := NewHostMatcher([]string{"hellofresh.*"})
    55  	w, err := test.Record(
    56  		"GET",
    57  		"/",
    58  		map[string]string{
    59  			"Content-Type": "application/json",
    60  			"Host":         "hellofresh.com",
    61  		},
    62  		mw.Handler(http.HandlerFunc(test.Ping)),
    63  	)
    64  	assert.NoError(t, err)
    65  
    66  	assert.Equal(t, http.StatusOK, w.Code)
    67  	assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
    68  }
    69  
    70  func TestNotMatchRegexHeader(t *testing.T) {
    71  	mw := NewHostMatcher([]string{"hellofresh.*"})
    72  	w, err := test.Record(
    73  		"GET",
    74  		"/",
    75  		map[string]string{
    76  			"Content-Type": "application/json",
    77  			"Host":         "api.hellofresh.com",
    78  		},
    79  		mw.Handler(http.HandlerFunc(test.Ping)),
    80  	)
    81  	assert.NoError(t, err)
    82  
    83  	assert.Equal(t, http.StatusNotFound, w.Code)
    84  	assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
    85  }