Spock unrecognized block label: given - groovy

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.

Related

Scriptrunner/ Copying Project while logged-in as another user

I want to use my script, so that it will be executed by someone who is not me, but another user (ServiceUser) in the Jira Instance.
This is my functioning code, but I do not know how to make someone else execute it.
import com.atlassian.jira.project.Project
import com.atlassian.jira.project.ProjectManager
import com.atlassian.jira.project.AssigneeTypes
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.user.ApplicationUser
import com.atlassian.jira.component.ComponentAccessor
import com.onresolve.scriptrunner.canned.jira.admin.CopyProject
import org.apache.log4j.Logger
import com.atlassian.jira.bc.projectroles.ProjectRoleService
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.security.roles.ProjectRole
import com.atlassian.jira.util.SimpleErrorCollection
import com.atlassian.jira.security.roles.ProjectRoleManager
import com.atlassian.jira.project.ProjectManager
import com.atlassian.jira.project.Project
import com.atlassian.jira.security.roles.ProjectRoleActor
import com.atlassian.jira.bc.project.ProjectCreationData
import com.atlassian.jira.bc.project.ProjectService
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.project.AssigneeTypes
import com.atlassian.jira.project.type.ProjectTypeKey
// the key for the new project
def projectKey = "EXA987"
def projectName = "EXA987"
def log = Logger.getLogger("com.onresolve.jira.groovy.MyScript")
Thread executorThread = new Thread(new Runnable() {
void run() {
def copyProject = new CopyProject()
def inputs = [
(CopyProject.FIELD_SOURCE_PROJECT) : "SWTEMP",
(CopyProject.FIELD_TARGET_PROJECT) : projectKey,
(CopyProject.FIELD_TARGET_PROJECT_NAME) : projectName,
(CopyProject.FIELD_COPY_VERSIONS) : false,
(CopyProject.FIELD_COPY_COMPONENTS) : false,
(CopyProject.FIELD_COPY_ISSUES) : false,
(CopyProject.FIELD_COPY_DASH_AND_FILTERS) : false,
]
def errorCollection = copyProject.doValidate(inputs, false)
if(errorCollection.hasAnyErrors()) {
log.warn("Couldn't create project: $errorCollection")
}
else {
def util = ComponentAccessor.getUserUtil()
def adminsGroup = util.getGroupObject("jira-administrators")
assert adminsGroup // must have jira-administrators group defined
def admins = util.getAllUsersInGroups([adminsGroup])
assert admins // must have at least one admin
ComponentAccessor.getJiraAuthenticationContext().setLoggedInUser(util.getUserByName(admins.first().name))
copyProject.doScript(inputs)
}
}
})
executorThread.start()
I stumbled upon other codes, using things like
def oldLoggedInUser = jiraAuthenticationContext.getLoggedInUser()
jiraAuthenticationContext.setLoggedInUser(serviceUser)
jiraAuthenticationContext.setLoggedInUser(oldLoggedInUser)
but it was not succesful for me.
I have used following solution to change user during script execution:
def authContext = ComponentAccessor.getJiraAuthenticationContext();
def currentUser = authContext.getLoggedInUser();
def superuser=ComponentAccessor.getUserManager().getUserByKey("ANOTHER_USER_ACCOUNT")
authContext.setLoggedInUser(superuser);
// < do the needed work>
authContext.setLoggedInUser(currentUser);
I had first issues as my used another account had not needed Jira access rights (and I got funny "user must be logged in" errors)

Attempting to assert 500 error, but response is null when conditions are met

