pyc-website

main website for pyc inc.

git clone https://9o.is/git/pyc-website.git

MongoTestKit.scala

(2144B)


      1 package inc.pyc
      2 
      3 import org.scalatest._
      4 import net.liftweb._
      5 import common._
      6 import http._
      7 import util._
      8 import mongodb._
      9 import util.{Props, StackableMaker}
     10 import util.Helpers.randomString
     11 import com.mongodb.{MongoClient, ServerAddress}
     12 
     13 // The sole mongo object for testing
     14 object TestMongo {
     15   val mongo = new MongoClient(new ServerAddress(
     16     Props.get("mongo.default.host", "127.0.0.1"),
     17     Props.getInt("mongo.default.port", 27017)
     18   ))
     19 }
     20 
     21 /**
     22   * Creates a `MongoIdentifier` and database named after the class.
     23   * Therefore, each Suite class shares the same database.
     24   * Database is dropped after all tests have been run in the suite.
     25   */
     26 trait MongoBeforeAndAfterAll extends BeforeAndAfterAll {
     27   this: Suite =>
     28 
     29   lazy val dbName = "pyc_test_"+this.getClass.getName
     30     .replace(".", "_")
     31     .toLowerCase
     32 
     33   def debug = false // db won't be dropped if this is true
     34 
     35   lazy val identifier = new ConnectionIdentifier {
     36     val jndiName = dbName
     37   }
     38 
     39   override def beforeAll(configMap: Map[String, Any]) {
     40     // define the db
     41     MongoDB.defineDb(identifier, TestMongo.mongo, dbName)
     42   }
     43 
     44   override def afterAll(configMap: Map[String, Any]) {
     45     if (!debug) { dropDb() }
     46   }
     47 
     48   protected def dropDb(): Unit = MongoDB.use(identifier) { db => db.dropDatabase }
     49 }
     50 
     51 /**
     52   * Basic Mongo suite for running Mongo tests.
     53   */
     54 trait MongoSuite extends AbstractSuite with MongoBeforeAndAfterAll {
     55   this: Suite =>
     56 
     57   def mongoIdentifier: StackableMaker[ConnectionIdentifier]
     58 
     59   abstract override def withFixture(test: NoArgTest) {
     60     mongoIdentifier.doWith(identifier) {
     61       super.withFixture(test)
     62     }
     63   }
     64 }
     65 
     66 /**
     67   * Mongo suite running within a LiftSession.
     68   */
     69 trait MongoSessionSuite extends AbstractSuite with MongoBeforeAndAfterAll {
     70   this: Suite =>
     71 
     72   def mongoIdentifier: StackableMaker[ConnectionIdentifier]
     73 
     74   // Override with `val` to share session amongst tests.
     75   protected def session = new LiftSession("", randomString(20), Empty)
     76 
     77   abstract override def withFixture(test: NoArgTest) {
     78     S.initIfUninitted(session) {
     79       mongoIdentifier.doWith(identifier) {
     80         super.withFixture(test)
     81       }
     82     }
     83   }
     84 }