本文整理汇总了Scala中play.api.http.Status类的典型用法代码示例。如果您正苦于以下问题:Scala Status类的具体用法?Scala Status怎么用?Scala Status使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Status类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: PlayWithFoodWithTestComponents
//设置package包名称以及导入依赖的类
package testhelpers
import config.ExampleComponents
import org.scalatest.BeforeAndAfterEach
import org.scalatestplus.play.PlaySpec
import org.scalatestplus.play.components.OneServerPerTestWithComponents
import play.api.db.evolutions.Evolutions
import play.api.http.Status
import play.api.libs.ws.WSClient
import play.api.test.{DefaultAwaitTimeout, FutureAwaits, Helpers, TestServer}
import play.api.{Application, Configuration}
import slick.dbio.DBIO
trait PlayWithFoodWithServerBaseTest extends PlaySpec
with OneServerPerTestWithComponents
with DefaultFutureDuration
with DefaultExecutionContext
with Status
with DefaultAwaitTimeout
with FutureAwaits
with BeforeAndAfterEach {
class PlayWithFoodWithTestComponents extends ExampleComponents(context) {
override def configuration: Configuration = {
val testConfig = Configuration.from(TestUtils.config)
val config = super.configuration
val testConfigMerged = config ++ testConfig
config.toString
testConfigMerged
}
implicit lazy val testWsClient: WSClient = wsClient
}
override def components: PlayWithFoodWithTestComponents = new PlayWithFoodWithTestComponents
private def runServerAndCleanUpInMemDb(c: PlayWithFoodWithTestComponents) = {
runServerAndExecute(c.application) {
val dbapi = c.dbApi
Evolutions.cleanupEvolutions(dbapi.database("default"))
}
}
override protected def afterEach(): Unit = {
runServerAndCleanUpInMemDb(components)
}
protected def runServerAndExecute[T](app: Application)(blockWithComponents: => T): T = {
Helpers.running(TestServer(port, app))(blockWithComponents)
}
def runAndAwaitResult[T](action: DBIO[T])(implicit components: ExampleComponents): T = {
TestUtils.runAndAwaitResult(action)(components.actionRunner, duration)
}
}
开发者ID:Dasiu,项目名称:play-framework-scala-example-project,代码行数:58,代码来源:PlayWithFoodWithServerBaseTest.scala
示例2: PlaySpecApplication
//设置package包名称以及导入依赖的类
package common
import org.scalatestplus.play.PlaySpec
import play.api.http.{ HeaderNames, HttpProtocol, HttpVerbs, Status }
import play.api.test._
class PlaySpecApplication extends PlaySpec
with PlayRunners
with HeaderNames
with Status
with HttpProtocol
with DefaultAwaitTimeout
with ResultExtractors
with Writeables
with RouteInvokers
with FutureAwaits
with HttpVerbs
示例3: HealthCheckFeature
//设置package包名称以及导入依赖的类
package com.reactivecore.quotes.workshop.api.feature
import com.reactivecore.quotes.workshop.api.QuotesWorkshopApiService
import org.scalatest.concurrent.{PatienceConfiguration, ScalaFutures}
import org.scalatest.time.{Seconds, Span}
import org.scalatest.{FeatureSpec, GivenWhenThen, Matchers}
import play.api.http.Status
class HealthCheckFeature extends FeatureSpec with GivenWhenThen with Matchers with ScalaFutures with PatienceConfiguration {
override implicit val patienceConfig = PatienceConfig(
timeout = scaled(Span(1, Seconds))
)
feature("health check") {
scenario("service is healthy") {
Given("a service")
val service = QuotesWorkshopApiService()
When("getting the /health endpoint")
val response = get(s"http://localhost:${service.port}/health").futureValue
Then("the response status should be OK")
response.status should be(Status.OK)
service.stop()
}
}
}
示例4: OptionsFeature
//设置package包名称以及导入依赖的类
package com.reactivecore.quotes.workshop.api.feature
import com.reactivecore.quotes.workshop.api.QuotesWorkshopApiService
import org.scalatest.concurrent.{PatienceConfiguration, ScalaFutures}
import org.scalatest.time.{Seconds, Span}
import org.scalatest.{FeatureSpec, GivenWhenThen, Matchers}
import play.api.http.Status
class OptionsFeature extends FeatureSpec with GivenWhenThen with Matchers with ScalaFutures with PatienceConfiguration {
override implicit val patienceConfig = PatienceConfig(
timeout = scaled(Span(1, Seconds))
)
feature("options") {
scenario("requests options of /items") {
Given("a service")
val service = QuotesWorkshopApiService()
When("requesting for the options of /items endpoint")
val response = options(s"http://localhost:${service.port}/items").futureValue
Then("the response status should be OK")
response.status should be(Status.OK)
service.stop()
}
}
}
示例5: ControllerTest
//设置package包名称以及导入依赖的类
package play.api.mvc.hal
import org.scalatest.{ FunSuite, Matchers }
import play.api.http.{ HeaderNames, Status }
import play.api.libs.json.Json
import play.api.mvc.{ Controller, Result }
import play.api.test.{ DefaultAwaitTimeout, FakeRequest, ResultExtractors }
import scala.concurrent.Future
class ControllerTest extends FunSuite with Matchers with ResultExtractors with HeaderNames with Status with DefaultAwaitTimeout {
class TestController() extends Controller with HalWriteController
test("A HAL Resource should be writeable") {
val controller = new TestController()
val result: Future[Result] = controller.hal().apply(FakeRequest())
val bodyText: String = contentAsString(result)
contentType(result) should equal(Some("application/hal+json"))
(Json.parse(bodyText) \ "foo").as[String] should equal("bar")
}
test("A Resource can be retrived as JSON") {
val controller = new TestController()
val result: Future[Result] = controller.halOrJson.apply(FakeRequest().withHeaders("Accept" -> "application/json"))
contentType(result) should equal(Some("application/json"))
}
test("A Resource can be retrived as HAL") {
val controller = new TestController()
val result: Future[Result] = controller.halOrJson.apply(FakeRequest().withHeaders("Accept" -> "application/hal+json"))
contentType(result) should equal(Some("application/hal+json"))
}
}
示例6: Problems
//设置package包名称以及导入依赖的类
package microtools.models
import play.api.data.validation.ValidationError
import play.api.http.Status
import play.api.libs.json.{JsPath, Json}
object Problems {
val BAD_REQUEST = Problem.forStatus(Status.BAD_REQUEST, "Bad request")
val UNAUTHORIZED = Problem.forStatus(Status.UNAUTHORIZED, "Unauthorized")
val FORBIDDEN = Problem.forStatus(Status.FORBIDDEN, "Forbidden")
val CONFLICT = Problem.forStatus(Status.CONFLICT, "Conflict")
val NOT_FOUND = Problem.forStatus(Status.NOT_FOUND, "Not found")
val GONE = Problem.forStatus(Status.GONE, "Gone")
val NOT_ACCEPTABLE = Problem.forStatus(Status.NOT_ACCEPTABLE, "Not acceptable")
val FAILED_DEPENDENCY = Problem.forStatus(Status.FAILED_DEPENDENCY, "Failed dependency")
val INTERNAL_SERVER_ERROR =
Problem.forStatus(Status.INTERNAL_SERVER_ERROR, "Internal server error")
val SERVICE_UNAVAILABLE =
Problem.forStatus(Status.SERVICE_UNAVAILABLE, "Service unavailable")
def jsonValidationErrors(jsonErrors: Seq[(JsPath, Seq[ValidationError])]): Problem =
BAD_REQUEST.copy(details = Some(Json.arr(jsonErrors.map {
case (path, errors) =>
Json.obj(
"path" -> path.toString(),
"errors" -> Json.arr(errors.map(_.messages.mkString(", ")))
)
})))
def jsonTransformErrors(jsonErrors: Seq[(JsPath, Seq[ValidationError])]): Problem =
NOT_ACCEPTABLE.copy(details = Some(Json.arr(jsonErrors.map {
case (path, errors) =>
Json.obj(
"path" -> path.toString(),
"errors" -> Json.arr(errors.map(_.messages.mkString(", ")))
)
})))
}
示例7: CheckedAction
//设置package包名称以及导入依赖的类
package microtools.actions
import microtools.models.{Problem, Problems, RequestContext}
import play.api.http.Status
import play.api.mvc.{ActionBuilder, Request, RequestHeader, Result}
import play.mvc.Http.HeaderNames
import scala.concurrent.Future
object CheckedAction {
case class RequestCondition(condition: RequestHeader => Boolean, problem: Problem)
case class CheckedAction(requirements: RequestCondition*) extends ActionBuilder[Request] {
override def invokeBlock[A](
request: Request[A],
block: (Request[A]) => Future[Result]
): Future[Result] = {
requirements
.find(!_.condition(request))
.map { failedCondition =>
Future.successful(failedCondition.problem.asResult(RequestContext.forRequest(request)))
}
.getOrElse {
block(request)
}
}
}
val RequireInternal = RequestCondition(
rh => rh.headers.get("x-zone").contains("internal"),
Problems.FORBIDDEN.withDetails("Only internal requests are allowed")
)
val RequireTLS = RequestCondition(
rh =>
rh.secure || rh.headers
.get(HeaderNames.X_FORWARDED_PROTO)
.contains("https"),
Problem
.forStatus(Status.UPGRADE_REQUIRED, "Upgrade required")
.withDetails("Require secure https")
)
}
示例8: Problem
//设置package包名称以及导入依赖的类
package de.lenabrueder.rfc7807
import de.lenabrueder.rfc7807.Problem.UrlConfiguration
import play.api.http.Status
import play.api.libs.json.JsonNaming.SnakeCase
import play.api.libs.json.{Json, JsonConfiguration}
case class Problem(`type`: String,
title: String,
status: Option[Int] = None,
detail: Option[String] = None,
instance: Option[String] = None)
object Problem {
private implicit val config = JsonConfiguration(SnakeCase)
implicit val format = Json.format[Problem]
sealed trait UrlConfiguration {
def url(code: String): String
}
case object DefaultUrlConfiguration extends UrlConfiguration {
override def url(code: String): String = s"https://httpstatuses.com/$code"
}
case class CustomUrlConfiguration(customUrl: String) extends UrlConfiguration {
def url(code: String) = customUrl.format(code)
}
}
trait LowPriorityProblemImplicits {
implicit val defaultUrlConfiguration = Problem.DefaultUrlConfiguration
}
trait Problematic {
def asProblem: Problem
}
trait EasyProblematic extends Problematic {
def errorCode: String
def message: Option[String] = None
def urlConfiguration: UrlConfiguration
override def asProblem: Problem =
Problem(`type` = urlConfiguration.url(errorCode), title = message getOrElse "unknown")
}
object Problematic {
def fromException(ex: Throwable)(implicit urlConfiguration: UrlConfiguration) = new Problematic {
override def asProblem: Problem = {
ex match {
case p: Problematic => p.asProblem
case _ => Problem(urlConfiguration.url(Status.INTERNAL_SERVER_ERROR.toString), ex.getMessage)
}
}
}
}
示例9: RendererISpec
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.emailrenderertemplate
import org.scalatest.words.EmptyWord
import org.scalatestplus.play.{OneServerPerSuite, PlaySpec, WsScalaTestClient}
import play.api.http.Status
import play.api.libs.json.Json
import play.api.test.Helpers._
class RendererISpec extends PlaySpec with OneServerPerSuite with WsScalaTestClient {
"email renderer" should {
"render the html and text content for sample1 template" in {
val result = await(wsUrl("/templates/sample1").
post(Json.obj("parameters" -> Json.obj("name" -> "Dr. Bruce Banner"))))
result.status mustBe Status.OK
(result.json \ "fromAddress").as[String] mustBe "<sample1> @gov.uk"
(result.json \ "subject").as[String] mustBe "New message for sample1 template"
(result.json \ "service").as[String] mustBe "REPLACE WITH YOUR TAX DOMAIN"
(result.json \ "plain").as[String] mustNot be(new EmptyWord())
(result.json \ "html").as[String] mustNot be(new EmptyWord())
(result.json \ "priority").as[String] mustBe "standard"
}
"return NOT_FOUND if template does not exist" in {
val result = await(wsUrl("/templates/notExistTemplate").
post(Json.obj("parameters" -> Json.obj("name" -> "Dr. Bruce Banner"))))
result.status mustBe NOT_FOUND
(result.json \ "reason").as[String] mustBe "Missing template with id: notExistTemplate"
}
"return BAD_REQUEST if required parameter is not in the request body" in {
val result = await(wsUrl("/templates/sample1").
post(Json.obj("parameters" -> Json.obj("noName" -> "Dr. Bruce Banner"))))
result.status mustBe BAD_REQUEST
(result.json \ "reason").as[String] mustBe "Failed to render template due to: key not found: name"
}
}
}
示例10: AdvertiserControllerSpec
//设置package包名称以及导入依赖的类
package scala.controllers.advert
import models.advert.{Advertiser, AdvertiserBusinessUpdate}
import models.social.{M8User, M8UserList, M8UserPosition}
import play.api.http.Status
import play.api.libs.json.Json
import play.api.test.Helpers._
import play.api.test.{FakeHeaders, FakeRequest, Helpers}
import utils._
class AdvertiserControllerSpec extends UnitSpec {
"AdvertiserController" must {
"get the advert by id" in {
val vladResult = registerVlad.get
val advertiserResult = registerWeiZhengAsAdvertiser.get
M8User.updatePosition(vladResult.userId, M8UserPosition(-25.274398, 133.775126))
Advertiser.confirmEmail(advertiserResult.advertiserId, advertiserResult.emailConfirmToken)
activeAdvertiser(advertiserResult.advertiserId)
Advertiser.updateBusiness(advertiserResult.advertiserId,
AdvertiserBusinessUpdate("Crazydog Apps", Some("012345678"),
Some("www.crazydog.com.au"), "4/15 Robinson Street", -25.274398, 133.775136, "We are a software company"))
val result = M8User.listAdvertsNearby(vladResult.userId, M8UserList(None, None, 0, 10))
val fakeRequest = FakeRequest(Helpers.GET,
controllers.advert.routes.AdvertiserController.getAdvert(result.get(0).advertId).url,
FakeHeaders(Seq(MobileApiTokenHeader -> Seq(mobileApiToken),
MobileAccessTokenHeader -> Seq(vladResult.accessToken))),
Json.obj()
)
verifyHttpResult(route(fakeRequest).get, Status.OK, "Crazydog Apps")
}
}
}
示例11: EffectiveDateResourceTimemachineOffSpec
//设置package包名称以及导入依赖的类
package cjp.catalogue.resource
import java.util.concurrent.TimeUnit
import akka.util.Timeout
import org.joda.time.DateTime
import org.mockito.Mockito._
import cjp.catalogue.repository.EffectiveDateRepository
import org.scalatest.mock.MockitoSugar
import org.scalatest.{Matchers, BeforeAndAfter, WordSpec}
import play.api.GlobalSettings
import play.api.http.{Status, HeaderNames}
import play.api.libs.json.Json
import play.api.mvc.{AnyContentAsJson, AnyContentAsText}
import play.api.test._
class EffectiveDateResourceTimemachineOffSpec extends WordSpec with BeforeAndAfter with PlayRunners with ResultExtractors with HeaderNames with Status with Matchers with MockitoSugar {
implicit val timeout = Timeout(10L, TimeUnit.SECONDS)
private val effectiveDateRepository = mock[EffectiveDateRepository]
private val controller = new EffectiveDateResource(effectiveDateRepository, enableTimemachine = false)
object TestGlobal extends GlobalSettings {
override def getControllerInstance[A](controllerClass: Class[A]): A =
controller.asInstanceOf[A]
}
before {
reset(effectiveDateRepository)
}
"calling PUT /manage/effectiveDate" should {
"return 403 if timemachine feature switch is disabled" in {
running(TestServer(18888, FakeApplication(withGlobal = Some(TestGlobal)))) {
val json = Json.parse("""{"effectiveDate":"2015-04-10T14:12:57.159Z"}""")
val request: FakeRequest[AnyContentAsJson] = FakeRequest().withJsonBody(json).withHeaders("ContentType" -> "application/json")
val result = controller.setEffectiveDate.apply(request)
status(result) should be(403)
verifyZeroInteractions(effectiveDateRepository)
}
}
}
"calling DELETE /manage/effectiveDate" should {
"return 403 if timemachine feature switch is disabled" in {
running(TestServer(18888, FakeApplication(withGlobal = Some(TestGlobal)))) {
val result = controller.resetEffectiveDate.apply(FakeRequest())
status(result) should be(403)
verifyZeroInteractions(effectiveDateRepository)
}
}
}
}
开发者ID:UKHomeOffice,项目名称:product-catalogue,代码行数:57,代码来源:EffectiveDateResourceTimemachineOffSpec.scala
示例12: HealthCheckResourceTest
//设置package包名称以及导入依赖的类
package cjp.catalogue.resource
import java.util.concurrent.TimeUnit
import akka.util.Timeout
import cjp.catalogue.util.BuildInfo
import org.mockito.Mockito._
import org.scalatest.mock.MockitoSugar
import org.scalatest.{BeforeAndAfter, Matchers, WordSpec}
import play.api.http.{HeaderNames, Status}
import play.api.test._
import scala.concurrent.Future
class HealthCheckResourceTest extends WordSpec with BeforeAndAfter with PlayRunners with ResultExtractors with HeaderNames with Status with Matchers with MockitoSugar {
implicit val timeout = Timeout(10L, TimeUnit.SECONDS)
private val buildInfo: Some[BuildInfo] = Some(BuildInfo(1, "lst-commit"))
"calling GET /healthcheck" should {
def healthcheck(reportHealth:Boolean) = {
val mongoHealthCheck = mock[MongoHealthCheck]
when(mongoHealthCheck.ping()).thenReturn(Future successful reportHealth)
val resource = new HealthCheckResource(mongoHealthCheck, buildInfo)
resource.healthCheck()(FakeRequest())
}
"show build info and the string 'healthy' when mongo reports healthy" in {
val result = healthcheck(reportHealth = true)
status(result) should be(200)
contentAsString(result) should be("healthy!\nbuild-number: 1")
}
"show build info and the string 'Unhealthy' when mongo reports unhealthy" in {
val result = healthcheck(reportHealth = false)
status(result) should be(500)
contentAsString(result) should be("unhealthy! Mongo reported a negative response to ping!\nbuild-number: 1")
}
}
"calling GET /ping" should {
"reports pong" in {
val resource = new HealthCheckResource(null, buildInfo)
val result = resource.ping()(FakeRequest())
status(result) should be(200)
contentAsString(result) should be("pong")
}
}
}
示例13: isDeniedEntry
//设置package包名称以及导入依赖的类
package auth.core.util
import javax.inject.Inject
import akka.stream.Materializer
import play.api.Configuration
import play.api.http.Status
import play.api.mvc._
import scala.concurrent.{ExecutionContext, Future}
private def isDeniedEntry(result: Result): Boolean =
result.header.status == Status.FORBIDDEN || result.header.status == Status.UNAUTHORIZED
}
class CookieSettings @Inject()(config: Configuration) {
val name = config.underlying.getString("filters.cookieauth.cookie.name")
val tokenHeader = config.underlying.getString("filters.cookieauth.cookie.token.header")
val maxAge = {
val age = config.underlying.getInt("filters.cookieauth.cookie.maxage")
if (age >= 0) Some(age) else None
}
val path = config.underlying.getString("filters.cookieauth.cookie.path")
val domain = {
val domain = config.underlying.getString("filters.cookieauth.cookie.domain")
if (domain.length >= 0) Some(domain) else None
}
val secure = config.underlying.getBoolean("filters.cookieauth.cookie.secure")
val httpOnly = config.underlying.getBoolean("filters.cookieauth.cookie.httpOnly")
def make(value: String): Cookie =
Cookie(name, value, maxAge, path, domain, secure, httpOnly)
}
示例14: SlackFail
//设置package包名称以及导入依赖的类
package com.kifi.slack.models
import play.api.http.Status
import play.api.http.Status._
import play.api.libs.json._
// Failures on our end that deal with slack
sealed abstract class SlackFail(val status: Int, val code: String, val extra: JsValue = JsNull) extends Exception(s"$code: ${Json.stringify(extra)}") {
import play.api.mvc.Results.Status
def asResponse = Status(status)(Json.obj("error" -> code, "extra" -> extra))
}
object SlackFail {
case object NoAppCredentials extends SlackFail(UNAUTHORIZED, "no_app_credentials")
case object NoAuthCode extends SlackFail(BAD_REQUEST, "no_auth_code")
case object InvalidAuthState extends SlackFail(BAD_REQUEST, "invalid_auth_state")
case class MalformedPayload(payload: JsValue) extends SlackFail(BAD_REQUEST, "malformed_payload", payload)
case class MalformedState(state: SlackAuthState) extends SlackFail(BAD_REQUEST, "malformed_state", JsString(state.state))
case class SlackResponse(response: SlackAPIErrorResponse) extends SlackFail(response.status, response.error, response.payload)
}
// Failures that Slack can give
case class SlackAPIErrorResponse(status: Int, error: String, payload: JsValue) extends Exception(s"$status response: $error ($payload)")
object SlackAPIErrorResponse {
def ApiError(status: Int, payload: JsValue) = SlackAPIErrorResponse(status, (payload \ "error").asOpt[String] getOrElse "api_error", payload)
val TokenRevoked = SlackAPIErrorResponse(Status.NOT_FOUND, SlackErrorCode.TOKEN_REVOKED, JsNull)
val WebhookRevoked = SlackAPIErrorResponse(Status.NOT_FOUND, SlackErrorCode.WEBHOOK_REVOKED, JsNull)
}
object SlackErrorCode {
def unapply(fail: SlackAPIErrorResponse) = Some(fail.error)
val ACCOUNT_INACTIVE = "account_inactive"
val ALREADY_REACTED = "already_reacted"
val CANT_UPDATE_MESSAGE = "cant_update_message"
val CHANNEL_NOT_FOUND = "channel_not_found"
val EDIT_WINDOW_CLOSED = "edit_window_closed"
val INVALID_AUTH = "invalid_auth"
val IS_ARCHIVED = "is_archived"
val MESSAGE_NOT_FOUND = "message_not_found"
val NOT_IN_CHANNEL = "not_in_channel"
val RESTRICTED_ACTION = "restricted_action"
val TOKEN_REVOKED = "token_revoked"
val WEBHOOK_REVOKED = "webhook_revoked"
}
示例15: beforeAll
//设置package包名称以及导入依赖的类
package uk.gov.hmrc.agentfiinvitation.support
import org.scalatest.{BeforeAndAfterAll, Suite}
import org.scalatest.concurrent.ScalaFutures
import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.WireMock
import com.github.tomakehurst.wiremock.client.WireMock._
import com.github.tomakehurst.wiremock.core.WireMockConfiguration._
import play.api.http.Status
trait FakeRelationshipService extends BeforeAndAfterAll with ScalaFutures {
this: Suite =>
val Host = "http://localhost"
val Port = 9427
lazy val wireMockServer = new WireMockServer(wireMockConfig().port(Port))
override def beforeAll(): Unit = {
super.beforeAll()
wireMockServer.start()
WireMock.configureFor(Host, Port)
wireMockServer.addStubMapping(
put(urlPathMatching("/agent-fi-relationship/relationships"))
.willReturn(
aResponse()
.withStatus(Status.CREATED))
.build())
}
override def afterAll(): Unit = {
println("Stopping the mock backend server")
super.afterAll()
wireMockServer.stop()
}
}