com.github.tomakehurst.wiremock.client.VerificationException: A request was unmatched by any stub mapping - wiremock

I am trying to create simple wiremock test app. I created stubs in mapping.json file but while running the test using "mvn clean test", I am getting VerificationException. My java code is-
String url = "http://localhost:8080/api/resources/";
HttpClient client = HttpClientBuilder.create().build();
HttpUriRequest request = new HttpGet(url);
request.addHeader("Content-Type", "application/json");
request.addHeader("Accept", "application/json");
HttpResponse response = client.execute(request);
verify(getRequestedFor(urlPathEqualTo("/api/resources/"))
.withHeader("Content-Type", equalTo("application/json")));
Can someone please let me know what I am missing. Json file-
{
"mappings": [
{
"request": {
"method": "GET",
"url": "/api/resources"
},
"response": {
"status": 200,
"bodyFileName": "Wiremock-test.json",
"headers": {
"Content-Type": "application/json"
}
}
}
]
}

Related

How to set a wiremock stub when there is a json is required in the query param

I am new to wiremock , I am trying to setup a stub for a get request which looks like
/details?employee-info={“name”:”rahul”}
I tried below stub but got exception
Stub:
{
"request": {
"method": "GET",
"urlPathPattern": "/details",
"queryParameters": {
"query-param": {
"equalTo": "{"\name\":\"rahul\"}"
}
},
"response": {
"status": 200,
"bodyFileName": "emplyeeDetails/rahul",
"headers": {
"Content-Type": "application/json"
}
}
}
}
Exception: java.lang.IllegalArgumentException: Invalid character found in the request target [/details?employee-info={%22name%22:%22rahul%22}].
Please help, many thanks in advance.

First success, second same request error stub response

Here my wiremock stub mapping:
{
"request": {
"method": "POST",
"urlPattern": "/api/myApp"
},
"response": {
"headers": {
"Content-Type": "application/json"
},
"status": 200
}
}
So when client execute http request with url pattern = /api/myApp then WireMock return success http status = 200.
Nice. It's work fine.
But I need when client execute second request with same url pattern the WireMock must return this stub response:
{
"request": {
"method": "POST",
"urlPattern": "/api/myApp"
},
"response": {
"headers": {
"Content-Type": "application/json"
},
"status": 401
}
}
So:
First request -> stub response 200
Second same request -> stub response 401
Is it possible by WireMock ?
If you are always going to have the pattern of the first call is successful and the second call is unsuccessful, you can use Scenarios to achieve this.
{
"scenarioName": "My Scenario",
"requiredScenarioState": "Started",
"newScenarioState": "Triggered Once",
"request": {}
"response": {
"status": 200
}
}
{
"scenarioName": "My Scenario",
"requiredScenarioState": "Triggered Once",
"newScenarioState": "Started",
"request": {}
"response": {
"status": 401
}
}
scenarioName is any string that you want to name the scenario
requiredScenarioState is the state the scenario has to be in. All Scenarios begin at a state of "Started".
newScenarioState is any string to denote the new Scenario State.
In the above, it will always alternate between successful 200 calls and unsuccessful 401 calls.
For more information on Stateful Behavior in WireMock, check out the docs

Always getting error "requestId is required" when doing POST on quickbooks payment API Apps Script

Im creating a script that will process a credit transaction and I always getting this response:
{
"errors": [
{
"code": "PMT-4002",
"type": "invalid_request",
"message": "requestId is required.",
"detail": "requestId",
"infoLink": "https://developer.intuit.com/v2/docs?redirectID=PayErrors"
}
]
}
Im trying to figure out where to put the "request-id" parameter on the request body. Here is my code:
function QBOcreatecharge(){
var token = "TOKEN"
var service = getQuickbooksService();
if (service.hasAccess()) {
var url = 'https://sandbox.api.intuit.com/quickbooks/v4/payments/charges'
var Details =
{
"amount": "80.00",
"currency": "USD",
"capture": "false",
"token": token
}
var params = {
headers: {
Authorization: 'Bearer ' + service.getAccessToken()
},
contentType: 'application/json',
method: 'POST',
payload: JSON.stringify(Details),
muteHttpExceptions:true
}
var response = UrlFetchApp.fetch(url, params);
var value = JSON.parse(response.getContentText())
Logger.log(value)
}
else{
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s', authorizationUrl);
}
}
How do I add the requestId parameter? I tried to insert it on the link, on the header and nothing work. Im using UrlFetch on Google Apps Script. Any help will be appreciated. Thanks!
The Request-Id is a header you need to send. e.g.:
headers: {
Authorization: 'Bearer ' + service.getAccessToken(),
'Request-Id': your unique value here
},
Intuit documents it here:
https://developer.intuit.com/app/developer/qbpayments/docs/develop/explore-the-quickbooks-payments-api/rest-api-features#identifiers

