コード例 #1
0
ファイル: builder_test.go プロジェクト: goodgravy/pact-go
func Test_Builder_CanBuild(t *testing.T) {
	builder := NewConsumerPactBuilder(&BuilderConfig{PactPath: "./pact_examples"}).
		ServiceConsumer("chrome browser").
		HasPactWith("go api")
	ps, _ := builder.GetMockProviderService()

	request := provider.NewJSONRequest("GET", "/user", "id=23", nil)
	header := make(http.Header)
	header.Add("content-type", "application/json")
	response := provider.NewJSONResponse(200, header)
	response.SetBody(`{ "id": 23, "firstName": "John", "lastName": "Doe" }`)

	if err := ps.Given("there is a user with id {23}").
		UponReceiving("get request for user with id {23}").
		With(*request).
		WillRespondWith(*response); err != nil {
		t.Error(err)
		t.FailNow()
	}

	request.Query = "id=200"
	response.Status = 404
	response.Headers = nil
	response.ResetContent()

	ps.Given("there is no user with id {200}").
		UponReceiving("get request for user with id {200}").
		With(*request).
		WillRespondWith(*response)

	if err := builder.Build(); err != nil {
		t.Error(err)
	}
}
コード例 #2
0
func Test_ProviderService_CanVerifyInteractions(t *testing.T) {
	ps := newMockProviderService(&BuilderConfig{})

	request := provider.NewJSONRequest("POST", "/luke", "action=attack", nil)
	response := provider.NewJSONResponse(200, nil)

	if err := ps.Given("Force is strong with Luke Skywalker").
		UponReceiving("Destroy death star").
		With(*request).
		WillRespondWith(*response); err != nil {
		t.Error(err)
	}

	url := ps.start()
	defer ps.stop()

	client := &http.Client{}
	if req, err := http.NewRequest(request.Method, fmt.Sprintf("%s%s?%s", url, request.Path, request.Query), nil); err != nil {
		t.Error(err)
		t.FailNow()
	} else if _, err := client.Do(req); err != nil {
		t.Error(err)
		t.FailNow()
	} else if err := ps.VerifyInteractions(); err != nil {
		t.Error(err)
		t.FailNow()
	}
}
コード例 #3
0
ファイル: http_server_test.go プロジェクト: goodgravy/pact-go
func getFakeInteraction() *Interaction {
	header := make(http.Header)
	header.Add("content-type", "application/json")
	i, _ := NewInteraction("description of the interaction",
		"some state",
		provider.NewJSONRequest("GET", "/", "param=xyzmk", header),
		provider.NewJSONResponse(201, header))
	i.Request.SetBody(`{ "firstName": "John", "lastName": "Doe" }`)

	return i
}
コード例 #4
0
func Test_ProviderService_CannotReigsterInteraction_WithInvalidData(t *testing.T) {
	ps := newMockProviderService(&BuilderConfig{})

	request := provider.NewJSONRequest("POST", "/luke", "action=attack", nil)
	response := provider.NewJSONResponse(200, nil)

	if err := ps.Given("Force is strong with Luke Skywalker").
		With(*request).
		WillRespondWith(*response); err == nil {
		t.Error("Should not be able to register interaction with empty description")
	}
}
コード例 #5
0
ファイル: pactgenerate.go プロジェクト: compasses/GOProjects
func (middleware *offlinemiddleware) RunPact(builder pact.Builder, path, method string, reqBody, respBody interface{}, statusCode int,
	consumerName, providerName string) {
	ms, msUrl := builder.GetMockProviderService()

	request := provider.NewJSONRequest(method, path, "", nil)
	if reqBody != nil {
		err := request.SetBody(reqBody)
		if err != nil {
			log.Println("Set request error ", err, " reqBody ", respBody)
		}
	}

	header := make(http.Header)
	header.Add("content-type", "application/json")
	response := provider.NewJSONResponse(statusCode, header)
	if respBody != nil {
		err := response.SetBody(respBody)
		if err != nil {
			log.Println("Set Response error ", err, " respBody ", respBody)
		}
	}

	//Register interaction for this test scope
	if err := ms.Given(consumerName).
		UponReceiving(providerName).
		With(*request).
		WillRespondWith(*response); err != nil {
		log.Println(err)
	}

	//log.Println("Register: ", " Request ", string(req), " response ", respBody)

	//test
	client := &ProviderAPIClient{baseURL: msUrl}
	if err := client.ClientRun(method, path, reqBody); err != nil {
		log.Println(err)
	}

	//Verify registered interaction
	if err := ms.VerifyInteractions(); err != nil {
		log.Println(err)
	}

	//Clear interaction for this test scope, if you need to register and verify another interaction for another test scope
	ms.ClearInteractions()
}
コード例 #6
0
func Test_ProviderService_CanReigsterInteraction_WithValidData(t *testing.T) {
	ps := newMockProviderService(&BuilderConfig{})

	header := make(http.Header)
	header.Add("content-type", "payload/nuclear")
	request := provider.NewJSONRequest("POST", "/luke", "action=attack", header)
	request.SetBody(`{ "simulation": false, "target": "Death Star" }`)

	response := provider.NewJSONResponse(200, nil)

	if err := ps.Given("Force is strong with Luke Skywalker").
		UponReceiving("Destroy death star").
		With(*request).
		WillRespondWith(*response); err != nil {
		t.Error(err)
	}
}
コード例 #7
0
func Test_Validator_ReturnsErrorFromResponseMatcher(t *testing.T) {
	v := newConsumerValidator(nil, nil, DefaultLogger)
	r := provider.NewJSONResponse(200, nil)
	r.SetBody(`{"name":"John Doe"}`)
	interaction, _ := consumer.NewInteraction("description", "state", provider.NewJSONRequest("Get", "/", "", nil), r)
	f := io.NewPactFile("consumer", "provider", []*consumer.Interaction{interaction})
	sa := &stateAction{setup: nil, teardown: nil}
	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(interaction.Response.Status)
		w.Write([]byte("bad json"))
	}))
	defer s.Close()
	u, _ := url.Parse(s.URL)

	v.ProviderService(&http.Client{}, u)
	if _, err := v.Validate(f, map[string]*stateAction{"state": sa}); err == nil {
		t.Errorf("expected error from response matcher")
	}
}
コード例 #8
0
func Test_ProviderService_CannotReigster_DuplicateInteraction(t *testing.T) {
	ps := newMockProviderService(&BuilderConfig{})

	request := provider.NewJSONRequest("POST", "/luke", "action=attack", nil)
	response := provider.NewJSONResponse(200, nil)

	if err := ps.Given("Force is strong with Luke Skywalker").
		UponReceiving("Destroy death star").
		With(*request).
		WillRespondWith(*response); err != nil {
		t.Error(err)
	}

	if err := ps.Given("Force is strong with Luke Skywalker").
		UponReceiving("Destroy death star").
		With(*request).
		WillRespondWith(*response); err == nil {
		t.Error("Should not allow to register duplicate interaction")
	}

}
コード例 #9
0
func Test_ProviderService_CanResetTransientState_AfterRegistration(t *testing.T) {
	ps := newMockProviderService(&BuilderConfig{})

	header := make(http.Header)
	header.Add("content-type", "payload/nuclear")
	request := provider.NewJSONRequest("POST", "/luke", "action=attack", header)
	request.SetBody(`{ "simulation": false, "target": "Death Star" }`)

	response := provider.NewJSONResponse(200, nil)

	if err := ps.Given("Force is strong with Luke Skywalker").
		UponReceiving("Destroy death star").
		With(*request).
		WillRespondWith(*response); err != nil {
		t.Error(err)
	}

	if ps.state != "" || ps.description != "" || ps.providerRequest != nil || ps.providerResponse != nil {
		t.Error("Provider services transient state is not cleared after interaction registration")
	}
}
コード例 #10
0
func Test_ProviderService_CanClearInteractions(t *testing.T) {
	ps := newMockProviderService(&BuilderConfig{})

	request := provider.NewJSONRequest("POST", "/luke", "action=attack", nil)
	response := provider.NewJSONResponse(200, nil)

	if err := ps.Given("Force is strong with Luke Skywalker").
		UponReceiving("Destroy death star").
		With(*request).
		WillRespondWith(*response); err != nil {
		t.Error(err)
	}

	ps.ClearInteractions()

	if !ps.service.IsTestScopeClear() {
		t.Error("Interactions have not been cleared")
	}
	if ps.state != "" || ps.description != "" || ps.providerRequest != nil || ps.providerResponse != nil {
		t.Error("Provider services transient state is not cleared after interaction registration")
	}
}
コード例 #11
0
func Test_ProviderService_CanReigsterDuplicateInteraction_InDifferentScope(t *testing.T) {
	ps := newMockProviderService(&BuilderConfig{})

	request := provider.NewJSONRequest("POST", "/luke", "action=attack", nil)
	response := provider.NewJSONResponse(200, nil)

	if err := ps.Given("Force is strong with Luke Skywalker").
		UponReceiving("Destroy death star").
		With(*request).
		WillRespondWith(*response); err != nil {
		t.Error(err)
	}

	ps.ClearInteractions()

	if err := ps.Given("Force is strong with Luke Skywalker").
		UponReceiving("Destroy death star").
		With(*request).
		WillRespondWith(*response); err != nil {
		t.Error(err)
	}

}
コード例 #12
0
func Test_Validator_ReturnsErrorWhenProvierStateIsMissing(t *testing.T) {
	v := newConsumerValidator(nil, nil, DefaultLogger)
	interaction, _ := consumer.NewInteraction("description", "state", provider.NewJSONRequest("Get", "/", "", nil), provider.NewJSONResponse(200, nil))
	f := io.NewPactFile("consumer", "provider", []*consumer.Interaction{interaction})

	expErrMsg := fmt.Sprintf(errNotFoundProviderStateMsg, interaction.State)
	v.ProviderService(&http.Client{}, &url.URL{})
	if _, err := v.Validate(f, nil); err == nil {
		t.Errorf("expected %s", expErrMsg)
	} else if err.Error() != expErrMsg {
		t.Errorf("expected %s, got %s", expErrMsg, err)
	}

}
コード例 #13
0
func buildTestProviderResponse(status int, h http.Header, body string) *provider.Response {
	pr := provider.NewJSONResponse(200, h)
	pr.SetBody(body)
	return pr
}
コード例 #14
0
func Test_ShouldVerify_Interactions(t *testing.T) {
	i, _ := NewInteraction("description", "state", provider.NewJSONRequest("GET", "/", "", nil), provider.NewJSONResponse(200, nil))
	registered := []*Interaction{i}
	requested := []*Interaction{i}
	if err := verifyInteractions(registered, requested); err != nil {
		t.Errorf("expected verfication to succed, got error: %s", err.Error())
	}
}
コード例 #15
0
func Test_ShouldVerify_UnexpectedInteractionVerfications(t *testing.T) {
	i, _ := NewInteraction("description", "state", provider.NewJSONRequest("GET", "/", "", nil), provider.NewJSONResponse(200, nil))
	registered := []*Interaction{}
	requested := []*Interaction{i}
	if err := verifyInteractions(registered, requested); err != nil {
		if !strings.Contains(err.Error(), errIntShouldNotBeCalled) {
			t.Errorf("expected message to contain: %s, actual message: %s", errIntShouldNotBeCalled, err.Error())
		}
	} else if err == nil {
		t.Error("expected unexpected calls interaction error")
	}
}
コード例 #16
0
func Test_ShouldVerify_MultipleSameInteractionCalls(t *testing.T) {
	i, _ := NewInteraction("description", "state", provider.NewJSONRequest("GET", "/", "", nil), provider.NewJSONResponse(200, nil))
	registered := []*Interaction{i}
	requested := []*Interaction{i, i, i}
	if err := verifyInteractions(registered, requested); err != nil {
		if !strings.Contains(err.Error(), fmt.Sprintf(errIntMultipleCalls, i.Description, i.State, len(requested))) {
			t.Errorf("expected message to contain: %s, actual message: %s",
				fmt.Sprintf(errIntMultipleCalls, i.Description, i.State, len(requested)), err.Error())
		}
	} else if err == nil {
		t.Error("expected multiple calls interaction error")
	}
}
コード例 #17
0
func Test_Validator_ExecutesSetupsAndTeardowns(t *testing.T) {
	i := 1
	v := newConsumerValidator(func() error {
		if i != 1 {
			t.Errorf("Expected this action to be called at %v position but is at %d", 1, i)
		} else {
			i++
		}
		return nil
	}, func() error {
		if i != 4 {
			t.Errorf("Expected this action to be called at %d position but is at %d", 4, i)
		}
		return nil
	}, DefaultLogger)

	sa := &stateAction{setup: func() error {
		if i != 2 {
			t.Errorf("Expected this action to be called at %d position but is at %d", 2, i)
		} else {
			i++
		}
		return nil
	}, teardown: func() error {
		if i != 3 {
			t.Errorf("Expected this action to be called at %d position but is at %d", 3, i)
		} else {
			i++
		}
		return nil
	}}

	interaction, _ := consumer.NewInteraction("description", "state", provider.NewJSONRequest("Get", "/", "", nil), provider.NewJSONResponse(200, nil))
	f := io.NewPactFile("consumer", "provider", []*consumer.Interaction{interaction})

	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(interaction.Response.Status)
	}))
	defer s.Close()
	u, _ := url.Parse(s.URL)

	v.ProviderService(&http.Client{}, u)
	if res, err := v.Validate(f, map[string]*stateAction{"state": sa}); err != nil {
		t.Error(err)
	} else if !res {
		t.Error("Validation Failed")
	} else if i != 4 {
		t.Error("Setup and teardown actions were not called correctly")
	}
}
コード例 #18
0
func Test_Validator_ReturnsErrorWhenRequestFails(t *testing.T) {
	v := newConsumerValidator(nil, nil, DefaultLogger)
	interaction, _ := consumer.NewInteraction("description", "state", provider.NewJSONRequest("Get", "/", "", nil), provider.NewJSONResponse(200, nil))
	f := io.NewPactFile("consumer", "provider", []*consumer.Interaction{interaction})
	sa := &stateAction{setup: nil, teardown: nil}
	u, _ := url.Parse("http://localhost:54322")

	v.ProviderService(&http.Client{}, u)
	if _, err := v.Validate(f, map[string]*stateAction{"state": sa}); err == nil {
		t.Errorf("expected error whilst making request")
	}
}
コード例 #19
0
func Test_Validator_ThrowsErrorFromSetupsAndTeardowns(t *testing.T) {
	testErr := errors.New("action error")
	fn := func() error {
		return testErr
	}

	sa := &stateAction{setup: nil, teardown: nil}

	interaction, _ := consumer.NewInteraction("description", "state", provider.NewJSONRequest("Get", "/", "", nil), provider.NewJSONResponse(200, nil))
	f := io.NewPactFile("consumer", "provider", []*consumer.Interaction{interaction})

	s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(interaction.Response.Status)
	}))
	defer s.Close()

	u, _ := url.Parse(s.URL)

	//test setup action for every interaction
	v := newConsumerValidator(fn, nil, DefaultLogger)
	v.ProviderService(&http.Client{}, u)
	if _, err := v.Validate(f, map[string]*stateAction{"state": sa}); err == nil {
		t.Errorf("expected %s", testErr)
	} else if err != testErr {
		t.Errorf("expected %s, got %s", testErr, err)
	}

	//test teardown action for every interaction
	v = newConsumerValidator(nil, fn, DefaultLogger)
	v.ProviderService(&http.Client{}, u)
	if _, err := v.Validate(f, map[string]*stateAction{"state": sa}); err == nil {
		t.Errorf("expected %s", testErr)
	} else if err != testErr {
		t.Errorf("expected %s, got %s", testErr, err)
	}

	//test setup action for specific interaction
	sa = &stateAction{setup: fn, teardown: nil}
	v = newConsumerValidator(nil, fn, DefaultLogger)
	v.ProviderService(&http.Client{}, u)
	if _, err := v.Validate(f, map[string]*stateAction{"state": sa}); err == nil {
		t.Errorf("expected %s", testErr)
	} else if err != testErr {
		t.Errorf("expected %s, got %s", testErr, err)
	}

	//test teardown action for every interaction
	sa = &stateAction{setup: nil, teardown: fn}
	v = newConsumerValidator(nil, fn, DefaultLogger)
	v.ProviderService(&http.Client{}, u)
	if _, err := v.Validate(f, map[string]*stateAction{"state": sa}); err == nil {
		t.Errorf("expected %s", testErr)
	} else if err != testErr {
		t.Errorf("expected %s, got %s", testErr, err)
	}
}