diff --git a/acceptance/uk/gov/hmrc/apidocumentation/BaseSpec.scala b/acceptance/uk/gov/hmrc/apidocumentation/BaseSpec.scala index cc1bc328..893b4e38 100644 --- a/acceptance/uk/gov/hmrc/apidocumentation/BaseSpec.scala +++ b/acceptance/uk/gov/hmrc/apidocumentation/BaseSpec.scala @@ -38,7 +38,14 @@ trait BaseSpec extends FeatureSpec with BeforeAndAfterEach with BeforeAndAfterAl override def fakeApplication(): Application = { GuiceApplicationBuilder() - .configure("run.mode" -> "Test") + .configure( + "microservice.services.developer-frontend.host" -> stubHost, + "microservice.services.developer-frontend.port" -> stubPort, + "microservice.services.api-platform-microservice.host" -> stubHost, + "microservice.services.api-platform-microservice.port" -> stubPort, + "microservice.services.third-party-developer.host" -> stubHost, + "microservice.services.third-party-developer.port" -> stubPort + ) .in(Mode.Prod) .build() } diff --git a/app/uk/gov/hmrc/apidocumentation/config/ApplicationConfig.scala b/app/uk/gov/hmrc/apidocumentation/config/ApplicationConfig.scala index 42b39ab0..584365a0 100644 --- a/app/uk/gov/hmrc/apidocumentation/config/ApplicationConfig.scala +++ b/app/uk/gov/hmrc/apidocumentation/config/ApplicationConfig.scala @@ -22,17 +22,8 @@ import uk.gov.hmrc.play.bootstrap.config.{RunMode, ServicesConfig} @ImplementedBy(classOf[ApplicationConfigImpl]) trait ApplicationConfig { - def contactFormServiceIdentifier: String - def contactPath: String - - def analyticsToken: Option[String] - def analyticsHost: String - def developerFrontendUrl: String - def reportAProblemPartialUrl: String - def reportAProblemNonJSUrl: String - def developerFrontendBaseUrl: String def thirdPartyDeveloperUrl: String def apiPlatformMicroserviceBaseUrl: String @@ -44,12 +35,9 @@ trait ApplicationConfig { def showProductionAvailability: Boolean def showSandboxAvailability: Boolean - def productionApiHost: String def productionWwwHost: String def productionApiBaseUrl: String - def sandboxApiHost: String - def sandboxWwwHost: String def sandboxApiBaseUrl: String def sandboxWwwBaseUrl: String @@ -61,10 +49,7 @@ trait ApplicationConfig { def subordinateBaseUrl: String def title: String - def isStubMode: Boolean def xmlApiBaseUrl: String - - def apidocumentationBaseUrl: String } @Singleton @@ -72,20 +57,9 @@ class ApplicationConfigImpl @Inject()(config: Configuration, runMode: RunMode) extends ServicesConfig(config, runMode) with ApplicationConfig { - val env = runMode.env - def getConfigDefaulted[A](key: String, default: A)(implicit loader: ConfigLoader[A]) = config.getOptional[A](key)(loader).getOrElse(default) - val contactFormServiceIdentifier = "API" - val contactPath = getConfigDefaulted(s"$env.contactPath", "") - - val analyticsToken = config.getOptional[String](s"$env.google-analytics.token").filterNot(_ == "") - val analyticsHost = getConfigDefaulted(s"$env.google-analytics.host", "auto") - - val developerFrontendUrl = getConfigDefaulted(s"$env.developer-frontend-url", "") - - val reportAProblemPartialUrl = s"$contactPath/contact/problem_reports_ajax?service=$contactFormServiceIdentifier" - val reportAProblemNonJSUrl = s"$contactPath/contact/problem_reports_nonjs?service=$contactFormServiceIdentifier" + val developerFrontendUrl = getString("developer-frontend-url") val developerFrontendBaseUrl = baseUrl("developer-frontend") val thirdPartyDeveloperUrl = baseUrl("third-party-developer") @@ -100,32 +74,26 @@ class ApplicationConfigImpl @Inject()(config: Configuration, runMode: RunMode) lazy val apiPlatformMicroserviceBaseUrl = baseUrl("api-platform-microservice") lazy val ramlPreviewMicroserviceBaseUrl = baseUrl("raml-preview-microservice") - val securedCookie = getConfigDefaulted(s"$env.cookie.secure", true) - val ramlPreviewEnabled = getConfigDefaulted(s"$env.features.ramlPreview", false) + val securedCookie = getBoolean("cookie.secure") + val ramlPreviewEnabled = getBoolean("features.ramlPreview") - val showProductionAvailability = getConfigDefaulted(s"$env.features.showProductionAvailability", false) - val showSandboxAvailability = getConfigDefaulted(s"$env.features.showSandboxAvailability", false) - val productionApiHost = getString("platform.production.api.host") + val showProductionAvailability = getBoolean("features.showProductionAvailability") + val showSandboxAvailability = getBoolean("features.showSandboxAvailability") val productionWwwHost = getString("platform.production.www.host") val productionApiBaseUrl = platformBaseUrl("platform.production.api") - val sandboxApiHost = getString("platform.sandbox.api.host") - val sandboxWwwHost = getString("platform.sandbox.www.host") val sandboxApiBaseUrl = platformBaseUrl("platform.sandbox.api") val sandboxWwwBaseUrl = platformBaseUrl("platform.sandbox.www") - val documentationRenderVersion = getConfigDefaulted(s"$env.features.documentationRenderVersion", "raml") - - val nameOfPrincipalEnvironment = getConfigDefaulted(s"$env.features.nameOfPrincipalEnvironment", "Production") - val nameOfSubordinateEnvironment = getConfigDefaulted(s"$env.features.nameOfSubordinateEnvironment", "Sandbox") - val principalBaseUrl = getConfigDefaulted(s"$env.features.principalBaseUrl", "https://api.service.hmrc.gov.uk") - val subordinateBaseUrl = getConfigDefaulted(s"$env.features.subordinateBaseUrl", "https://test-api.service.hmrc.gov.uk") + val documentationRenderVersion = getString("features.documentationRenderVersion") - val apidocumentationBaseUrl = getString("apidocumentation.base.url") + val nameOfPrincipalEnvironment = getString("features.nameOfPrincipalEnvironment") + val nameOfSubordinateEnvironment = getString("features.nameOfSubordinateEnvironment") + val principalBaseUrl = getString("features.principalBaseUrl") + val subordinateBaseUrl = getString("features.subordinateBaseUrl") val title = "HMRC Developer Hub" - val isStubMode = env == "Stub" - val xmlApiBaseUrl = getConfigDefaulted(s"$env.xml-api.base-url", "https://www.gov.uk") + val xmlApiBaseUrl = getString("xml-api.base-url") private def platformBaseUrl(key: String) = { (getConfigDefaulted(s"$key.protocol", ""), getConfigDefaulted(s"$key.host", "")) match { diff --git a/app/uk/gov/hmrc/apidocumentation/connectors/ProxiedHttpClient.scala b/app/uk/gov/hmrc/apidocumentation/connectors/ProxiedHttpClient.scala index 6d6e399f..73e206d8 100644 --- a/app/uk/gov/hmrc/apidocumentation/connectors/ProxiedHttpClient.scala +++ b/app/uk/gov/hmrc/apidocumentation/connectors/ProxiedHttpClient.scala @@ -19,12 +19,10 @@ package uk.gov.hmrc.apidocumentation.connectors import akka.actor.ActorSystem import javax.inject.{Inject, Singleton} import play.api.Configuration -import play.api.http.HeaderNames.ACCEPT -import play.api.libs.ws.{WSClient, WSProxyServer, WSRequest} -import uk.gov.hmrc.http.HeaderCarrier -import uk.gov.hmrc.http.logging.Authorization +import play.api.http.HeaderNames +import play.api.libs.ws.{WSClient, WSProxyServer, WSRequest => PlayWSRequest} +import uk.gov.hmrc.http.Authorization import uk.gov.hmrc.play.audit.http.HttpAuditing -import uk.gov.hmrc.play.bootstrap.config.RunMode import uk.gov.hmrc.play.bootstrap.http.DefaultHttpClient import uk.gov.hmrc.play.http.ws.{WSProxy, WSProxyConfiguration} @@ -32,31 +30,33 @@ import uk.gov.hmrc.play.http.ws.{WSProxy, WSProxyConfiguration} class ProxiedHttpClient @Inject()(config: Configuration, httpAuditing: HttpAuditing, wsClient: WSClient, - actorSystem: ActorSystem, - runMode: RunMode) + actorSystem: ActorSystem) extends DefaultHttpClient(config, httpAuditing, wsClient, actorSystem) with WSProxy { val authorization: Option[Authorization] = None - val apiKeyHeader: Option[(String, String)] = None - private val env = runMode.env + val apiKeyHeader: Option[String] = None def withHeaders(bearerToken: String, apiKey: String = ""): ProxiedHttpClient = { - new ProxiedHttpClient(config, httpAuditing, wsClient, actorSystem, runMode) { + new ProxiedHttpClient(config, httpAuditing, wsClient, actorSystem) { override val authorization = Some(Authorization(s"Bearer $bearerToken")) - override val apiKeyHeader: Option[(String, String)] = if ("" == apiKey) None else Some("x-api-key" -> apiKey) + override val apiKeyHeader = if (apiKey.isEmpty) None else Some(apiKey) } } - override def wsProxyServer: Option[WSProxyServer] = WSProxyConfiguration(s"$env.proxy", config) + override def wsProxyServer: Option[WSProxyServer] = WSProxyConfiguration("proxy", config) - override def buildRequest[A](url: String, headers: Seq[(String, String)])(implicit hc: HeaderCarrier): WSRequest = { - val extraHeaders = hc.extraHeaders :+ (ACCEPT -> "application/hmrc.vnd.1.0+json") - val extraHeadersWithMaybeApiKeyHeader = - if (apiKeyHeader.isDefined) extraHeaders :+ apiKeyHeader.get - else extraHeaders + override def buildRequest[A](url: String, headers: Seq[(String, String)]): PlayWSRequest = { + val extraHeaders: Seq[(String,String)] = headers ++ + authorization.map(v => (HeaderNames.AUTHORIZATION -> v.value)).toSeq ++ + apiKeyHeader.map(v => ProxiedHttpClient.API_KEY_HEADER_NAME -> v).toSeq ++ + Seq(ProxiedHttpClient.ACCEPT_HMRC_JSON_HEADER) - val hcWithBearerAndAccept = hc.copy(authorization = authorization, extraHeaders = extraHeadersWithMaybeApiKeyHeader) - - super.buildRequest(url)(hcWithBearerAndAccept) + super.buildRequest(url, extraHeaders) } } + +object ProxiedHttpClient { + val API_KEY_HEADER_NAME = "x-api-key" + val ACCEPT_HMRC_JSON_HEADER = HeaderNames.ACCEPT -> "application/hmrc.vnd.1.0+json" +} + diff --git a/app/uk/gov/hmrc/apidocumentation/controllers/ApiDocumentationController.scala b/app/uk/gov/hmrc/apidocumentation/controllers/ApiDocumentationController.scala index 1fd88880..0f5b65df 100644 --- a/app/uk/gov/hmrc/apidocumentation/controllers/ApiDocumentationController.scala +++ b/app/uk/gov/hmrc/apidocumentation/controllers/ApiDocumentationController.scala @@ -131,7 +131,7 @@ class ApiDocumentationController @Inject()( (for { userId <- extractDeveloperIdentifier(loggedInUserService.fetchLoggedInUser()) api <- apiDefinitionService.fetchExtendedDefinition(service, userId) - cacheBust = bustCache(appConfig.isStubMode, cacheBuster) + cacheBust = bustCache(cacheBuster) apiDocumentation <- doRenderApiDocumentation(service, version, cacheBust, api, navLinks, userId) } yield apiDocumentation) recover { case e: NotFoundException => @@ -143,7 +143,7 @@ class ApiDocumentationController @Inject()( } } - def bustCache(stubMode: Boolean, cacheBuster: Option[Boolean]): Boolean = stubMode || cacheBuster.getOrElse(false) + def bustCache(cacheBuster: Option[Boolean]): Boolean = cacheBuster.getOrElse(false) private def doRenderApiDocumentation(service: String, version: String, cacheBuster: Boolean, apiOption: Option[ExtendedAPIDefinition], navLinks: Seq[NavLink], developerId: Option[DeveloperIdentifier])(implicit request: Request[AnyContent], messagesProvider: MessagesProvider): Future[Result] = { diff --git a/app/uk/gov/hmrc/apidocumentation/services/LoggedInUserService.scala b/app/uk/gov/hmrc/apidocumentation/services/LoggedInUserService.scala index 01ef727e..750c43ae 100644 --- a/app/uk/gov/hmrc/apidocumentation/services/LoggedInUserService.scala +++ b/app/uk/gov/hmrc/apidocumentation/services/LoggedInUserService.scala @@ -24,7 +24,7 @@ import play.api.mvc.{ControllerComponents, Request, RequestHeader} import uk.gov.hmrc.apidocumentation.config.ApplicationConfig import uk.gov.hmrc.apidocumentation.models.{Developer, Session} import uk.gov.hmrc.http.HeaderCarrier -import uk.gov.hmrc.play.HeaderCarrierConverter +import uk.gov.hmrc.play.http.HeaderCarrierConverter import uk.gov.hmrc.play.bootstrap.controller.BackendController import scala.concurrent.{ExecutionContext, Future} @@ -91,5 +91,5 @@ trait CookieEncoding { trait HeaderCarrierConversion extends uk.gov.hmrc.play.bootstrap.controller.BackendBaseController { override implicit def hc(implicit rh: RequestHeader): HeaderCarrier = - HeaderCarrierConverter.fromHeadersAndSessionAndRequest(rh.headers, Some(rh.session), Some(rh)) + HeaderCarrierConverter.fromRequestAndSession(rh, rh.session) } diff --git a/build.sbt b/build.sbt index f06d6074..e0daa5dd 100644 --- a/build.sbt +++ b/build.sbt @@ -19,7 +19,7 @@ import bloop.integrations.sbt.BloopDefaults lazy val plugins: Seq[Plugins] = Seq.empty lazy val playSettings: Seq[Setting[_]] = Seq.empty lazy val microservice = (project in file(".")) - .enablePlugins(Seq(PlayScala, SbtAutoBuildPlugin, SbtGitVersioning, SbtDistributablesPlugin, SbtArtifactory) ++ plugins: _*) + .enablePlugins(Seq(PlayScala, SbtAutoBuildPlugin, SbtDistributablesPlugin) ++ plugins: _*) .settings( name := appName ) @@ -49,6 +49,7 @@ lazy val microservice = (project in file(".")) .settings(playSettings: _*) .settings(scalaSettings: _*) .settings(publishingSettings: _*) + .settings(ScoverageSettings(): _*) .settings(defaultSettings(): _*) .settings( targetJvm := "jvm-1.8", @@ -62,9 +63,11 @@ lazy val microservice = (project in file(".")) .settings(unmanagedResourceDirectories in Compile += baseDirectory.value / "resources") .settings(inConfig(TemplateTest)(Defaults.testSettings): _*) + .settings(inConfig(TemplateTest)(BloopDefaults.configSettings)) .settings( Test / testOptions := Seq(Tests.Argument(TestFrameworks.ScalaTest, "-eT")), Test / unmanagedSourceDirectories += baseDirectory.value / "test", + Test / unmanagedSourceDirectories += baseDirectory.value / "testcommon", Test / fork := false, Test / parallelExecution := false ) @@ -75,6 +78,7 @@ lazy val microservice = (project in file(".")) .settings( testOptions in AcceptanceTest := Seq(Tests.Argument(TestFrameworks.ScalaTest, "-eT")), AcceptanceTest / unmanagedSourceDirectories += baseDirectory.value / "acceptance", + AcceptanceTest / unmanagedSourceDirectories += baseDirectory.value / "testcommon", AcceptanceTest / unmanagedResourceDirectories := Seq((baseDirectory in AcceptanceTest).value / "test", (baseDirectory in AcceptanceTest).value / "target/web/public/test"), AcceptanceTest / fork := false, AcceptanceTest / parallelExecution := false, @@ -98,26 +102,3 @@ lazy val playPublishingSettings: Seq[sbt.Setting[_]] = Seq( publishAllArtefacts lazy val appName = "api-documentation-frontend" - -val ScoverageExclusionPatterns = List( - "", - "definition.*", - "sandbox.*", - "live.*", - "prod.*", - "testOnlyDoNotUseInAppConf.*", - "uk.gov.hmrc.config.*", - "app.Routes", - "app.RoutesPrefix", - "controllers.javascript", - "com.kenshoo.play.metrics.javascript", - "com.kenshoo.play.metrics", - ".*Reverse.*", - "uk.gov.hmrc.controllers.Reverse*", -) - -// Coverage configuration -// TODO ebridge - Fix and set back to 85 -coverageMinimum := 80 -coverageFailOnMinimum := true -coverageExcludedPackages := ScoverageExclusionPatterns.mkString("",";","") diff --git a/conf/application.conf b/conf/application.conf index 8606aaa1..0fb04596 100644 --- a/conf/application.conf +++ b/conf/application.conf @@ -41,16 +41,14 @@ play.modules.enabled += "uk.gov.hmrc.play.bootstrap.AuditModule" # Provides an implementation of MetricsFilter. Use `uk.gov.hmrc.play.bootstrap.graphite.GraphiteMetricsModule` or create your own. # A metric filter must be provided play.modules.enabled += "uk.gov.hmrc.play.bootstrap.graphite.GraphiteMetricsModule" - play.modules.enabled += "uk.gov.hmrc.play.bootstrap.HttpClientModule" # Provides an implementation and configures all filters required by a Platform frontend microservice. play.modules.enabled += "uk.gov.hmrc.play.bootstrap.FrontendModule" +play.modules.enabled += "uk.gov.hmrc.play.http.metrics.Module" play.http.filters = "uk.gov.hmrc.apidocumentation.Filters" -play.modules.enabled += "uk.gov.hmrc.play.http.metrics.Module" - play.http.errorHandler = "uk.gov.hmrc.apidocumentation.ErrorHandler" metrics { @@ -58,8 +56,8 @@ metrics { rateUnit = SECONDS durationUnit = SECONDS showSamples = true - jvm = true - enabled = true + jvm = false + enabled = false } platform { @@ -81,8 +79,6 @@ platform { } } - - default.source = "default-src 'self' 'unsafe-inline' www.googletagmanager.com www.googleanalytics.com www.google-analytics.com" script.source = "script-src 'unsafe-inline' 'self' data: localhost:12345 localhost:9032 www.google-analytics.com www.googletagmanager.com tagmanager.google.com" font.source = "font-src 'self' data: localhost:12345 https://ssl.gstatic.com https://www.gstatic.com https://fonts.gstatic.com https://fonts.googleapis.com" @@ -91,9 +87,6 @@ style.source = "style-src 'self' localhost:9032 'unsafe-inline' https://tagmanag play.filters.headers.contentSecurityPolicy = ${?default.source} ";" ${?script.source} ";" ${?font.source} ";" ${?img.source} ";" ${?style.source} -wiremock-port = 11111 -wiremock-port = ${?WIREMOCK_PORT} - assets { version = "3.11.0" version = ${?ASSETS_FRONTEND_VERSION} @@ -119,145 +112,57 @@ urls { } } -Stub { - cookie.secure = false - - auditing { - enabled = false - traceRequests = false - } - - api-platform.bearer-token = DUMMY - - features { - groupedDocumentation = true - ramlPreview = true - showProductionAvailability = true - showSandboxAvailability = true - } - - microservice { - services { - developer-frontend { - host = localhost - port = ${wiremock-port} - } - - third-party-developer { - host = localhost - port = ${wiremock-port} - } +developer-frontend-url = "http://localhost:9685" - api-platform-microservice { - host = localhost - port = ${wiremock-port} - } +cookie.secure = false - raml-preview-microservice { - host = localhost - port = 9604 - } - } - } +features { + ramlPreview = true + showProductionAvailability = false + showSandboxAvailability = false + documentationRenderVersion = "specification" + nameOfPrincipalEnvironment = "QA" + nameOfSubordinateEnvironment = "Development" + principalBaseUrl = "https://api.qa.tax.service.gov.uk" + subordinateBaseUrl = "https://api.development.tax.service.gov.uk" } -Test { - cookie.secure = false - - auditing { - enabled = false - traceRequests = false - } +auditing { + enabled = false + traceRequests = false - api-platform.bearer-token = DUMMY - - features { - groupedDocumentation = true - ramlPreview = true - showProductionAvailability = true - showSandboxAvailability = true - } - - microservice { - services { - developer-frontend { - host = localhost - port = ${wiremock-port} - } - - third-party-developer { - host = localhost - port = ${wiremock-port} - } - - api-platform-microservice { - host = localhost - port = ${wiremock-port} - } - - raml-preview-microservice { - host = localhost - port = 9604 - } + consumer { + baseUri { + host = "localhost" + port = 8100 } } } -Dev { - cookie.secure = false - contactPath = "http://localhost:9250" - - developer-frontend-url = "http://localhost:9685" - - api-platform.bearer-token = DUMMY +xml-api { + base-url = "https://www.gov.uk" +} - auditing { - enabled = false - traceRequests = false - consumer { - baseUri { - host = "localhost" - port = 8100 - } +microservice { + services { + developer-frontend { + host = localhost + port = 9685 } - } - - features { - groupedDocumentation = true - ramlPreview = true - // either raml or specification - documentationRenderVersion = "specification" - // Environment re-branding - nameOfPrincipalEnvironment = "QA" - nameOfSubordinateEnvironment = "Development" - principalBaseUrl = "https://api.qa.tax.service.gov.uk" - subordinateBaseUrl = "https://api.development.tax.service.gov.uk" - } - - microservice { - services { - developer-frontend { - host = localhost - port = 9685 - } - third-party-developer { - host = localhost - port = 9615 - } + third-party-developer { + host = localhost + port = 9615 + } - api-platform-microservice { - host = localhost - port = 9602 - } + api-platform-microservice { + host = localhost + port = 9602 + } - raml-preview-microservice { - host = localhost - port = 9604 - } + raml-preview-microservice { + host = localhost + port = 9604 } } } - -Prod { -} diff --git a/project/AppDependencies.scala b/project/AppDependencies.scala index 703164af..ca97ed52 100644 --- a/project/AppDependencies.scala +++ b/project/AppDependencies.scala @@ -11,7 +11,7 @@ object AppDependencies { lazy val compile = Seq( ws, ehcache, - "uk.gov.hmrc" %% "bootstrap-play-26" % "2.2.0", + "uk.gov.hmrc" %% "bootstrap-play-26" % "4.0.0", "uk.gov.hmrc" %% "url-builder" % "3.4.0-play-26", "uk.gov.hmrc" %% "http-metrics" % "1.11.0", "uk.gov.hmrc" %% "govuk-template" % "5.61.0-play-26", @@ -27,15 +27,14 @@ object AppDependencies { lazy val test = Seq( "io.cucumber" %% "cucumber-scala" % "5.7.0", "io.cucumber" % "cucumber-junit" % "5.7.0", - "uk.gov.hmrc" %% "hmrctest" % "3.10.0-play-26", "org.pegdown" % "pegdown" % "1.6.0", "com.typesafe.play" %% "play-test" % PlayVersion.current, "org.scalatestplus.play" %% "scalatestplus-play" % "3.1.3", - "org.mockito" % "mockito-core" % "1.10.19", + "org.mockito" %% "mockito-scala-scalatest" % "1.7.1", "org.seleniumhq.selenium" % "selenium-java" % "3.141.59", "org.seleniumhq.selenium" % "selenium-firefox-driver" % "3.141.59", "org.seleniumhq.selenium" % "selenium-chrome-driver" % "3.141.59", - "com.github.tomakehurst" % "wiremock" % "1.58", + "com.github.tomakehurst" % "wiremock-jre8-standalone" % "2.27.1", "org.jsoup" % "jsoup" % "1.12.1" ).map(_.withConfigurations(Some(testScopes))) } diff --git a/project/ScoverageSettings.scala b/project/ScoverageSettings.scala new file mode 100644 index 00000000..ce4d6f80 --- /dev/null +++ b/project/ScoverageSettings.scala @@ -0,0 +1,24 @@ +import scoverage.ScoverageKeys._ + +object ScoverageSettings { + def apply() = Seq( + coverageMinimum := 80, + coverageFailOnMinimum := true, + coverageHighlighting := true, + coverageExcludedPackages := List( + "", + "definition.*", + "sandbox.*", + "live.*", + "prod.*", + "testOnlyDoNotUseInAppConf.*", + "uk\\.gov\\.hmrc\\.config.*", + "app.Routes", + "app.RoutesPrefix", + "controllers.javascript", + "com\\.kenshoo\\.play\\.metrics.*", + ".*Reverse.*", + "uk\\.gov\\.hmrc\\.controllers\\.Reverse.*", + ).mkString(";") + ) +} \ No newline at end of file diff --git a/project/build.properties b/project/build.properties index 0837f7a1..dbae93bc 100644 --- a/project/build.properties +++ b/project/build.properties @@ -1 +1 @@ -sbt.version=1.3.13 +sbt.version=1.4.9 diff --git a/project/plugins.sbt b/project/plugins.sbt index 965340ea..91e02ade 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -1,10 +1,8 @@ resolvers += "HMRC-open-artefacts-maven" at "https://open.artefacts.tax.service.gov.uk/maven2" resolvers += Resolver.url("HMRC-open-artefacts-ivy", url("https://open.artefacts.tax.service.gov.uk/ivy2"))(Resolver.ivyStylePatterns) -addSbtPlugin("uk.gov.hmrc" % "sbt-auto-build" % "2.14.0") -addSbtPlugin("uk.gov.hmrc" % "sbt-git-versioning" % "2.2.0") +addSbtPlugin("uk.gov.hmrc" % "sbt-auto-build" % "3.0.0") addSbtPlugin("uk.gov.hmrc" % "sbt-distributables" % "2.1.0") -addSbtPlugin("uk.gov.hmrc" % "sbt-artifactory" % "1.13.0") addSbtPlugin("com.typesafe.play" % "sbt-plugin" % "2.6.24") addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.6.0") @@ -16,5 +14,4 @@ addSbtPlugin("org.scalastyle" %% "scalastyle-sbt-plugin" % "1.0.0") addSbtPlugin("ch.epfl.scala" % "sbt-bloop" % "1.4.8") -addSbtPlugin("net.virtual-void" % "sbt-dependency-graph" % "0.10.0-RC1") diff --git a/run_in_stub_mode.sh b/run_in_stub_mode.sh deleted file mode 100755 index 963b06eb..00000000 --- a/run_in_stub_mode.sh +++ /dev/null @@ -1,3 +0,0 @@ -#!/bin/bash - -sbt "~run -Drun.mode=Stub -Dhttp.port=9680 $*" diff --git a/run_local.sh b/run_local.sh index a86fa6fe..c925821b 100755 --- a/run_local.sh +++ b/run_local.sh @@ -1,3 +1,3 @@ #!/bin/bash -sbt "run -Drun.mode=Dev -Dhttp.port=9680 $*" +sbt "run -Dhttp.port=9680 $*" diff --git a/run_local_with_dependencies.sh b/run_local_with_dependencies.sh index 293f96f3..73012a74 100755 --- a/run_local_with_dependencies.sh +++ b/run_local_with_dependencies.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash sm --start ASSETS_FRONTEND -r 3.11.0 -sm --start API_DEFINITION THIRD_PARTY_APPLICATION API_EXAMPLE_MICROSERVICE API_PLATFORM_MICROSERVICE +sm --start API_DEFINITION THIRD_PARTY_APPLICATION API_EXAMPLE_MICROSERVICE API_PLATFORM_MICROSERVICE THIRD_PARTY_DEVELOPER_FRONTEND CONTACT_FRONTEND ./run_local.sh diff --git a/test/uk/gov/hmrc/apidocumentation/FiltersSpec.scala b/test/uk/gov/hmrc/apidocumentation/FiltersSpec.scala index 8a7cb44e..26ad17a8 100644 --- a/test/uk/gov/hmrc/apidocumentation/FiltersSpec.scala +++ b/test/uk/gov/hmrc/apidocumentation/FiltersSpec.scala @@ -16,22 +16,18 @@ package unit.uk.gov.hmrc.apidocumentation -import akka.actor.ActorSystem -import akka.stream.{ActorMaterializer, Materializer} -import org.mockito.Matchers.{any, eq => meq} -import org.mockito.Mockito.{never, verify, when} -import org.scalatestplus.mockito.MockitoSugar import play.api.mvc.{RequestHeader, Result, Session} import play.api.test.FakeRequest import uk.gov.hmrc.apidocumentation.SessionRedirectFilter -import uk.gov.hmrc.play.test.UnitSpec +import uk.gov.hmrc.apidocumentation.common.utils.AsyncHmrcSpec import scala.concurrent.{ExecutionContext, Future} +import play.api.test.NoMaterializer +import akka.stream.Materializer -class FiltersSpec(implicit ec: ExecutionContext) extends UnitSpec with MockitoSugar { +class FiltersSpec(implicit ec: ExecutionContext) extends AsyncHmrcSpec { trait Setup { - implicit val sys = ActorSystem("FiltersSpec") - implicit val mat: Materializer = ActorMaterializer() + implicit val mat: Materializer = NoMaterializer val mockResult = mock[Result] when(mockResult.withSession(any[Session])).thenReturn(mockResult) @@ -53,7 +49,7 @@ class FiltersSpec(implicit ec: ExecutionContext) extends UnitSpec with MockitoSu await(filter.apply(nextFilter)(requestHeader)) - verify(mockResult).withSession(meq(Session(defaultSession.toMap + ("access_uri" -> path)))) + verify(mockResult).withSession(eqTo(Session(defaultSession.toMap + ("access_uri" -> path)))) } "remove the current uri in the session when the path is for the index page" in new Setup { @@ -66,7 +62,7 @@ class FiltersSpec(implicit ec: ExecutionContext) extends UnitSpec with MockitoSu await(filter.apply(nextFilter)(requestHeader)) - verify(mockResult).withSession(meq(Session(defaultSession.toMap))) + verify(mockResult).withSession(eqTo(Session(defaultSession.toMap))) } "not add the current uri to the session when the path is not for a documentation page" in new Setup { diff --git a/test/uk/gov/hmrc/apidocumentation/connectors/ApiPlatformMicroserviceConnectorSpec.scala b/test/uk/gov/hmrc/apidocumentation/connectors/ApiPlatformMicroserviceConnectorSpec.scala index 3e0e4476..b6d238dc 100644 --- a/test/uk/gov/hmrc/apidocumentation/connectors/ApiPlatformMicroserviceConnectorSpec.scala +++ b/test/uk/gov/hmrc/apidocumentation/connectors/ApiPlatformMicroserviceConnectorSpec.scala @@ -18,14 +18,12 @@ package uk.gov.hmrc.apidocumentation.connectors import java.util.UUID -import org.mockito.Mockito.when -import play.api.http.Status.INTERNAL_SERVER_ERROR +import play.api.Configuration +import play.api.http.Status.{INTERNAL_SERVER_ERROR} import uk.gov.hmrc.apidocumentation.config.ApplicationConfig import uk.gov.hmrc.apidocumentation.utils.ApiPlatformMicroserviceHttpMockingHelper import uk.gov.hmrc.http.HeaderCarrier -import uk.gov.hmrc.play.bootstrap.http.HttpClient -import scala.concurrent.ExecutionContext.Implicits.global import uk.gov.hmrc.http.UpstreamErrorResponse import uk.gov.hmrc.apidocumentation.models.UuidIdentifier import uk.gov.hmrc.apidocumentation.models.UserId @@ -38,26 +36,28 @@ class ApiPlatformMicroserviceConnectorSpec extends ConnectorSpec { val bearer = "TestBearerToken" val apiKeyTest = UUID.randomUUID().toString - trait LocalSetup extends ApiPlatformMicroserviceHttpMockingHelper { - val mockConfig = mock[ApplicationConfig] - override val mockHttpClient: HttpClient = mock[HttpClient] - - override val apiPlatformMicroserviceBaseUrl = "/mockUrl" - when(mockConfig.apiPlatformMicroserviceBaseUrl).thenReturn(apiPlatformMicroserviceBaseUrl) + val serviceName = "someService" + val userId = UuidIdentifier(UserId.random) - val serviceName = "someService" - val userId = UuidIdentifier(UserId.random) + val apiName1 = "Calendar" + val apiName2 = "HelloWorld" - val apiName1 = "Calendar" - val apiName2 = "HelloWorld" + val stubConfig = Configuration( + "metrics.jvm" -> false, + "microservice.services.api-platform-microservice.host" -> stubHost, + "microservice.services.api-platform-microservice.port" -> stubPort + ) - val underTest = new ApiPlatformMicroserviceConnector(mockHttpClient, mockConfig) + trait LocalSetup extends ApiPlatformMicroserviceHttpMockingHelper { + val config = app.injector.instanceOf[ApplicationConfig] + val apiPlatformMicroserviceBaseUrl = config.apiPlatformMicroserviceBaseUrl + val underTest = app.injector.instanceOf[ApiPlatformMicroserviceConnector] } "fetchApiDefinitionsByCollaborator" should { "call the underlying http client with the user id argument" in new LocalSetup { - whenGetAllDefinitionsByUserId(Some(userId))(apiDefinition(apiName1), apiDefinition(apiName2)) + whenGetAllDefinitionsByUserId(userId)(apiDefinition(apiName1), apiDefinition(apiName2)) val result = await(underTest.fetchApiDefinitionsByCollaborator(Some(userId))) @@ -66,7 +66,7 @@ class ApiPlatformMicroserviceConnectorSpec extends ConnectorSpec { } "call the underlying http client without a user id argument" in new LocalSetup { - whenGetAllDefinitionsByUserId(None)(apiDefinition(apiName1), apiDefinition(apiName2)) + whenGetAllDefinitionsByUserId(apiDefinition(apiName1), apiDefinition(apiName2)) val result = await(underTest.fetchApiDefinitionsByCollaborator(None)) @@ -75,7 +75,7 @@ class ApiPlatformMicroserviceConnectorSpec extends ConnectorSpec { } "throw an exception correctly" in new LocalSetup { - whenGetAllDefinitionsFails(UpstreamException) + whenGetAllDefinitionsFails(400) intercept[UpstreamException.type] { await(underTest.fetchApiDefinitionsByCollaborator(None)) @@ -104,7 +104,7 @@ class ApiPlatformMicroserviceConnectorSpec extends ConnectorSpec { } "throw an exception correctly" in new LocalSetup { - whenGetDefinitionFails(serviceName)(UpstreamException) + whenGetDefinitionFails(serviceName)(400) intercept[UpstreamException.type] { await(underTest.fetchApiDefinition(serviceName, None)) diff --git a/test/uk/gov/hmrc/apidocumentation/connectors/ConnectorSpec.scala b/test/uk/gov/hmrc/apidocumentation/connectors/ConnectorSpec.scala index fa6450de..eb1ad3df 100644 --- a/test/uk/gov/hmrc/apidocumentation/connectors/ConnectorSpec.scala +++ b/test/uk/gov/hmrc/apidocumentation/connectors/ConnectorSpec.scala @@ -16,14 +16,22 @@ package uk.gov.hmrc.apidocumentation.connectors -import org.scalatest.concurrent.ScalaFutures -import org.scalatestplus.mockito.MockitoSugar +import play.api.{Application, Configuration} import play.api.libs.json.Json import uk.gov.hmrc.apidocumentation.models.{APIDefinition, ExtendedAPIDefinition} import uk.gov.hmrc.apidocumentation.models.JsonFormatters._ -import uk.gov.hmrc.play.test.UnitSpec +import uk.gov.hmrc.apidocumentation.common.utils._ +import org.scalatestplus.play.guice.GuiceOneAppPerSuite +import play.api.inject.guice.GuiceApplicationBuilder -trait ConnectorSpec extends UnitSpec with ScalaFutures with MockitoSugar { +trait ConnectorSpec extends AsyncHmrcSpec with WireMockSugar with WireMockSugarExtensions with GuiceOneAppPerSuite { + + def stubConfig: Configuration + + override def fakeApplication(): Application = + GuiceApplicationBuilder() + .configure(stubConfig) + .build() def extendedApiDefinition(name: String) = { Json.parse(s"""{ diff --git a/test/uk/gov/hmrc/apidocumentation/connectors/DeveloperFrontendConnectorSpec.scala b/test/uk/gov/hmrc/apidocumentation/connectors/DeveloperFrontendConnectorSpec.scala index 1a81826e..d4084c4e 100644 --- a/test/uk/gov/hmrc/apidocumentation/connectors/DeveloperFrontendConnectorSpec.scala +++ b/test/uk/gov/hmrc/apidocumentation/connectors/DeveloperFrontendConnectorSpec.scala @@ -16,28 +16,28 @@ package uk.gov.hmrc.apidocumentation.connectors -import org.mockito.Matchers.{any, eq => meq} -import org.mockito.Mockito.when +import com.github.tomakehurst.wiremock.client.WireMock._ import play.twirl.api.Html import uk.gov.hmrc.apidocumentation.config.ApplicationConfig import uk.gov.hmrc.apidocumentation.models._ import uk.gov.hmrc.http.HeaderCarrier -import uk.gov.hmrc.play.bootstrap.http.HttpClient -import uk.gov.hmrc.play.http.metrics.{API, NoopApiMetrics} import uk.gov.hmrc.play.partials.HtmlPartial - -import scala.concurrent.ExecutionContext.Implicits.global -import scala.concurrent.Future +import play.api.test.Helpers._ +import uk.gov.hmrc.apidocumentation.models.JsonFormatters._ +import play.api.Configuration +import uk.gov.hmrc.play.http.metrics.API class DeveloperFrontendConnectorSpec extends ConnectorSpec { val developerFrontendUrl = "http://developer-frontend.example.com" - trait Setup { - val mockHttpClient = mock[HttpClient] - val mockAppConfig = mock[ApplicationConfig] - val connector = new DeveloperFrontendConnector(mockHttpClient, mockAppConfig, new NoopApiMetrics) + val stubConfig = Configuration( + "microservice.services.developer-frontend.host" -> stubHost, + "microservice.services.developer-frontend.port" -> stubPort + ) - when(mockAppConfig.developerFrontendBaseUrl).thenReturn(developerFrontendUrl) + trait Setup { + val config = app.injector.instanceOf[ApplicationConfig] + val connector = app.injector.instanceOf[DeveloperFrontendConnector] } "api" should { @@ -51,8 +51,16 @@ class DeveloperFrontendConnectorSpec extends ConnectorSpec { "return fetched nav links and pass headers by" in new Setup { implicit val hc = HeaderCarrier(extraHeaders = Seq("possibleAuthHeader" -> "possibleAuthHeaderVal")) - when(mockHttpClient.GET[Seq[NavLink]](meq(s"$developerFrontendUrl/developer/user-navlinks"))(any(), any(), any())) - .thenReturn(Future.successful(Seq(NavLink("Some random link", "/developer/345435345342523534253245")))) + stubFor( + get( + urlPathEqualTo("/developer/user-navlinks") + ) + .willReturn( + aResponse() + .withStatus(OK) + .withJsonBody(Seq(NavLink("Some random link", "/developer/345435345342523534253245"))) + ) + ) val result = await(connector.fetchNavLinks()) result shouldBe List(NavLink("Some random link", "/developer/345435345342523534253245", false)) @@ -64,8 +72,16 @@ class DeveloperFrontendConnectorSpec extends ConnectorSpec { implicit val hc = HeaderCarrier() val response = HtmlPartial.Success(None, Html("

some terms of use

")) - when(mockHttpClient.GET[HtmlPartial](meq(s"$developerFrontendUrl/developer/partials/terms-of-use"))(any(), any(), any())) - .thenReturn(Future.successful(response)) + stubFor( + get( + urlPathEqualTo("/developer/partials/terms-of-use") + ) + .willReturn( + aResponse() + .withStatus(OK) + .withBody(response.content.toString) + ) + ) val result = await(connector.fetchTermsOfUsePartial()) result shouldBe response diff --git a/test/uk/gov/hmrc/apidocumentation/connectors/DownloadConnectorSpec.scala b/test/uk/gov/hmrc/apidocumentation/connectors/DownloadConnectorSpec.scala index 5bb0167c..45b21cc5 100644 --- a/test/uk/gov/hmrc/apidocumentation/connectors/DownloadConnectorSpec.scala +++ b/test/uk/gov/hmrc/apidocumentation/connectors/DownloadConnectorSpec.scala @@ -16,9 +16,8 @@ package uk.gov.hmrc.apidocumentation.connectors -import org.mockito.Mockito.when import play.api.http.Status._ -import play.api.mvc.Results +import play.api.mvc.Results._ import play.api.routing.sird._ import play.api.test.WsTestClient import play.core.server.Server @@ -26,14 +25,19 @@ import uk.gov.hmrc.apidocumentation.config.ApplicationConfig import uk.gov.hmrc.http.{HeaderCarrier, InternalServerException, NotFoundException} import scala.concurrent.ExecutionContext.Implicits.global +import play.api.Configuration class DownloadConnectorSpec extends ConnectorSpec { val apiDocumentationUrl = "https://api-documentation.example.com" val serviceName = "hello-world" val version = "1.0" + val stubConfig = Configuration( + "Test.metrics.jvm" -> false + ) trait Setup { + implicit val hc = HeaderCarrier() val mockAppConfig = mock[ApplicationConfig] when(mockAppConfig.apiPlatformMicroserviceBaseUrl).thenReturn("") @@ -42,7 +46,6 @@ class DownloadConnectorSpec extends ConnectorSpec { "downloadResource" should { "return resource when found" in new Setup { Server.withRouterFromComponents() { components => - import Results._ import components.{defaultActionBuilder => Action} { case GET(p"/combined-api-definitions/hello-world/1.0/documentation/some/resource") => Action { @@ -60,7 +63,6 @@ class DownloadConnectorSpec extends ConnectorSpec { "throw NotFoundException when not found" in new Setup { Server.withRouterFromComponents() { components => - import Results._ import components.{defaultActionBuilder => Action} { case GET(p"/combined-api-definitions/hello-world/1.0/documentation/some/resourceNotThere") => Action { @@ -80,7 +82,6 @@ class DownloadConnectorSpec extends ConnectorSpec { "throw InternalServerException for any other response" in new Setup { Server.withRouterFromComponents() { components => - import Results._ import components.{defaultActionBuilder => Action} { case GET(p"/combined-api-definitions/hello-world/1.0/documentation/some/resourceInvalid") => Action { diff --git a/test/uk/gov/hmrc/apidocumentation/connectors/ProxiedHttpClientSpec.scala b/test/uk/gov/hmrc/apidocumentation/connectors/ProxiedHttpClientSpec.scala index 2c104d75..72eda031 100644 --- a/test/uk/gov/hmrc/apidocumentation/connectors/ProxiedHttpClientSpec.scala +++ b/test/uk/gov/hmrc/apidocumentation/connectors/ProxiedHttpClientSpec.scala @@ -19,18 +19,13 @@ package uk.gov.hmrc.apidocumentation.connectors import java.util.UUID import akka.actor.ActorSystem -import org.mockito.Matchers.any -import org.mockito.Mockito.when -import org.scalatest.concurrent.ScalaFutures -import org.scalatestplus.mockito.MockitoSugar -import play.api.{ConfigLoader, Configuration, Mode} +import play.api.{ConfigLoader, Configuration} import play.api.libs.ws.{WSClient, WSRequest} -import uk.gov.hmrc.http.logging.Authorization +import uk.gov.hmrc.http.Authorization import uk.gov.hmrc.play.audit.http.HttpAuditing -import uk.gov.hmrc.play.bootstrap.config.RunMode -import uk.gov.hmrc.play.test.UnitSpec +import uk.gov.hmrc.apidocumentation.common.utils.AsyncHmrcSpec -class ProxiedHttpClientSpec extends UnitSpec with ScalaFutures with MockitoSugar { +class ProxiedHttpClientSpec extends AsyncHmrcSpec { private val actorSystem = ActorSystem("test-actor-system") @@ -41,15 +36,13 @@ class ProxiedHttpClientSpec extends UnitSpec with ScalaFutures with MockitoSugar val mockConfig: Configuration = mock[Configuration] val mockHttpAuditing: HttpAuditing = mock[HttpAuditing] val mockWsClient: WSClient = mock[WSClient] - val mockRunMode: RunMode = mock[RunMode] - when(mockRunMode.env).thenReturn(Mode.Test.toString) when(mockConfig.get[String](any[String])(any[ConfigLoader[String]])).thenReturn("") when(mockConfig.get[Int](any[String])(any[ConfigLoader[Int]])).thenReturn(0) - when(mockConfig.get[Boolean]("Test.proxy.proxyRequiredForThisEnvironment")).thenReturn(true) + when(mockConfig.get[Boolean]("proxy.proxyRequiredForThisEnvironment")).thenReturn(true) when(mockWsClient.url(url)).thenReturn(mock[WSRequest]) - val underTest = new ProxiedHttpClient(mockConfig, mockHttpAuditing, mockWsClient, actorSystem, mockRunMode) + val underTest = new ProxiedHttpClient(mockConfig, mockHttpAuditing, mockWsClient, actorSystem) } "withHeaders" should { @@ -59,7 +52,7 @@ class ProxiedHttpClientSpec extends UnitSpec with ScalaFutures with MockitoSugar private val result = underTest.withHeaders(bearerToken, apiKey) result.authorization shouldBe Some(Authorization(s"Bearer $bearerToken")) - result.apiKeyHeader shouldBe Some("x-api-key" -> apiKey) + result.apiKeyHeader shouldBe Some(apiKey) } "when apiKey is empty String, apiKey header is None" in new Setup { diff --git a/test/uk/gov/hmrc/apidocumentation/connectors/UserSessionConnectorSpec.scala b/test/uk/gov/hmrc/apidocumentation/connectors/UserSessionConnectorSpec.scala index a10895b4..44a1d6e1 100644 --- a/test/uk/gov/hmrc/apidocumentation/connectors/UserSessionConnectorSpec.scala +++ b/test/uk/gov/hmrc/apidocumentation/connectors/UserSessionConnectorSpec.scala @@ -16,29 +16,28 @@ package uk.gov.hmrc.apidocumentation.connectors -import org.mockito.Matchers.{any, eq => meq} -import org.mockito.Mockito.when -import uk.gov.hmrc.apidocumentation.config.ApplicationConfig import uk.gov.hmrc.apidocumentation.models.{Developer, LoggedInState, Session, SessionInvalid} import uk.gov.hmrc.http.HeaderCarrier -import uk.gov.hmrc.play.bootstrap.http.HttpClient -import uk.gov.hmrc.play.http.metrics.{API, NoopApiMetrics} +import uk.gov.hmrc.play.http.metrics.API -import scala.concurrent.ExecutionContext.Implicits.global -import scala.concurrent.Future import uk.gov.hmrc.apidocumentation.models.UserId +import play.api.Configuration +import com.github.tomakehurst.wiremock.client.WireMock._ +import play.api.test.Helpers._ +import uk.gov.hmrc.apidocumentation.models.JsonFormatters._ class UserSessionConnectorSpec extends ConnectorSpec { val thirdPartyDeveloperUrl = "https://third-party-developer.example.com" val sessionId = "A_SESSION_ID" + val stubConfig = Configuration( + "metrics.jvm" -> false, + "microservice.services.third-party-developer.host" -> stubHost, + "microservice.services.third-party-developer.port" -> stubPort + ) trait Setup { implicit val hc = HeaderCarrier() - val mockHttpClient = mock[HttpClient] - val mockAppConfig = mock[ApplicationConfig] - val connector = new UserSessionConnector(mockHttpClient, mockAppConfig, new NoopApiMetrics) - - when(mockAppConfig.thirdPartyDeveloperUrl).thenReturn(thirdPartyDeveloperUrl) + val connector = app.injector.instanceOf[UserSessionConnector] } "api" should { @@ -51,8 +50,16 @@ class UserSessionConnectorSpec extends ConnectorSpec { "return the session when found" in new Setup { val session = Session(sessionId, LoggedInState.LOGGED_IN, Developer("developer@example.com", "Firstname", "Lastname", UserId.random)) - when(mockHttpClient.GET[Option[Session]](meq(s"$thirdPartyDeveloperUrl/session/$sessionId"))(any(), any(), any())) - .thenReturn(Future.successful(Some(session))) + stubFor( + get( + urlPathEqualTo(s"/session/$sessionId") + ) + .willReturn( + aResponse() + .withStatus(OK) + .withJsonBody(session) + ) + ) val result = await(connector.fetchSession(sessionId)) @@ -60,9 +67,15 @@ class UserSessionConnectorSpec extends ConnectorSpec { } "throw SessionInvalid when not found" in new Setup { - when(mockHttpClient.GET[Option[Session]](meq(s"$thirdPartyDeveloperUrl/session/$sessionId"))(any(), any(), any())) - .thenReturn(Future.successful(None)) - + stubFor( + get( + urlPathEqualTo(s"/session/$sessionId") + ) + .willReturn( + aResponse() + .withStatus(NOT_FOUND) + ) + ) intercept[SessionInvalid] { await(connector.fetchSession(sessionId)) } diff --git a/test/uk/gov/hmrc/apidocumentation/controllers/ApiDocumentationControllerSpec.scala b/test/uk/gov/hmrc/apidocumentation/controllers/ApiDocumentationControllerSpec.scala index 86fe5ecf..1d7c1a41 100644 --- a/test/uk/gov/hmrc/apidocumentation/controllers/ApiDocumentationControllerSpec.scala +++ b/test/uk/gov/hmrc/apidocumentation/controllers/ApiDocumentationControllerSpec.scala @@ -16,8 +16,7 @@ package uk.gov.hmrc.apidocumentation.controllers -import org.mockito.Matchers.any -import org.mockito.Mockito.when +import play.api.test.Helpers._ import play.api.http.Status.{INTERNAL_SERVER_ERROR, NOT_FOUND, OK, SEE_OTHER} import play.api.mvc.MessagesControllerComponents import uk.gov.hmrc.apidocumentation.models._ @@ -25,9 +24,9 @@ import uk.gov.hmrc.apidocumentation.views.html._ import uk.gov.hmrc.apidocumentation.ErrorHandler import uk.gov.hmrc.apidocumentation.mocks.services._ import uk.gov.hmrc.apidocumentation.controllers.utils._ -import uk.gov.hmrc.apidocumentation.utils.ApiDefinitionTestDataHelper import uk.gov.hmrc.http.NotFoundException import uk.gov.hmrc.apidocumentation.mocks.config._ +import scala.concurrent.Future.successful import scala.concurrent.ExecutionContext.Implicits.global import scala.concurrent.Future.failed @@ -35,7 +34,7 @@ import uk.gov.hmrc.apidocumentation.models.apispecification.{ApiSpecification, D import uk.gov.hmrc.apidocumentation.connectors.RamlPreviewConnector import uk.gov.hmrc.apidocumentation.controllers.ApiDocumentationController.RamlParseException -class ApiDocumentationControllerSpec extends CommonControllerBaseSpec with PageRenderVerification with ApiDefinitionTestDataHelper { +class ApiDocumentationControllerSpec extends CommonControllerBaseSpec with PageRenderVerification { trait Setup extends ApiDocumentationServiceMock with AppConfigMock @@ -120,9 +119,9 @@ class ApiDocumentationControllerSpec extends CommonControllerBaseSpec with PageR "redirect to the documentation page for the specified version" in new Setup { theUserIsLoggedIn() theDefinitionServiceWillReturnAnApiDefinition(extendedApiDefinition(serviceName, "1.0")) - val result = await(underTest.redirectToApiDocumentation(serviceName, Some(version), Option(true))(request)) + val result = underTest.redirectToApiDocumentation(serviceName, Some(version), Option(true))(request) status(result) shouldBe SEE_OTHER - result.header.headers.get("location") shouldBe Some(s"/api-documentation/docs/api/service/hello-world/${version}?cacheBuster=true") + headers(result).get("location") shouldBe Some(s"/api-documentation/docs/api/service/hello-world/${version}?cacheBuster=true") } } @@ -132,9 +131,9 @@ class ApiDocumentationControllerSpec extends CommonControllerBaseSpec with PageR "redirect to the documentation page" in new Setup { theUserIsLoggedIn() theDefinitionServiceWillReturnAnApiDefinition(extendedApiDefinition(serviceName, "1.0")) - val result = await(underTest.redirectToApiDocumentation(serviceName, version, Option(true))(request)) + val result = underTest.redirectToApiDocumentation(serviceName, version, Option(true))(request) status(result) shouldBe SEE_OTHER - result.header.headers.get("location") shouldBe Some(s"/api-documentation/docs/api/service/hello-world/1.0?cacheBuster=true") + headers(result).get("location") shouldBe Some(s"/api-documentation/docs/api/service/hello-world/1.0?cacheBuster=true") } "redirect to the documentation page for api in private trial for user without authorisation" in new Setup { @@ -143,9 +142,9 @@ class ApiDocumentationControllerSpec extends CommonControllerBaseSpec with PageR APIAccessType.PRIVATE, loggedIn = true, authorised = false, isTrial = Some(true)) theDefinitionServiceWillReturnAnApiDefinition(privateTrialAPIDefinition) - val result = await(underTest.redirectToApiDocumentation(serviceName, None, Option(true))(request)) + val result = underTest.redirectToApiDocumentation(serviceName, None, Option(true))(request) status(result) shouldBe SEE_OTHER - result.header.headers.get("location") shouldBe Some(s"/api-documentation/docs/api/service/hello-world/1.0?cacheBuster=true") + headers(result).get("location") shouldBe Some(s"/api-documentation/docs/api/service/hello-world/1.0?cacheBuster=true") } "redirect to the documentation page for api in private trial for user with authorisation" in new Setup { @@ -154,9 +153,9 @@ class ApiDocumentationControllerSpec extends CommonControllerBaseSpec with PageR APIAccessType.PRIVATE, loggedIn = true, authorised = true, isTrial = Some(true)) theDefinitionServiceWillReturnAnApiDefinition(privateTrialAPIDefinition) - val result = await(underTest.redirectToApiDocumentation(serviceName, None, Option(true))(request)) + val result = underTest.redirectToApiDocumentation(serviceName, None, Option(true))(request) status(result) shouldBe SEE_OTHER - result.header.headers.get("location") shouldBe Some(s"/api-documentation/docs/api/service/hello-world/1.0?cacheBuster=true") + headers(result).get("location") shouldBe Some(s"/api-documentation/docs/api/service/hello-world/1.0?cacheBuster=true") } "redirect to the documentation page for the latest accessible version" in new Setup { @@ -185,9 +184,9 @@ class ApiDocumentationControllerSpec extends CommonControllerBaseSpec with PageR ) theDefinitionServiceWillReturnAnApiDefinition(apiDefinition) - val result = await(underTest.redirectToApiDocumentation("hello-world", version, Option(true))(request)) + val result = underTest.redirectToApiDocumentation("hello-world", version, Option(true))(request) status(result) shouldBe SEE_OTHER - result.header.headers.get("location") shouldBe Some("/api-documentation/docs/api/service/hello-world/1.0?cacheBuster=true") + headers(result).get("location") shouldBe Some("/api-documentation/docs/api/service/hello-world/1.0?cacheBuster=true") } "display the not found page when invalid service specified" in new Setup { @@ -461,7 +460,7 @@ class ApiDocumentationControllerSpec extends CommonControllerBaseSpec with PageR "render 500 page when service throws exception" in new Setup with RamlPreviewEnabled { val url = "http://host:port/some.path.to.a.raml.document" - when(ramlPreviewConnector.fetchPreviewApiSpecification(any())(any())).thenReturn(failed(RamlParseException("Expected unit test failure"))) + when(ramlPreviewConnector.fetchPreviewApiSpecification(*)(*)).thenReturn(failed(RamlParseException("Expected unit test failure"))) val result = underTest.previewApiDocumentation(Some(url))(request) verifyErrorPageRendered(expectedStatus = INTERNAL_SERVER_ERROR, expectedError = "Expected unit test failure")(result) } @@ -469,16 +468,10 @@ class ApiDocumentationControllerSpec extends CommonControllerBaseSpec with PageR } "bustCache" should { - "override value of the query parameter if in stub mode" in new Setup { - underTest.bustCache(stubMode = false, Some(true)) shouldBe true - underTest.bustCache(stubMode = false, Some(false)) shouldBe false - underTest.bustCache(stubMode = true, Some(true)) shouldBe true - underTest.bustCache(stubMode = true, Some(false)) shouldBe true - } - - "return true if no query parameter was provided and the app is running in Stub mode" in new Setup { - underTest.bustCache(stubMode = false, None) shouldBe false - underTest.bustCache(stubMode = true, None) shouldBe true + "honour the passed in parameter" in new Setup { + underTest.bustCache(Some(true)) shouldBe true + underTest.bustCache(Some(false)) shouldBe false + underTest.bustCache(None) shouldBe false } } @@ -491,11 +484,10 @@ class ApiDocumentationControllerSpec extends CommonControllerBaseSpec with PageR TestEndpoint("{service-url}/employers-paye/ddd") ) - when(documentationService.buildTestEndpoints(any(), any())(any())).thenReturn(endpoints) + when(documentationService.buildTestEndpoints(*, *)(*)).thenReturn(successful(endpoints)) val result = underTest.fetchTestEndpointJson("employers-paye", "1.0")(request) - val actualPage = await(result) - actualPage.header.status shouldBe OK - bodyOf(actualPage) should include regex s"aaa.*ddd.*www.*zzz" + status(result) shouldBe OK + contentAsString(result) should include regex s"aaa.*ddd.*www.*zzz" } } diff --git a/test/uk/gov/hmrc/apidocumentation/controllers/CommonControllerBaseSpec.scala b/test/uk/gov/hmrc/apidocumentation/controllers/CommonControllerBaseSpec.scala index c3fa6760..4c527f45 100644 --- a/test/uk/gov/hmrc/apidocumentation/controllers/CommonControllerBaseSpec.scala +++ b/test/uk/gov/hmrc/apidocumentation/controllers/CommonControllerBaseSpec.scala @@ -16,10 +16,8 @@ package uk.gov.hmrc.apidocumentation.controllers -import org.scalatest.concurrent.ScalaFutures -import org.scalatestplus.mockito.MockitoSugar +import play.api.test.Helpers._ import org.scalatestplus.play.guice.GuiceOneAppPerSuite -import play.api.http.Status._ import play.api.mvc._ import play.api.test.FakeRequest import play.api.Application @@ -28,18 +26,11 @@ import uk.gov.hmrc.apidocumentation.models._ import uk.gov.hmrc.apidocumentation.models.APIAccessType.APIAccessType import uk.gov.hmrc.apidocumentation.utils.ApiDefinitionTestDataHelper import uk.gov.hmrc.http.HeaderCarrier -import uk.gov.hmrc.play.test.UnitSpec +import uk.gov.hmrc.apidocumentation.common.utils.AsyncHmrcSpec import scala.concurrent.Future -class CommonControllerBaseSpec - extends UnitSpec - with ScalaFutures - with MockitoSugar - with ApiDefinitionTestDataHelper - with GuiceOneAppPerSuite - { - +class CommonControllerBaseSpec extends AsyncHmrcSpec with ApiDefinitionTestDataHelper with GuiceOneAppPerSuite { override def fakeApplication(): Application = GuiceApplicationBuilder() .configure(("metrics.jvm", false)) @@ -125,21 +116,19 @@ class CommonControllerBaseSpec def aServiceGuide(name: String) = ServiceGuide(name, "context") - def verifyRedirectToLoginPage(actualPageFuture: Future[Result], service: String, version: String) { - val actualPage = await(actualPageFuture) + def verifyRedirectToLoginPage(actualPage: Future[Result], service: String, version: String) { status(actualPage) shouldBe 303 - actualPage.header.headers.get("Location") shouldBe Some("/developer/login") - actualPage.session.get("access_uri") shouldBe Some(s"/api-documentation/docs/api/service/$service/$version") + headers(actualPage).get("Location") shouldBe Some("/developer/login") + session(actualPage).get("access_uri") shouldBe Some(s"/api-documentation/docs/api/service/$service/$version") } def pageTitle(pagePurpose: String) = s"$pagePurpose - HMRC Developer Hub - GOV.UK" - def isPresentAndCorrect(includesText: String, title: String)(fResult: Future[Result]): Unit = { - val result = await(fResult) + def isPresentAndCorrect(includesText: String, title: String)(result: Future[Result]): Unit = { status(result) shouldBe OK - bodyOf(result) should include(includesText) - bodyOf(result) should include(pageTitle(title)) + contentAsString(result) should include(includesText) + contentAsString(result) should include(pageTitle(title)) } } diff --git a/test/uk/gov/hmrc/apidocumentation/controllers/DocumentationControllerSpec.scala b/test/uk/gov/hmrc/apidocumentation/controllers/DocumentationControllerSpec.scala index 9c8c174f..9bbc7324 100644 --- a/test/uk/gov/hmrc/apidocumentation/controllers/DocumentationControllerSpec.scala +++ b/test/uk/gov/hmrc/apidocumentation/controllers/DocumentationControllerSpec.scala @@ -16,10 +16,9 @@ package uk.gov.hmrc.apidocumentation.controllers -import org.mockito.Matchers.any -import org.mockito.Mockito.when import play.api.http.Status.MOVED_PERMANENTLY import play.api.mvc._ +import play.api.test.Helpers._ import play.twirl.api.Html import uk.gov.hmrc.apidocumentation.{controllers, ErrorHandler} import uk.gov.hmrc.apidocumentation.connectors.DeveloperFrontendConnector @@ -29,8 +28,6 @@ import uk.gov.hmrc.apidocumentation.services.PartialsService import uk.gov.hmrc.apidocumentation.views.html._ import uk.gov.hmrc.apidocumentation.mocks.services._ import uk.gov.hmrc.apidocumentation.mocks.config._ - -import uk.gov.hmrc.http.HeaderCarrier import uk.gov.hmrc.play.partials.HtmlPartial import scala.concurrent.ExecutionContext.Implicits.global @@ -99,7 +96,7 @@ class DocumentationControllerSpec "DocumentationController" should { "fetch the terms of use from third party developer and render them in the terms of use page" in new Setup { when( - developerFrontendConnector.fetchTermsOfUsePartial()(any[HeaderCarrier]) + developerFrontendConnector.fetchTermsOfUsePartial()(*) ).thenReturn( Future.successful( HtmlPartial.Success(None, Html("

blah blah blah

")) @@ -144,9 +141,9 @@ class DocumentationControllerSpec } "display the Income Tax (MTD) End-to-End Service Guide page" in new Setup { - val result = await(underTest.mtdIncomeTaxServiceGuidePage()(request)) + val result = underTest.mtdIncomeTaxServiceGuidePage()(request) status(result) shouldBe MOVED_PERMANENTLY - result.header.headers.get("Location") shouldBe Some( + headers(result).get("Location") shouldBe Some( "/guides/income-tax-mtd-end-to-end-service-guide/" ) } diff --git a/test/uk/gov/hmrc/apidocumentation/controllers/DownloadControllerSpec.scala b/test/uk/gov/hmrc/apidocumentation/controllers/DownloadControllerSpec.scala index 14739206..8d4ad2bc 100644 --- a/test/uk/gov/hmrc/apidocumentation/controllers/DownloadControllerSpec.scala +++ b/test/uk/gov/hmrc/apidocumentation/controllers/DownloadControllerSpec.scala @@ -16,8 +16,6 @@ package uk.gov.hmrc.apidocumentation.controllers -import org.mockito.Matchers.any -import org.mockito.Mockito._ import play.api.http.Status._ import play.api.mvc._ import uk.gov.hmrc.apidocumentation.ErrorHandler diff --git a/test/uk/gov/hmrc/apidocumentation/controllers/PageRenderVerification.scala b/test/uk/gov/hmrc/apidocumentation/controllers/PageRenderVerification.scala index 46f9536a..9f75e74b 100644 --- a/test/uk/gov/hmrc/apidocumentation/controllers/PageRenderVerification.scala +++ b/test/uk/gov/hmrc/apidocumentation/controllers/PageRenderVerification.scala @@ -16,54 +16,57 @@ package uk.gov.hmrc.apidocumentation.controllers.utils -import play.api.http.Status._ +import play.api.test.Helpers._ import play.api.mvc._ import uk.gov.hmrc.apidocumentation.controllers.{routes, CommonControllerBaseSpec} import uk.gov.hmrc.apidocumentation.models._ import uk.gov.hmrc.apidocumentation.mocks.services.NavigationServiceMock import scala.concurrent.Future +import play.api.test.NoMaterializer trait PageRenderVerification { self: CommonControllerBaseSpec => import NavigationServiceMock.sidebarLink + private implicit val materializer = NoMaterializer + lazy val homeBreadcrumb = Crumb("Home", routes.DocumentationController.indexPage().url) lazy val apiDocsBreadcrumb = Crumb("API Documentation", routes.ApiDocumentationController.apiIndexPage(None, None, None).url) - def titleOf(result: Result) = { + def titleOf(result: Future[Result]) = { val titleRegEx = """]*>(.*)""".r - val title = titleRegEx.findFirstMatchIn(bodyOf(result)).map(_.group(1)) + val title = titleRegEx.findFirstMatchIn(contentAsString(result)).map(_.group(1)) title.isDefined shouldBe true title.get } - def subNavIsRendered(result: Result) = { - bodyOf(result).contains("