How to seeResponseContainsJson two levels deep with Codeception? - php

I am new to Codeception and I am trying to test my web service using the same. Right now I am trying to figure out how to dig deep and test the output that comes from different API points. For example, I am trying to create a user and check if the response contains the necessary details.
CreateUserCept.php
<?php
$faker = Faker\Factory::create();
$I = new ApiTester($scenario);
$I->wantTo('create a new user');
$I->haveHttpHeader('Authorization', 'Bearer ' . file_get_contents('tests/api/token'));
$I->sendPost('users', [
"first_name" => "Test",
"last_name" => "Test",
"email" => 'test#test.com',
"password" => "testing",
"role" => "1"
]);
$I->seeResponseCodeIs(200);
$I->seeResponseIsJson();
The response looks something like:
{
"status": "success",
"data": {
"first_name": "Test",
"last_name": "Test",
"email": "test#test.com",
"updated_at": "2015-11-12 09:08:31",
"created_at": "2015-11-12 09:08:31",
"id": 54
},
"errors": null,
"message": "Resource Created Successfully"
}
Now I can do assertions like:
$I->seeResponseContainsJson(['status' => 'success']);
And it works like a charm but when I do this:
$I->seeResponseContainsJson(['data.first_name' => 'Test']);
It fails. What is the correct way to dig into these and check the JSON response is correct?

This worked for me finally:
$I->seeResponseContainsJson(['data' => [
'first_name' => 'Test'
]]);

Related

Need help. Prepared envelope registered but not sent to email

I am just starting to work this lib and need some help in first steps.
I need to have template for sending to defined in code recipients with prefilled data.
I have template with fullName field and one sign field
In code I am creating new envelope. Code example is:
$envelopeDefinition = new \DocuSign\eSign\Model\EnvelopeDefinition(
[
'status' => 'sent',
'template_id' => $templateId,
]
);
$signer = new \DocuSign\eSign\Model\TemplateRole(
[
'email' => $email,
'name' => $name,
'role_name' => 'signer',
'client_user_id' => 1000,
'tabs' => new \DocuSign\eSign\Model\Tabs(
[
'sign_here_tabs' => [
new \DocuSign\eSign\Model\SignHere(['tab_label' => 'sign'])
]
]
)
]
);
$envelopeDefinition->setTemplateRoles([$signer]);
$envelopeApi = new \DocuSign\eSign\Api\EnvelopesApi($authService->getAuthorizedApiClient());
$envelopeApi->createEnvelope($accountId, $envelopeDefinition);
Envelope was created and it is displayed in manage tab in DocusignUI
In history there are only register event listed. I can't see any sending invitations to email event
No email was received
Could you explain what's wrong with my code?
Addition
I am also trying to create new template in similar way as in EG008CreateTemplate from examples in short version to check if there are any problems with my template configuration.
My request sends post-data:
{
"description": "Example template created via the API",
"documents": [
{
"documentBase64": "...",
"documentId": "1",
"fileExtension": "pdf",
"name": "Debug Agreement"
}
],
"emailSubject": "Please sign this document",
"name": "Debug Agreement Template",
"recipients": {
"signers": [
{
"recipientId": "1",
"roleName": "signer",
"routingOrder": "1",
"tabs": {
"numberTabs": [
{
"documentId": "1",
"font": "helvetica",
"fontSize": "size14",
"pageNumber": "1",
"required": "false",
"tabLabel": "numbersOnly",
"width": "84",
"xPosition": "163",
"yPosition": "260"
}
],
"signHereTabs": [
{
"documentId": "1",
"pageNumber": "1",
"xPosition": "191",
"yPosition": "148"
}
],
"textTabs": [
{
"documentId": "1",
"font": "helvetica",
"fontSize": "size14",
"height": "23",
"pageNumber": "1",
"required": "false",
"tabLabel": "text",
"width": "84",
"xPosition": "153",
"yPosition": "230"
}
]
}
}
]
},
"shared": "false",
"status": "created"
}
And receives again error The request body is missing or improperly formatted. New Account definition(s) not found in the request body.
Who can explain what does this error means? I can't find any descriptions for this case
Take out this line:
'client_user_id' => 1000
This line is used for embedded signing, which is not sending an email, because you embed it in your app.
You want remote signing with an email, so you shouldn't provide a client_user_id.
After digging up code and request process it was detected that accountId was empty and request called https://demo.docusign.net/restapi/v2.1/accounts//templates
Provided error message is not correct as I tend to think.
It is strange for me that I was able to get templates list, create new envelopes with empty accountId...

