How to get last request from mock? - soap

I have groovy spript in test step, and MockOperation in MockService.
How to get last request in script?
Now I can check only time of last mock request:
def project = testRunner.testCase.testSuite.project
def mock = testRunner.testCase.testSuite.project.mockServices["mock"]
def service = mock.getMockOperationByName("service")
def req = service.getLastMockResult()

Welcome to Stackoverflow.
For a specific response, you really need to clarify a few things.
In your description, you describe you want "last request". In your code, you do "getLastMockResult". Do you want the last request or the last response?
Is it SOAP or REST?
You also make use of "mockIss". Where does that come from? Is just a typo, and really you mean the "mock" from the previous line?
On a more generic note, given this is a SOAP request, and the Groovy Script teststep is situated in the same testcase as the Soap Request teststep, you should be able to do something like this:
def request = context.expand( '${Name of Soap Request teststep#Request#declare namespace soap=\'http://www.w3.org/2003/05/soap-envelope\'; //soap:Envelope[1]}' )
def response = context.expand( '${Name of Soap Request teststep#Response#declare namespace soap=\'http://www.w3.org/2003/05/soap-envelope\'; //soap:Envelope[1]}' )
log.info request
log.info response

Related

mocking a request with a payload using wiremock

I'm currently trying to mock external server using Wiremock.
One of my external server endpoint takes a payload.
This endpoint is defined as follow :
def sendRequestToMockServer(payload: String) = {
for {
request_entity <- Marshal(payload).to[RequestEntity]
response <- Http().singleRequest(
HttpRequest(
method = HttpMethods.GET,
uri = "http://localhost:9090/login",
entity = request_entity
)
)
} yield {
response
}
}
To mock this endpoint using Wiremock, I have written the following code :
stubFor(
get(urlEqualTo("/login"))
.willReturn(
aResponse()
.withHeader("Content-Type","application/json")
.withBodyFile("wireMockResponse.json")
.withStatus(200)
)
.withRequestBody(matchingJsonPath("requestBody.json"))
)
where I Have defined the request body in the requestBody.json file.
But when I run tests , I keep getting an error indicating that the requested Url is not found.
I'm thinking that the error is related to this line withRequestBody(matchingJsonPath("requestBody.json")), because when I comment it the error disappear.
Any suggestions on how to work around this?
matchingJsonPath does not populate a file at a provided filepath, but instead evaluates the JsonPath provided. See documentation.
I'm not entirely sure there is a way to provide the request body as a .json file. If you copy the contents of the file into the withRequest(equalToJson(_yourJsonHere_)), does it work? If it does, you could get the file contents as a JSON string above the definition and provide it to the function (or I guess, make a function to return a JSON string from a .json file).
Additionally, you could make a custom request matcher that does the parsing for you. I think I'd recommend this only if the above does not work.

validating response outside of context manager?

[EDITED: I realized after reading response that I oversimplified my question.]
I am new to Locust and not sure how to solve this problem.
I have function (call it "get_doc") that is passed a locust.HttpSession() and uses it to issue an HTTP request. It gets the response and parses it, returning it up several layers of call. One of these higher-level calls looks at the returned, parsed document to decide if the response was what was expected or not. If not, I want Locust to mark the request/response as failed. A code sketch would be:
class MyUser (HttpUser):
#task
def mytask(self):
behavior1 (self.client)
def bahavior1(session):
doc = get_doc(session, url1)
if not doc_ok (doc):
??? how to register a failure with Locust here...
doc2 = get_doc(session, url2)
...
def get_doc(http_session, url):
page = http_session.get(url)
doc = parse (page)
return doc
There may be several behavior[n] functions and several Locust users calling them.
A constraint is that I would like to keep Locust-specific stuff out of bahavior1() so that I can call it with an ordinary Requests session. I have tried to do something like this in get_doc() (the catch_response parameter and success/fail stuff is actually conditionalized on 'session' being an HttpSession object):
def get_doc (session, meth, url):
resp = session.request (meth, url, catch_response=True)
doc = parse (resp.content)
doc.logfns = resp.success, resp.failure
return doc
and then in behavior1() or some higher up-chain caller I can
doc.logfns[1]("Document not as expected")
or
doc.logfns[0] # Looks good!
Unfortunately this is not working; the calls to them produce no errors but Locust doesn't seem to record any successes or failures either. I am not sure if it should work or I bungled something in my code. Is this feasible? Is there a better way?
You can make get_doc a context manager, call .get with catch_response=True and yield instead of return inside it. Similar to how it is done here: https://github.com/SvenskaSpel/locust-plugins/blob/2cbbdda9ae37b6cbb0a11cf69aca80b164198aec/locust_plugins/users/rest.py#L22
And then use it like this
def mytask(self):
with get_doc(self.client, url) as doc:
if not doc_ok(doc):
doc.failure(”doc was not ok :(”)
If you want, you can add the parsed doc as a field on the response before yielding in your doc function, or call doc.failure() inside doc_ok.

How to pass parameter to SOAP request in SOAPUI

I'm newbie to soap and soapui, I'm trying to create a test case in which I will send the same request(XML attachment) many times(about 500), the problem is that each time I need to increment/change a value in the request (the id).
Therefore, I wonder if the is a way to pass this parameter to the attached xml file ? or if there is another ways to do the test case.
Thank you in advance
UPDATE
here is the content of the xml file :
<mod:sendMSG xmlns:mod="http://test.soap/service/model">
<id>${#Project#parameter1}</id>
<date>2016-04-03T04:03:00</date>
<infos>
<firstName>AT </firstName>
<lastName>AT </lastName>
......
</infos>
</mod:sendMSG>
which is included in the soap request, ass shown in the following image :
Test steps:
Groovy Script
SOAP Request (disabled)
I disabled the SOAP Request because it runs once more after the script has already looped the request x times.
Groovy script:
int loops = 500;
for ( iter in 1..loops ) {
//Overwrite the 'parameter1' property at project level
testRunner.testCase.testSuite.project.setPropertyValue("parameter1", iter.toString())
//log.info("iter: " + testRunner.testCase.testSuite.project.getPropertyValue("parameter1"));
// Run the teststep named 'SOAP Request'
def testStep = testRunner.testCase.testSteps['SOAP Request'];
testStep.run( testRunner, context )
}
Now you should be able to run your TestCase. I recommend saving your project before, I had some problems with SoapUI crashing on me when running.

Splitting a REST response to separate fields in groovy and soapUI

I am working on a test suite in SoapUI that contain both REST and SOAP requests.
The scenario begins with a REST request. From the response I need to take the user name value.
The response is the following:
{
"user_name": "Z.ZCLGN",
"first_name": "Tester1",
"user_code": "19225",
"last_name": "QA"
}
I need the "Z.ZCLGN". How do I split the username value so I could transfer it to the next Soap Request? should I use split like I'm trying to do and if so how?
Thats what I have so far in a groovy script:
def responseAsXml = context.expand( '${GetToken#ResponseAsXml#declare namespace ns1=\'https://10.1.9.13/cvbs/oauth2/token\'; //ns1:Response[1]/ns1:user[1]}' )
log.info responseAsXml
def (user_name, first_name, Tester1, user_code, last_name) = responseAsXml.split("")
You don't need Groovy scripting for that.
Use Property Transfer.
http://www.soapui.org/Functional-Testing/transferring-property-values.html
But if you love scripting so much you still want to do it, here you go:
def json = new JsonSlurper().parseText(jsonText)
def userName = json.user_name
// now use userName in some other request by setting a property, for exampl
testRunner.testCase.setPropertyValue( "MyProp", userName )
More help about Json parsing here:
http://mrhaki.blogspot.se/2011/04/groovy-goodness-parse-json-with.html
But I would also recommend reading the tips for SoapUI beginners:
http://www.soapui.org/Getting-Started/10-tips-for-the-soapui-beginner.html

How do I set the POST headers of Play! 2.0 webservice query?

I am building a webservice request that submits some data to a 3rd party service we use:
val promise = WS.url("http://example.com/api/xxx/testers?api_key=%s" format(prefineryAPIKey)).post(requestBody)
val data = promise.value.get.body
The variable requestBody is XML content and I need to send this post with "Content-Type: text/xml". How do I set that inside the webservice? Does it work like Play!'s result by chaining .as("text/xml")?
Thanks
Found it! I had to dig around the API docs and decrypt some of the compiler errors, but basically the above will look like:
val promise = WS
.url("http://example.com/api/xxx/testers?api_key=%s" format(prefineryAPIKey))
.withHeaders("Content-Type" -> "text/xml")
.post(requestBody)
When you call WS you are putting together a WSRequestHolder. The docs for WSRequest are here:
http://www.playframework.org/documentation/api/2.0/scala/index.html#play.api.libs.ws.WS$$WSRequestHolder