Resetting FakeApplication in-memory-database H2 before/after each test - scala

How do I reset the database inside the FakeApplication using inMemoryDatabase after or before each test? I want the state of the database returned to its initial state after each single test. Either rollback or clearing the database and running SetupData() again is fine.
I have tried many various things. The database is never reset between each test. How do I do this?
When running the following test suite the state of the database continues from test to test. So if I modify some data in Test2 then it is affecting Test3.
trait TestUtil {
/**
* Executes a block of code in a running application.
*/
def running[T](fakeApp: FakeApplication)(block: => T): T = {
synchronized {
try {
Play.start(fakeApp)
setup_data()
block
} finally {
Play.stop()
}
}
}
def setup_data() = {
//add data to the database
}
}
I tried using the above trait to have the Play App stop after each test but it does not help.
#RunWith(classOf[JUnitRunner])
class ConditionTests2 extends Specification with TestUtil {
sequential // Make the tests run sequentially instead of in parallel
// test1
"element with id 1" should {
"should have name PETER" in {
running(new FakeApplication(additionalConfiguration = inMemoryDatabase("test"))) {
// name should be "PETER"
}
}
}
// test2
"renaming element with id 1" should {
"successfully modify element 1" in {
running(new FakeApplication(additionalConfiguration = inMemoryDatabase("test"))) {
// Set Name = "John"
}
}
}
// test3
"element with id 1" should {
"should have name PETER" in {
running(new FakeApplication(additionalConfiguration = inMemoryDatabase("test"))) {
// name should be "PETER"
// fails because name is now JOHN
}
}
}
}

Related

Correctly commit to database using #Transactional in spring-data

I have a test function, that should perform the following task
insert data to db
query db and verify data is as expected
The problem is that in my test, the data has not been committed to the db, like it's stuck in some transactional step, how can I surely commit the data before the second query is executed.
This is a part of my test function, #Rollback(false) is just for development phase.
#Test
#Rollback(false)
....
reportJobManager.saveOutput(savedDef, pipeline, results, null)
reportJobManager.retryRetention(savedDef, listOf(csvDeliverbale))
saveOutput func. sample code
#Transactional
fun saveOutput() {
if (deliverable.type.name == "DATA_RETENTION_RESULT") {
finishedPipeline.postProcessors.forEach {
//it(definition, dbDeliverable)
val dbRetention = ReportRetention(
deliverable = dbDeliverable,
definition = definition,
retryCount = 1L
)
val retentionUploadSaved = retentionRepository.save(dbRetention)
if (retentionUploadSaved.id == null) {
throw IllegalStateException("Retention upload was not saved!")
}
}
}
}
retryRetention func code
fun retryRetention(definition: ReportDefinition, listOfDeliverables: List<Deliverable>) {
retentionRepository.findAll().forEach {
if (it.state.name == "NOT_UPLOADED" && it.retryCount!!.toInt() < 5) {
if (it.deliverable?.success == true) {
it.state = RetentionUploadStatus.UPLOADED
println("RetentionUploadStatus->UPLOADED")
} else {
val schemaService = SchemaServiceImpl()
val schemas = schemaService.initializeSchemas(definition, emptyMap())
val parameters = definition.parameterPolicy.policy(schemas.parametersSchema)
val delivery = deliveryPolicyService.policy<Deliverable>(ValidDeliveryPolicy.RETENTION_ONLY, schemas.deliverySchema)
val deliveryFunction = delivery.createDeliveryStep()
deliveryFunction(parameters, listOfDeliverables)
it.retryCount = it.retryCount!!.plus(1L)
}
retentionRepository.save(it)
}
}
}
If you have a method saveOutput() with #Transactional annotation, you need to add #Transactional above every other method that is calling saveOutput() for the transaction to actually commit.

Race condition with RxJava's PublishSubject

