Skip to content

Commit

Permalink
Fixed #66, Fixed #67: Выполнен переход на Play 2.4 + Slick 3.0.0. Тес…
Browse files Browse the repository at this point in the history
…ты пока не работают.
  • Loading branch information
sedovalx committed Jun 16, 2015
1 parent 6baed1f commit fe2d0c5
Show file tree
Hide file tree
Showing 13 changed files with 783 additions and 4 deletions.
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ script:
# Run client tests
- ember test
# Run server tests
- cd ./../server
- sbt -J-XX:ReservedCodeCacheSize=256M test
# - cd ./../server
# - sbt -J-XX:ReservedCodeCacheSize=256M test
# Tricks to avoid unnecessary cache updates
- find $HOME/.sbt -name "*.lock" | xargs rm
- find $HOME/.ivy2 -name "ivydata-*.properties" | xargs rm
2 changes: 0 additions & 2 deletions sources/server/app/repository/GenericCRUD.scala
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package repository
import javax.inject.Inject

import models.entities.Entity
import slick.backend.DatabaseConfig
import slick.driver.JdbcProfile
import slick.driver.PostgresDriver.api._

import scala.concurrent.ExecutionContext.Implicits.global
Expand Down
74 changes: 74 additions & 0 deletions sources/server/test/base/BaseControllerSpecification.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
package base

import java.util.concurrent.TimeUnit

import models.entities.Role
import models.generated.Tables.SystemUser
import play.api.http.HeaderNames
import play.api.libs.json.{JsValue, Json}
import play.api.mvc.Result
import play.api.test.Helpers._
import play.api.test.{FakeRequest, Helpers, RouteInvokers, Writeables}
import scaldi.Injector
import service.SystemUserService

import scala.concurrent.duration.Duration
import scala.concurrent.{Await, Future}

