Skip to content

Instantly share code, notes, and snippets.

@jeantil
Last active August 29, 2015 14:02
Show Gist options
  • Save jeantil/c5cd188761e76fa45ac0 to your computer and use it in GitHub Desktop.
Save jeantil/c5cd188761e76fa45ac0 to your computer and use it in GitHub Desktop.
package helpers
object Generators {
private val epoch = new DateTime(0)
val nameGen = for {
head <- Gen.alphaUpperChar
size<- Gen.choose(1,10)
tail <- Gen.listOfN(size,Gen.alphaLowerChar)
} yield (head +: tail).mkString("")
}
The MIT License (MIT)
Copyright (c) 2014 Jean Helou
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
package helpers
abstract class WithTestApplication(val app: FakeApplication = FakeApplication()) extends Around with Scope {
import stubs.TestExecutionContext._
import scala.concurrent.Await
import play.modules.reactivemongo.ReactiveMongoPlugin
import scala.concurrent.duration._
lazy val dbName = Generators.nameGen.sample.get // create a new random database name for this test
lazy val db= new MongoDriver().connection(Seq("localhost")).db(dbName)
lazy val appWithFakeDb = app.copy(additionalConfiguration = app.additionalConfiguration + ("mongodb.db" -> dbName))
implicit def implicitApp: FakeApplication = appWithFakeDb
override def around[T: AsResult](t: => T): Result ={
try{
Helpers.running(appWithFakeDb)({
val logger = Logger("helpers.WithTestApplication")
logger.info("preparing to run tests")
try {
//db fixtures which are not created by the application
}catch {
case e:Throwable => logger.error("unable to save data",e); throw e;
}
val r = AsResult.effectively(t)
r
})
}finally{
val dropped = db.drop()
dropped.recover{ case throwable =>
println(s"unable to drop test db $dbName")
println(throwable.getMessage)
throwable.printStackTrace()
}.map(_ => db.connection.close())
Await.result(dropped, 10.seconds)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment