groovy spock testing Mock and returned proxy - groovy

Spock Testing - new spock user.
Problem with using Spock in terms of mocking return value.
the classUnderTest has an apply method. The first step is to get AssetType attribute from a Term. Both AssetType and Term are interfaces.
The test fails as it seems that AssetType is not returned rather the created Spock proxy
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'Mock for type 'AssetType' named 'assetType'' with class 'com.sun.proxy.$Proxy11' to class 'com.collibra.dgc.core.model.meta.AssetType'
public Errors apply(){
def at=t.getType()
...
}
import spock.lang.Specification
import com.collibra.dgc.core.component.representation.TermComponent;
import com.collibra.dgc.core.component.relation.RelationComponent;
import com.collibra.dgc.core.model.representation.Representation
import com.collibra.dgc.core.model.representation.Term;
import com.collibra.dgc.core.api.component.assignment.AssignmentApi
impoort com.collibra.dgc.core.api.internal.dto.instance.view.table.AssetTableOutputRequest
import com.collibra.dgc.core.api.model.meta.type.AssetType
import com.collibra.dgc.core.model.representation.Representation;
class CustomExceptionRuleValidator1Spec extends Specification{
Term term=Mock()
AssetType assetType=Mock()
def """If validate"""() {
given:
RelationComponent relationComponent=Mock();
TermComponent termComponent=Mock();
AssignmentApi assignmentApi=Mock()
ConceptType dataElementConceptType=new DataElementConceptType(assignmentApi)
ConceptType.register(dataElementConceptType)
CustomExceptionRuleValidator classUnderTest=new CustomExceptionRuleValidator(relationComponent,termComponent);
classUnderTest.withTerm(term)
when:
Errors errors=classUnderTest.apply()
then:
1 * term.getType() >> assetType
1 * assetType.getName()>>"Data Element"
1 * term.getSignifier() >> "my data element"
errors.hasErrors()
}
}

Seems in the classpath there was another AssetType apart from
import com.collibra.dgc.core.api.model.meta.type.AssetType
and this caused the behaviour experienced.

Related

How to Mock a flask-restful class with kwargs

From Intermediate-Usage Flask-RESTful 0.3.7 documentation
in the Passing Constructor Parameters Into Resources section at the bottom, how would you write a test in order to mock kwargs? Side note: I tweaked it so the Smart Engine class is passed directly rather than being instantiated to a variable then passed.
from flask_restful import Resource
class TodoNext(Resource):
def __init__(self, **kwargs):
# smart_engine is a black box dependency
self.smart_engine = kwargs['smart_engine']
def get(self):
return self.smart_engine.next_todo()
You can inject the required dependency into TodoNext like so:
api.add_resource(TodoNext, '/next',
resource_class_kwargs={ 'smart_engine': SmartEngine() })
Test class in question:
import unittest
class TestTodoNext(unittest.TestCase):
todo_next_instance = TodoNext() # How would you mock smart_engine in this case?
You can use Mock object from unittest.mock to mock smart_engine.
import unittest
from unittest.mock import Mock
class TestTodoNext(unittest.TestCase):
smart_engine = Mock()
smart_engine.next_todo.return_value = "YOUR DESIRED RETURN VALUE"
todo_next_instance = TodoNext(smart_engine=smart_engine)
self.assertEqual(todo_next_instace.get(), "YOUR DESIRED RETURN VALUE")

PeeWee model has no 'select' attribute error

I'm in the process of creating an application for a personal project I'm working on that involves Python 3, peewee, and (for the moment) Sqlite3. In main, I'm importing a 2 model classes (student and course) which are subclasses of a basemodel class I create.
The import statements located in main.py:
from models.course import Course
from models.student import Student
The models/BaseModel.py
from peewee import *
db = SqliteDatabase('database/attendance.db')
class BaseModel:
class Meta:
database = db
The models/course.py
from peewee import *
from models.basemodel import BaseModel
class Course(BaseModel):
cid = PrimaryKeyField()
title = TextField()
active = BooleanField()
class Meta:
table_name = 'courses'
When I try to do a simply query to retrieve courses, I receive an error message.
Example query:
active_courses = Course.select().where(Course.active == True)
The error message I receive is:
AttributeError: type object 'Course' has no attribute 'select'
Your BaseModel class needs to extend peewee.Model:
class BaseModel(peewee.Model):
...

