本文整理汇总了Scala中uk.gov.hmrc.play.test.UnitSpec类的典型用法代码示例。如果您正苦于以下问题:Scala UnitSpec类的具体用法?Scala UnitSpec怎么用?Scala UnitSpec使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了UnitSpec类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: FieldMappingsSpec
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.agentmappingfrontend.controllers
import org.scalatest.EitherValues
import play.api.data.FormError
import uk.gov.hmrc.play.test.UnitSpec
class FieldMappingsSpec extends UnitSpec with EitherValues {
"utr bind" should {
val utrMapping = utr.withPrefix("testKey")
def bind(fieldValue: String) = utrMapping.bind(Map("testKey" -> fieldValue))
"accept valid UTRs" in {
bind("2000000000") shouldBe Right("2000000000")
}
"give \"error.required\" error when it is not supplied" in {
utrMapping.bind(Map.empty).left.value should contain only FormError("testKey", "error.required")
}
"give \"error.required\" error when it is empty" in {
bind("").left.value should contain only FormError("testKey", "error.required")
}
"give \"error.required\" error when it only contains a space" in {
bind(" ").left.value should contain only FormError("testKey", "error.required")
}
"give \"error.utr.invalid\" error when it is invalid" in {
bind("20000000000").left.value should contain only FormError("testKey", "error.utr.invalid")
}
}
"arn bind" should {
val arnMapping = arn.withPrefix("testKey")
def bind(fieldValue: String) = arnMapping.bind(Map("testKey" -> fieldValue))
"accept valid ARN" in {
bind("TARN0000001") shouldBe Right("TARN0000001")
}
"give \"error.required\" error when it is not supplied" in {
arnMapping.bind(Map.empty).left.value should contain only FormError("testKey", "error.required")
}
"give \"error.required\" error when it is empty" in {
bind("").left.value should contain only FormError("testKey", "error.required")
}
"give \"error.required\" error when it only contains a space" in {
bind(" ").left.value should contain only FormError("testKey", "error.required")
}
"give \"error.arn.invalid\" error when it is invalid" in {
bind("ARN0000001").left.value should contain only FormError("testKey", "error.arn.invalid")
}
}
}
示例2: get
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.ups.controllers
import org.scalatest.BeforeAndAfterAll
import org.scalatest.concurrent.ScalaFutures
import org.scalatestplus.play.{OneServerPerSuite, WsScalaTestClient}
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.ws.WSRequest
import uk.gov.hmrc.play.test.UnitSpec
trait DatabaseName {
val testName: String = "updated-print-suppressions"
}
trait TestServer
extends ScalaFutures
with DatabaseName
with UnitSpec
with BeforeAndAfterAll
with OneServerPerSuite
with WsScalaTestClient {
override implicit lazy val app = new GuiceApplicationBuilder()
.configure(Map("auditing.enabled" -> false,
"mongodb.uri" -> "mongodb://localhost:27017/updated-print-suppressions",
"application.router" -> "testOnlyDoNotUseInAppConf.Routes"
))
.build()
def `/preferences/sa/individual/print-suppression`(updatedOn: Option[String], offset: Option[String], limit: Option[String], isAdmin: Boolean = false) = {
val queryString = List(
updatedOn.map(value => "updated-on" -> value),
offset.map(value => "offset" -> value),
limit.map(value => "limit" -> value)
).flatten
if (isAdmin)
wsUrl("/test-only/preferences/sa/individual/print-suppression").withQueryString(queryString: _*)
else
wsUrl("/preferences/sa/individual/print-suppression").withQueryString(queryString: _*)
}
def get(url: WSRequest) = url.get().futureValue
}
示例3: SectionEmptyValuesMatchingSpec
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.decisionservice
import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures}
import org.scalatest.{BeforeAndAfterEach, Inspectors, LoneElement}
import uk.gov.hmrc.decisionservice.model._
import uk.gov.hmrc.decisionservice.model.rules.{SectionCarryOver, SectionRule, SectionRuleSet}
import uk.gov.hmrc.decisionservice.ruleengine.SectionFactMatcher
import uk.gov.hmrc.play.test.UnitSpec
class SectionEmptyValuesMatchingSpec extends UnitSpec with BeforeAndAfterEach with ScalaFutures with LoneElement with Inspectors with IntegrationPatience {
"section fact with empty values matcher" should {
"produce fact error when fact is missing answers for which there is no match and corresponding rule values are not all empty in any of the rules" in {
val fact = Map(
("question1" -> "yes"),
("question2" -> ""),
("question3" -> ""))
val rules = List(
SectionRule(List("yes","yes","yes"), SectionCarryOver("high" , true)),
SectionRule(List("yes","no" ,"no" ), SectionCarryOver("medium", true)),
SectionRule(List("no" ,"yes","" ), SectionCarryOver("low" , false))
)
val ruleSet = SectionRuleSet(List("question1", "question2", "question3"), rules)
val response = SectionFactMatcher.matchFacts(fact, ruleSet)
response.isLeft shouldBe true
response.leftMap { error =>
error shouldBe a [FactError]
}
}
"produce rules error when fact is missing answers for which there is no match but corresponding rule values are empty in at least one rule" in {
val fact = Map(
("question1" -> "yes"),
("question2" -> ""),
("question3" -> ""))
val rules = List(
SectionRule(List("yes","yes","yes"), SectionCarryOver("high" , true)),
SectionRule(List("yes","no" ,"" ), SectionCarryOver("medium", true)),
SectionRule(List("no" ,"" ,"" ), SectionCarryOver("low" , false))
)
val ruleSet = SectionRuleSet(List("question1", "question2", "question3"), rules)
val response = SectionFactMatcher.matchFacts(fact, ruleSet)
response.isLeft shouldBe true
response.leftMap { error =>
error shouldBe a [RulesFileError]
}
}
}
}
示例4: EmptyValuesValidatorSpec
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.decisionservice
import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures}
import org.scalatest.{BeforeAndAfterEach, Inspectors, LoneElement}
import uk.gov.hmrc.decisionservice.model.rules.{SectionCarryOver, SectionRule}
import uk.gov.hmrc.decisionservice.model._
import uk.gov.hmrc.decisionservice.ruleengine.EmptyValuesValidator
import uk.gov.hmrc.play.test.UnitSpec
class EmptyValuesValidatorSpec extends UnitSpec with BeforeAndAfterEach with ScalaFutures with LoneElement with Inspectors with IntegrationPatience {
object SectionEmptyValuesValidator extends EmptyValuesValidator {
type ValueType = String
type Rule = SectionRule
type RuleResult = SectionCarryOver
def valueEmpty(s: String) = s.isEmpty
}
"empty values validator" should {
"produce fact error if FactsEmptySet is a subset of MaximumRulesEmptySet" in {
val fact = Map(
("question1" -> "yes"),
("question2" -> ""),
("question3" -> ""))
val rules = List(
SectionRule(List("yes","yes","yes"), SectionCarryOver("high" , true)),
SectionRule(List("yes","no" ,"no" ), SectionCarryOver("medium", true)),
SectionRule(List("no" ,"yes","" ), SectionCarryOver("low" , false))
)
val error = SectionEmptyValuesValidator.noMatchError(fact,rules)
error shouldBe a [FactError]
}
"produce rules error if FactsEmptySet is a superset of MaximumRulesEmptySet" in {
val fact = Map(
("question1" -> "yes"),
("question2" -> ""),
("question3" -> ""))
val rules = List(
SectionRule(List("yes","yes","yes"), SectionCarryOver("high" , true)),
SectionRule(List("yes","no" ,"" ), SectionCarryOver("medium", true)),
SectionRule(List("no" ,"" ,"" ), SectionCarryOver("low" , false))
)
val error = SectionEmptyValuesValidator.noMatchError(fact,rules)
error shouldBe a [RulesFileError]
}
}
}
示例5: MatrixRulesLoaderSpec
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.decisionservice
import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures}
import org.scalatest.{BeforeAndAfterEach, Inspectors, LoneElement}
import uk.gov.hmrc.decisionservice.model.RulesFileLoadError
import uk.gov.hmrc.decisionservice.model.rules.SectionCarryOver
import uk.gov.hmrc.decisionservice.ruleengine.{MatrixFactMatcher, MatrixRulesLoader, RulesFileMetaData}
import uk.gov.hmrc.play.test.UnitSpec
class MatrixRulesLoaderSpec extends UnitSpec with BeforeAndAfterEach with ScalaFutures with LoneElement with Inspectors with IntegrationPatience {
val csvFilePath = "/matrix.csv"
val csvFilePathError = "/matrix_error.csv"
val csvMetadata = RulesFileMetaData(2, 1, csvFilePath)
val csvMetadataError = RulesFileMetaData(2, 1, csvFilePathError)
"matrix rules loader" should {
"load matrix rules from a csv file" in {
val maybeRules = MatrixRulesLoader.load(csvMetadata)
maybeRules.isRight shouldBe true
maybeRules.map { ruleset =>
ruleset.rules should have size 3
ruleset.headings should have size 2
}
}
"return error if file is not found" in {
val maybeRules = MatrixRulesLoader.load(RulesFileMetaData(2, 1, csvFilePath + "xx"))
maybeRules.isLeft shouldBe true
maybeRules.leftMap { error =>
error shouldBe a [RulesFileLoadError]
}
}
"return error if file contains invalid data" in {
val maybeRules = MatrixRulesLoader.load(csvMetadataError)
maybeRules.isLeft shouldBe true
maybeRules.leftMap { error =>
error shouldBe a [RulesFileLoadError]
}
}
"provide valid input for an inference against fact" in {
val matrixFacts = Map(
("BusinessStructure" -> SectionCarryOver("high", true)), ("Substitute" -> SectionCarryOver("high" , false))
)
val maybeRules = MatrixRulesLoader.load(csvMetadata)
maybeRules.isRight shouldBe true
maybeRules.map { ruleset =>
ruleset.rules should have size 3
ruleset.headings should have size 2
val response = MatrixFactMatcher.matchFacts(matrixFacts, ruleset)
response.isRight shouldBe true
response.map { decision =>
decision.value should equal("out of IR35")
}
}
}
}
}
示例6: MatrixEmptyValuesMatchingSpec
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.decisionservice
import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures}
import org.scalatest.{BeforeAndAfterEach, Inspectors, LoneElement}
import uk.gov.hmrc.decisionservice.model._
import uk.gov.hmrc.decisionservice.model.rules.{MatrixDecision, MatrixRule, MatrixRuleSet, SectionCarryOver}
import uk.gov.hmrc.decisionservice.ruleengine.MatrixFactMatcher
import uk.gov.hmrc.play.test.UnitSpec
class MatrixEmptyValuesMatchingSpec extends UnitSpec with BeforeAndAfterEach with ScalaFutures with LoneElement with Inspectors with IntegrationPatience {
"matrix fact with empty values matcher" should {
"produce fact error when fact is missing answers for which rule values are not empty" in {
val matrixFacts = Map(
("BusinessStructure" -> SectionCarryOver("high", true)),
("Substitute" -> SectionCarryOver("" , false)),
("FinancialRisk" -> SectionCarryOver("" , false))
)
val matrixRules = List(
MatrixRule(List(SectionCarryOver("high" , true ),SectionCarryOver("high" , true ),SectionCarryOver("low" , true )), MatrixDecision("self employed")),
MatrixRule(List(SectionCarryOver("high" , true ),SectionCarryOver("low" , false),SectionCarryOver("low" , true )), MatrixDecision("in IR35")),
MatrixRule(List(SectionCarryOver("medium", true ),SectionCarryOver("high", true ),SectionCarryOver("low" , true )), MatrixDecision("out of IR35"))
)
val matrixRuleSet = MatrixRuleSet(List("BusinessStructure", "Substitute", "FinancialRisk"), matrixRules)
val response = MatrixFactMatcher.matchFacts(matrixFacts, matrixRuleSet)
println(response)
response.isLeft shouldBe true
response.leftMap { error =>
error shouldBe a [FactError]
}
}
"produce rules error when fact is missing answers for which there is no match but corresponding rule values are empty in at least one rule" in {
val matrixFacts = Map(
("BusinessStructure" -> SectionCarryOver("high", true)),
("Substitute" -> SectionCarryOver("" , false)),
("FinancialRisk" -> SectionCarryOver("" , false))
)
val matrixRules = List(
MatrixRule(List(SectionCarryOver("high" , true ),SectionCarryOver("high" , true ),SectionCarryOver("low" , true )), MatrixDecision("self employed")),
MatrixRule(List(SectionCarryOver("high" , true ),SectionCarryOver("low" , false),SectionCarryOver("low" , true )), MatrixDecision("in IR35")),
MatrixRule(List(SectionCarryOver("medium", true ),SectionCarryOver("", true ),SectionCarryOver("" , true )), MatrixDecision("out of IR35"))
)
val matrixRuleSet = MatrixRuleSet(List("BusinessStructure", "Substitute", "FinancialRisk"), matrixRules)
val response = MatrixFactMatcher.matchFacts(matrixFacts, matrixRuleSet)
println(response)
response.isLeft shouldBe true
response.leftMap { error =>
error shouldBe a [RulesFileError]
}
}
}
}
示例7: DecisionRequestSpec
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.decisionservice
import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures}
import org.scalatest.{BeforeAndAfterEach, Inspectors, LoneElement}
import play.api.libs.json.{JsValue, Json}
import uk.gov.hmrc.decisionservice.model.api.{Section, QuestionSet}
import uk.gov.hmrc.play.test.UnitSpec
class DecisionRequestSpec extends UnitSpec with BeforeAndAfterEach with ScalaFutures with LoneElement with Inspectors with IntegrationPatience {
val json =
"""
|{
| "version" : "1.0",
| "sections" : [ {
| "name" : "personal-service",
| "facts" : {
| "1" : true,
| "2" : false,
| "3" : true
| }
| } ]
|}
|
""".stripMargin
"decision request json" should {
"be correctly converted to Scala object" in {
val parsed = Json.parse(json)
val jsResult = Json.fromJson[QuestionSet](parsed)
jsResult.isSuccess shouldBe true
val obj = jsResult.get
obj.sections should have size 1
obj.sections(0).facts should have size 3
val m:Map[String,Boolean] = obj.sections(0).facts
val res = (1 to 3).flatMap(i => m.get(i.toString))
res should contain theSameElementsInOrderAs (List(true, false, true))
}
}
"decision request Scala object" should {
"be correctly converted to json object" in {
val personalServiceQuestions = Map("1" -> true, "2" -> false, "3" -> true)
val helperQuestions = Map("1" -> false, "2" -> false, "3" -> false)
val controlQuestions = Map("1" -> true, "2" -> true, "3" -> true)
val sections = List(
Section("personal-service", personalServiceQuestions),
Section("helper", helperQuestions),
Section("control", controlQuestions)
)
val decisionRequest = QuestionSet("1.0", sections)
val jsValue:JsValue = Json.toJson(decisionRequest)
val jsections = jsValue \\ "sections"
val jfacts = jsValue \\ "facts"
jsections should have size 1
jfacts should have size 3
}
}
}
示例8: MatrixFactMatcherSpec
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.decisionservice
import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures}
import org.scalatest.{BeforeAndAfterEach, Inspectors, LoneElement}
import uk.gov.hmrc.decisionservice.model._
import uk.gov.hmrc.decisionservice.model.rules.{MatrixDecision, MatrixRule, MatrixRuleSet, SectionCarryOver}
import uk.gov.hmrc.decisionservice.ruleengine.MatrixFactMatcher
import uk.gov.hmrc.play.test.UnitSpec
class MatrixFactMatcherSpec extends UnitSpec with BeforeAndAfterEach with ScalaFutures with LoneElement with Inspectors with IntegrationPatience {
"matrix fact matcher" should {
"produce correct result for a sample matrix fact" in {
val matrixFacts = Map(
("BusinessStructure" -> SectionCarryOver("high", true)), ("Substitute" -> SectionCarryOver("high" , false))
)
val matrixRules = List(
MatrixRule(List(SectionCarryOver("high" , true ),SectionCarryOver("low" , true )), MatrixDecision("in IR35")),
MatrixRule(List(SectionCarryOver("high" , true ),SectionCarryOver("high", false)), MatrixDecision("out of IR35")),
MatrixRule(List(SectionCarryOver("medium", true ),SectionCarryOver("high", true )), MatrixDecision("in IR35"))
)
val matrixRuleSet = MatrixRuleSet(List("BusinessStructure", "Substitute"), matrixRules)
val response = MatrixFactMatcher.matchFacts(matrixFacts, matrixRuleSet)
response.isRight shouldBe true
response.map { decision =>
decision.value should equal("out of IR35")
}
}
"produce correct result for a partial fact" in {
val matrixFacts = Map(
("BusinessStructure" -> SectionCarryOver("high", true)),
("Substitute" -> SectionCarryOver("low" , false)),
("FinancialRisk" -> SectionCarryOver("" , false))
)
val matrixRules = List(
MatrixRule(List(SectionCarryOver("high" , true ),SectionCarryOver("high" , true ),SectionCarryOver("" , true )), MatrixDecision("self employed")),
MatrixRule(List(SectionCarryOver("high" , true ),SectionCarryOver("low" , false),SectionCarryOver("" , true )), MatrixDecision("in IR35")),
MatrixRule(List(SectionCarryOver("medium", true ),SectionCarryOver("high", true ),SectionCarryOver("low" , true )), MatrixDecision("out of IR35"))
)
val matrixRuleSet = MatrixRuleSet(List("BusinessStructure", "Substitute", "FinancialRisk"), matrixRules)
val response = MatrixFactMatcher.matchFacts(matrixFacts, matrixRuleSet)
response.isRight shouldBe true
response.map { decision =>
decision.value should equal("in IR35")
}
}
}
}
示例9: SectionRulesLoaderSpec
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.decisionservice
import org.scalatest.concurrent.{IntegrationPatience, ScalaFutures}
import org.scalatest.{BeforeAndAfterEach, Inspectors, LoneElement}
import uk.gov.hmrc.decisionservice.model.RulesFileLoadError
import uk.gov.hmrc.decisionservice.ruleengine.{RulesFileMetaData, SectionFactMatcher, SectionRulesLoader}
import uk.gov.hmrc.play.test.UnitSpec
class SectionRulesLoaderSpec extends UnitSpec with BeforeAndAfterEach with ScalaFutures with LoneElement with Inspectors with IntegrationPatience {
val csvFilePath = "/business_structure.csv"
val csvFilePathError = "/business_structure_error.csv"
val csvMetadata = RulesFileMetaData(3, 2, csvFilePath)
val csvMetadataError = RulesFileMetaData(3, 2, csvFilePathError)
"section rules loader" should {
"load section rules from a csv file" in {
val maybeRules = SectionRulesLoader.load(csvMetadata)
maybeRules.isRight shouldBe true
maybeRules.map { ruleset =>
ruleset.rules should have size 4
ruleset.headings should have size 3
}
}
"return error if file is not found" in {
val maybeRules = SectionRulesLoader.load(RulesFileMetaData(3, 2, csvFilePath + "xx"))
maybeRules.isLeft shouldBe true
maybeRules.leftMap { error =>
error shouldBe a [RulesFileLoadError]
}
}
"return error if file contains invalid data" in {
val maybeRules = SectionRulesLoader.load(csvMetadataError)
maybeRules.isLeft shouldBe true
maybeRules.leftMap { error =>
error shouldBe a [RulesFileLoadError]
}
}
"provide valid input for an inference against fact" in {
val fact = Map(
("Q1" -> "yes"),
("Q2" -> "no"),
("Q3" -> "yes"))
val maybeRules = SectionRulesLoader.load(csvMetadata)
maybeRules.isRight shouldBe true
maybeRules.map { ruleset =>
ruleset.rules should have size 4
ruleset.headings should have size 3
val response = SectionFactMatcher.matchFacts(fact, ruleset)
response.isRight shouldBe true
response.map { sectionResult =>
sectionResult.value should equal("low")
sectionResult.exit should equal(true)
}
}
}
}
}
示例10: NoInvitationsPlatformISpec
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.agentinvitations.scenarios
import org.scalatest.{Inside, Inspectors}
import org.scalatest.concurrent.Eventually
import uk.gov.hmrc.agentinvitations.support._
import uk.gov.hmrc.domain.{AgentCode, Nino}
import uk.gov.hmrc.play.test.UnitSpec
class NoInvitationsPlatformISpec extends UnitSpec with MongoAppAndStubs with Inspectors with Inside with Eventually with Requests {
private implicit val arn = RandomArn()
private implicit val agentCode = AgentCode("LMNOP123456")
private val nino: Nino = nextNino
"Before the Agency has sent any invitations" in {
val agency = new AgencyRequests(this, arn, port)
val client = new ClientRequests(this, nino, port)
given().agentAdmin(arn, agentCode).isLoggedInWithSessionId().andIsSubscribedToAgentServices()
given().client(clientId = nino).isLoggedInWithSessionId()
info("the Agency sent invitations should be empty")
val agencyResponse = agency.sentInvitations()
agencyResponse.numberOfInvitations shouldBe 0
agencyResponse.links.invitations shouldBe 'empty
agencyResponse.links.selfLink shouldBe s"/agent-invitations/agencies/${arn.value}/invitations/sent"
agencyResponse.embedded.isEmpty shouldBe true
info("the Clients received invitations should be empty")
val clientResponse = client.getInvitations()
clientResponse.numberOfInvitations shouldBe 0
clientResponse.links.invitations shouldBe 'empty
clientResponse.links.selfLink shouldBe s"/agent-invitations/clients/ni/${nino.value}/invitations/received"
clientResponse.embedded.isEmpty shouldBe true
}
}
示例11: anEndpointAccessibleForMtdAgentsOnly
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.agentinvitations.support
import uk.gov.hmrc.domain.{AgentCode, Nino}
import uk.gov.hmrc.play.http.HttpResponse
import uk.gov.hmrc.play.test.UnitSpec
import uk.gov.hmrc.agentinvitations.controllers.ErrorResults._
trait SecuredEndpointBehaviours extends AkkaMaterializerSpec {
this: UnitSpec with AppAndStubs =>
def anEndpointAccessibleForMtdAgentsOnly(makeRequest: => HttpResponse): Unit = {
"return 401 when the requester is an Agent but not authenticated" in {
given().agentAdmin(RandomArn(), AgentCode("tehCode")).isNotLoggedIn()
makeRequest.status shouldBe 401
makeRequest.body shouldBe bodyOf(GenericUnauthorized)
}
"return 403 Forbidden when the requester is a logged as a NON MTD Agent" in {
given().agentAdmin(RandomArn(), AgentCode("tehCode")).isLoggedIn().andIsNotSubscribedToAgentServices()
makeRequest.status shouldBe 403
makeRequest.body shouldBe bodyOf(AgentNotSubscribed)
}
}
def anEndpointAccessibleForSaClientsOnly(id: Nino)(makeRequest: => HttpResponse): Unit = {
"return 401 when the requester is not authenticated" in {
given().client(clientId = id).isNotLoggedIn()
makeRequest.status shouldBe 401
makeRequest.body shouldBe bodyOf(GenericUnauthorized)
}
}
}
示例12: materializer
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.agentinvitations.support
import akka.stream.ActorMaterializer
import com.fasterxml.jackson.databind.JsonMappingException
import org.scalatest.matchers.{MatchResult, Matcher}
import play.api.mvc.Result
import uk.gov.hmrc.play.http.HttpResponse
import uk.gov.hmrc.play.test.UnitSpec
import scala.util.Try
trait ErrorResultMatchers { this: UnitSpec =>
implicit def materializer: ActorMaterializer
class ErrorResultMatcher(expectedResult: Result) extends Matcher[HttpResponse] {
override def apply(left: HttpResponse): MatchResult = {
val expectedBodyJson = jsonBodyOf(expectedResult)
val rawNegatedFailureMessage =
s"""Response had expected status ${expectedResult.header.status} and body "$expectedBodyJson""""
if (left.status != expectedResult.header.status) {
MatchResult(
false,
s"""Response had status ${left.status} not expected status ${expectedResult.header.status}""",
rawNegatedFailureMessage
)
} else {
Try(left.json)
.map(json =>
MatchResult(
json == expectedBodyJson,
s"""Response had body "$json" not expected body "$expectedBodyJson""",
rawNegatedFailureMessage))
.recover {
case e: JsonMappingException =>
MatchResult(
false,
s"""Response had body "${left.body}" which did not parse as JSON due to exception:\n$e""",
rawNegatedFailureMessage)
}.get
}
}
}
def matchErrorResult(expectedResult: Result) = new ErrorResultMatcher(expectedResult)
}
示例13: RendererControllerISpec
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.hmrcemailrenderer
import org.scalatest.concurrent.ScalaFutures
import org.scalatestplus.play.{OneServerPerSuite, ServerProvider, WsScalaTestClient}
import play.api.libs.json._
import uk.gov.hmrc.play.config.ServicesConfig
import uk.gov.hmrc.play.http.test.ResponseMatchers
import uk.gov.hmrc.play.test.UnitSpec
class RendererControllerISpec extends UnitSpec
with ServicesConfig
with WsScalaTestClient
with OneServerPerSuite
with ScalaFutures
with ResponseMatchers
with ServerProvider {
"POST /templates/:templateId" should {
"return 200 and yield the rendered template data when supplied a valid templateId" in {
val params = Map(
"verificationLink" -> "/abc"
)
val response = wsUrl(s"/templates/verifyEmailAddress").post(Json.obj("parameters" -> params))
response should have(
status(200),
jsonProperty(__ \ "fromAddress", "HMRC digital <[email protected]>"),
jsonProperty(__ \ "subject", "HMRC electronic communications: verify your email address"),
jsonProperty(__ \ "service", "sa"),
jsonProperty(__ \ "plain"),
jsonProperty(__ \ "html")
)
}
"return 404 when a non-existent templateId is specified on the path" in {
wsUrl(s"/templates/nonExistentTemplateId").
post(Json.obj("parameters" -> Map.empty[String, String])) should have(status(404))
}
"return 400 and indicate the first point of failure when the parameters for the template are not supplied" in {
wsUrl(s"/templates/verifyEmailAddress")
.post(Json.obj("parameters" -> Map.empty[String, String])) should have(
status(400),
jsonProperty(__ \ "reason", "key not found: verificationLink")
)
}
}
}
示例14: AuthConnectorISpec
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.agentsubscription.connectors
import java.net.URL
import org.scalatestplus.play.OneAppPerSuite
import uk.gov.hmrc.agentsubscription.WSHttp
import uk.gov.hmrc.agentsubscription.auth.Authority
import uk.gov.hmrc.agentsubscription.stubs.AuthStub
import uk.gov.hmrc.agentsubscription.support.WireMockSupport
import uk.gov.hmrc.play.http.HeaderCarrier
import uk.gov.hmrc.play.http.logging.MdcLoggingExecutionContext._
import uk.gov.hmrc.play.test.UnitSpec
class AuthConnectorISpec extends UnitSpec with OneAppPerSuite with WireMockSupport with AuthStub {
private implicit val hc = HeaderCarrier()
private val authBaseUrl = new URL(s"http://localhost:$wireMockPort")
private lazy val connector: AuthConnector = new AuthConnector(authBaseUrl, WSHttp)
private val authorityUrl = new URL(authBaseUrl, "/auth/authority")
"AuthConnector currentAuthority" should {
"return Authority when an authority detail is available" in {
requestIsAuthenticated().andIsAnAgent()
await(connector.currentAuthority()) shouldBe Some(Authority(
fetchedFrom = authorityUrl,
authProviderId = Some("12345-credId"),
authProviderType = Some("GovernmentGateway"),
affinityGroup = "Agent",
enrolmentsUrl = "/auth/oid/556737e15500005500eaf68f/enrolments"))
}
"return Authority when user-details does not include an auth provider" in {
requestIsAuthenticated().andIsAnAgentWithoutAuthProvider()
await(connector.currentAuthority()) shouldBe Some(Authority(
fetchedFrom = authorityUrl,
authProviderId = None,
authProviderType = None,
affinityGroup = "Agent",
enrolmentsUrl = "/auth/oid/556737e15500005500eaf68f/enrolments"))
}
"return none when an authority detail is unavailable" in {
requestIsNotAuthenticated()
await(connector.currentAuthority()) shouldBe None
}
}
}
示例15: BaseISpec
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.agentsubscription.support
import org.scalatestplus.play.OneServerPerSuite
import play.api.Application
import play.api.inject.guice.GuiceApplicationBuilder
import uk.gov.hmrc.play.test.UnitSpec
abstract class BaseISpec extends UnitSpec with OneServerPerSuite with WireMockSupport {
override implicit lazy val app: Application = appBuilder
.build()
protected def appBuilder: GuiceApplicationBuilder =
new GuiceApplicationBuilder()
.configure(
"microservice.services.auth.port" -> wireMockPort,
"microservice.services.des.port" -> wireMockPort,
"microservice.services.gg.port" -> wireMockPort,
"microservice.services.gg-admin.port" -> wireMockPort
)
}