diff --git a/it/controllers/subscription/SubscriptionControllerISpec.scala b/it/controllers/subscription/SubscriptionControllerISpec.scala index 1af2a6bf..e8671a4c 100644 --- a/it/controllers/subscription/SubscriptionControllerISpec.scala +++ b/it/controllers/subscription/SubscriptionControllerISpec.scala @@ -16,106 +16,75 @@ package controllers.subscription -import connectors._ import helpers.ComponentSpecBase import helpers.IntegrationTestConstants._ -import helpers.WireMockDSL.HTTPVerbMapping.{Get, Post} -import helpers.WireMockDSL._ -import helpers.servicemocks.AuthStub._ -import helpers.servicemocks.BusinessDetailsStub._ -import helpers.servicemocks.GGAdminStub._ -import helpers.servicemocks.SubscriptionStub._ +import helpers.servicemocks._ import models.frontend.FESuccessResponse import play.api.http.Status._ -import play.api.libs.json.Json class SubscriptionControllerISpec extends ComponentSpecBase { "subscribe" should { "call the subscription service successfully when auth succeeds for a business registration" in { - stub when Get(authority) thenReturn stubbedAuthResponse - stub when Get(authIDs) thenReturn stubbedIDs - multiline( - stub - when Post(RegistrationConnector.newRegistrationUri(testNino), registerRequestPayload) - thenReturn registrationResponse - ) - multiline( - stub - when Post(SubscriptionConnector.businessSubscribeUri(testNino), businessSubscriptionRequestPayload) - thenReturn testBusinessSubscriptionResponse - ) - stub when Post(GGAdminConnector.addKnownFactsUri) thenReturn testAddKnownFactsResponse - stub when Post(GGConnector.enrolUri) thenReturn OK + Given("I setup the wiremock stubs") + AuthStub.stubAuthSuccess() + RegistrationStub.stubNewRegistrationSuccess() + SubscriptionStub.stubBusinessSubscribeSuccess() + GGAdminStub.stubAddKnownFactsSuccess() + GGConnectorStub.stubEnrolSuccess() + AuthenticatorStub.stubRefreshProfileSuccess() - stub when Post(AuthenticatorConnector.refreshProfileUri) thenReturn NO_CONTENT + When("I call POST /subscription/:nino where nino is the test nino with a Business Request") + val res = IncomeTaxSubscription.createSubscription(feBusinessRequest) - IncomeTaxSubscription.createSubscription(feBusinessRequest) should have( + Then("The result should have a HTTP status of OK and a body containing the MTDID") + res should have( httpStatus(OK), jsonBodyAs[FESuccessResponse](FESuccessResponse(Some(testMtditId))) ) } - "call the subscription service successfully when auth succeeds for a property registration" in { - stub when Get(authority) thenReturn stubbedAuthResponse - stub when Get(authIDs) thenReturn stubbedIDs - multiline( - stub - when Post(RegistrationConnector.newRegistrationUri(testNino), registerRequestPayload) - thenReturn registrationResponse - ) - multiline( - stub - when Post(SubscriptionConnector.propertySubscribeUri(testNino), Json.obj()) - thenReturn testPropertySubscriptionResponse - ) - stub when Post(GGAdminConnector.addKnownFactsUri) thenReturn testAddKnownFactsResponse - stub when Post(GGConnector.enrolUri) thenReturn OK - stub when Post(AuthenticatorConnector.refreshProfileUri) thenReturn NO_CONTENT + Given("I setup the wiremock stubs") + AuthStub.stubAuthSuccess() + RegistrationStub.stubNewRegistrationSuccess() + SubscriptionStub.stubPropertySubscribeSuccess() + GGAdminStub.stubAddKnownFactsSuccess() + GGConnectorStub.stubEnrolSuccess() + AuthenticatorStub.stubRefreshProfileSuccess() + + When("I call POST /subscription/:nino where nino is the test nino with a Property Request") + val res = IncomeTaxSubscription.createSubscription(fePropertyRequest) - IncomeTaxSubscription.createSubscription(fePropertyRequest) should have( + Then("The result should have a HTTP status of OK and a body containing the MTDID") + res should have( httpStatus(OK), jsonBodyAs[FESuccessResponse](FESuccessResponse(Some(testMtditId))) ) } "call the subscription service successfully when auth succeeds for a business and property registration" in { - stub when Get(authority) thenReturn stubbedAuthResponse - stub when Get(authIDs) thenReturn stubbedIDs - multiline( - stub - when Post(RegistrationConnector.newRegistrationUri(testNino), registerRequestPayload) - thenReturn registrationResponse - ) - multiline( - stub - when Post(SubscriptionConnector.propertySubscribeUri(testNino), Json.obj()) - thenReturn testPropertySubscriptionResponse - ) - multiline( - stub - when Post(SubscriptionConnector.businessSubscribeUri(testNino), businessSubscriptionRequestPayload) - thenReturn testBusinessSubscriptionResponse - ) - stub when Post(GGAdminConnector.addKnownFactsUri) thenReturn testAddKnownFactsResponse - stub when Post(GGConnector.enrolUri) thenReturn OK - stub when Post(AuthenticatorConnector.refreshProfileUri) thenReturn NO_CONTENT + Given("I setup the wiremock stubs") + AuthStub.stubAuthSuccess() + RegistrationStub.stubNewRegistrationSuccess() + SubscriptionStub.stubBusinessSubscribeSuccess() + SubscriptionStub.stubPropertySubscribeSuccess() + GGAdminStub.stubAddKnownFactsSuccess() + GGConnectorStub.stubEnrolSuccess() + AuthenticatorStub.stubRefreshProfileSuccess() + + When("I call POST /subscription/:nino where nino is the test nino with both a property request and a business request") + val res = IncomeTaxSubscription.createSubscription(feBothRequest) - IncomeTaxSubscription.createSubscription(feBothRequest) should have( + Then("The result should have a HTTP status of OK and a body containing the MTDID") + res should have( httpStatus(OK), jsonBodyAs[FESuccessResponse](FESuccessResponse(Some(testMtditId))) ) - stub verify Post(SubscriptionConnector.businessSubscribeUri(testNino), businessSubscriptionRequestPayload) - stub verify Post(SubscriptionConnector.propertySubscribeUri(testNino), Json.obj()) - } - - "fail when get authority fails" in { - stubGetAuthorityFailure() + Then("Business subscription should have been called") + SubscriptionStub.verifyBusinessSubscribe() - IncomeTaxSubscription.createSubscription(feBusinessRequest) should have( - httpStatus(UNAUTHORIZED), - emptyBody - ) + Then("Property subscription should have been called") + SubscriptionStub.verifyPropertySubscribe() } } } diff --git a/it/controllers/subscription/SubscriptionStatusControllerISpec.scala b/it/controllers/subscription/SubscriptionStatusControllerISpec.scala index 7e01cf24..4a5ec848 100644 --- a/it/controllers/subscription/SubscriptionStatusControllerISpec.scala +++ b/it/controllers/subscription/SubscriptionStatusControllerISpec.scala @@ -16,38 +16,30 @@ package controllers.subscription -import connectors.BusinessDetailsConnector._ import helpers.ComponentSpecBase import helpers.IntegrationTestConstants._ -import helpers.WireMockDSL.HTTPVerbMapping.Get -import helpers.WireMockDSL._ -import helpers.servicemocks.AuthStub._ -import helpers.servicemocks.BusinessDetailsStub._ +import helpers.servicemocks.{AuthStub, BusinessDetailsStub} import models.frontend.FESuccessResponse import play.api.http.Status._ class SubscriptionStatusControllerISpec extends ComponentSpecBase { "subscribe" should { "call the subscription service successfully when auth succeeds" in { - stub when Get(authority) thenReturn stubbedAuthResponse - stub when Get(authIDs) thenReturn stubbedIDs - stub when Get(getBusinessDetailsUri(testNino)) thenReturn registrationResponse + Given("I setup the wiremock stubs") + AuthStub.stubAuthSuccess() + BusinessDetailsStub.stubGetBusinessDetailsSuccess() - IncomeTaxSubscription.getSubscriptionStatus(testNino) should have( + When("I call GET /subscription/:nino where nino is the test nino") + val res = IncomeTaxSubscription.getSubscriptionStatus(testNino) + + Then("The result should have a HTTP status of OK and a body containing the MTDID") + res should have( httpStatus(OK), jsonBodyAs[FESuccessResponse](FESuccessResponse(Some(testMtditId))) ) - stub verify Get(getBusinessDetailsUri(testNino)) - } - - "fail when get authority fails" in { - stubGetAuthorityFailure() - - IncomeTaxSubscription.getSubscriptionStatus(testNino) should have( - httpStatus(UNAUTHORIZED), - emptyBody - ) + Then("Get business details should have been called") + BusinessDetailsStub.verifyGetBusinessDetails() } } } diff --git a/it/controllers/throttling/UserAccessControllerISpec.scala b/it/controllers/throttling/UserAccessControllerISpec.scala index 9e06c198..aebefde2 100644 --- a/it/controllers/throttling/UserAccessControllerISpec.scala +++ b/it/controllers/throttling/UserAccessControllerISpec.scala @@ -17,54 +17,73 @@ package controllers.throttling import helpers.ComponentSpecBase -import helpers.WireMockDSL.HTTPVerbMapping.Get -import helpers.WireMockDSL._ -import helpers.servicemocks.AuthStub._ +import helpers.DatabaseHelpers._ import helpers.IntegrationTestConstants._ +import helpers.servicemocks.AuthStub import play.api.http.Status._ -import helpers.DatabaseHelpers._ -import play.api.libs.concurrent.Execution.Implicits._ class UserAccessControllerISpec extends ComponentSpecBase { "GET /throttle/:nino" should { "return OK when the service has not received any requests" in { - stub when Get(authority) thenReturn stubbedAuthResponse - stub when Get(authIDs) thenReturn stubbedIDs + Given("The database is empty") + IncomeTaxSubscription.dropThrottleRepo() + + Given("I setup the wiremock stubs") + AuthStub.stubAuthSuccess() + + When("I call the endpoint") + val res = IncomeTaxSubscription.checkUserAccess(testNino) - IncomeTaxSubscription.checkUserAccess(testNino) should have ( + Then("The result should have a HTTP status of OK") + res should have ( httpStatus(OK) ) } "return OK when the service has not received too many requests" in { + Given("The database contains a non full user count record") IncomeTaxSubscription.insertUserCount(nonFullUserCount) - stub when Get(authority) thenReturn stubbedAuthResponse - stub when Get(authIDs) thenReturn stubbedIDs + Given("I setup the wiremock stubs") + AuthStub.stubAuthSuccess() - IncomeTaxSubscription.checkUserAccess(testNino) should have ( + When("I call the endpoint") + val res = IncomeTaxSubscription.checkUserAccess(testNino) + + Then("The result should have a HTTP status of OK") + res should have ( httpStatus(OK) ) } "return OK for a returning user" in { + Given("The database contains a full user count record which contains the matching user") IncomeTaxSubscription.insertUserCount(matchingUserCount) - stub when Get(authority) thenReturn stubbedAuthResponse - stub when Get(authIDs) thenReturn stubbedIDs + Given("I setup the wiremock stubs") + AuthStub.stubAuthSuccess() + + When("I call the endpoint") + val res = IncomeTaxSubscription.checkUserAccess(testNino) - IncomeTaxSubscription.checkUserAccess(testNino) should have ( + Then("The result should have a HTTP status of OK") + res should have ( httpStatus(OK) ) } "return TOO_MANY_REQUESTS when the service has received too many requests and it is a new userID" in { + Given("The database contains a full user count record which contains the matching user") IncomeTaxSubscription.insertUserCount(maxUserCount) - stub when Get(authority) thenReturn stubbedAuthResponse - stub when Get(authIDs) thenReturn stubbedIDs + Given("I setup the wiremock stubs") + AuthStub.stubAuthSuccess() + + When("I call the endpoint") + val res = IncomeTaxSubscription.checkUserAccess(testNino) - IncomeTaxSubscription.checkUserAccess(testNino) should have ( + Then("The result should have a HTTP status of TOO_MANY_REQUESTS") + res should have ( httpStatus(TOO_MANY_REQUESTS) ) } diff --git a/it/helpers/ComponentSpecBase.scala b/it/helpers/ComponentSpecBase.scala index 2883a621..8d40315c 100644 --- a/it/helpers/ComponentSpecBase.scala +++ b/it/helpers/ComponentSpecBase.scala @@ -16,6 +16,7 @@ package helpers +import helpers.servicemocks.WireMockMethods import models.frontend.FERequest import models.throttling.UserCount import org.scalatest._ @@ -28,6 +29,7 @@ import play.api.{Application, Environment, Mode} import reactivemongo.api.commands.WriteResult import repositories.{Repositories, ThrottleMongoRepository} import uk.gov.hmrc.play.test.UnitSpec +import play.api.libs.concurrent.Execution.Implicits._ import scala.concurrent.ExecutionContext @@ -35,7 +37,7 @@ trait ComponentSpecBase extends UnitSpec with GivenWhenThen with TestSuite with GuiceOneServerPerSuite with ScalaFutures with IntegrationPatience with Matchers with WiremockHelper with BeforeAndAfterEach with BeforeAndAfterAll with Eventually - with CustomMatchers { + with CustomMatchers with WireMockMethods { override implicit lazy val app: Application = new GuiceApplicationBuilder() .in(Environment.simple(mode = Mode.Dev)) @@ -65,7 +67,7 @@ trait ComponentSpecBase extends UnitSpec override def beforeEach(): Unit = { super.beforeEach() - await(throttleMongoRepository.dropDb) + await(IncomeTaxSubscription.dropThrottleRepo()) } override def afterAll(): Unit = { @@ -92,7 +94,8 @@ trait ComponentSpecBase extends UnitSpec ) } - def insertUserCount(userCount: UserCount)(implicit ec: ExecutionContext): WriteResult = await(throttleMongoRepository.insert(userCount)) + def insertUserCount(userCount: UserCount): WriteResult = await(throttleMongoRepository.insert(userCount)) + def dropThrottleRepo(): Unit = await(throttleMongoRepository.drop) } } diff --git a/it/helpers/WireMockDSL.scala b/it/helpers/WireMockDSL.scala deleted file mode 100644 index 612875ed..00000000 --- a/it/helpers/WireMockDSL.scala +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2017 HM Revenue & Customs - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package helpers - -import com.github.tomakehurst.wiremock.client.WireMock._ -import com.github.tomakehurst.wiremock.client.{MappingBuilder, ResponseDefinitionBuilder} -import com.github.tomakehurst.wiremock.matching.EqualToPattern -import com.github.tomakehurst.wiremock.stubbing.StubMapping -import helpers.WireMockDSL.HTTPVerbMapping.{Get, HTTPVerbStub, Post} -import play.api.http.Status -import play.api.libs.json.{JsValue, Writes} - -import scala.reflect.ClassTag - - -object WireMockDSL { - val stub = WireMockStub - - def multiline(stub: StubMapping): StubMapping = stub - - def when(verbStub: HTTPVerbStub): WireMockStub = stub.when(verbStub) - - class WireMockStub(mapping: => MappingBuilder) { - def thenReturn[T](value: T)(implicit writes: Writes[T]): StubMapping = thenReturn(writes.writes(value)) - - def thenReturn(jsValue: JsValue): StubMapping = - createStubFor( - aResponse() - .withStatus(Status.OK).withBody(jsValue.toString) - ) - - private def createStubFor(response: ResponseDefinitionBuilder) = { - stubFor(mapping.willReturn(response)) - } - - def thenReturn(status: Int): StubMapping = - createStubFor( - aResponse() - .withStatus(status) - ) - } - - object WireMockStub { - def when(verbStub: HTTPVerbStub): WireMockStub = new WireMockStub(verbStub.mapping) - - def verify(verbStub: HTTPVerbStub): Unit = verbStub match { - case Get(uri) => WiremockHelper.verifyGet(uri) - case req @ Post(uri, _) => WiremockHelper.verifyPost(uri, req.jsonString) - case _ => () - } - } - - object HTTPVerbMapping { - - sealed trait HTTPVerbStub { - val uri: String - - val mapping: MappingBuilder - } - - case class Get(uri: String) extends HTTPVerbStub { - override val mapping = get(urlMatching(uri)) - } - - case class Put(uri: String) extends HTTPVerbStub { - override val mapping = put(urlMatching(uri)) - } - - case class Post[T] private(uri: String, optBody: Option[T])(implicit writes: Writes[T]) extends HTTPVerbStub { - override val mapping = { - val uriMapping = post(urlMatching(uri)) - optBody match { - case Some(body) => uriMapping.withRequestBody(new EqualToPattern(writes.writes(body).toString())) - case None => uriMapping - } - } - - val jsonString = optBody map (writes.writes(_).toString) - } - - object Post { - def apply(uri: String): Post[String] = new Post[String](uri, None) - - def apply[T](uri: String, body: T)(implicit writes: Writes[T]): Post[T] = new Post[T](uri, Some(body)) - } - - } - -} - diff --git a/it/helpers/servicemocks/AuthStub.scala b/it/helpers/servicemocks/AuthStub.scala index 2cb03385..5b557b39 100644 --- a/it/helpers/servicemocks/AuthStub.scala +++ b/it/helpers/servicemocks/AuthStub.scala @@ -16,20 +16,32 @@ package helpers.servicemocks +import com.github.tomakehurst.wiremock.stubbing.StubMapping import helpers.{IntegrationTestConstants, WiremockHelper} -import models.auth.{Authority, UserIds} +import models.auth.UserIds import play.api.http.Status +import play.api.http.Status._ import play.api.libs.json.{JsObject, Json} -object AuthStub { +object AuthStub extends WireMockMethods { val authIDs = "/uri/to/ids" val authority = "/auth/authority" val gatewayID = "12345" val internalID = "internal" val externalID = "external" + val userIDs = UserIds(internalId = internalID, externalId = externalID) - val stubbedAuthResponse: JsObject = { + def stubAuthSuccess(): StubMapping = { + stubAuthoritySuccess() + stubAuthorityUserIDsSuccess() + } + + def stubAuthoritySuccess(): StubMapping = + when(method = GET, uri = authority) + .thenReturn(status = OK, body = successfulAuthResponse) + + def successfulAuthResponse: JsObject = { Json.obj( "uri" -> "/auth/oid/58a2e8c82e00008c005d4699", "userDetailsLink" -> "/uri/to/user-details", @@ -40,7 +52,9 @@ object AuthStub { ) } - val stubbedIDs = UserIds(internalId = internalID, externalId = externalID) + def stubAuthorityUserIDsSuccess(): StubMapping = + when(method = GET, uri = authIDs) + .thenReturn(status = OK, body = userIDs) def stubGetAuthoritySuccess(): Unit = { val authBody = IntegrationTestConstants.Auth.authResponseJson("/auth/oid/58a2e8c82e00008c005d4699", "/uri/to/user-details", "12345", authIDs).toString() diff --git a/it/helpers/servicemocks/AuthenticatorStub.scala b/it/helpers/servicemocks/AuthenticatorStub.scala new file mode 100644 index 00000000..7dc20769 --- /dev/null +++ b/it/helpers/servicemocks/AuthenticatorStub.scala @@ -0,0 +1,27 @@ +/* + * Copyright 2017 HM Revenue & Customs + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package helpers.servicemocks + +import com.github.tomakehurst.wiremock.stubbing.StubMapping +import connectors.AuthenticatorConnector +import play.api.http.Status._ + +object AuthenticatorStub extends WireMockMethods { + def stubRefreshProfileSuccess(): StubMapping = + when(method = POST, uri = AuthenticatorConnector.refreshProfileUri) + .thenReturn(status = NO_CONTENT) +} diff --git a/it/helpers/servicemocks/BusinessDetailsStub.scala b/it/helpers/servicemocks/BusinessDetailsStub.scala index 2265a71d..13acf91a 100644 --- a/it/helpers/servicemocks/BusinessDetailsStub.scala +++ b/it/helpers/servicemocks/BusinessDetailsStub.scala @@ -16,15 +16,22 @@ package helpers.servicemocks +import com.github.tomakehurst.wiremock.stubbing.StubMapping import connectors.BusinessDetailsConnector._ import helpers.IntegrationTestConstants._ import helpers.{IntegrationTestConstants, WiremockHelper} +import play.api.http.Status._ import play.api.libs.json.JsValue -object BusinessDetailsStub { +object BusinessDetailsStub extends WireMockMethods { val registrationResponse: JsValue = IntegrationTestConstants.GetBusinessDetailsResponse.successResponse(testNino, testSafeId, testMtditId) - def verifyGetBusinessDetails(nino: String): Unit = { - WiremockHelper.verifyGet(getBusinessDetailsUri(nino)) + def verifyGetBusinessDetails(): Unit = { + verify(method = GET, uri = getBusinessDetailsUri(testNino)) } + + def stubGetBusinessDetailsSuccess(): StubMapping = when(method = GET, uri = getBusinessDetailsUri(testNino)) + .thenReturn(status = OK, body = registrationResponse) + + } diff --git a/it/helpers/servicemocks/GGAdminStub.scala b/it/helpers/servicemocks/GGAdminStub.scala index 9adac44b..7a749527 100644 --- a/it/helpers/servicemocks/GGAdminStub.scala +++ b/it/helpers/servicemocks/GGAdminStub.scala @@ -16,8 +16,15 @@ package helpers.servicemocks +import com.github.tomakehurst.wiremock.stubbing.StubMapping +import connectors.GGAdminConnector import models.gg.KnownFactsSuccessResponseModel +import play.api.http.Status._ -object GGAdminStub { +object GGAdminStub extends WireMockMethods { val testAddKnownFactsResponse: KnownFactsSuccessResponseModel = KnownFactsSuccessResponseModel(1) + + def stubAddKnownFactsSuccess(): StubMapping = + when(method = POST, uri = GGAdminConnector.addKnownFactsUri) + .thenReturn(status = OK, body = testAddKnownFactsResponse) } diff --git a/it/helpers/servicemocks/GGConnectorStub.scala b/it/helpers/servicemocks/GGConnectorStub.scala new file mode 100644 index 00000000..6b08fb5f --- /dev/null +++ b/it/helpers/servicemocks/GGConnectorStub.scala @@ -0,0 +1,27 @@ +/* + * Copyright 2017 HM Revenue & Customs + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package helpers.servicemocks + +import com.github.tomakehurst.wiremock.stubbing.StubMapping +import connectors.GGConnector +import play.api.http.Status._ + +object GGConnectorStub extends WireMockMethods { + def stubEnrolSuccess(): StubMapping = + when(method = POST, uri = GGConnector.enrolUri) + .thenReturn(status = OK) +} diff --git a/it/helpers/servicemocks/RegistrationStub.scala b/it/helpers/servicemocks/RegistrationStub.scala new file mode 100644 index 00000000..44f06dbc --- /dev/null +++ b/it/helpers/servicemocks/RegistrationStub.scala @@ -0,0 +1,31 @@ +/* + * Copyright 2017 HM Revenue & Customs + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package helpers.servicemocks + +import com.github.tomakehurst.wiremock.stubbing.StubMapping +import connectors.RegistrationConnector +import helpers.IntegrationTestConstants._ +import models.registration.RegistrationSuccessResponseModel +import play.api.http.Status._ + +object RegistrationStub extends WireMockMethods { + val successfulRegistrationResponse: RegistrationSuccessResponseModel = RegistrationSuccessResponseModel(testMtditId) + + def stubNewRegistrationSuccess(): StubMapping = + when(method = POST, uri = RegistrationConnector.newRegistrationUri(testNino), body = registerRequestPayload) + .thenReturn(status = OK, body = successfulRegistrationResponse) +} diff --git a/it/helpers/servicemocks/SubscriptionStub.scala b/it/helpers/servicemocks/SubscriptionStub.scala index a6b3f649..40ce0e67 100644 --- a/it/helpers/servicemocks/SubscriptionStub.scala +++ b/it/helpers/servicemocks/SubscriptionStub.scala @@ -16,12 +16,17 @@ package helpers.servicemocks +import com.github.tomakehurst.wiremock.stubbing.StubMapping +import connectors.SubscriptionConnector +import connectors.SubscriptionConnector._ import models.subscription.IncomeSourceModel import models.subscription.business.BusinessSubscriptionSuccessResponseModel import helpers.IntegrationTestConstants._ import models.subscription.property.PropertySubscriptionResponseModel +import play.api.http.Status._ +import play.api.libs.json.Json -object SubscriptionStub { +object SubscriptionStub extends WireMockMethods { val testBusinessSubscriptionResponse: BusinessSubscriptionSuccessResponseModel = BusinessSubscriptionSuccessResponseModel( testSafeId, @@ -35,4 +40,15 @@ object SubscriptionStub { testMtditId, IncomeSourceModel(testSourceId) ) + + def stubBusinessSubscribeSuccess(): StubMapping = + when(method = POST, uri = SubscriptionConnector.businessSubscribeUri(testNino), body = businessSubscriptionRequestPayload) + .thenReturn(status = OK, body = testBusinessSubscriptionResponse) + + def stubPropertySubscribeSuccess(): StubMapping = + when(method = POST, uri = SubscriptionConnector.propertySubscribeUri(testNino), body = Json.obj()) + .thenReturn(status = OK, body = testPropertySubscriptionResponse) + + def verifyBusinessSubscribe(): Unit = verify(method = POST, uri = businessSubscribeUri(testNino), businessSubscriptionRequestPayload) + def verifyPropertySubscribe(): Unit = verify(method = POST, uri = propertySubscribeUri(testNino), Json.obj()) } diff --git a/it/helpers/servicemocks/WireMockMethods.scala b/it/helpers/servicemocks/WireMockMethods.scala new file mode 100644 index 00000000..e37deae8 --- /dev/null +++ b/it/helpers/servicemocks/WireMockMethods.scala @@ -0,0 +1,108 @@ +/* + * Copyright 2017 HM Revenue & Customs + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package helpers.servicemocks + +import com.github.tomakehurst.wiremock.client.MappingBuilder +import com.github.tomakehurst.wiremock.client.WireMock._ +import com.github.tomakehurst.wiremock.matching.UrlPattern +import com.github.tomakehurst.wiremock.stubbing.StubMapping +import helpers.WiremockHelper +import play.api.libs.json.Writes + +trait WireMockMethods { + def when[T](method: HTTPMethod, uri: String, body: T)(implicit writes: Writes[T]): Mapping = { + when(method, uri, Map.empty, body) + } + + def when(method: HTTPMethod, uri: String, headers: Map[String, String] = Map.empty): Mapping = { + new Mapping(method, uri, headers, None) + } + + def when[T](method: HTTPMethod, uri: String, headers: Map[String, String], body: T)(implicit writes: Writes[T]): Mapping = { + val stringBody = writes.writes(body).toString() + new Mapping(method, uri, headers, Some(stringBody)) + } + + class Mapping (method: HTTPMethod, uri:String, headers: Map[String, String], body: Option[String]) { + private val mapping = { + val uriMapping = method.wireMockMapping(urlMatching(uri)) + + val uriMappingWithHeaders = headers.foldLeft(uriMapping){ + case (m, (key, value)) => m.withHeader(key, equalTo(value) ) + } + + body match { + case Some(extractedBody) => uriMappingWithHeaders.withRequestBody(equalTo(extractedBody)) + case None => uriMappingWithHeaders + } + } + + def thenReturn[T](status: Int, body: T)(implicit writes: Writes[T]): StubMapping = { + val stringBody = writes.writes(body).toString() + thenReturnInternal(status, Map.empty, Some(stringBody)) + } + + def thenReturn[T](status: Int, headers: Map[String, String], body: T)(implicit writes: Writes[T]): StubMapping = { + val stringBody = writes.writes(body).toString() + thenReturnInternal(status, headers, Some(stringBody)) + } + + def thenReturn(status: Int, headers: Map[String, String] = Map.empty): StubMapping = { + thenReturnInternal(status, headers, None) + } + + private def thenReturnInternal(status: Int, headers: Map[String, String], body: Option[String]): StubMapping = { + val response = { + val statusResponse = aResponse().withStatus(status) + val responseWithHeaders = headers.foldLeft(statusResponse){ + case (res, (key, value)) => res.withHeader(key, value) + } + body match { + case Some(extractedBody) => responseWithHeaders.withBody(extractedBody) + case None => responseWithHeaders + } + } + + stubFor(mapping.willReturn(response)) + } + } + + def verify(method: HTTPMethod, uri: String): Unit = verifyInternal(method, uri, None) + def verify[T](method: HTTPMethod, uri: String, body: T)(implicit writes: Writes[T]): Unit = { + val stringBody = writes.writes(body).toString() + verifyInternal(method, uri, Some(stringBody)) + } + + private def verifyInternal(method: HTTPMethod, uri: String, bodyString: Option[String]): Unit = method match { + case GET => WiremockHelper.verifyGet(uri) + case POST => WiremockHelper.verifyPost(uri, bodyString) + case _ => () + } + + sealed trait HTTPMethod { + val wireMockMapping: UrlPattern => MappingBuilder + } + case object GET extends HTTPMethod { + override val wireMockMapping = get _ + } + case object POST extends HTTPMethod { + override val wireMockMapping = post _ + } + case object PUT extends HTTPMethod{ + override val wireMockMapping = put _ + } +}