本文整理汇总了Scala中play.api.test.PlaySpecification类的典型用法代码示例。如果您正苦于以下问题:Scala PlaySpecification类的具体用法?Scala PlaySpecification怎么用?Scala PlaySpecification使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了PlaySpecification类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: NotFoundPageTest
//设置package包名称以及导入依赖的类
package functional
import me.cs.easypost.Constants
import me.cs.easypost.models.RootModel
import org.junit.runner.RunWith
import org.specs2.runner.JUnitRunner
import play.api.test.{PlaySpecification, WithBrowser}
@RunWith(classOf[JUnitRunner])
class NotFoundPageTest extends PlaySpecification {
val rootModel = new RootModel
"Application" should {
"Display Action Not Found on a bad request" in new WithBrowser {
browser.goTo("/boum")
browser.$(rootModel.TitleId).getTexts().get(0) must equalTo(Constants.ActionNotFound)
}
}
}
示例2: IndexPageTest
//设置package包名称以及导入依赖的类
package me.cs.easypost
import me.cs.easypost.models.RootModel
import org.junit.runner.RunWith
import org.specs2.runner.JUnitRunner
import play.api.test.{PlaySpecification, WithBrowser}
@RunWith(classOf[JUnitRunner])
class IndexPageTest extends PlaySpecification {
val rootModel = new RootModel
"Application" should {
"display correctly the index page" in new WithBrowser {
browser.goTo("/")
browser.$(rootModel.TitleId).getTexts().get(0) must equalTo(rootModel.Title)
}
}
}
示例3: HomeControllerSpec
//设置package包名称以及导入依赖的类
package controllers
import models.UsersRepository
import org.specs2.execute.{AsResult, Result}
import org.specs2.mutable.Around
import org.specs2.specification.Scope
import play.api.Application
import play.api.mvc._
import play.api.test.{FakeRequest, PlaySpecification}
class HomeControllerSpec extends PlaySpecification with Results {
abstract class WithTestApplication extends Around with Scope with TestEnvironment {
lazy val app: Application = fakeApp
lazy val controller = new HomeController(knolxControllerComponent)
override def around[T: AsResult](t: => T): Result = {
TestHelpers.running(app)(AsResult.effectively(t))
}
}
"HomeController" should {
"redirect index page to sessions page" in new WithTestApplication {
val result = controller.index(FakeRequest())
status(result) must be equalTo SEE_OTHER
}
}
}
示例4: LoginAPITestextends
//设置package包名称以及导入依赖的类
package integration.api
import com.github.simplyscala.MongodProps
import org.specs2.mutable.Before
import scala.language.existentials
import play.api.libs.json.Json
import play.api.test.{FakeRequest, PlaySpecification, WithApplication}
class LoginAPITestextends extends PlaySpecification {
"respond to the no login data Action" in new WithApplication {
val Some(result) = route(app, FakeRequest(POST, "/login"))
status(result) must equalTo(400)
}
"response to the with loign data but no authentication" in new WithApplication {
val Some(result) = route(app, FakeRequest(POST, "/login").withJsonBody(Json.parse("""{"username":"no_data", "password":"abc"}""") ))
status(result) must equalTo(401)
contentType(result) must beSome("application/json")
}
"response to the with login data and authentication" in new WithApplication {
val Some(result) = route(app, FakeRequest(POST, "/login").withJsonBody(Json.parse("""{"username":"mubeen", "password":"mubeen"}""")))
status(result) must equalTo(200)
contentType(result) must beSome("application/json")
}
}
示例5: MetaSpec
//设置package包名称以及导入依赖的类
package meta
import macros.Model
import play.api.libs.json.Json
import play.api.test.PlaySpecification
import slick.model.Table
class MetaSpec extends PlaySpecification {
@Model
case class MyTest(int: Int, str: String)
val testee = MyTest(4, "four", "orestis")
"Macro annotations" should {
"augment with account" in {
testee.accountId === "orestis"
}
"define implicit conversion method" in {
Json.toJson(testee) === Json.obj(
"int" -> 4, "str" -> "four", "accountId" -> "orestis"
)
}
"extend to Slick table definition" in {
testee.isInstanceOf[Table] === true
}
}
}
示例6: ApplicationSpec
//设置package包名称以及导入依赖的类
package controllers
import com.knoldus.search.AutoCompleteProcessor
import org.junit.runner.RunWith
import org.specs2.runner.JUnitRunner
import play.api.mvc.Results
import play.api.test.{FakeRequest, PlaySpecification, WithApplication}
import org.specs2.mock.Mockito
@RunWith(classOf[JUnitRunner])
class ApplicationSpec extends PlaySpecification with Results with Mockito {
val mockedProcessor = mock[AutoCompleteProcessor]
val mockedJars = mock[WebJarAssets]
val testController = new Application(mockedJars, mockedProcessor)
"Application" should {
"search suggestion" in new WithApplication {
mockedProcessor.getMatches("java") returns List("java", "javascript", "jQuery")
val result = testController.searchText("java").apply(FakeRequest("GET", "/search_text"))
val resultAsString = contentAsString(result)
resultAsString === """["java","javascript","jQuery"]"""
status(result) must be equalTo 200
}
"search movies" in new WithApplication {
mockedProcessor.getMovies("Batman v Superman: Dawn of Justice") returns List("""{"Title":"Batman v Superman: Dawn of Justice","Year":"2016","Released":"25 Mar 2016","Genre":"Action, Adventure, Sci-Fi","Director":"Zack Snyder","Plot":"steel.","Poster":"http://ia.media-imdb.com/images/M/[email protected]_V1_SX300.jpg","imdbRating":"7.0"}""")
val result = testController.searchMovie("Batman v Superman: Dawn of Justice").apply(FakeRequest("GET", "/search_content"))
status(result) must be equalTo 200
}
}
}
示例7: AutoCompleteProcessorTest
//设置package包名称以及导入依赖的类
package com.knoldus.search
import java.io.File
import com.knoldus.util.ESManager
import org.elasticsearch.action.admin.indices.refresh.RefreshRequest
import org.elasticsearch.client.Client
import org.specs2.specification.BeforeAfterAll
import play.api.test.{PlaySpecification, WithApplication}
import util.TestHelper
import scala.io.Source
class AutoCompleteProcessorTest extends PlaySpecification with TestHelper with BeforeAfterAll {
val autoCompleteProcessor = new AutoCompleteProcessor(new ESManager {
override lazy val client: Client = localClient.client
})
val client: Client = localClient.client
val index = "movie"
override def afterAll = {
client.close()
client.admin().indices().prepareDelete(index).get
}
override def beforeAll = {
val settings = Source.fromFile(new File("extra/es-mapping.json")).mkString
client.admin().indices().prepareCreate(index).setSource(settings).get
val bulkRequest = client.prepareBulk()
Source.fromFile(new File("extra/movies.json")).getLines().foreach {
movie => bulkRequest.add(client.prepareIndex(index, "movies").setSource(movie))
}
bulkRequest.get()
client.admin().indices().refresh(new RefreshRequest(index)).get
}
"Play Specification" should {
"autocomplete" in new WithApplication {
val result = autoCompleteProcessor.getMatches("go")
assert(result === List("Gone Girl"))
}
"get movies" in new WithApplication {
val result = autoCompleteProcessor.getMovies("Gone Girl")
assert(result.head.contains("Gone Girl"))
}
}
}
开发者ID:knoldus,项目名称:activator-play-elasticsearch-autocomplete.g8,代码行数:54,代码来源:AutoCompleteProcessorTest.scala
示例8: IssueDAOSpec
//设置package包名称以及导入依赖的类
package issue.model
import java.util.Date
import models.issue.{ Issue, IssueDAO, Status }
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
import play.api.test.PlaySpecification
import scalikejdbc.specs2.mutable.AutoRollback
import scalikejdbc._
import setting.DBTestSetting
@RunWith(classOf[JUnitRunner])
class IssueDAOSpec extends PlaySpecification with DBTestSetting {
sequential
val issueDAO = new IssueDAO
"IssueDAO.list" should {
"return all issue list " in new AutoRollback {
sql"""INSERT INTO issue(issue, raised_date, challenge, status)
VALUES ('Write some code handing error in controller', '2016-10-18', 'Dont understand how to handle error', 'DONE')"""
.update().apply()
val issues = issueDAO.list.get
issues must haveSize(1)
issues.head.status.status must beEqualTo("DONE")
issues.head.issue must beEqualTo("Write some code handing error in controller")
issues.head.challenge must beEqualTo("Dont understand how to handle error")
}
"return empty Seq if there is no issue" in new AutoRollback {
val issues = issueDAO.list.get
issues must beEmpty
}
}
"IssueDAO.save" should {
"return genereated key " in new AutoRollback {
val dummyIssue = Issue(0, "Write some code handing error in controller", "Dont understand how to handle error",
new Date(), Status.NOT_YET)
val generatedKey = issueDAO.save(dummyIssue)
generatedKey.get.toInt should be > 0
}
}
}
示例9: UserDAOSpec
//设置package包名称以及导入依赖的类
package user.model
import models.exception.EntityNotFound
import models.user.{ User, UserDAO }
import play.api.test.PlaySpecification
import setting.DBTestSetting
import scalikejdbc._
import scalikejdbc.specs2.AutoRollback
import scala.util.{ Failure, Success }
class UserDAOSpec extends PlaySpecification with DBTestSetting {
val userDAO = new UserDAO
val name = "Tinh"
val email = "[email protected]"
val password = "1234"
val encryptPassword = "03ac674216f3e15c761ee1a5e255f067953623c8b388b4459e13f978d7c846f4"
trait AutoRollbackFeature extends AutoRollback {
sql"""
insert into user(`name`,`email`,`password`) values(${name},${email},${encryptPassword})
""".update().apply()
}
"UserDAO " should {
"authenticate(email: String, password: String) " should {
"return user if email and password are correct" in new AutoRollbackFeature {
val user = userDAO.authenticate(email, password).get
user.name must beEqualTo(name)
user.email must beEqualTo(email)
user.password must beEqualTo(encryptPassword)
}
}
"return none if password is same but email is different" in new AutoRollbackFeature {
userDAO.authenticate("[email protected]", password) must beEqualTo(Failure(EntityNotFound("Entity not found")))
}
"return none if email is same but password is different" in new AutoRollbackFeature {
userDAO.authenticate(email, "123") must beEqualTo(Failure(EntityNotFound("Entity not found")))
}
"return none if email and password are different" in new AutoRollbackFeature {
userDAO.authenticate("[email protected]", "123") must beEqualTo(Failure(EntityNotFound("Entity not found")))
}
}
}
示例10: VehiclesControllerSpec
//设置package包名称以及导入依赖的类
package controllers
import play.api.data.FormError
import play.api.mvc.Controller
import play.api.test.{PlaySpecification, WithApplication, FakeRequest}
import repositories.VehiclesFakeRepository
class VehiclesControllerSpec extends PlaySpecification {
trait Context extends Controller with VehiclesController {
def vehiclesRepository = new VehiclesFakeRepository {}
}
"Vehicles controller" should {
"present search" in new WithApplication with Context {
val result = searchPrompt(FakeRequest())
status(result) mustEqual OK
}
"give details of a vehicle" in new WithApplication with Context {
val result = search(FakeRequest().withFormUrlEncodedBody("registration" -> vehiclesRepository.ford.registration,
"make" -> vehiclesRepository.ford.make))
status(result) mustEqual OK
}
}
"Vehicles form" should {
"read from request" in new WithApplication with Context {
val formBinding = form.bind(Map("registration" -> "BLAH", "make" -> "BLAH")) // TODO Validations e.g. PP is not a valid registration.
formBinding.get mustEqual ("BLAH", "BLAH")
}
"give errors for missing data" in new WithApplication with Context {
val formBinding = form.bind(Map.empty[String, String])
formBinding.errors must contain(exactly(FormError("registration", "error.required"), FormError("make", "error.required")))
}
}
}
示例11: SecurityFilterSpec
//设置package包名称以及导入依赖的类
package org.zalando.zhewbacca
import play.api.inject._
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.mvc.Results._
import play.api.mvc._
import play.api.test.{FakeRequest, PlaySpecification}
import play.api.{Application, Mode}
class SecurityFilterSpec extends PlaySpecification with BodyParsers {
val TestTokenInfo = TokenInfo("", Scope.Empty, "token type", "user uid")
val routes: PartialFunction[(String, String), Handler] = {
// test action returning action type. Shows the usage and makes it possible to test basic behaviour
// security rules described in 'security_filter.conf' file
case ("GET", "/") => Action { request =>
import TokenInfoConverter._
Ok(request.tokenInfo.tokenType)
}
case ("GET", "/unprotected") => Action {
Ok
}
}
def appWithRoutes: Application = new GuiceApplicationBuilder()
.in(Mode.Test)
.bindings(bind[AuthProvider] to new AlwaysPassAuthProvider(TestTokenInfo))
.routes(routes)
.configure(
"play.http.filters" -> "org.zalando.zhewbacca.TestingFilters",
"authorisation.rules.file" -> "security_filter.conf"
)
.build
"SecurityFilter" should {
"allow protected inner action to access token info" in {
val response = route(appWithRoutes, FakeRequest(GET, "/")).get
status(response) must beEqualTo(OK)
contentAsString(response) must beEqualTo(TestTokenInfo.tokenType)
}
"deny an access when there is no security rule for the reguest is given" in {
val response = route(appWithRoutes, FakeRequest(GET, "/unprotected-by-mistake")).get
status(response) must beEqualTo(FORBIDDEN)
}
}
}
示例12: MultiLoginCacheIdContainerSpec
//设置package包名称以及导入依赖的类
package jp.t2v.lab.play2.auth
import play.api.cache.Cache
import play.api.test.{PlaySpecification, WithApplication}
class MultiLoginCacheIdContainerSpec extends PlaySpecification {
sequential
val container = new MultiLoginCacheIdContainer[String]
"starting a new session" should {
"work" in new WithApplication {
val user = "user"
val token = container.startNewSession(user, 1000)
Cache.get(token + container.tokenSuffix) === Some(user)
}
"time out" in new WithApplication {
val token = container.startNewSession("user", 1)
Thread.sleep(2000)
Cache.get(token + container.tokenSuffix) should beNone
}
}
"removing a session" should {
"work" in new WithApplication {
val user = "user"
val token = container.startNewSession(user, 1000)
container.remove(token)
Cache.get(token + container.tokenSuffix) should beNone
}
}
"getting a session" should {
"work" in new WithApplication {
val user = "user"
val token = container.startNewSession(user, 1000)
container.get(token) === Some(user)
}
}
"prolonging a session timeout" should {
"work" in new WithApplication {
val user = "user"
val token = container.startNewSession(user, 1)
container.prolongTimeout(token, 100)
Thread.sleep(2000)
Cache.get(token + container.tokenSuffix) === Some(user)
}
}
}
示例13: LoadDataServiceSpec
//设置package包名称以及导入依赖的类
package services
import models._
import org.specs2.mock.Mockito
import play.api.cache.CacheApi
import play.api.test.PlaySpecification
import utils.ReadHelper
import scala.concurrent.Future
class LoadDataServiceSpec extends PlaySpecification with Mockito {
val cache: CacheApi = mock[CacheApi]
val readerUtility: ReadHelper = mock[ReadHelper]
val loadDataService = new LoadDataService(cache, readerUtility)
val runways = List(Runway(1L, 1L, "ident", "len", "width", "surface", "ident"))
val airports = List(Airport(1L, "h1", "airType", "name", "iso", "region", runways))
val countryData = List(Country(1L, "aus", "australia", airports))
val airportRunways = List(CountryRunway("aus", List("type")))
val runwayIndents = List(RunwayIdent("ident", 1))
val runwayStr = List("""246281,27232,"FV76",3704,50,"ASP",0,0,"08",-19.0119,30.0199,,78,,"26",-19.0098,30.0304,,258,""", """246281,27232,"FV76",3704,50,"ASP",0,0,"08",-19.0119,30.0199,,78,,"26",-19.0098,30.0304,,258,""")
val airportStr = List("""27232,"FV76","small_airport","Kwekwe East Airport",-19.010799407958984,30.02519989013672,4025,"AF","ZW","ZW-MI",,"no","FV76",,"FV76",,,""", """27232,"FV76","small_airport","Kwekwe East Airport",-19.010799407958984,30.02519989013672,4025,"AF","ZW","ZW-MI",,"no","FV76",,"FV76",,,""")
val countriesStr = List("""302612,"ZW","Zimbabwe","AF","http://en.wikipedia.org/wiki/Zimbabwe",""", """302612,"ZW","Zimbabwe","AF","http://en.wikipedia.org/wiki/Zimbabwe",""")
"LoadDataServiceSpec" should {
"be able to get data" in {
readerUtility.loadData("runways", "./app/resources/runways.csv") returns Future.successful(runwayStr)
readerUtility.loadData("airports", "./app/resources/airports.csv") returns Future.successful(airportStr)
readerUtility.loadData("countries", "./app/resources/countries.csv") returns Future.successful(countriesStr)
val result = await(loadDataService.storeData)
result.head.name must beEqualTo("Zimbabwe")
}
}
}
示例14: dependency
//设置package包名称以及导入依赖的类
package com.clemble.loveit.common
import akka.stream.Materializer
import akka.stream.scaladsl.{Sink, Source}
import play.api.Mode
import play.api.inject.guice.GuiceApplicationBuilder
import play.api.libs.json.{Reads, Writes}
import play.api.test.PlaySpecification
import reactivemongo.api.MongoDriver
import scala.collection.immutable
import scala.reflect.ClassTag
trait ThankSpecification extends PlaySpecification {
implicit lazy val application = ThankSpecification.application
def dependency[T: ClassTag]: T = {
application.injector.instanceOf[T]
}
import com.clemble.loveit.test.util._
def someRandom[T](implicit generator: Generator[T]) = generator.generate()
def view[S, V](source: S)(implicit sWrites: Writes[S], vReads: Reads[V]): V = {
vReads.reads(sWrites.writes(source)).get
}
implicit lazy val materializer: Materializer = dependency[Materializer]
implicit class SourceToList[T](source: Source[T, _]) {
def toSeq(): immutable.Seq[T] = {
await(source.runWith(Sink.seq[T]))
}
}
}
object ThankSpecification {
lazy val application = {
val app = new GuiceApplicationBuilder().
in(Mode.Test).
build
app
}
}
示例15: setupData
//设置package包名称以及导入依赖的类
package base
import models.store.{OrdersAction, ProductAction, UserStepAction}
import org.specs2.mock.Mockito
import org.specs2.specification.{BeforeAfterAll, BeforeAfterEach}
import play.api.test.{FakeApplication, PlaySpecification}
import play.api.{Application, Logger}
import slick.driver.MySQLDriver.api._
import utils.Slick
import scala.concurrent.Await
trait SpecBase extends PlaySpecification with Mockito with BeforeAfterEach with BeforeAfterAll with Slick{
val logger = Logger.logger
val app = {
val application = FakeApplication(
additionalConfiguration = Map("isTestApp" -> true))
play.api.Play.start(application)
application
}
private def setupData(application: Application) {
if (application.configuration.getBoolean("isTestApp").getOrElse(false)) {
Await.result( db.run(
DBIO.seq(
OrdersAction.delete,
ProductAction.delete,
UserStepAction.delete
)
),duration)
}
}
def beforeAll(): Unit = {
}
override protected def before: Any = {
setupData(app)
}
override protected def after: Any = {
}
def afterAll(): Unit = {
}
}