github.com/Secbyte/godog@v0.7.14-0.20200116175429-d8f0aeeb70cf/examples/api/api_test.go (about)

     1  package main
     2  
     3  import (
     4  	"encoding/json"
     5  	"fmt"
     6  	"net/http"
     7  	"net/http/httptest"
     8  	"reflect"
     9  
    10  	"github.com/DATA-DOG/godog"
    11  	"github.com/DATA-DOG/godog/gherkin"
    12  )
    13  
    14  type apiFeature struct {
    15  	resp *httptest.ResponseRecorder
    16  }
    17  
    18  func (a *apiFeature) resetResponse(interface{}) {
    19  	a.resp = httptest.NewRecorder()
    20  }
    21  
    22  func (a *apiFeature) iSendrequestTo(method, endpoint string) (err error) {
    23  	req, err := http.NewRequest(method, endpoint, nil)
    24  	if err != nil {
    25  		return
    26  	}
    27  
    28  	// handle panic
    29  	defer func() {
    30  		switch t := recover().(type) {
    31  		case string:
    32  			err = fmt.Errorf(t)
    33  		case error:
    34  			err = t
    35  		}
    36  	}()
    37  
    38  	switch endpoint {
    39  	case "/version":
    40  		getVersion(a.resp, req)
    41  	default:
    42  		err = fmt.Errorf("unknown endpoint: %s", endpoint)
    43  	}
    44  	return
    45  }
    46  
    47  func (a *apiFeature) theResponseCodeShouldBe(code int) error {
    48  	if code != a.resp.Code {
    49  		return fmt.Errorf("expected response code to be: %d, but actual is: %d", code, a.resp.Code)
    50  	}
    51  	return nil
    52  }
    53  
    54  func (a *apiFeature) theResponseShouldMatchJSON(body *gherkin.DocString) (err error) {
    55  	var expected, actual interface{}
    56  
    57  	// re-encode expected response
    58  	if err = json.Unmarshal([]byte(body.Content), &expected); err != nil {
    59  		return
    60  	}
    61  
    62  	// re-encode actual response too
    63  	if err = json.Unmarshal(a.resp.Body.Bytes(), &actual); err != nil {
    64  		return
    65  	}
    66  
    67  	// the matching may be adapted per different requirements.
    68  	if !reflect.DeepEqual(expected, actual) {
    69  		return fmt.Errorf("expected JSON does not match actual, %v vs. %v", expected, actual)
    70  	}
    71  	return nil
    72  }
    73  
    74  func FeatureContext(s *godog.Suite) {
    75  	api := &apiFeature{}
    76  
    77  	s.BeforeScenario(api.resetResponse)
    78  
    79  	s.Step(`^I send "(GET|POST|PUT|DELETE)" request to "([^"]*)"$`, api.iSendrequestTo)
    80  	s.Step(`^the response code should be (\d+)$`, api.theResponseCodeShouldBe)
    81  	s.Step(`^the response should match json:$`, api.theResponseShouldMatchJSON)
    82  }