HTTP request to Cloud-Convert not working

I am trying to use fetch to POST an API call to Cloud Convert and getting the following error:
message: "The given data was invalid."
code: "INVALID_DATA"
errors: {...}
tasks: Array(1)
0: "The tasks field is required."
Here is my code (on Wix):
export async function convertMp4toMp3(fileUrl, filename) {
filename = filename.replace(/mp4/gi, "mp3")
let job = {
tasks: {
"import-2": {
"operation": "import/url",
"url": fileUrl
},
"task-1": {
"operation": "convert",
"input_format": "mp4",
"output_format": "mp3",
"engine": "ffmpeg",
"input": [
"import-2"
],
"audio_codec": "mp3",
"audio_qscale": 0
},
"export-1": {
"operation": "export/google-cloud-storage",
"input": [
"task-1"
],
"project_id": "project-id",
"bucket": "bucket",
"client_email": "client_emailXXXXXXX",
"file": filename,
"private_key": "My Private Key
}
}
}
let options = {
"method": "POST",
"body": job,
"headers": {
"Authorization": "Bearer MyApiKey",
"Content-type": "application/json"
}
}
let response = await fetch("https://api.cloudconvert.com/v2/jobs", options)
console.log(response.json())
}
As you can see, the "tasks" field is populated with the jobs...
The fetch API does not automatically encode JSON.
Try:
let options = {
"method": "POST",
"body": JSON.stringify(job),
"headers": {
"Authorization": "Bearer MyApiKey",
"Content-type": "application/json"
}
}

Wiremock Capture path param and return in the response body

I am trying to create dynamic mocks using WireMock. I have a situation where if I specify URL like :
http://localhost:8089/api/account/abc#abc.com
then I should receive response like:
{
"account" : "abc#abc.com"
}
In brief, the path param is returned in the response body. I am able to make the request URL generic by using urlPathPattern set to /api/account/([a-z]*) however, I am not sure how should I capture abc#abc.com and return this in the response using regular expressions.
In WireMock the regular expressions can be used to recognize the email format in the Request Matching. For the purpose of this example I used a very crude example. Your production implementation may require a more robust approach.
This request:
http://localhost:8181/api/account/someone#somewhere.net
Is matched by this rule:
{
"request": {
"method": "GET",
"urlPathPattern": "/api/account/([a-z]*#[a-z]*.[a-z]*)"
},
"response": {
"status": 200,
"jsonBody": {
"account": "{{request.path.[2]}}"
},
"transformers": ["response-template"],
"headers": {
"Content-Type": "application/json"
}
}
}
And returns this response:
{
"account": "someone#somewhere.net"
}
It makes use of a Response Template processing functionality in WireMock. The Request Model variables [{{request.path.[2]}}] can be used to obtain sections from the request.
The same can be done using WireMock.Net - Response-Templating
The rule looks like:
{
"Request": {
"Path": {
"Matchers": [
{
"Name": "RegexMatcher",
"Pattern": "^/api/account/([a-z]*#[a-z]*.[a-z]*)$"
}
]
},
"Methods": [
"get"
]
},
"Response": {
"StatusCode": 200,
"BodyAsJson": {
"account": "{{request.PathSegments.[2]}}"
},
"UseTransformer": true,
"Headers": {
"Content-Type": "application/json"
}
}
}