When I automated this I came to know that the 500 error that is thrown is given by server. But at our code level we have handled the exception and the response =null
So when I tried to assert with response.status==500 it fails as the response is altogether null.
package test
import geb.spock.GebReportingSpec
import groovyx.net.http.RESTClient
import net.sf.json.JSON
import org.apache.log4j.Logger
import spock.lang.Specification
import spock.lang.Unroll
class EventsAPITest extends GebReportingSpec{
static Logger logger = Logger.getLogger("EventsAPITest");
#Unroll
def "Call calendar event for Invalid Location id 110 throws groovyx.net.http.HttpResponseException"() {
given:
RESTClient restClient = new RESTClient("https://test-api2.club-os.com")
def response=restClient.get(path: '/authenticate',requestContentType: JSON,query:[
'username': 'apiuser',
'password':'apipassword',
])
def authToken=response.data.token
logger.info"Token:" +authToken
restClient.defaultRequestHeaders['Authorization'] = authToken
def locationId=110
when:
response=restClient.get(path: '/locations/'+locationId+'/events',requestContentType: JSON, query:[
'startTimeStartAt': '2018-05-25T17:00:00.000Z',
'startTimeEndAt':'2018-06-01T17:00:00.000Z',
'eventTypeId' : 2 ])
then:
thrown groovyx.net.http.HttpResponseException
logger.info"Response: "+ response
// assert response.data.errorMessage=="Error"
assert response.status == 500
//assert response.status == 500
// assert response.data.errorMessage == "An unknown error occurred"
}
I would like to be able to assert a 500 error and have that returned.
This is not spock-specific. Your code throws an exception, therefore it cannot return a value.
UPDATE after kriegaex's advice in the comments.
By assigning the result of the thrown groovyx.net.http.HttpResponseException expression to a variable, you can access the exception's state. This exception's API is documented here: http://javadox.com/org.codehaus.groovy.modules.http-builder/http-builder/0.6/groovyx/net/http/HttpResponseException.html.
You can access the statusCode property directly, and you have a response property too. That's everything you need to test your conditions.
This is the resulting code:
import geb.spock.GebReportingSpec
import groovyx.net.http.RESTClient
import net.sf.json.JSON
import org.apache.log4j.Logger
import spock.lang.Specification
import spock.lang.Unroll
class EventsAPITest extends GebReportingSpec{
static Logger logger = Logger.getLogger("EventsAPITest");
#Unroll
def "Call calendar event for Invalid Location id 110 throws groovyx.net.http.HttpResponseException"() {
given:
RESTClient restClient = new RESTClient("https://test-api2.club-os.com")
def response=restClient.get(path: '/authenticate',requestContentType: JSON,query:[
'username': 'apiuser',
'password':'apipassword',
])
def authToken=response.data.token
logger.info"Token:" +authToken
restClient.defaultRequestHeaders['Authorization'] = authToken
def locationId=110
when:
response=restClient.get(path: '/locations/'+locationId+'/events',requestContentType: JSON, query:[
'startTimeStartAt': '2018-05-25T17:00:00.000Z',
'startTimeEndAt':'2018-06-01T17:00:00.000Z',
'eventTypeId' : 2 ])
then:
//Here, assign the exception to a variable.
def e= thrown groovyx.net.http.HttpResponseException
logger.info"Response: "+ e.response
// assert response.data.errorMessage=="Error"
assert e.response.status == 500
//assert response.status == 500
// assert response.data.errorMessage == "An unknown error occurred"
}

Compile Groovy Script from command prompt which contains soapui libraries

I am trying to create a script library and compile a groovy class as described in https://stackoverflow.com/a/35498212/9997207
Groovy Script
import groovy.json.*
import com.eviware.soapui.*
class ScriptLibrary {
def context
def testRunner
def log
def boolean setHeaderValues(userId, password){
try{
loginTestStep = testRunner.testCase.testSuite.testCases["SetHeaderParameters"].testSteps["SetHeaderParametersJsonRequest"]
def request = loginTestStep.getPropertyValue("Request").toString()
def jsonReq = new JsonSlurper().parseText(request);
def builder = new JsonBuilder(jsonReq)
builder.content.userId=userId
builder.content.password=password
def jsonReqAsString = JsonOutput.toJson(jsonReq)
loginTestStep.setPropertyValue("Request",jsonReqAsString)
def contextJsonRequest = new WsdlTestRunContext(loginTestStep);
loginTestStep.run(testRunner,contextJsonRequest)
def response = loginTestStep.getPropertyValue("Response").toString()
def jsonResponse = new JsonSlurper().parseText(response);
def accessTokenFromResponse = jsonResponse.accessToken.toString()
def userPermissionFromResponse = jsonResponse.userPermissionIds.toString()
def userIdFromResponse = jsonResponse.userId.toString()
testRunner.testCase.testSuite.project.setPropertyValue("HEADER_USER_ID", userIdFromResponse)
testRunner.testCase.testSuite.project.setPropertyValue("HEADER_USER_PERMISSION", userPermissionFromResponse)
testRunner.testCase.testSuite.project.setPropertyValue("HEADER_ACCESS_TOKEN", accessTokenFromResponse)
log.info "Header set with values "+userIdFromResponse+":::"+userPermissionFromResponse+":::"+accessTokenFromResponse
setHeader = true
}
return setHeader
}
catch (Exception ex) {
log.info "Header Not Set " +ex
setHeader = false
testRunner.testCase.testSuite.project.setPropertyValue("HEADER_USER_ID", "")
testRunner.testCase.testSuite.project.setPropertyValue("HEADER_USER_PERMISSION", "")
testRunner.testCase.testSuite.project.setPropertyValue("HEADER_ACCESS_TOKEN", "")
return setHeader
}
}
}
Getting following compilation error while trying to compile the groovy script from the command prompt
C:\Path\apache-groovy-binary-2.5.1\groovy-2.5.1\bin\GroovyScripts>groovy ScriptLibrary.groovy
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
C:\Path\apache-groovy-binary-2.5.1\groovy-2.5.1\bin\GroovyScripts\ScriptLibrary.groovy: 20: unable to resolve class WsdlTestRunContext
# line 20, column 26.
def contextJsonRequest = new WsdlTestRunContext(loginTestStep);
^
1 error
You have to include soupui-{version}.jar file in the classpath to resolve this dependency issue. You can find it in SoapUI-{version}/bin folder. Let's say that SoapUI 5.4.0 is located in /tmp/SoapUI-5.4.0/. In this case I can compile a script with following command:
groovyc -d classes -cp ".:/tmp/SoapUI-5.4.0/bin/soapui-5.4.0.jar" script.groovy
Keep in mind that this command is run from the folder where script.groovy is located and compiled class can be found in ./classes/script.class

groovy spock testing Mock and returned proxy

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.

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