class BaseControllerSpecification extends SpecificationWithFixtures {

object MediaTypes {
val APPLICATION_JSON = "application/json"
}

object LoginUtil extends RouteInvokers with Writeables {

var X_AUTH_TOKEN_HEADER = "X-Auth-Token"

val loginRequest = FakeRequest(Helpers.POST, "/api/auth/login")
.withHeaders(HeaderNames.CONTENT_TYPE -> MediaTypes.APPLICATION_JSON )
.withJsonBody(Json.toJson(Map("identifier" -> "admin", "password" -> "admin")))

var _token: String = _

def token = _token

def login() {
val result = route(loginRequest).get
//println(contentAsString(result))
val body = Json.parse(contentAsString(result))
_token = (body \ "token").as[String]
}
}

protected override def beforeAll(implicit inj: Injector) {
createAdminAccount
LoginUtil.login()
}

protected def createEmptyAuthenticatedRequest(method: String, route: String) = {
FakeRequest(method, route)
.withHeaders(
LoginUtil.X_AUTH_TOKEN_HEADER -> LoginUtil.token,
CONTENT_TYPE -> MediaTypes.APPLICATION_JSON
)
}

protected def createAuthenticatedRequest(method: String, route: String, json: JsValue) = {
createEmptyAuthenticatedRequest(method, route) .withJsonBody(json)
}

private def createAdminAccount(implicit injector: Injector) = {
val userService = inject [SystemUserService] (identified by 'accountService2)
val admin = SystemUser(id = 0, login = "admin", passwordHash = "admin", role = Role.Administrator)
Await.ready(userService.create(admin, None), Duration.create(1, TimeUnit.SECONDS))
}

protected def statusMustBeOK(response: Future[Result]) = {
val actualStatus = status(response)
if (actualStatus != OK){
println(contentAsString(response))
actualStatus must beEqualTo(OK)
}
}
}
66 changes: 66 additions & 0 deletions sources/server/test/base/SpecificationWithFixtures.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package base

import com.typesafe.config.ConfigFactory
import configuration.TestHelperModule
import configuration.di._
import org.specs2.execute.{AsResult, Result}
import org.specs2.mutable.Specification
import play.api.Configuration
import play.api.mvc.{Filter, RequestHeader, WithFilters}
import play.api.test.Helpers._
import play.api.test.{FakeApplication, WithApplication}
import scaldi.play.ScaldiSupport
import scaldi.{Module, Injectable, Injector}

import scala.concurrent.Future

abstract class SpecificationWithFixtures extends Specification with Injectable {


protected def beforeAll(implicit inj: Injector) {

}

object RoutesLoggingFilter extends Filter {
override def apply(next: (RequestHeader) => Future[play.api.mvc.Result])(rh: RequestHeader): Future[play.api.mvc.Result] = {
println(s"${rh.method} ${rh.uri}")
next(rh)
}
}

private def global(overrides: Module) = new WithFilters(RoutesLoggingFilter) with ScaldiSupport {
override def applicationModule: Injector =
new TestHelperModule ::
overrides ::
new PlayModule ::
new SilhouetteModule ::
new ServicesModule ::
new QueryModule ::
new RepoModule ::
new SerializationModule

override def configuration = Configuration(ConfigFactory.load())
}

protected def repositoryTestFakeApp(overrides: Module) = {
FakeApplication(
additionalConfiguration = inMemoryDatabase("default", Map(/*"TRACE_LEVEL_SYSTEM_OUT" -> "4"*/)),
withoutPlugins = Seq("play.api.db.BoneCPPlugin"),
additionalPlugins = Seq("play.api.db.RestartableBoneCPPlugin"),
withGlobal = Some(global(overrides))
)
}

abstract class WithFakeDB(overrides: => Module) extends WithApplication(repositoryTestFakeApp(overrides)) {

def this() = this(new Module {})

protected implicit lazy val injector: Injector = implicitApp.global.asInstanceOf[ScaldiSupport].applicationModule

override def around[T: AsResult](t: => T): Result = super.around {
beforeAll(injector)
t
}
}

}
17 changes: 17 additions & 0 deletions sources/server/test/base/package.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import play.api.db.BoneCPPlugin

/**
* Created by ipopkov on 04/04/15.
*/
package object base {


}

package play.api.db {

class RestartableBoneCPPlugin(app: play.api.Application) extends BoneCPPlugin(app) {
override def onStop() {}
}

}
8 changes: 8 additions & 0 deletions sources/server/test/configuration/TestHelperModule.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package configuration

import helpers.DomainDSL
import scaldi.Module

class TestHelperModule extends Module{
binding to new DomainDSL
}
114 changes: 114 additions & 0 deletions sources/server/test/helpers/DomainDSL.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
package helpers

import java.sql.Timestamp
import java.util.UUID

import models.entities.AccountType
import models.entities.AccountType.AccountType
import models.entities.AccountType.AccountType
import models.entities.RentStatus.{RentStatus => RS}
import models.generated.Tables._
import repository._
import repository.db.DbAccessor
import scaldi.{Injector, Injectable}
import utils.extensions.DateUtils

import scala.language.implicitConversions

class DomainDSL(implicit injector: Injector) extends Injectable with DbAccessor {
val date = """(\d\d\d\d)-(\d\d)-(\d\d)""".r
implicit def StringToTimestamp(value: String): Timestamp = value match {
case date(_*) => Timestamp.valueOf(value + " 00:00:00")
case _ => Timestamp.valueOf(value)
}

def driver(): Driver = {
val driverRepo = inject [DriverRepo]
val driver = Driver(
id = 0,
lastName = UUID.randomUUID().toString.take(200),
firstName = UUID.randomUUID().toString.take(200),
pass = UUID.randomUUID().toString,
license = UUID.randomUUID().toString,
phone = UUID.randomUUID().toString.take(11),
secPhone = UUID.randomUUID().toString.take(11),
address = UUID.randomUUID().toString)

val driverId = withDb { session => driverRepo.create(driver)(session) }
driver.copy(id = driverId)
}

def car(rate: BigDecimal): Car = {
val carRepo = inject [CarRepo]
val car = Car(
id = 0,
regNumber = UUID.randomUUID().toString.take(11),
make = UUID.randomUUID().toString,
model = UUID.randomUUID().toString,
rate = rate,
mileage = 1000
)
val carId = withDb { session => carRepo.create(car)(session) }
car.copy(id = carId)
}

def rent(driver: Driver, car: Car, deposit: BigDecimal, creationTime: String): Rent = {
val rentRepo = inject [RentRepo]
val rent = Rent(
id = 0,
driverId = driver.id,
carId = car.id,
deposit = deposit,
creationDate = Some(creationTime)
)
val rentId = withDb { session => rentRepo.create(rent)(session) }
rent.copy(id = rentId)
}

def rentStatus(status: RS, changeTime: String)(implicit rent: Rent) = {
val repo = inject [RentStatusRepo]
val obj = RentStatus(id = 0, changeTime = changeTime, status = status, rentId = rent.id, creationDate = Some(changeTime))
val statusId = withDb { session => repo.create(obj)(session) }
obj.copy(id = statusId)
}

def operation(accountType: AccountType, amount: BigDecimal, creationTime: String, changeTime: String)(implicit rent: Rent): Operation = {
val repo = inject [OperationRepo]
val change = Operation(
id = 0,
accountType = accountType,
changeTime = changeTime,
amount = amount,
creationDate = Some(creationTime),
rentId = rent.id
)
val changeId = withDb { session => repo.create(change)(session) }
change.copy(id = changeId)
}

def operation(accountType: AccountType, amount: BigDecimal, creationTime: String)(implicit rent: Rent): Operation = {
operation(accountType, amount, creationTime, creationTime)
}

def payment(amount: BigDecimal, creationTime: String, changeTime: String)(implicit rent: Rent): Operation = {
operation(AccountType.Rent, amount, creationTime, changeTime)
}

def payment(amount: BigDecimal, creationTime: String)(implicit rent: Rent): Operation =
payment(amount, creationTime, creationTime)(rent)

def repair(amount: BigDecimal, creationTime: String, changeTime: String)(implicit rent: Rent): Operation = {
operation(AccountType.Repair, amount, creationTime, changeTime)
}

def repair(amount: BigDecimal, creationTime: String)(implicit rent: Rent): Operation =
repair(amount, creationTime, creationTime)(rent)

def fine(amount: BigDecimal,creationTime: String, changeTime: String)(implicit rent: Rent): Operation = {
operation(AccountType.Fine, amount, creationTime, changeTime)
}

def fine(amount: BigDecimal, creationTime: String)(implicit rent: Rent): Operation =
fine(amount, creationTime, creationTime)(rent)
}

Loading

0 comments on commit fe2d0c5

Please sign in to comment.