How to send dynamic template mail via guzzle HTTP in PHP

I'm trying to send an email via Dynamic template in SendGrid using Guzzle HTTP in PHP.
But I was not able to send mail. As I get only the error like below without any reason in it.
Type: GuzzleHttp\Exception\ClientException
Message: Client error: `POST https://api.sendgrid.com/v3/mail/send` resulted in a `400 Bad Request` response: {"errors":[{"message":"Bad Request","field":null,"help":null}]}
My PHP example code:
require __DIR__.'../../vendor/autoload.php';
$CLIENT = new GuzzleHttp\Client();
$response = $CLIENT->request('POST', 'https://api.sendgrid.com/v3/mail/send', [
"headers" => [
"Authorization" => "Bearer my-api-key",
"Content-Type" => "application/json"
],
'data' => '{
"from": {
"email": "admin#example.com"
},
"personalizations": [{
"to": [{
"email": "me#gmail.com"
}],
"dynamic_template_data": {
"email_data": [{
"id": "2",
"title": "Artificial Intelligence in Health Care",
"image": "https://example.com//uploads/3663581583995181_0724.jpg",
"description": "Immediate application of AI in the Health Care domains."
}, {
"id": "199",
"title": "Aesthetics Skill Discussion 3 by Jranand",
"image": "",
"description": "Aesthetics Skill Discussion 3 by Jranand"
}]
}
}],
"template_id": "my-template-id"
}',
]);
echo $response->getStatusCode();
I was able to send an email via the dynamic template test method in SendGrid with the same dynamic_template_data. But trying this with Guzzle HTTP. I m not able to find the reason for the error.
Able to send an email with dynamic JSON data in the testing.
Can anyone help me out to solve the problem?
Thanks in advance.
There is no data request option in json, you need to change your code either you can use json request option from guzzle(will need lesser effort) or you can directly right your body.
try{
$CLIENT = new GuzzleHttp\Client();
$data = [
"from" => [
"email" => "admin#example.com"
],
"personalizations" => [
[
"to" => [
[
"email" => "me#gmail.com"
]
],
"dynamic_template_data" => [
"email_data" => [
[
"id" => "2",
"title" => "Artificial Intelligence in Health Care",
"image" => "https://example.com//uploads/3663581583995181_0724.jpg",
"description"=> "Immediate application of AI in the Health Care domains."
],
[
"id" => "199",
"title" => "Aesthetics Skill Discussion 3 by Jranand",
"image" => "",
"description" => "Aesthetics Skill Discussion 3 by Jranand"
]
]
]
]
],
"template_id" => "my-template-id"
];
$response = $CLIENT->request('POST', 'https://api.sendgrid.com/v3/mail/send', [
"headers" => [
"Authorization" => "Bearer my-api-key",
"Content-Type" => "application/json"
],
'json' => $data,
]);
if ($guzzleResponse->getStatusCode() == 200) {
$response = json_decode($guzzleResponse->getBody(),true);
//perform your action with $response
}
}
catch(\GuzzleHttp\Exception\RequestException $e){
// you can catch here 400 response errors and 500 response errors and log those errors
}catch(Exception $e){
//other errors
}

Retrieving data from two collections in MongoDB with PHP having _id as a value already

I'm trying to use aggregate to return token and kyc_status in an API call.
I have below data in tokens collection
{
"_id": {
"$oid": "5fca628feb1f03d82c76e85f"
},
"user_id": "5fca62d0eb1f03d82c76e860",
"token": "token_here",
"valid_till": "2021-01-03",
"created": "2020-12-04 20:27:05",
"modified": "2020-12-04 20:27:05"
}
then I have below data in users collection
{
"_id": {
"$oid": "5fca62d0eb1f03d82c76e860"
},
"seller_type_id": "",
"status": {
"$numberInt": "1"
},
"kyc_status": "pending",
"username": "user_name",
"password": "password_here",
"email": "email_here",
"primary_contact": "primary",
"secondary_contact": "secondary"
}
Now i have id 5fca62d0eb1f03d82c76e860 in $user_id PHP variable
I'm using the below code to achieve to show kyc_status and token
$result = $collection->aggregate( [
[ '$lookup' => [
'from' => 'users',
'localField' => '_id',
'foreignField' => 'user_id',
'as' => 'user_role'
]
],
[ '$unwind' => '$user_info' ],
[
'$project' => [ 'kyc_staus' => '$user_info.kyc_status' ]
]
]
);
I do not get any out put when I print the $result variable it shows me a whole lot of data but does not show what I want, I searched and tried most of StackOverflow answers to the same but did not get any.
Can anyone let me know where i am goring wrong / what should i do to get the desired output?