When using a PublishSubject in conjunction with blockingGet(), there seems to be a race condition where a subscriber does not receive the events.
I attached a basic JUnit test in Kotlin, which has 2 methods.
rxTestBroken() shows the broken behavior with a PublishSubject.
rxTestOk() shows that everything works fine with a BehaviorSubject, because the latter replays the last event in case the subscriber is not subscribed in time.
Where does this race condition come from and is using a BehaviorSubject the correct fix?
import io.reactivex.Single
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import java.util.concurrent.TimeUnit
class StateMachine(val stateSubject: Subject<Int>) {
companion object {
val STATE_IDLE = 1
val STATE_READY = 2
}
val output = 10L
var currentState = STATE_IDLE
fun scheduleNextState(nextState: Int) {
Thread(Runnable {
currentState = nextState
stateSubject.onNext(currentState)
}).start()
}
fun start() = scheduleNextState(STATE_READY)
fun stop() = scheduleNextState(STATE_IDLE)
}
class RxTest {
fun stateOutput(stateSubject: Subject<Int>): Single<Int> {
val stateMachine = StateMachine(stateSubject)
val waitForIdle = stateSubject
.startWith(stateMachine.currentState)
.doOnNext {
if (it != StateMachine.STATE_IDLE) { stateMachine.stop() }
}
.filter { it == StateMachine.STATE_IDLE }
.firstOrError()
val scanFile = stateSubject
.doOnSubscribe { stateMachine.start() }
.filter {
when (it) {
StateMachine.STATE_READY -> true
StateMachine.STATE_IDLE -> false
else -> throw RuntimeException("Wrong state $it")
}
}
.firstOrError()
.map { stateMachine.output.toInt() }
.doFinally { stateMachine.stop() }
return waitForIdle.flatMap { scanFile }.timeout(1, TimeUnit.SECONDS).onErrorReturnItem(-1)
}
#Test
fun rxTestBroken() {
for (i in 1..10000) {
assertThat(stateOutput(PublishSubject.create<Int>()).blockingGet())
.withFailMessage("worked $i times")
.isEqualTo(10)
}
}
#Test
fun rxTestOk() {
for (i in 1..10000) {
assertThat(stateOutput(BehaviorSubject.createDefault(StateMachine.STATE_IDLE)).blockingGet())
.withFailMessage("worked $i times")
.isEqualTo(10)
}
}
}

Grails 3.0.9 not updating object with MongoDB

I've problems updating a domain class. I'm using Grails 3.0.9 and MongoDB (for Gorm 5.0.0.RC1)
In my build.gradle:
compile "org.grails.plugins:mongodb:5.0.0.RC1"
compile "org.mongodb:mongodb-driver:3.0.2"
compile "org.grails:grails-datastore-gorm-mongodb:5.0.0.RC1"
runtime 'org.springframework.data:spring-data-mongodb:1.8.1.RELEASE'
compile("org.grails:gorm-mongodb-spring-boot:5.0.0.RC1")
The test:
#Integration
class CompanyControllerIntegrationSpec extends Specification{
def grailsApplication
Company company
RestBuilder rest
def setupData() {
company = Company.buildWithoutSave().save(flush: true, failOnError: true)
}
def setup(){
rest = new RestBuilder()
}
def "test update a company" (){
def company2
given:
setupData()
def id = company.id
when:
RestResponse response = rest.put("http://localhost:${grailsApplication.config.server.port}/${company.companyKey}/company") {
json {
name = "newName"
description = "new Description"
}
}
company2 = Company.findById(id)
then:
response.status == 200
response.json.name == "newName"
company2.name == "newName"
company2.description == "new Description"
}
def cleanup() {
Company.collection.remove(new BasicDBObject())
}
}}
The controller:
class CompanyController extends ExceptionController{
static allowedMethods = ['update':'PUT','show':'GET',
'updateNew':'PUT','showNew':'GET']
CompanyService companyService
def update(String companyKey){
def object = request.JSON?request.JSON:params
Company companyOut = companyService.update(object, companyKey)
render text:companyOut as JSON, status:HttpStatus.OK
}
}
The service:
class CompanyService {
def securityService
def grailsApplication
public Company update(object, String companyKey) throws ForbiddenException, InvalidRequestException, NotFoundException{
Company company = findByKey(companyKey)
if (object.name!=null)
company.name = object.name
if (object.description!=null)
company.description = object.description
if (object.enterprise!=null)
company.enterprise = object.enterprise
if (object.genKey!=null)
company.companyKey = UUID.randomUUID().toString()
if (!company.save(flush:true)){
println company.errors
throw new InvalidRequestException("Some parameters are missing or are invalid: "+company.errors.fieldErrors.field)
}
return company
}
public Company findByKey(String companyKey) throws NotFoundException, ForbiddenException {
if (!companyKey){
throw new ForbiddenException("The company key has not been given")
}
Company company = Company.findByCompanyKey(companyKey)
if (!company){
throw new NotFoundException("No company exists for the given key")
}
return company
}
}
The results of the test are:
- response.status is 200
- response.json.name is "newName"
- company.name is old name ("company 1")
If I don't do the cleanup, the database still have the old value. I've followed the save method, also inside Mongo gorm classes, and I've seen that one problem is that the fields are not being marked as dirty, but don't know why.
With other Domain classes that are similar to this one, the update is done without problems and the properties are marked as dirty.

How can we tell Grails MongoDB unit test to use a db?