groovy.lang.MissingPropertyException: No such property:

I am trying to get my head around groovy scripting to make some changes to a jenkins pipeline and I keep getting this error:
groovy.lang.MissingPropertyException: No such property: credentials for class:
I have tried declaring the variable with def but I still get the exception, eclipse does not recognise that the property exists.
What am I doing wrong?!
#!/usr/bin/groovy
package common.pipeline
import common.pipeline.Credentials
Credentials credentials = new Credentials()
def withCredentials(steps) {
credentials.productionPipeline(steps)
}
This script will be compiled by groovy into a Script class with the field definition inside the run method, and with another method withCredentials that is trying to access the field (kinda like this):
import common.pipeline.Credentials
class Script1 extends Script {
def withCredentials(steps) {
credentials.productionPipeline(steps)
}
def run(args) {
Credentials credentials = new Credentials()
}
}
As you can see, this won't work, as the credentials aren't at Field level in the class...
Groovy has an annotation to make this happen:
#!/usr/bin/groovy
package common.pipeline
import common.pipeline.Credentials
import groovy.transform.Field
#Field Credentials credentials = new Credentials()
def withCredentials(steps) {
credentials.productionPipeline(steps)
}

Spock unrecognized block label: given

I have the following spock test.
package com.arch.unit.category
import com.arch.domain.category.Category
import com.arch.domain.category.CategoryRepository
import com.arch.handler.category.CategoryCreateHandler
import com.arch.message.command.category.CategoryCreateCommand
import spock.lang.Specification
def "create category expected succeed"() {
given:
def command = new CategoryCreateCommand("Php")
and:
categoryRepository.save(_ as Category) >> new Category("Php")
when:
def response = handler.execute(command)
then:
response.code == 100
}
It is not working. I get an error "Error:(20, 16) Groovyc: Unrecognized block label: given"
My dependencies
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile('org.codehaus.groovy:groovy-all')
testCompile('org.spockframework:spock-core:1.1-groovy-2.4-rc-4')
testCompile('org.spockframework:spock-spring:1.1-groovy-2.4-rc-4')
Environment : Windows, Java8, Intellij Community Edition
It's worked my mac before. But now not working.

ALL time groovy compilation error

All time am getting below error message in groovy...
Could not understand whats causing this " Unexpected token error" ????
I used to think only PERL give bad compilation error,now groovy outperforming it..
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
D:\Playground\groovy\release-b-work\cmd_line_soapui\trial.groovy: 12:
unexpected token: myrunner # line 12, column 1.
myrunner.setProjectFile("D:\soapui-release-B\try.xml");
^
1 error
Code taken from comment;
import com.eviware.soapui.SoapUIProTestCaseRunner;
import com.eviware.soapui.support.*;
import com.eviware.soapui.model.*;
import com.eviware.soapui.impl.wsdl.*;
import com.eviware.soapui.*;
class trial {
def myrunner = new com.eviware.soapui.SoapUIProTestCaseRunner();
myrunner.setProjectFile("D:\soapui-release-B\try.xml");
myrunner.setTestSuite("MediaAssetServiceTestSuite");
myrunner.setTestCase("createMediaAsset TestCase");
myrunner.run();
}
You need to put your code in a method
You can't just add code into a class at class level
Try:
import com.eviware.soapui.SoapUIProTestCaseRunner;
import com.eviware.soapui.support.*;
import com.eviware.soapui.model.*;
import com.eviware.soapui.impl.wsdl.*;
import com.eviware.soapui.*;
class trial {
def someMethod() {
def myrunner = new com.eviware.soapui.SoapUIProTestCaseRunner();
myrunner.setProjectFile("D:\soapui-release-B\try.xml");
myrunner.setTestSuite("MediaAssetServiceTestSuite");
myrunner.setTestCase("createMediaAsset TestCase");
myrunner.run();
}
}

Resources