How do I get a property of non object in php?

This is the array:
$response = array( 'message-count' => '1', 'messages' => array ( 0 => array ( 'to' => '12345667888', 'message-id' => 'XXXXXXXXXXX', 'status' => '0', 'remaining-balance' => '9.26820000', 'message-price' => '0.03330000', 'network' => '11111', ), ), );
What code do I use to get like, for example, the 'message-id' 's data?
I've tried $response->messages["message-id"];
but what I get is Trying to get property 'messages' of non-object
Tried a lot of others as well they are all returning the same error
I am quite new to this so I hope I could get some help here
Sorry:
Vardump gives me this, made a mistake with the code above
'{
"message-count": "1",
"messages": [{
"to": "12345667888",
"message-id": "XXXXXXXXXXX",
"status": "0",
"remaining-balance": "9.20160000",
"message-price": "0.03330000",
"network": "11111"
}]
}'
response is an array, you can't get messages like -> , You should get message-id by this way:
$jsonStr = '{
"message-count": "1",
"messages": [{
"to": "12345667888",
"message-id": "XXXXXXXXXXX",
"status": "0",
"remaining-balance": "9.20160000",
"message-price": "0.03330000",
"network": "11111"
}]
}';
$data = json_decode($jsonStr);
$messageId = $data->messages[0]->{'message-id'};
echo $messageId; //or var_dump($messageId)
Your array contains non-object values so you can retrieve the values as below.
<?php
$response = array('message-count' => '1', 'messages' => array(0 => array('to' => '12345667888', 'message-id' => 'XXXXXXXXXXX', 'status' => '0', 'remaining-balance' => '9.26820000', 'message-price' => '0.03330000', 'network' => '11111',),),);
echo $response['messages'][0]['message-id'];
// Output
// XXXXXXXXXXX
I would use array_column function like this
array_column($response['messages'], 'message-id');
$msg = '{
"message-count": "1",
"messages": [{
"to": "12345667888",
"message-id": "XXXXXXXXXXX",
"status": "0",
"remaining-balance": "9.20160000",
"message-price": "0.03330000",
"network": "11111"
}]
}';
$data = json_decode($msg);
$messageId = $data->messages[0]->{'message-id'};
var_dump($messageId);
If you have more than one message in the list then,
$messages = $data->messages;
foreach ($messages as $index => $message) {
var_dump($message); // whole message detail
var_dump($message->{'message-id'});// message-id
}

Elasticseach doesn't map all given fields [PHP]

I'm working with Elasticsearch-PHP client. I want to index my datas, but I have a problem with mapping. There is a problem: I create my data array, everything works fine, but when I add this array to my index body => my_data_array some datas show up, but not all of them. I don't know why. I just digged and try all of following steps but nothing changed.
I just attached my snippets.
This my controller file where I index datas:
{
$params = ['body' => []];
foreach($all_ads as $key => $ads){
$params['body'][] = [
'index' => [
'_index' => 'demo_data',
'_type' => 'demo',
'_id' => $ads->id
]
];
$params['body'][] = $ads->indexParams();
}
$responses = $client->bulk($params);
this is result json object:
"response": [
{
"id": 85345,
"old_id": "5088063",
"user_id": "2706",
"category_id": "15",
"type": "3",
"title": array[3],
"slug": "",
"sub_region_id": "8",
"condition": "1",
"username": "John Doe",
"price": "82000",
"price_type": "1",
"no_phone": "0",
"views": "29",
"hot": "0",
"vip": "0",
"price_measure": "0"
}
I have a datafield and it is not visible here.
Its data mapping structure
'data' => [
'type' => 'object',
'properties' => [
'key_id' => ['type' => 'integer'],
'value_id' => ['type' => 'integer'],
'key' => ['type' => 'keyword'],
'value' => ['type' => 'keyword']
]
]
How can I fix it?
I just check some question from here and github issue forum but nothing helps. Thanks!
You have to follow solution of the question. Its maybe helpful for you.
Elasticsearch mapping not working as expected
Ask Question

Categories