Skip to content

Commit

Permalink
change mock server to move the assert within the test function rather…
Browse files Browse the repository at this point in the history
… than in the server handler
  • Loading branch information
jdevost committed Oct 24, 2018
1 parent 62550f3 commit d9aa571
Show file tree
Hide file tree
Showing 2 changed files with 99 additions and 87 deletions.
159 changes: 86 additions & 73 deletions scenariolib/event_searchandclick_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,46 +37,10 @@ func TestSearchAndClickEventValid(t *testing.T) {
func TestDecorateSearchAndClickEvent(t *testing.T) {
scenariolib.InitLogger(os.Stdout, os.Stdout, os.Stdout, os.Stderr)

expected := map[string]ExpectedRequest{
"/rest/search/": {
Method: "POST",
Headers: map[string]string{
"Authorization": "Bearer bot.searchToken",
"Content-Type": "application/json",
},
Body: []byte(`{
"q": "aaaaaaaaaaa",
"numberOfResults": 20,
"tab": "All",
"pipeline": "besttechCommunity"
}`),
},
"/rest/v15/analytics/search/": {
Method: "POST",
Headers: map[string]string{
"Authorization": "Bearer bot.analyticsToken",
"Content-Type": "application/json",
},
Body: []byte(`{
"language": "en",
"device": "Bot",
"customData": {
"JSUIVersion": "0.0.0.0;0.0.0.0",
"customData1": "customValue 1",
"ipaddress": "216.249.112.8"
},
"anonymous": true,
"originLevel1": "BotSearch",
"originLevel2": "",
"searchQueryUid": "",
"queryText": "aaaaaaaaaaa",
"actionCause": "searchboxSubmit",
"contextual": false
}`),
},
}
// All requests caught by the Test server will be added to 'requests'
requests := make(map[string]RestRequest)

server := createMockServer(t, expected)
server := createTestServer(t, requests)
defer server.Close() // Close the server when test finishes

event := &scenariolib.SearchAndClickEvent{}
Expand All @@ -91,46 +55,55 @@ func TestDecorateSearchAndClickEvent(t *testing.T) {

v.SetupGeneral()
event.Execute(v)

// Validate the search request we expect Execute() to send.
req, exists := requests["/rest/search/"]
assert(t, exists, "Missing request for /rest/search/")
equals(t, "POST", req.Method)
equals(t, "Bearer bot.searchToken", req.Headers["Authorization"])
equals(t, "application/json", req.Headers["Content-Type"])
expectedBody := []byte(`{
"q": "aaaaaaaaaaa",
"numberOfResults": 20,
"tab": "All",
"pipeline": "besttechCommunity"
}`)
eq, err := JSONBytesEqual(expectedBody, req.Body)
assert(t, eq, "The Request's body for Search is not what we expected\nGot: %s\nExp: %s", expectedBody, req.Body)

// Validate analytics request we expect Execute() to send.
req, exists = requests["/rest/v15/analytics/search/"]
assert(t, exists, "Missing request for /rest/v15/analytics/search/")
equals(t, "POST", req.Method)
equals(t, "Bearer bot.analyticsToken", req.Headers["Authorization"])
equals(t, "application/json", req.Headers["Content-Type"])
expectedBody = []byte(`{
"language": "en",
"device": "Bot",
"customData": {
"JSUIVersion": "0.0.0.0;0.0.0.0",
"customData1": "customValue 1",
"ipaddress": "216.249.112.8"
},
"anonymous": true,
"originLevel1": "BotSearch",
"originLevel2": "",
"searchQueryUid": "",
"queryText": "aaaaaaaaaaa",
"actionCause": "searchboxSubmit",
"contextual": false
}`)
eq, err = JSONBytesEqual(expectedBody, req.Body)
assert(t, eq, "The Request's body for Analytics is not what we expected\nGot: %s\nExp: %s", expectedBody, req.Body)
}

func TestDecorateSearchAndClickEvent2(t *testing.T) {
scenariolib.InitLogger(os.Stdout, os.Stdout, os.Stdout, os.Stderr)

expected := map[string]ExpectedRequest{
"/rest/search/": {
Method: "POST",
Headers: map[string]string{
"Authorization": "Bearer bot.searchToken",
"Content-Type": "application/json",
},
Body: []byte(`{"q":"Gostbuster","numberOfResults":20,"tab":"All","pipeline":"ML"}`),
},
"/rest/v15/analytics/search/": {
Method: "POST",
Headers: map[string]string{
"Authorization": "Bearer bot.analyticsToken",
"Content-Type": "application/json",
},
Body: []byte(`{
"language": "en",
"device": "Bot",
"customData": {
"JSUIVersion": "0.0.0.0;0.0.0.0",
"c_isbot": "true",
"ipaddress": "198.199.154.209"
},
"username": "avery.caldwell@hexzone.com",
"originLevel1": "Movie",
"originLevel2": "default",
"searchQueryUid": "",
"queryText": "Gostbuster",
"actionCause": "searchboxSubmit",
"contextual": false
}`),
},
}
// All requests caught by the Test server will be added to 'requests'
requests := make(map[string]RestRequest)

server := createMockServer(t, expected)
server := createTestServer(t, requests)
defer server.Close() // Close the server when test finishes

event := &scenariolib.SearchAndClickEvent{}
Expand All @@ -145,4 +118,44 @@ func TestDecorateSearchAndClickEvent2(t *testing.T) {

v.SetupGeneral()
event.Execute(v)

// Validate the search request we expect Execute() to send.
req, exists := requests["/rest/search/"]
assert(t, exists, "Missing request for /rest/search/")
equals(t, "POST", req.Method)
equals(t, "Bearer bot.searchToken", req.Headers["Authorization"])
equals(t, "application/json", req.Headers["Content-Type"])
expectedBody := []byte(`{
"q": "Gostbuster",
"numberOfResults": 20,
"tab": "All",
"pipeline": "ML"
}`)
eq, err := JSONBytesEqual(expectedBody, req.Body)
assert(t, eq, "The Request's body for Search is not what we expected\nGot: %s\nExp: %s", expectedBody, req.Body)

// Validate analytics request we expect Execute() to send.
req, exists = requests["/rest/v15/analytics/search/"]
assert(t, exists, "Missing request for /rest/v15/analytics/search/")
equals(t, "POST", req.Method)
equals(t, "Bearer bot.analyticsToken", req.Headers["Authorization"])
equals(t, "application/json", req.Headers["Content-Type"])
expectedBody = []byte(`{
"language": "en",
"device": "Bot",
"customData": {
"JSUIVersion": "0.0.0.0;0.0.0.0",
"c_isbot": "true",
"ipaddress": "198.199.154.209"
},
"username": "avery.caldwell@hexzone.com",
"originLevel1": "Movie",
"originLevel2": "default",
"searchQueryUid": "",
"queryText": "Gostbuster",
"actionCause": "searchboxSubmit",
"contextual": false
}`)
eq, err = JSONBytesEqual(expectedBody, req.Body)
assert(t, eq, "The Request's body for Analytics is not what we expected\nGot: %s\nExp: %s", expectedBody, req.Body)
}
27 changes: 13 additions & 14 deletions scenariolib/uabot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func equals(tb testing.TB, exp, act interface{}) {
}
}

type ExpectedRequest struct {
type RestRequest struct {
Method string
Headers map[string]string
Body []byte
Expand All @@ -66,29 +66,28 @@ func JSONBytesEqual(a, b []byte) (bool, error) {
return reflect.DeepEqual(j2, j), nil
}

func createMockServer(t testing.TB, expected map[string]ExpectedRequest) *httptest.Server {
// This a proxy to intercept requests sent to platform endpoints and add them into a map (receivedRequests).
// receivedRequests will then be used for validation in unit tests.
func createTestServer(t testing.TB, receivedRequests map[string]RestRequest) *httptest.Server {
// Start a local HTTP server to intercept requests
// Using url to match the expected responses above.
// Using url as key for the map of received requests.
server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
url := req.URL.String()

expReq, exists := expected[url]
assert(t, exists, "MISSING expected request for %s", url)
headers := make(map[string]string)

// Test request parameters
equals(t, req.Method, expReq.Method)

for k, v := range expReq.Headers {
equals(t, v, req.Header.Get(k))
for k := range req.Header {
headers[k] = req.Header.Get(k)
}

body, err := ioutil.ReadAll(req.Body)
if err != nil {
panic(err)
}

eq, err := JSONBytesEqual(expReq.Body, body)
assert(t, eq, "The Request's body is not what we expected\nGot: %s\nExp: %s", body, req.Body)
receivedRequests[url] = RestRequest{
Method: req.Method,
Headers: headers,
Body: body,
}

// Send back a static response
rw.Write([]byte(`{"status":"OK"}`))
Expand Down

0 comments on commit d9aa571

Please sign in to comment.