I setup a db in MongoDB called spotlight. To connect to that database, I use the following environment setup in DataSource.groovy:
grails {
mongo {
host = "localhost"
port = 27017
}
}
environments {
development { // MongoDB instance running without --auth flag.
grails {
mongo {
databaseName = "spotlight"
}
}
}
test {
grails { // MongoDB instance running without --auth flag.
mongo {
databaseName = "spotlight"
}
}
}
}
This is my unit test class:
#TestMixin(MongoDbTestMixin)
class BiographySpec extends Specification {
def setup() {
}
def cleanup() {
}
void "given a bio then find() returns that bio object"() {
given:
mongoDomain([Biography])
Biography bio = new Biography()
def nameOf1stImage = "firstImage.png"
def nameOf2ndImage = "secondImage.png"
def nameInBio = "star"
def descriptionOfBio = "a description"
def id = 0;
bio.firstImage = nameOf1stImage
bio.secondImage = nameOf2ndImage
bio.name = nameInBio
bio.description = descriptionOfBio
bio.images = [nameOf1stImage,nameOf2ndImage]
when:
bio.save(flush:true);
id = bio.id
then:
Biography bioFromDb = bio.get(id)
bioFromDb.firstImage == nameOf1stImage
bioFromDb.secondImage == nameOf2ndImage
bioFromDb.name == nameInBio
bioFromDb.description == descriptionOfBio
}
}
I ran grails test-app, and Grails created a biography document in test db, not spotlight db. Is there anything wrong with the way I configure environments setttings in DataSource.groovy ?

return/break a function from the derived base class

In my REST API service layer, I have a class ProductService.
The following logic exists in all my functions: Do Validate, if validation fails i throw invalid exception, if passes, i continue to the next try-catch and throw general-error in case of failure:
def addProduct(request:AddProductRequest): BaseResponse[String] =
{
try
{
request.validate
}
catch
{
case ex: Exception => {
Logger.error("Failed to add product, Validation failed", ex);
val errorResponse:ErrorResponse[String] = new ErrorResponseList().InvalidParameters
errorResponse.addMessage(ex.getMessage)
return errorResponse
}
}
try
{
val addedProductId = productRepository.addProduct(request.language, request.tenantId, request.product)
DTOResponse(addedProductId)
}
catch
{
case ex: Exception => {
Logger.error("Failed to add product to tenant Id="+request.tenantId+" language="+request.language, ex);
val errorResponse:ErrorResponse[String] = new ErrorResponseList().GeneralError
errorResponse.addMessage(ex.getMessage())
return errorResponse
}
}
}
Now, instead of repeating the request.validate with the same try and catch for all functions, i created a base class with the following function:
abstract class ServiceBase {
def validate[T](request:BaseRequest)
{
try
{
request.validate
}
catch
{
case ex: Exception => {
Logger.error("Validation failed", ex);
val errorResponse:ErrorResponse[String] = new ErrorResponseList().InvalidParameters
errorResponse.addMessage(ex.getMessage)
return errorResponse
}
}
}
So now, my addProduct(..) will look like:
validate(request)
..the rest of the code - the 2nd try-catch
This saves alot of lines.
The problem is that if validation fails, it will never return. I get the following errors in ServiceBase:
Multiple markers at this line
- enclosing method validate has result type Unit: return value discarded
- enclosing method validate has result type Unit: return value discarded
- a pure expression does nothing in statement position; you may be omitting necessary
parentheses
validate has no return type (and thus defaults to returning Unit), in ServiceBase your signature for validate should look like this:
def validate[T](request:BaseRequest): BaseResponse[String] =
(assuming you want to return a BaseResponse[String])
this may be useful to someone, someday, functional programming.. Did we say ^_^
Changed the ServiceBase validate to:
def validate[T](request:BaseRequest):Option[BaseResponse[T]] =
{
try
{
request.validate
None
}
catch
{
case ex: Exception => {
Logger.error("Validation failed", ex);
val errorResponse:ErrorResponse[T] = new ErrorResponseList().InvalidParameters
errorResponse.addMessage(ex.getMessage)
return Some(errorResponse)
}
}
}
And now i do:
def getProducts(request:GetProductsRequest) :BaseResponse[ProductSearchResults] =
{
validate[ProductSearchResults](request).getOrElse(
{
try
{
val products = productRepository.getProducts(request.language,request.tenantId,request.productIds)
val foundProducts = for (product <- products) yield (product.id)
val notFoundProducts = request.productIds filterNot (foundProducts.toSet)
val responseWrapper = new ProductSearchResults(products, notFoundProducts)
DTOResponse(responseWrapper)
}
catch
{
case ex: Exception => {
Logger.error("Failed to get products from tenant Id="+request.tenantId+" language="+request.language, ex);
val errorResponse:ErrorResponse[ProductSearchResults] = new ErrorResponseList().GeneralError
errorResponse.addMessage(ex.getMessage())
return errorResponse
}
}})
}