checking partcular filed in a response in spring cloud contact creation - spring-cloud-contract

Is there any way to test only particular field in a response is matching with the given text or not while writing a contract using spring-cloud-contract framework.
package contracts
import org.springframework.cloud.contract.spec.Contract
Contract.make {
request {
method 'GET'
url value(consumer(regex('/app/emp/employee/[0-9]{3}')), producer('/app/emp/employee/151'))
}
response {
status 200
body([
subjectsList: null,
errorResponse: null,
status: 'success',
employeeList: null,
Employee: [
EmployeeId: 151,
firstName: 'xxx',
lastName: 'xxx',
middleName: 'xxx',
dateOfBirth: 01012001,
status: 'inbound',
cin: '345',
ssn: null,
EmployeeType: 'HoH',
preferredLanguage: 'french',
preferredContactMethod: null,
createdBy: null,
creadtedOn: null,
updatedBy: null,
updatedOn: null,
transactionId: null
],
paginated: null
])
headers {
header('Content-Type': value(
producer(regex('application/json.*')),
Employee('application/json')
))
}
}
}
Instead of writing complete response, Is there any way to check only particular attribute present in the response for ex: language = 'french'
Thanks in advance, your help is very much appreciated.

Sure, just remove all the other fields. Whatever you put in the body will get asserted. BTW what you do with the contract looks like a schema. If a field is null that means that it has to be there and it has to be null or rather it's optional?
If you want to do any custom assertion on the part of / whole body you can use this http://cloud.spring.io/spring-cloud-static/Dalston.SR4/multi/multi__contract_dsl.html#_dynamic_properties_in_matchers_sections and pass any jsonpath element for custom assertion
BTW for the response you can write headers { contentType(applicationJson()) }

Related

'Note' property not being added in clockify

How do I set the note field?
When I try to add a new Client with the following data (taken from logged request):
method: 'post',
data: '{"name":"Inger Lise Suprice AS","note":"10017"}',
I get the following response:
data: {
id: '***',
name: 'Inger Lise Suprice AS',
workspaceId: '***',
archived: false,
address: null,
note: null <-----
}
Notice the 'note' field is null, even though I set the field in the request.
I followed the example in the documentation. Assuming this is a bug.

How to return true if x data exists in JSON or CSV from API on Wordpress website

is there any easy method to call APIs from Wordpress website and return true or false, depends if some data is there?
Here is the API:
https://api.covalenthq.com/v1/137/address/0x3FEb1D627c96cD918f2E554A803210DA09084462/balances_v2/?&format=JSON&nft=true&no-nft-fetch=true&key=ckey_docs
here is a JSON:
{
"data": {
"address": "0x3feb1d627c96cd918f2e554a803210da09084462",
"updated_at": "2021-11-13T23:25:27.639021367Z",
"next_update_at": "2021-11-13T23:30:27.639021727Z",
"quote_currency": "USD",
"chain_id": 137,
"items": [
{
"contract_decimals": 0,
"contract_name": "PublicServiceKoalas",
"contract_ticker_symbol": "PSK",
"contract_address": "0xc5df71db9055e6e1d9a37a86411fd6189ca2dbbb",
"supports_erc": [
"erc20"
],
"logo_url": "https://logos.covalenthq.com/tokens/137/0xc5df71db9055e6e1d9a37a86411fd6189ca2dbbb.png",
"last_transferred_at": "2021-11-13T09:45:36Z",
"type": "nft",
"balance": "0",
"balance_24h": null,
"quote_rate": 0.0,
"quote_rate_24h": null,
"quote": 0.0,
"quote_24h": null,
"nft_data": null
}
],
"pagination": null
},
"error": false,
"error_message": null,
"error_code": null
}
I want to check if there is "PSK" in contract_ticker_symbol, if it exist and "balance" is > 0 ... then return true.
Is there any painless method because I'm not a programmer...
The Python requests library can handle this. You'll have to install it with pip first (package installer for Python).
I also used a website called JSON Parser Online to see what was going on with all of the data first so that I would be able to make sense of it in my code:
import requests
def main():
url = "https://api.covalenthq.com/v1/137/address/0x3FEb1D627c96cD918f2E554A803210DA09084462/balances_v2/?&format" \
"=JSON&nft=true&no-nft-fetch=true&key=ckey_docs "
try:
response = requests.get(url).json()
for item in response['data']['items']:
# First, find 'PSK' in the list
if item['contract_ticker_symbol'] == "PSK":
# Now, check the balance
if item['balance'] == 0:
return True
else:
return False
except requests.ConnectionError:
print("Exception")
if __name__ == "__main__":
print(main())
This is what is going on:
I am pulling all of the data from the API.
I am using a try/except clause because I need the code to
handle if I can't make a connection to the site.
I am looping through all of the 'items' to find the correct 'item'
that includes the contract ticker symbol for 'PSK'.
I am checking the balance in that item and returning the logic that you wanted.
The script is running itself at the end, but you can always just rename this function and have some other code call it to check it.

