From 8d3581bff3235d2ebf6c4dca78cb312df6ee2638 Mon Sep 17 00:00:00 2001 From: Narendra Vijayarao Date: Fri, 11 Sep 2020 11:57:31 +0100 Subject: [PATCH] Removed sample endpoint for disclosures (#22) --- app/v1/connectors/SampleConnector.scala | 43 ---- app/v1/controllers/SampleController.scala | 108 --------- .../requestParsers/SampleRequestParser.scala | 32 --- .../validators/SampleValidator.scala | 43 ---- app/v1/hateoas/HateoasLinks.scala | 8 - ...pleAuditDetail.scala => AuditDetail.scala} | 8 +- ...uditResponse.scala => AuditResponse.scala} | 6 +- app/v1/models/hateoas/RelType.scala | 1 - .../models/request/sample/SampleRawData.scala | 22 -- .../request/sample/SampleRequestBody.scala | 27 --- .../request/sample/SampleRequestData.scala | 22 -- .../response/des/DesSampleResponse.scala | 25 --- .../response/sample/SampleResponse.scala | 38 ---- app/v1/services/EnrolmentsAuthService.scala | 3 + app/v1/services/SampleService.scala | 55 ----- conf/v1.routes | 3 +- it/v1/endpoints/AuthISpec.scala | 48 ++-- it/v1/endpoints/SampleControllerISpec.scala | 205 ----------------- .../public/api/conf/1.0/sample_post.raml | 36 --- test/v1/connectors/SampleConnectorSpec.scala | 62 ------ .../v1/controllers/SampleControllerSpec.scala | 206 ------------------ .../SampleRequestParserSpec.scala | 77 ------- .../validators/SampleValidatorSpec.scala | 105 --------- .../connectors/MockSampleConnector.scala | 41 ---- .../MockSampleRequestParser.scala | 35 --- .../v1/mocks/services/MockSampleService.scala | 44 ---- .../validators/MockSampleValidator.scala | 37 ---- ...DetailSpec.scala => AuditDetailSpec.scala} | 10 +- .../sample/SampleRequestBodySpec.scala | 55 ----- .../response/des/DesSampleResponseSpec.scala | 34 --- .../response/sample/SampleResponseSpec.scala | 33 --- test/v1/services/SampleServiceSpec.scala | 85 -------- 32 files changed, 34 insertions(+), 1523 deletions(-) delete mode 100644 app/v1/connectors/SampleConnector.scala delete mode 100644 app/v1/controllers/SampleController.scala delete mode 100644 app/v1/controllers/requestParsers/SampleRequestParser.scala delete mode 100644 app/v1/controllers/requestParsers/validators/SampleValidator.scala rename app/v1/models/audit/{SampleAuditDetail.scala => AuditDetail.scala} (83%) rename app/v1/models/audit/{SampleAuditResponse.scala => AuditResponse.scala} (77%) delete mode 100644 app/v1/models/request/sample/SampleRawData.scala delete mode 100644 app/v1/models/request/sample/SampleRequestBody.scala delete mode 100644 app/v1/models/request/sample/SampleRequestData.scala delete mode 100644 app/v1/models/response/des/DesSampleResponse.scala delete mode 100644 app/v1/models/response/sample/SampleResponse.scala delete mode 100644 app/v1/services/SampleService.scala delete mode 100644 it/v1/endpoints/SampleControllerISpec.scala delete mode 100644 resources/public/api/conf/1.0/sample_post.raml delete mode 100644 test/v1/connectors/SampleConnectorSpec.scala delete mode 100644 test/v1/controllers/SampleControllerSpec.scala delete mode 100644 test/v1/controllers/requestParsers/SampleRequestParserSpec.scala delete mode 100644 test/v1/controllers/requestParsers/validators/SampleValidatorSpec.scala delete mode 100644 test/v1/mocks/connectors/MockSampleConnector.scala delete mode 100644 test/v1/mocks/requestParsers/MockSampleRequestParser.scala delete mode 100644 test/v1/mocks/services/MockSampleService.scala delete mode 100644 test/v1/mocks/validators/MockSampleValidator.scala rename test/v1/models/audit/{SampleAuditDetailSpec.scala => AuditDetailSpec.scala} (82%) delete mode 100644 test/v1/models/request/sample/SampleRequestBodySpec.scala delete mode 100644 test/v1/models/response/des/DesSampleResponseSpec.scala delete mode 100644 test/v1/models/response/sample/SampleResponseSpec.scala delete mode 100644 test/v1/services/SampleServiceSpec.scala diff --git a/app/v1/connectors/SampleConnector.scala b/app/v1/connectors/SampleConnector.scala deleted file mode 100644 index 6307bbd..0000000 --- a/app/v1/connectors/SampleConnector.scala +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2020 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 v1.connectors - -import config.AppConfig -import javax.inject.{Inject, Singleton} -import uk.gov.hmrc.http.HeaderCarrier -import uk.gov.hmrc.http.HttpClient -import v1.connectors.httpparsers.StandardDesHttpParser._ -import v1.models.request.sample.SampleRequestData -import v1.models.response.EmptyJsonBody -import v1.models.response.des.DesSampleResponse - -import scala.concurrent.{ExecutionContext, Future} - -@Singleton -class SampleConnector @Inject()(val http: HttpClient, - val appConfig: AppConfig) extends BaseDesConnector { - - def doConnectorThing(request: SampleRequestData)( - implicit hc: HeaderCarrier, - ec: ExecutionContext): Future[DesOutcome[DesSampleResponse]] = { - - post( - body = EmptyJsonBody, - DesUri[DesSampleResponse](s"income-tax/nino/${request.nino}/taxYear/${request.desTaxYear}/someService") - ) - } -} diff --git a/app/v1/controllers/SampleController.scala b/app/v1/controllers/SampleController.scala deleted file mode 100644 index 5935ca6..0000000 --- a/app/v1/controllers/SampleController.scala +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2020 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 v1.controllers - -import cats.data.EitherT -import cats.implicits._ -import javax.inject.{Inject, Singleton} -import play.api.http.MimeTypes -import play.api.libs.json.{JsValue, Json} -import play.api.mvc.{Action, AnyContentAsJson, ControllerComponents} -import uk.gov.hmrc.http.HeaderCarrier -import uk.gov.hmrc.play.audit.http.connector.AuditResult -import utils.Logging -import v1.controllers.requestParsers.SampleRequestParser -import v1.hateoas.HateoasFactory -import v1.models.audit.{AuditEvent, SampleAuditDetail, SampleAuditResponse} -import v1.models.auth.UserDetails -import v1.models.errors._ -import v1.models.request.sample.SampleRawData -import v1.models.response.sample.SampleHateoasData -import v1.services.{SampleService, _} - -import scala.concurrent.{ExecutionContext, Future} - -@Singleton -class SampleController @Inject()(val authService: EnrolmentsAuthService, - val lookupService: MtdIdLookupService, - requestDataParser: SampleRequestParser, - sampleService: SampleService, - hateoasFactory: HateoasFactory, - auditService: AuditService, - cc: ControllerComponents)(implicit ec: ExecutionContext) - extends AuthorisedController(cc) with BaseController with Logging { - - implicit val endpointLogContext: EndpointLogContext = - EndpointLogContext(controllerName = "SampleController", endpointName = "sample-endpoint") - - def handleRequest(nino: String, taxYear: String): Action[JsValue] = - authorisedAction(nino).async(parse.json) { implicit request => - val rawData = SampleRawData(nino, taxYear, AnyContentAsJson(request.body)) - val result = - for { - parsedRequest <- EitherT.fromEither[Future](requestDataParser.parseRequest(rawData)) - serviceResponse <- EitherT(sampleService.doServiceThing(parsedRequest)) - vendorResponse <- EitherT.fromEither[Future]( - hateoasFactory.wrap(serviceResponse.responseData, SampleHateoasData(nino)).asRight[ErrorWrapper]) - } yield { - logger.info( - s"[${endpointLogContext.controllerName}][${endpointLogContext.endpointName}] - " + - s"Success response received with CorrelationId: ${serviceResponse.correlationId}") - auditSubmission(createAuditDetails(rawData, CREATED, serviceResponse.correlationId, request.userDetails)) - - Created(Json.toJson(vendorResponse)) - .withApiHeaders(serviceResponse.correlationId) - .as(MimeTypes.JSON) - } - - result.leftMap { errorWrapper => - val correlationId = getCorrelationId(errorWrapper) - val result = errorResult(errorWrapper).withApiHeaders(correlationId) - auditSubmission(createAuditDetails(rawData, result.header.status, correlationId, request.userDetails, Some(errorWrapper))) - result - }.merge - } - - private def errorResult(errorWrapper: ErrorWrapper) = { - (errorWrapper.error: @unchecked) match { - case MtdErrorWithCustomMessage(RuleIncorrectOrEmptyBodyError.code) | BadRequestError | NinoFormatError | TaxYearFormatError | - RuleTaxYearRangeInvalidError => - BadRequest(Json.toJson(errorWrapper)) - case NotFoundError => NotFound(Json.toJson(errorWrapper)) - case DownstreamError => InternalServerError(Json.toJson(errorWrapper)) - } - } - - private def createAuditDetails(rawData: SampleRawData, - statusCode: Int, - correlationId: String, - userDetails: UserDetails, - errorWrapper: Option[ErrorWrapper] = None): SampleAuditDetail = { - val response = errorWrapper - .map { wrapper => - SampleAuditResponse(statusCode, Some(wrapper.auditErrors)) - } - .getOrElse(SampleAuditResponse(statusCode, None)) - - SampleAuditDetail(userDetails.userType, userDetails.agentReferenceNumber, rawData.nino, rawData.taxYear, correlationId, response) - } - - private def auditSubmission(details: SampleAuditDetail)(implicit hc: HeaderCarrier, ec: ExecutionContext): Future[AuditResult] = { - val event = AuditEvent("sampleAuditType", "sample-transaction-type", details) - auditService.auditEvent(event) - } -} \ No newline at end of file diff --git a/app/v1/controllers/requestParsers/SampleRequestParser.scala b/app/v1/controllers/requestParsers/SampleRequestParser.scala deleted file mode 100644 index 2f0f0d9..0000000 --- a/app/v1/controllers/requestParsers/SampleRequestParser.scala +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright 2020 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 v1.controllers.requestParsers - -import javax.inject.Inject -import uk.gov.hmrc.domain.Nino -import v1.controllers.requestParsers.validators.SampleValidator -import v1.models.domain.DesTaxYear -import v1.models.request.sample -import v1.models.request.sample.{SampleRawData, SampleRequestBody, SampleRequestData} - -class SampleRequestParser @Inject()(val validator: SampleValidator) - extends RequestParser[SampleRawData, SampleRequestData] { - - override protected def requestFor(data: SampleRawData): SampleRequestData = - sample.SampleRequestData(Nino(data.nino), DesTaxYear.fromMtd(data.taxYear), data.body.json.as[SampleRequestBody]) - -} \ No newline at end of file diff --git a/app/v1/controllers/requestParsers/validators/SampleValidator.scala b/app/v1/controllers/requestParsers/validators/SampleValidator.scala deleted file mode 100644 index 358ca86..0000000 --- a/app/v1/controllers/requestParsers/validators/SampleValidator.scala +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2020 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 v1.controllers.requestParsers.validators - -import v1.controllers.requestParsers.validators.validations._ -import v1.models.errors.MtdError -import v1.models.request.sample.{SampleRawData, SampleRequestBody} - -class SampleValidator extends Validator[SampleRawData] { - - private val validationSet = List(parameterFormatValidation, bodyFormatValidator) - - private def parameterFormatValidation: SampleRawData => List[List[MtdError]] = (data: SampleRawData) => { - List( - NinoValidation.validate(data.nino), - TaxYearValidation.validate(data.taxYear) - ) - } - - private def bodyFormatValidator: SampleRawData => List[List[MtdError]] = { data => - List( - JsonFormatValidation.validate[SampleRequestBody](data.body.json) - ) - } - - override def validate(data: SampleRawData): List[MtdError] = { - run(validationSet, data).distinct - } -} \ No newline at end of file diff --git a/app/v1/hateoas/HateoasLinks.scala b/app/v1/hateoas/HateoasLinks.scala index 79c4783..680eaf9 100644 --- a/app/v1/hateoas/HateoasLinks.scala +++ b/app/v1/hateoas/HateoasLinks.scala @@ -24,18 +24,10 @@ import v1.models.hateoas.RelType._ trait HateoasLinks { //Domain URIs - - private def sampleUri(appConfig: AppConfig, nino: String): String = - s"/${appConfig.apiGatewayContext}/$nino/sample-endpoint" - private def disclosuresUri(appConfig: AppConfig, nino: String, taxYear: String) = s"/${appConfig.apiGatewayContext}/$nino/$taxYear" //API resource links - - def sampleLink(appConfig: AppConfig, nino: String): Link = - Link(href = sampleUri(appConfig, nino), method = GET, rel = SAMPLE_ENDPOINT_REL) - def amendDisclosures(appConfig: AppConfig, nino: String, taxYear: String): Link = Link( href = disclosuresUri(appConfig, nino, taxYear), diff --git a/app/v1/models/audit/SampleAuditDetail.scala b/app/v1/models/audit/AuditDetail.scala similarity index 83% rename from app/v1/models/audit/SampleAuditDetail.scala rename to app/v1/models/audit/AuditDetail.scala index 94ecef8..fb6b35b 100644 --- a/app/v1/models/audit/SampleAuditDetail.scala +++ b/app/v1/models/audit/AuditDetail.scala @@ -18,16 +18,16 @@ package v1.models.audit import play.api.libs.json.{Json, OWrites} -case class SampleAuditDetail( +case class AuditDetail( userType: String, agentReferenceNumber: Option[String], nino: String, taxYear: String, `X-CorrelationId`: String, - response: SampleAuditResponse + response: AuditResponse ) -object SampleAuditDetail { - implicit val writes: OWrites[SampleAuditDetail] = Json.writes[SampleAuditDetail] +object AuditDetail { + implicit val writes: OWrites[AuditDetail] = Json.writes[AuditDetail] } diff --git a/app/v1/models/audit/SampleAuditResponse.scala b/app/v1/models/audit/AuditResponse.scala similarity index 77% rename from app/v1/models/audit/SampleAuditResponse.scala rename to app/v1/models/audit/AuditResponse.scala index a1f1181..087657d 100644 --- a/app/v1/models/audit/SampleAuditResponse.scala +++ b/app/v1/models/audit/AuditResponse.scala @@ -18,8 +18,8 @@ package v1.models.audit import play.api.libs.json.{Json, OWrites} -case class SampleAuditResponse(httpStatus: Int, errors: Option[Seq[AuditError]]) +case class AuditResponse(httpStatus: Int, errors: Option[Seq[AuditError]]) -object SampleAuditResponse { - implicit val writes: OWrites[SampleAuditResponse] = Json.writes[SampleAuditResponse] +object AuditResponse { + implicit val writes: OWrites[AuditResponse] = Json.writes[AuditResponse] } diff --git a/app/v1/models/hateoas/RelType.scala b/app/v1/models/hateoas/RelType.scala index 5fa0ff4..8980727 100644 --- a/app/v1/models/hateoas/RelType.scala +++ b/app/v1/models/hateoas/RelType.scala @@ -17,7 +17,6 @@ package v1.models.hateoas object RelType { - val SAMPLE_ENDPOINT_REL = "sample-rel" val AMEND_DISCLOSURES = "amend-disclosures" val DELETE_DISCLOSURES = "delete-disclosures" diff --git a/app/v1/models/request/sample/SampleRawData.scala b/app/v1/models/request/sample/SampleRawData.scala deleted file mode 100644 index 29b1551..0000000 --- a/app/v1/models/request/sample/SampleRawData.scala +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright 2020 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 v1.models.request.sample - -import play.api.mvc.AnyContentAsJson -import v1.models.request.RawData - -case class SampleRawData(nino: String, taxYear: String, body: AnyContentAsJson) extends RawData diff --git a/app/v1/models/request/sample/SampleRequestBody.scala b/app/v1/models/request/sample/SampleRequestBody.scala deleted file mode 100644 index 5e6b270..0000000 --- a/app/v1/models/request/sample/SampleRequestBody.scala +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2020 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 v1.models.request.sample - -import play.api.libs.json.{Json, OWrites, Reads} - -case class SampleRequestBody(data: String) - -object SampleRequestBody { - implicit val reads: Reads[SampleRequestBody] = Json.reads[SampleRequestBody] - - implicit val writes: OWrites[SampleRequestBody] = Json.writes[SampleRequestBody] -} \ No newline at end of file diff --git a/app/v1/models/request/sample/SampleRequestData.scala b/app/v1/models/request/sample/SampleRequestData.scala deleted file mode 100644 index 053b1e6..0000000 --- a/app/v1/models/request/sample/SampleRequestData.scala +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright 2020 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 v1.models.request.sample - -import uk.gov.hmrc.domain.Nino -import v1.models.domain.DesTaxYear - -case class SampleRequestData(nino: Nino, desTaxYear: DesTaxYear, body: SampleRequestBody) diff --git a/app/v1/models/response/des/DesSampleResponse.scala b/app/v1/models/response/des/DesSampleResponse.scala deleted file mode 100644 index c70f480..0000000 --- a/app/v1/models/response/des/DesSampleResponse.scala +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright 2020 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 v1.models.response.des - -import play.api.libs.json.{Json, Reads} - -case class DesSampleResponse(responseData: String) - -object DesSampleResponse { - implicit val reads: Reads[DesSampleResponse] = Json.reads[DesSampleResponse] -} diff --git a/app/v1/models/response/sample/SampleResponse.scala b/app/v1/models/response/sample/SampleResponse.scala deleted file mode 100644 index ccca94b..0000000 --- a/app/v1/models/response/sample/SampleResponse.scala +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright 2020 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 v1.models.response.sample - -import config.AppConfig -import play.api.libs.json.{Json, OWrites} -import v1.hateoas.{HateoasLinks, HateoasLinksFactory} -import v1.models.hateoas.{HateoasData, Link} - -case class SampleResponse(responseData: String) - -object SampleResponse extends HateoasLinks { - implicit val writes: OWrites[SampleResponse] = Json.writes[SampleResponse] - - implicit object AmendLinksFactory extends HateoasLinksFactory[SampleResponse, SampleHateoasData] { - override def links(appConfig: AppConfig, data: SampleHateoasData): Seq[Link] = { - import data._ - Seq(sampleLink(appConfig, nino)) - } - } - -} - -case class SampleHateoasData(nino: String) extends HateoasData diff --git a/app/v1/services/EnrolmentsAuthService.scala b/app/v1/services/EnrolmentsAuthService.scala index a07ef4e..cff202f 100644 --- a/app/v1/services/EnrolmentsAuthService.scala +++ b/app/v1/services/EnrolmentsAuthService.scala @@ -62,6 +62,9 @@ class EnrolmentsAuthService @Inject()(val connector: AuthConnector) { logger.warn(s"[EnrolmentsAuthService][authorised] No AgentReferenceNumber defined on agent enrolment.") Left(DownstreamError) } + case _ ~ _ => + logger.warn(s"[EnrolmentsAuthService][authorised] Invalid AffinityGroup.") + Future.successful(Left(UnauthorisedError)) } recoverWith { case _: MissingBearerToken => Future.successful(Left(UnauthorisedError)) case _: AuthorisationException => Future.successful(Left(UnauthorisedError)) diff --git a/app/v1/services/SampleService.scala b/app/v1/services/SampleService.scala deleted file mode 100644 index 4ac19f5..0000000 --- a/app/v1/services/SampleService.scala +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2020 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 v1.services - -import cats.data.EitherT -import cats.implicits._ -import javax.inject.{Inject, Singleton} -import uk.gov.hmrc.http.HeaderCarrier -import utils.Logging -import v1.connectors.SampleConnector -import v1.controllers.EndpointLogContext -import v1.models.errors.{DownstreamError, ErrorWrapper, NotFoundError} -import v1.models.outcomes.ResponseWrapper -import v1.models.request.sample.SampleRequestData -import v1.models.response.sample.SampleResponse -import v1.support.DesResponseMappingSupport - -import scala.concurrent.{ExecutionContext, Future} - -@Singleton -class SampleService @Inject()(sampleConnector: SampleConnector) extends DesResponseMappingSupport with Logging { - - def doServiceThing(request: SampleRequestData)( - implicit hc: HeaderCarrier, - ec: ExecutionContext, - logContext: EndpointLogContext): Future[Either[ErrorWrapper, ResponseWrapper[SampleResponse]]] = { - - val result = for { - desResponseWrapper <- EitherT(sampleConnector.doConnectorThing(request)).leftMap(mapDesErrors(desErrorMap)) - } yield desResponseWrapper.map(des => SampleResponse(des.responseData)) // *If* need to convert to Mtd - - result.value - } - - private def desErrorMap = - Map( - "NOT_FOUND" -> NotFoundError, - "SERVER_ERROR" -> DownstreamError, - "SERVICE_UNAVAILABLE" -> DownstreamError - ) -} diff --git a/conf/v1.routes b/conf/v1.routes index 88e0bb7..42eff14 100644 --- a/conf/v1.routes +++ b/conf/v1.routes @@ -1,4 +1,3 @@ -POST /:nino/:taxYear/sample-endpoint v1.controllers.SampleController.handleRequest(nino: String, taxYear: String) PUT /:nino/:taxYear v1.controllers.AmendDisclosuresController.amendDisclosures(nino: String, taxYear: String) DELETE /:nino/:taxYear v1.controllers.DeleteDisclosuresController.deleteDisclosures(nino: String, taxYear: String) -GET /:nino/:taxYear v1.controllers.RetrieveDisclosuresController.retrieveDisclosures(nino: String, taxYear: String) \ No newline at end of file +GET /:nino/:taxYear v1.controllers.RetrieveDisclosuresController.retrieveDisclosures(nino: String, taxYear: String) diff --git a/it/v1/endpoints/AuthISpec.scala b/it/v1/endpoints/AuthISpec.scala index d03efe8..e9a96b6 100644 --- a/it/v1/endpoints/AuthISpec.scala +++ b/it/v1/endpoints/AuthISpec.scala @@ -19,7 +19,7 @@ package v1.endpoints import com.github.tomakehurst.wiremock.stubbing.StubMapping import play.api.http.HeaderNames.ACCEPT import play.api.http.Status -import play.api.libs.json.{JsValue, Json} +import play.api.http.Status.NO_CONTENT import play.api.libs.ws.{WSRequest, WSResponse} import support.IntegrationBaseSpec import v1.models.domain.DesTaxYear @@ -28,37 +28,25 @@ import v1.stubs.{AuditStub, AuthStub, DesStub, MtdIdLookupStub} class AuthISpec extends IntegrationBaseSpec { private trait Test { - val nino = "AA123456A" - val taxYear = "2017-18" - val data = "someData" - val correlationId = "X-123" - - val requestJson: String = - s""" - |{ - |"data": "$data" - |} - """.stripMargin + + val nino: String = "AA123456A" + val taxYear: String = "2021-22" + val correlationId: String = "X-123" + + def uri: String = s"/$nino/$taxYear" + + def desUri: String = s"/disc-placeholder/disclosures/$nino/${DesTaxYear.fromMtd(taxYear)}" def setupStubs(): StubMapping def request(): WSRequest = { setupStubs() - buildRequest(s"/$nino/$taxYear/sample-endpoint") + buildRequest(uri) .withHttpHeaders((ACCEPT, "application/vnd.hmrc.1.0+json")) } - - def desUri: String = s"/income-tax/nino/$nino/taxYear/${DesTaxYear.fromMtd(taxYear)}/someService" - - val desResponse: JsValue = Json.parse( - """ - | { - | "responseData" : "someResponse" - | } - """.stripMargin) } - "Calling the sample endpoint" when { + "Calling the 'delete disclosures' endpoint" when { "the NINO cannot be converted to a MTD ID" should { @@ -71,23 +59,23 @@ class AuthISpec extends IntegrationBaseSpec { MtdIdLookupStub.internalServerError(nino) } - val response: WSResponse = await(request().post(Json.parse(requestJson))) + val response: WSResponse = await(request().delete) response.status shouldBe Status.INTERNAL_SERVER_ERROR } } "an MTD ID is successfully retrieve from the NINO and the user is authorised" should { - "return 201" in new Test { + "return 204" in new Test { override def setupStubs(): StubMapping = { AuditStub.audit() AuthStub.authorised() MtdIdLookupStub.ninoFound(nino) - DesStub.onSuccess(DesStub.POST, desUri, Status.OK, desResponse) + DesStub.onSuccess(DesStub.DELETE, desUri, NO_CONTENT) } - val response: WSResponse = await(request().post(Json.parse(requestJson))) - response.status shouldBe Status.CREATED + val response: WSResponse = await(request().delete) + response.status shouldBe Status.NO_CONTENT } } @@ -102,7 +90,7 @@ class AuthISpec extends IntegrationBaseSpec { AuthStub.unauthorisedNotLoggedIn() } - val response: WSResponse = await(request().post(Json.parse(requestJson))) + val response: WSResponse = await(request().delete) response.status shouldBe Status.FORBIDDEN } } @@ -118,7 +106,7 @@ class AuthISpec extends IntegrationBaseSpec { AuthStub.unauthorisedOther() } - val response: WSResponse = await(request().post(Json.parse(requestJson))) + val response: WSResponse = await(request().delete) response.status shouldBe Status.FORBIDDEN } } diff --git a/it/v1/endpoints/SampleControllerISpec.scala b/it/v1/endpoints/SampleControllerISpec.scala deleted file mode 100644 index 70639ea..0000000 --- a/it/v1/endpoints/SampleControllerISpec.scala +++ /dev/null @@ -1,205 +0,0 @@ -/* - * Copyright 2020 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 WARRANTIED OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package v1.endpoints - -import com.github.tomakehurst.wiremock.stubbing.StubMapping -import play.api.http.HeaderNames.ACCEPT -import play.api.http.Status -import play.api.libs.json.{JsValue, Json} -import play.api.libs.ws.{WSRequest, WSResponse} -import support.IntegrationBaseSpec -import v1.models.domain.DesTaxYear -import v1.models.errors._ -import v1.stubs.{AuditStub, AuthStub, DesStub, MtdIdLookupStub} - -class SampleControllerISpec extends IntegrationBaseSpec { - - private trait Test { - - val nino = "AA123456A" - val taxYear = "2017-18" - val correlationId = "X-123" - - val requestJson: JsValue = Json.parse( - s""" - |{ - |"data": "someData" - |} - """.stripMargin) - - def setupStubs(): StubMapping - - def uri: String - - def request(): WSRequest = { - setupStubs() - buildRequest(uri) - .withHttpHeaders((ACCEPT, "application/vnd.hmrc.1.0+json")) - } - - val responseBody: JsValue = Json.parse(s""" - |{ - | "responseData" : "someResponse", - | "links": [ - | { - | "href": "/individuals/disclosures/$nino/sample-endpoint", - | "method": "GET", - | "rel": "sample-rel" - | } - | ] - |} - |""".stripMargin) - - def errorBody(code: String): String = - s""" - | { - | "code": "$code", - | "reason": "des message" - | } - """.stripMargin - } - - "Calling the sample endpoint" should { - - trait SampleTest extends Test { - def uri: String = s"/$nino/$taxYear/sample-endpoint" - - def desUri: String = s"/income-tax/nino/$nino/taxYear/${DesTaxYear.fromMtd(taxYear)}/someService" - - val desResponse: JsValue = Json.parse( - """ - | { - | "responseData" : "someResponse" - | } - """.stripMargin) - } - - "return a 201 status code" when { - - "any valid request is made" in new SampleTest { - - override def setupStubs(): StubMapping = { - AuditStub.audit() - AuthStub.authorised() - MtdIdLookupStub.ninoFound(nino) - DesStub.onSuccess(DesStub.POST, desUri, Status.OK, desResponse) - } - - val response: WSResponse = await(request().post(requestJson)) - response.status shouldBe Status.CREATED - response.json shouldBe responseBody - response.header("Content-Type") shouldBe Some("application/json") - } - } - - "return bad request error" when { - "badly formed json body" in new SampleTest { - private val json = - s""" - |{ - | badJson - |} - """.stripMargin - - override def setupStubs(): StubMapping = { - AuditStub.audit() - AuthStub.authorised() - MtdIdLookupStub.ninoFound(nino) - } - - val response: WSResponse = await(request().addHttpHeaders(("Content-Type", "application/json")).post(json)) - response.status shouldBe Status.BAD_REQUEST - response.json shouldBe Json.toJson(BadRequestError) - } - } - - "return error according to spec" when { - - val validRequestBodyJson: JsValue = Json.parse( - """ - |{ - |"data": "someData" - |} - """.stripMargin - ) - - val nonsenseRequestBody: JsValue = Json.parse( - """ - |{ - | "field": "value" - |} - """.stripMargin - ) - - "validation error" when { - def validationErrorTest(requestNino: String, requestTaxYear: String, requestBody: JsValue, expectedStatus: Int, expectedBody: MtdError): Unit = { - s"validation fails with ${expectedBody.code} error" in new SampleTest { - - override val nino: String = requestNino - override val taxYear: String = requestTaxYear - override val requestJson: JsValue = requestBody - - override def setupStubs(): StubMapping = { - AuditStub.audit() - AuthStub.authorised() - MtdIdLookupStub.ninoFound(nino) - } - - val response: WSResponse = await(request().post(requestJson)) - response.status shouldBe expectedStatus - response.json shouldBe Json.toJson(expectedBody) - } - } - - val input = Seq( - ("AA1123A", "2017-18", validRequestBodyJson,Status.BAD_REQUEST, NinoFormatError), - ("AA123456A", "20177", validRequestBodyJson, Status.BAD_REQUEST, TaxYearFormatError), - ("AA123456A", "2015-17", validRequestBodyJson, Status.BAD_REQUEST, RuleTaxYearRangeInvalidError), - ("AA123456A", "2017-18", nonsenseRequestBody, Status.BAD_REQUEST, RuleIncorrectOrEmptyBodyError.copy(paths = Some(Seq("/data"))))) - - - input.foreach(args => (validationErrorTest _).tupled(args)) - } - - "des service error" when { - def serviceErrorTest(desStatus: Int, desCode: String, expectedStatus: Int, expectedBody: MtdError): Unit = { - s"des returns an $desCode error and status $desStatus" in new SampleTest { - - override def setupStubs(): StubMapping = { - AuditStub.audit() - AuthStub.authorised() - MtdIdLookupStub.ninoFound(nino) - DesStub.onError(DesStub.POST, desUri, desStatus, errorBody(desCode)) - } - - val response: WSResponse = await(request().post(requestJson)) - response.status shouldBe expectedStatus - response.json shouldBe Json.toJson(expectedBody) - } - } - - val input = Seq( - (Status.BAD_REQUEST, "INVALID_REQUEST", Status.INTERNAL_SERVER_ERROR, DownstreamError), - (Status.SERVICE_UNAVAILABLE, "SERVICE_UNAVAILABLE", Status.INTERNAL_SERVER_ERROR, DownstreamError), - (Status.INTERNAL_SERVER_ERROR, "SERVER_ERROR", Status.INTERNAL_SERVER_ERROR, DownstreamError), - (Status.BAD_REQUEST, "NOT_FOUND", Status.NOT_FOUND, NotFoundError)) - - input.foreach(args => (serviceErrorTest _).tupled(args)) - } - } - } -} \ No newline at end of file diff --git a/resources/public/api/conf/1.0/sample_post.raml b/resources/public/api/conf/1.0/sample_post.raml deleted file mode 100644 index 14946e8..0000000 --- a/resources/public/api/conf/1.0/sample_post.raml +++ /dev/null @@ -1,36 +0,0 @@ -is: - - headers.acceptJson - - headers.contentTypeJson - - headers.testScenarioHeader - - errors.formatNino - - errors.formatTaxYear - - errors.clientOrAgentNotAuthorised - - errors.notFound -displayName: Sample endpoint [test only] -description: This endpoint allows a user to see an example endpoint. -(annotations.sandboxData): !include scenarios/common.md -(annotations.scope): "write:self-assessment" -securedBy: [ sec.oauth_2_0: { scopes: [ "write:self-assessment" ] } ] -body: - application/json: - type: !include schemas/sample_request.json - examples: - example-1: - description: sample request body - value: !include examples/request_1.json -responses: - 201: - body: - application/json: - type: !include schemas/sample_response.json - examples: - example-1: - description: Sample example 1 - value: !include examples/example_1.json - example-2: - description: Sample example 2 - value: !include examples/example_2.json - headers: - X-CorrelationId: - example: c75f40a6-a3df-4429-a697-471eeec46435 - description: Unique ID for operation tracking
String, 36 characters. \ No newline at end of file diff --git a/test/v1/connectors/SampleConnectorSpec.scala b/test/v1/connectors/SampleConnectorSpec.scala deleted file mode 100644 index a67afb4..0000000 --- a/test/v1/connectors/SampleConnectorSpec.scala +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2020 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 v1.connectors - -import mocks.MockAppConfig -import uk.gov.hmrc.domain.Nino -import v1.mocks.MockHttpClient -import v1.models.domain.DesTaxYear -import v1.models.response.EmptyJsonBody -import v1.models.outcomes.ResponseWrapper -import v1.models.request.sample.{SampleRequestBody, SampleRequestData} -import v1.models.response.des.DesSampleResponse - -import scala.concurrent.Future - -class SampleConnectorSpec extends ConnectorSpec { - - val taxYear = DesTaxYear("2018") - val nino = Nino("AA123456A") - val calcId = "041f7e4d-87b9-4d4a-a296-3cfbdf92f7e2" - - class Test extends MockHttpClient with MockAppConfig { - val connector: SampleConnector = new SampleConnector(http = mockHttpClient, appConfig = mockAppConfig) - - val desRequestHeaders: Seq[(String, String)] = Seq("Environment" -> "des-environment", "Authorization" -> s"Bearer des-token") - MockedAppConfig.desBaseUrl returns baseUrl - MockedAppConfig.desToken returns "des-token" - MockedAppConfig.desEnvironment returns "des-environment" - } - - "doService" must { - val request = SampleRequestData(nino, taxYear, SampleRequestBody("someData")) - - "post an empty body and return the result" in new Test { - val outcome = Right(ResponseWrapper(correlationId, DesSampleResponse(calcId))) - - MockedHttpClient - .post( - url = s"$baseUrl/income-tax/nino/${nino.nino}/taxYear/${taxYear.value}/someService", - body = EmptyJsonBody, - requiredHeaders ="Environment" -> "des-environment", "Authorization" -> s"Bearer des-token" - ) - .returns(Future.successful(outcome)) - - await(connector.doConnectorThing(request)) shouldBe outcome - } - } -} diff --git a/test/v1/controllers/SampleControllerSpec.scala b/test/v1/controllers/SampleControllerSpec.scala deleted file mode 100644 index c054285..0000000 --- a/test/v1/controllers/SampleControllerSpec.scala +++ /dev/null @@ -1,206 +0,0 @@ -/* - * Copyright 2020 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 v1.controllers - -import play.api.libs.json.Json -import play.api.mvc.{AnyContentAsJson, Result} -import uk.gov.hmrc.domain.Nino -import uk.gov.hmrc.http.HeaderCarrier -import v1.mocks.hateoas.MockHateoasFactory -import v1.mocks.requestParsers.MockSampleRequestParser -import v1.mocks.services.{MockAuditService, MockEnrolmentsAuthService, MockMtdIdLookupService, MockSampleService} -import v1.models.audit.{AuditError, AuditEvent, SampleAuditDetail, SampleAuditResponse} -import v1.models.domain.DesTaxYear -import v1.models.errors._ -import v1.models.hateoas.Method.GET -import v1.models.hateoas.{HateoasWrapper, Link} -import v1.models.outcomes.ResponseWrapper -import v1.models.request.sample -import v1.models.request.sample.{SampleRequestBody, SampleRequestData} -import v1.models.response.sample.{SampleHateoasData, SampleResponse} - -import scala.concurrent.ExecutionContext.Implicits.global -import scala.concurrent.Future - -class SampleControllerSpec - extends ControllerBaseSpec - with MockEnrolmentsAuthService - with MockMtdIdLookupService - with MockSampleService - with MockSampleRequestParser - with MockHateoasFactory - with MockAuditService { - - trait Test { - val hc = HeaderCarrier() - - val controller = new SampleController( - authService = mockEnrolmentsAuthService, - lookupService = mockMtdIdLookupService, - requestDataParser = mockRequestDataParser, - sampleService = mockSampleService, - hateoasFactory = mockHateoasFactory, - auditService = mockAuditService, - cc = cc - ) - - MockedMtdIdLookupService.lookup(nino).returns(Future.successful(Right("test-mtd-id"))) - MockedEnrolmentsAuthService.authoriseUser() - } - - private val nino = "AA123456A" - private val taxYear = "2017-18" - private val correlationId = "X-123" - - private val requestBodyJson = Json.parse("""{ - | "data" : "someData" - |} - """.stripMargin) - - private val responseBody = Json.parse("""{ - | "responseData" : "result", - | "links": [ - | { - | "href": "/foo/bar", - | "method": "GET", - | "rel": "test-relationship" - | } - | ] - |} - """.stripMargin) - - val response = SampleResponse("result") - - private val requestBody = SampleRequestBody("someData") - - private val rawData = sample.SampleRawData(nino, taxYear, AnyContentAsJson(requestBodyJson)) - private val requestData = SampleRequestData(Nino(nino), DesTaxYear.fromMtd(taxYear), requestBody) - val testHateoasLink = Link(href = "/foo/bar", method = GET, rel = "test-relationship") - - "handleRequest" should { - "return CREATED" when { - "happy path" in new Test { - - MockSampleRequestDataParser - .parse(rawData) - .returns(Right(requestData)) - - MockSampleService - .doServiceThing(requestData) - .returns(Future.successful(Right(ResponseWrapper(correlationId, SampleResponse("result"))))) - - MockHateoasFactory.wrap(response, SampleHateoasData(nino)) - .returns(HateoasWrapper(response, Seq(testHateoasLink))) - - val result: Future[Result] = controller.handleRequest(nino, taxYear)(fakePostRequest(requestBodyJson)) - - status(result) shouldBe CREATED - contentAsJson(result) shouldBe responseBody - header("X-CorrelationId", result) shouldBe Some(correlationId) - - val detail = SampleAuditDetail("Individual", None, nino, taxYear, correlationId, SampleAuditResponse(CREATED, None)) - val event: AuditEvent[SampleAuditDetail] = - AuditEvent[SampleAuditDetail]("sampleAuditType", "sample-transaction-type", detail) - MockedAuditService.verifyAuditEvent(event).once - } - } - - "return the error as per spec" when { - "parser errors occur" must { - def errorsFromParserTester(error: MtdError, expectedStatus: Int): Unit = { - s"a ${error.code} error is returned from the parser" in new Test { - - MockSampleRequestDataParser - .parse(rawData) - .returns(Left(ErrorWrapper(Some(correlationId), error, None))) - - val result: Future[Result] = controller.handleRequest(nino, taxYear)(fakePostRequest(requestBodyJson)) - - status(result) shouldBe expectedStatus - contentAsJson(result) shouldBe Json.toJson(error) - header("X-CorrelationId", result) shouldBe Some(correlationId) - - val detail = SampleAuditDetail( - "Individual", - None, - nino, - taxYear, - header("X-CorrelationId", result).get, - SampleAuditResponse(expectedStatus, Some(Seq(AuditError(error.code)))) - ) - val event: AuditEvent[SampleAuditDetail] = - AuditEvent[SampleAuditDetail]("sampleAuditType", "sample-transaction-type", detail) - MockedAuditService.verifyAuditEvent(event).once - } - } - - val input = Seq( - (BadRequestError, BAD_REQUEST), - (NinoFormatError, BAD_REQUEST), - (TaxYearFormatError, BAD_REQUEST), - (RuleTaxYearRangeInvalidError, BAD_REQUEST), - (RuleIncorrectOrEmptyBodyError, BAD_REQUEST), - (DownstreamError, INTERNAL_SERVER_ERROR) - ) - - input.foreach(args => (errorsFromParserTester _).tupled(args)) - } - - "service errors occur" must { - def serviceErrors(mtdError: MtdError, expectedStatus: Int): Unit = { - s"a $mtdError error is returned from the service" in new Test { - - MockSampleRequestDataParser - .parse(rawData) - .returns(Right(requestData)) - - MockSampleService - .doServiceThing(requestData) - .returns(Future.successful(Left(ErrorWrapper(Some(correlationId), mtdError)))) - - val result: Future[Result] = controller.handleRequest(nino, taxYear)(fakePostRequest(requestBodyJson)) - - status(result) shouldBe expectedStatus - contentAsJson(result) shouldBe Json.toJson(mtdError) - header("X-CorrelationId", result) shouldBe Some(correlationId) - - val detail = SampleAuditDetail( - "Individual", - None, - nino, - taxYear, - header("X-CorrelationId", result).get, - SampleAuditResponse(expectedStatus, Some(Seq(AuditError(mtdError.code)))) - ) - val event: AuditEvent[SampleAuditDetail] = - AuditEvent[SampleAuditDetail]("sampleAuditType", "sample-transaction-type", detail) - MockedAuditService.verifyAuditEvent(event).once - } - } - - val input = Seq( - (NinoFormatError, BAD_REQUEST), - (TaxYearFormatError, BAD_REQUEST), - (NotFoundError, NOT_FOUND), - (DownstreamError, INTERNAL_SERVER_ERROR) - ) - - input.foreach(args => (serviceErrors _).tupled(args)) - } - } - } -} \ No newline at end of file diff --git a/test/v1/controllers/requestParsers/SampleRequestParserSpec.scala b/test/v1/controllers/requestParsers/SampleRequestParserSpec.scala deleted file mode 100644 index c6c13a1..0000000 --- a/test/v1/controllers/requestParsers/SampleRequestParserSpec.scala +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright 2020 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 v1.controllers.requestParsers - -import play.api.libs.json.Json -import play.api.mvc.AnyContentAsJson -import support.UnitSpec -import uk.gov.hmrc.domain.Nino -import v1.mocks.validators.MockSampleValidator -import v1.models.domain.DesTaxYear -import v1.models.errors._ -import v1.models.request.sample -import v1.models.request.sample.{SampleRequestBody, SampleRequestData} - -class SampleRequestParserSpec extends UnitSpec { - val nino = "AA123456B" - val taxYear = "2017-18" - val calcId = "someCalcId" - - private val requestBodyJson = Json.parse( - """{ - | "data" : "someData" - |} - """.stripMargin) - - val inputData = - sample.SampleRawData(nino, taxYear, AnyContentAsJson(requestBodyJson)) - - trait Test extends MockSampleValidator { - lazy val parser = new SampleRequestParser(mockValidator) - } - - "parse" should { - - "return a request object" when { - "valid request data is supplied" in new Test { - MockSampleValidator.validate(inputData).returns(Nil) - - parser.parseRequest(inputData) shouldBe - Right(SampleRequestData(Nino(nino), DesTaxYear("2018"), SampleRequestBody("someData"))) - } - } - - "return an ErrorWrapper" when { - - "a single validation error occurs" in new Test { - MockSampleValidator.validate(inputData) - .returns(List(NinoFormatError)) - - parser.parseRequest(inputData) shouldBe - Left(ErrorWrapper(None, NinoFormatError, None)) - } - - "multiple validation errors occur" in new Test { - MockSampleValidator.validate(inputData) - .returns(List(NinoFormatError, TaxYearFormatError)) - - parser.parseRequest(inputData) shouldBe - Left(ErrorWrapper(None, BadRequestError, Some(Seq(NinoFormatError, TaxYearFormatError)))) - } - } - } -} \ No newline at end of file diff --git a/test/v1/controllers/requestParsers/validators/SampleValidatorSpec.scala b/test/v1/controllers/requestParsers/validators/SampleValidatorSpec.scala deleted file mode 100644 index 1f269c7..0000000 --- a/test/v1/controllers/requestParsers/validators/SampleValidatorSpec.scala +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Copyright 2020 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 v1.controllers.requestParsers.validators - -import play.api.libs.json.{JsValue, Json} -import play.api.mvc.AnyContentAsJson -import support.UnitSpec -import v1.models.errors._ -import v1.models.request.sample - -class SampleValidatorSpec extends UnitSpec { - - private val validNino = "AA123456A" - private val validTaxYear = "2018-19" - - private val requestBodyJson: JsValue = Json.parse( - """{ - | "data" : "someData" - |} - """.stripMargin) - - private val nonValidRequestBodyJson: JsValue = Json.parse( - """{ - | "data" : true - |} - """.stripMargin) - - private val emptyRequestBodyJson: JsValue = Json.parse("""{}""") - - private val nonsenseRequestBodyJson: JsValue = Json.parse("""{"field": "value"}""") - - private val validRawRequestBody = AnyContentAsJson(requestBodyJson) - private val emptyRawRequestBody = AnyContentAsJson(emptyRequestBodyJson) - private val nonsenseRawRequestBody = AnyContentAsJson(nonsenseRequestBodyJson) - private val nonValidRawRequestBody = AnyContentAsJson(nonValidRequestBodyJson) - - val validator = new SampleValidator() - - "running a validation" should { - "return no errors" when { - "a valid request is supplied" in { - validator.validate(sample.SampleRawData(validNino, validTaxYear, validRawRequestBody)) shouldBe Nil - } - } - - "return NinoFormatError error" when { - "an invalid nino is supplied" in { - validator.validate(sample.SampleRawData("A12344A", validTaxYear, validRawRequestBody)) shouldBe - List(NinoFormatError) - } - } - - "return TaxYearFormatError error" when { - "an invalid tax year is supplied" in { - validator.validate(sample.SampleRawData(validNino, "20178", validRawRequestBody)) shouldBe - List(TaxYearFormatError) - } - } - - "return RuleTaxYearRangeInvalidError error" when { - "an out of range tax year is supplied" in { - validator.validate(sample.SampleRawData(validNino, "2016-18", validRawRequestBody)) shouldBe - List(RuleTaxYearRangeInvalidError) - } - } - - "return RuleIncorrectOrEmptyBodyError error" when { - "an empty JSON body is submitted" in { - validator.validate(sample.SampleRawData(validNino, validTaxYear, emptyRawRequestBody)) shouldBe - List(RuleIncorrectOrEmptyBodyError) - } - - "a non-empty JSON body is submitted without any expected fields" in { - validator.validate(sample.SampleRawData(validNino, validTaxYear, nonsenseRawRequestBody)) shouldBe - List(RuleIncorrectOrEmptyBodyError.copy(paths = Some(Seq("/data")))) - } - - "the submitted request body is not in the correct format" in { - validator.validate(sample.SampleRawData(validNino, validTaxYear, nonValidRawRequestBody)) shouldBe - List(RuleIncorrectOrEmptyBodyError.copy(paths = Some(Seq("/data")))) - } - } - - "return multiple errors" when { - "request supplied has multiple errors" in { - validator.validate(sample.SampleRawData("A12344A", "20178", validRawRequestBody)) shouldBe - List(NinoFormatError, TaxYearFormatError) - } - } - } -} \ No newline at end of file diff --git a/test/v1/mocks/connectors/MockSampleConnector.scala b/test/v1/mocks/connectors/MockSampleConnector.scala deleted file mode 100644 index 6898f86..0000000 --- a/test/v1/mocks/connectors/MockSampleConnector.scala +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2020 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 v1.mocks.connectors - -import org.scalamock.handlers.CallHandler -import org.scalamock.scalatest.MockFactory -import uk.gov.hmrc.http.HeaderCarrier -import v1.connectors.{DesOutcome, SampleConnector} -import v1.models.request.sample.SampleRequestData -import v1.models.response.des.DesSampleResponse - -import scala.concurrent.{ExecutionContext, Future} - -trait MockSampleConnector extends MockFactory { - - val mockSampleConnector: SampleConnector = mock[SampleConnector] - - object MockSampleConnector { - - def doConnectorThing(requestData: SampleRequestData): CallHandler[Future[DesOutcome[DesSampleResponse]]] = { - (mockSampleConnector - .doConnectorThing(_: SampleRequestData)(_: HeaderCarrier, _: ExecutionContext)) - .expects(requestData, *, *) - } - } - -} diff --git a/test/v1/mocks/requestParsers/MockSampleRequestParser.scala b/test/v1/mocks/requestParsers/MockSampleRequestParser.scala deleted file mode 100644 index 59aa83b..0000000 --- a/test/v1/mocks/requestParsers/MockSampleRequestParser.scala +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2020 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 v1.mocks.requestParsers - -import org.scalamock.handlers.CallHandler -import org.scalamock.scalatest.MockFactory -import v1.controllers.requestParsers.SampleRequestParser -import v1.models.errors.ErrorWrapper -import v1.models.request.sample.{SampleRawData, SampleRequestData} - -trait MockSampleRequestParser extends MockFactory { - - val mockRequestDataParser: SampleRequestParser = mock[SampleRequestParser] - - object MockSampleRequestDataParser { - def parse(data: SampleRawData): CallHandler[Either[ErrorWrapper, SampleRequestData]] = { - (mockRequestDataParser.parseRequest(_: SampleRawData)).expects(data) - } - } - -} diff --git a/test/v1/mocks/services/MockSampleService.scala b/test/v1/mocks/services/MockSampleService.scala deleted file mode 100644 index bdc7e42..0000000 --- a/test/v1/mocks/services/MockSampleService.scala +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2020 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 v1.mocks.services - -import org.scalamock.handlers.CallHandler -import org.scalamock.scalatest.MockFactory -import uk.gov.hmrc.http.HeaderCarrier -import v1.controllers.EndpointLogContext -import v1.models.errors.ErrorWrapper -import v1.models.outcomes.ResponseWrapper -import v1.models.request.sample.SampleRequestData -import v1.models.response.sample.SampleResponse -import v1.services.SampleService - -import scala.concurrent.{ExecutionContext, Future} - -trait MockSampleService extends MockFactory { - - val mockSampleService: SampleService = mock[SampleService] - - object MockSampleService { - - def doServiceThing(requestData: SampleRequestData): CallHandler[Future[Either[ErrorWrapper, ResponseWrapper[SampleResponse]]]] = { - (mockSampleService - .doServiceThing(_: SampleRequestData)(_: HeaderCarrier, _: ExecutionContext, _: EndpointLogContext)) - .expects(requestData, *, *, *) - } - } - -} diff --git a/test/v1/mocks/validators/MockSampleValidator.scala b/test/v1/mocks/validators/MockSampleValidator.scala deleted file mode 100644 index 44c6bd5..0000000 --- a/test/v1/mocks/validators/MockSampleValidator.scala +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2020 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 v1.mocks.validators - -import org.scalamock.handlers.CallHandler1 -import org.scalamock.scalatest.MockFactory -import v1.controllers.requestParsers.validators.SampleValidator -import v1.models.errors.MtdError -import v1.models.request.sample.SampleRawData - -class MockSampleValidator extends MockFactory { - - val mockValidator: SampleValidator = mock[SampleValidator] - - object MockSampleValidator { - - def validate(data: SampleRawData): CallHandler1[SampleRawData, List[MtdError]] = { - (mockValidator - .validate(_: SampleRawData)) - .expects(data) - } - } -} diff --git a/test/v1/models/audit/SampleAuditDetailSpec.scala b/test/v1/models/audit/AuditDetailSpec.scala similarity index 82% rename from test/v1/models/audit/SampleAuditDetailSpec.scala rename to test/v1/models/audit/AuditDetailSpec.scala index 8add73e..63497de 100644 --- a/test/v1/models/audit/SampleAuditDetailSpec.scala +++ b/test/v1/models/audit/AuditDetailSpec.scala @@ -20,15 +20,15 @@ import play.api.http.Status import play.api.libs.json.Json import support.UnitSpec -class SampleAuditDetailSpec extends UnitSpec { +class AuditDetailSpec extends UnitSpec { private val userType = "Organisation" private val agentReferenceNumber = Some("012345678") private val nino = "AA123456A" private val taxYear = "2017-18" private val `X-CorrelationId` = "X-123" - private val responseSuccess = SampleAuditResponse(Status.SEE_OTHER, None) - private val responseFail = SampleAuditResponse(Status.BAD_REQUEST, Some(Seq(AuditError("FORMAT_NINO")))) + private val responseSuccess = AuditResponse(Status.SEE_OTHER, None) + private val responseFail = AuditResponse(Status.BAD_REQUEST, Some(Seq(AuditError("FORMAT_NINO")))) "writes" when { "passed an audit model with all fields provided" should { @@ -47,7 +47,7 @@ class SampleAuditDetailSpec extends UnitSpec { |} """.stripMargin) - val model = SampleAuditDetail(userType, agentReferenceNumber, nino, taxYear, `X-CorrelationId`, responseSuccess) + val model = AuditDetail(userType, agentReferenceNumber, nino, taxYear, `X-CorrelationId`, responseSuccess) Json.toJson(model) shouldBe json } @@ -73,7 +73,7 @@ class SampleAuditDetailSpec extends UnitSpec { |} """.stripMargin) - val model = SampleAuditDetail(userType, None, nino, taxYear, `X-CorrelationId`, responseFail) + val model = AuditDetail(userType, None, nino, taxYear, `X-CorrelationId`, responseFail) Json.toJson(model) shouldBe json } diff --git a/test/v1/models/request/sample/SampleRequestBodySpec.scala b/test/v1/models/request/sample/SampleRequestBodySpec.scala deleted file mode 100644 index 76c08fa..0000000 --- a/test/v1/models/request/sample/SampleRequestBodySpec.scala +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2020 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 v1.models.request.sample - -import play.api.libs.json.{JsError, JsObject, Json} -import support.UnitSpec - -class SampleRequestBodySpec extends UnitSpec { - - private val inputJson = Json.parse( - """ - |{ - | "data": "someData" - |} - """.stripMargin - ) - - private val model = SampleRequestBody(data = "someData") - - "SampleRequestBody" when { - "read from valid JSON" should { - "produce the expected SampleRequestBody object" in { - inputJson.as[SampleRequestBody] shouldBe model - } - } - - "read from empty JSON" should { - "produce a JsError" in { - val invalidJson = JsObject.empty - - invalidJson.validate[SampleRequestBody] shouldBe a[JsError] - } - } - - "written to JSON" should { - "produce the expected JsObject" in { - Json.toJson(model) shouldBe inputJson - } - } - } -} \ No newline at end of file diff --git a/test/v1/models/response/des/DesSampleResponseSpec.scala b/test/v1/models/response/des/DesSampleResponseSpec.scala deleted file mode 100644 index d55375c..0000000 --- a/test/v1/models/response/des/DesSampleResponseSpec.scala +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright 2020 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 v1.models.response.des - -import play.api.libs.json.Json -import support.UnitSpec - -class DesSampleResponseSpec extends UnitSpec { - "Json reads" should { - "use specified format" in { - val json = Json.parse( - """ - |{ - | "responseData": "someResponse" - |}""".stripMargin) - - json.as[DesSampleResponse] shouldBe DesSampleResponse("someResponse") - } - } -} diff --git a/test/v1/models/response/sample/SampleResponseSpec.scala b/test/v1/models/response/sample/SampleResponseSpec.scala deleted file mode 100644 index 7be39f3..0000000 --- a/test/v1/models/response/sample/SampleResponseSpec.scala +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright 2020 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 v1.models.response.sample - -import play.api.libs.json.Json -import support.UnitSpec - -class SampleResponseSpec extends UnitSpec { - "writes" must { - "write expected JSON format" in { - Json.toJson(SampleResponse("someData")) shouldBe Json.parse( - """ - |{ - | "responseData" : "someData" - |} - """.stripMargin) - } - } -} diff --git a/test/v1/services/SampleServiceSpec.scala b/test/v1/services/SampleServiceSpec.scala deleted file mode 100644 index b62d78c..0000000 --- a/test/v1/services/SampleServiceSpec.scala +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2020 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 v1.services - -import support.UnitSpec -import uk.gov.hmrc.domain.Nino -import uk.gov.hmrc.http.HeaderCarrier -import v1.controllers.EndpointLogContext -import v1.mocks.connectors.MockSampleConnector -import v1.models.domain.DesTaxYear -import v1.models.errors._ -import v1.models.outcomes.ResponseWrapper -import v1.models.request.sample.{SampleRequestBody, SampleRequestData} -import v1.models.response.des.DesSampleResponse -import v1.models.response.sample.SampleResponse - -import scala.concurrent.ExecutionContext.Implicits.global -import scala.concurrent.Future - -class SampleServiceSpec extends UnitSpec { - - private val nino = "AA123456A" - private val taxYear = "2017-18" - private val correlationId = "X-123" - - private val requestBody = SampleRequestBody("someData") - - private val requestData = SampleRequestData(Nino(nino), DesTaxYear.fromMtd(taxYear), requestBody) - - trait Test extends MockSampleConnector { - implicit val hc: HeaderCarrier = HeaderCarrier() - implicit val logContext: EndpointLogContext = EndpointLogContext("c", "ep") - - val service = new SampleService( - sampleConnector = mockSampleConnector - ) - } - - "service" when { - "service call successsful" must { - "return mapped result" in new Test { - MockSampleConnector.doConnectorThing(requestData) - .returns(Future.successful(Right(ResponseWrapper(correlationId, DesSampleResponse("result"))))) - - await(service.doServiceThing(requestData)) shouldBe Right(ResponseWrapper(correlationId, SampleResponse("result"))) - } - } - - "unsuccessful" must { - "map errors according to spec" when { - - def serviceError(desErrorCode: String, error: MtdError): Unit = - s"a $desErrorCode error is returned from the service" in new Test { - - MockSampleConnector.doConnectorThing(requestData) - .returns(Future.successful(Left(ResponseWrapper(correlationId, DesErrors.single(DesErrorCode(desErrorCode)))))) - - await(service.doServiceThing(requestData)) shouldBe Left(ErrorWrapper(Some(correlationId), error)) - } - - val input = Seq( - ("NOT_FOUND", NotFoundError), - ("SERVER_ERROR", DownstreamError), - ("SERVICE_UNAVAILABLE", DownstreamError) - ) - - input.foreach(args => (serviceError _).tupled(args)) - } - } - } -}