How to test pact with null data

I am aware of that PACT expects provider data need to be in our control, but I am facing following situation
I have pact contract for multiple consumers, all have some mandatory attribute and some are optional attribute, but business logic suppress all the attribute which are having null value, but according to contract I would still be needing that value as null,
what should I do for it?
Edit 1:
i.e let's say below my contract looks
consumer sent request with below params:
{ "method": "GET", "path" : "/pathOfApi", "headers":{ "accept": "json" } }
Provider responds with below data:
{ "Status": 200,
"body" :[
{"country" : "string",
"countryId" :"string",
"postalcode": "string",
"addressLine1" :"string",
"addressLine2" : "string"
"customerName" : "string",
"customerId" : "string"
}
]
now not all customer has address line 2, now in production if addressLine 2 is null it won't be present in output of api, but for our contract field should be present with null
If your provider does not return a field, but the consumer is expecting null, then either the consumer needs to change their expectation (because it's incorrect) or the provider should update its implementation to return null values.
Just because a consumer asks for something doesn't mean you need to do it!
If in some instances the field is present and other it is not, you need to write two tests to cover each case. I'd suggest covering one case with all of the fields, and another with the minimum set of fields (see https://docs.pact.io/faq/#why-is-there-no-support-for-specifying-optional-attributes).

AppSync BatchDeleteItem not executes properly

I'm working on a React Native application with AppSync, and following is my schema to the problem:
type JoineeDeletedConnection {
items: [Joinee]
nextToken: String
}
type Mutation {
deleteJoinee(ids: [ID!]): [Joinee]
}
In 'request mapping template' to resolver to deleteJoinee, I have following (following the tutorial from https://docs.aws.amazon.com/appsync/latest/devguide/tutorial-dynamodb-batch.html):
#set($ids = [])
#foreach($id in ${ctx.args.ids})
#set($map = {})
$util.qr($map.put("id", $util.dynamodb.toString($id)))
$util.qr($ids.add($map))
#end
{
"version" : "2018-05-29",
"operation" : "BatchDeleteItem",
"tables" : {
"JoineesTable": $util.toJson($ids)
}
}
..and in 'response mapping template' to the resolver,
$util.toJson($ctx.result.data.JoineesTable)
The problem is, when I ran the query, I got empty result and nothing deleted to database as well:
// calling the query
mutation DeleteJoinee {
deleteJoinee(ids: ["xxxx", "xxxx"])
{
id
}
}
// returns
{
"data": {
"deleteJoinee": [
null
]
}
}
I finally able to solve this puzzle, thanks to the answer mentioned here to point me to some direction.
Although, I noticed that JoineesTable does have trusted entity/role to the IAM 'Roles' section, yet it wasn't working for some reason. Looking into this more, I noticed that the existing policy had following actions as default:
"Action": [
"dynamodb:DeleteItem",
"dynamodb:GetItem",
"dynamodb:PutItem",
"dynamodb:Query",
"dynamodb:Scan",
"dynamodb:UpdateItem"
]
Once I added following two more actions to the list, things have started working:
"dynamodb:BatchWriteItem",
"dynamodb:BatchGetItem"
Thanks to #Vasileios Lekakis and #Ionut Trestian on this appSync quest )

meteor autocomplete server-side

I'm writing a meteor app and I'm trying to add an autocomplete feature to a search box. The data is very large and is on the server, so I can't have it all on the client. It's basically a database of users. If I'm not wrong, the mizzao:autocomplete package should make that possible, but I can't seem to get it to work.
Here's what I have on the server:
Meteor.publish('autocompleteViewers', function(selector, options) {
Autocomplete.publishCursor(viewers.find(selector, options), this);
this.ready();
});
And here are the settings I use for the search box on the client:
getSettings: function() {
return {
position: 'bottom',
limit: 5,
rules: [{
subscription: 'autocompleteViewers',
field: '_id',
matchAll: false,
options: '',
template: Template.vLegend
}],
};
}
But I keep getting this error on the client:
Error: Collection name must be specified as string for server-side search at validateRule
I don't really understand the problem. When I look at the package code, it just seems like it's testing whether the subscription field is a string and not a variable, which it is. Any idea what the problem could be? Otherwise is there a minimum working example I could go from somewhere? I couldn't find one in the docs.
Error: Collection name must be specified as string for server-side search at validateRule
You get this error because you don't specify a Collection name in quotes.
getSettings: function() {
return {
position: 'bottom',
limit: 5,
rules: [{
subscription: 'autocompleteViewers',
field: '_id',
matchAll: false,
collection: 'viewers', // <- specify your collection, in your case it is a "viewers" collection.
options: '',
template: Template.vLegend
}],
};
}
For more information please read here.
Hope this helps!

Resources