How to catch an exception in phpunit - php

I am working on a functional test to check a specific user can't update a resource, in this case the API replays with a 404 error. This is the test:
static::createClient()->request(
'PUT',
'/api/bookings/' . $bookingIdToUpdate,
[
'auth_bearer' => $token,
'json' => [
'requestedBy' => 'a new value for this field',
],
]
);
self::assertResponseStatusCodeSame(Response::HTTP_NOT_FOUND, 'This user is not expected to be able to update this booking');
when I run this test, I get a 404 response, which is fine:
Testing App\Tests\Integration\BookingTest
2020-01-21T15:00:07+00:00 [error] Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\NotFoundHttpException: "Not Found" at /var/www/html/vendor/api-platform/core/src/EventListener/ReadListener.php line 116
. 1 / 1 (100%)
Time: 38.89 seconds, Memory: 42.50 MB
OK (1 test, 1 assertion)
so the test is passing but the console is still displaying the exception. so I added this just before client call:
$this->expectException(NotFoundHttpException::class);
and this is the result:
Testing App\Tests\Integration\BookingTest
2020-01-21T15:15:05+00:00 [error] Uncaught PHP Exception Symfony\Component\HttpKernel\Exception\NotFoundHttpException: "Not Found" at /var/www/html/vendor/api-platform/core/src/EventListener/ReadListener.php line 116
F 1 / 1 (100%)
Time: 41.39 seconds, Memory: 42.50 MB
There was 1 failure:
1) App\Tests\Integration\BookingTest::testUserCantUpdateABookingFromAnotherOrganisation
Failed asserting that exception of type "Symfony\Component\HttpKernel\Exception\NotFoundHttpException" is thrown.
FAILURES!
Tests: 1, Assertions: 2, Failures: 1.
as you can see the exception is thrown, but at the same time I am getting an error saying it was not. Any idea how to catch this?

Ensure you call the following method first:
$client->catchExceptions(false);
For example:
public function testUserCantUpdateABookingFromAnotherOrganisation()
{
$this->expectException(NotFoundHttpException::class);
$client = static::createClient();
$client->catchExceptions(false);
$client->request('GET', '/foo/bar');
$client->request(
'PUT',
'/api/bookings/' . $bookingIdToUpdate,
[
'auth_bearer' => $token,
'json' => [
'requestedBy' => 'a new value for this field',
],
]
);
self::assertResponseStatusCodeSame(Response::HTTP_NOT_FOUND, 'This user is not expected to be able to update this booking');
}

Related

Magento API throws 500 error, says check exception log but nothing is there

I am using guzzle to test upload products with the Magento API. Whenever I run this script:
<?php
require_once ('connparams.php');
try {
$response = $client->request('post', 'products',
[
"headers" => $headers,
'body' => json_encode([
'product' =>
['attribute_set_id' => 13],
['sku' => 12548],
['name' => 'widget'],
['price' => 1],
['type_id' => 'simple']
])
]);
}
I get the following error (which I'm outputting to a txt file with the catch block):
ERROR at: 06:50:15 pm | 500 | Internal Server Error | An error has happened during application run. See exception log for details.
When I check the exception log in Magento, there is not a new entry. There are entries for exceptions when I test the API with swagger.

Error: Failure when receiving data from the peer php GuzzleHttp

I'm trying to make post request and the post request is working but I'm not getting the response
$client = new \GuzzleHttp\Client(['headers' => ['Authorization' => 'Basic ' . 'token==']]);
$data = $client->post(
'url',
[
'form_params' => [
'address' => 'addreww',
'name' => 'Zia Sultan',
'phone_number' => '2136000000',
]
]
);
return $data;
What I'm getting in my insomnia
Error: Failure when receiving data from the peer
You're code is working, post method returns ResponseInterface, we need to fetch the content from it, we need to first fetch the StreamInterface by calling getBody() and chaining it will getContents() gives us the actual response. Keep debug mode On, to get find the exact error for Error: Failure when receiving data from the peer, and when this error occurs, share the entire trace with us
try {
$response = (new \GuzzleHttp\Client())->post(
'url',
[
'headers' => [
'Authorization' => 'Basic ' . 'token=='
],
'form_params' => [
'address' => 'addreww',
'name' => 'Zia Sultan',
'phone_number' => '2136000000',
],
// 'http_errors' => false, // Set to false to disable throwing exceptions on an HTTP protocol errors (i.e., 4xx and 5xx responses)
// 'debug' => true,
// 'connect_timeout' => 30 // number of seconds to wait while trying to connect to a server, Use 0 to wait indefinitely (the default behavior)
// 'read_timeout' => 10 // timeout to use when reading a streamed body, default value is default_socket_timeout in php.ini
// 'timeout' => 30 // the total timeout of the request in seconds. Use 0 to wait indefinitely (the default behavior).
]
);
return $response->getBody()->getContents();
} catch (Throwable $exception) {
print_r($exception);
}
I was returning the data only but I needed to return getBody() like this way
$data->getBody()
Its working now

PHP Soapclient returns object has no property

When sending a request from my PHP soapclient as described below, I get:
[getInterestAndExchangeRates failed: Please check inparameters in Xxx].
I suspect that it is the [$response] line that has wrong syntax. More specific the [$searchRequestParameters]. I have checked that all the content in the array is in the correct order.
Question:
Is there something wrong with below code syntax?
I have followed following instructions:
https://swea.riksbank.se/sweaWS/docs/api/call/getInterestAndExchangeRates.htm
<?php
/**
* A soapclient request to Swedish Central bank, API.
*/
$client = new SoapClient("https://swea.riksbank.se/sweaWS/wsdl/sweaWS_ssl.wsdl");
$searchGroupSeries = array(
"groupid" => 2,
"seriesid" => "SECBREPOEFF"
);
$searchRequestParameters = array (
"aggregateMethod" => "W",
"avg" => true,
"datefrom" => "2018-01-01",
"dateto" => "2019-01-01",
"languageid" => "en",
"max" => true,
"min" => false,
"searchGroupSeries" => $searchGroupSeries,
"ultimo" => false
);
// Test 1 (pointing out above array, does not work):
$response = $client->__soapCall("getInterestAndExchangeRates", $searchRequestParameters);
// Test 2 (wrap in above array inside another array, does not work):
// $response = $client->__soapCall('getInterestAndExchangeRates', array('searchRequestParameters' => $searchRequestParameters));
var_dump($response);
Error:
PHP Fatal error: Uncaught SoapFault exception: [soap:Server] getInterestAndExchangeRates failed: Please check inparameters in [path]_(does_not_work).php:22
Stack trace:
#0 [path]_(does_not_work).php(22): SoapClient->__soapCall('getInterestAndE...', Array)
#1 {main}
thrown in [path]_(does_not_work).php on line 22

WooCommerce Rest API returning invalid paramter 'shipping_lines' in create order

Creating a order from php rest api of woo-commerce version: wc/v3 and getting error
other apis are working fine tried with v2 still getting the same error
<?php
require __DIR__ . '/vendor/autoload.php';
use Automattic\WooCommerce\Client;
$wc = new Client(
'https://example.com/',
'client key',
'client secret',
[
'wp_api' => true,
'version' => 'wc/v3',
]
);
$data = [
'payment_method' => 'cod',
....
'shipping_lines' => [
[
'method_id' => 'flat_rate',
'method_title' => 'Flat Rate',
'total' => 10
]
]
];
print_r($wc->post('orders', $data));
Getting this error, if i remove shipping lines working fine and creating the order
[07-May-2019 06:39:45 UTC] PHP Fatal error: Uncaught Automattic\WooCommerce\HttpClient\HttpClientException: Error: Invalid parameter(s): shipping_lines [rest_invalid_param] in /home/gathhnaw/public_html/mapi/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php:350
Stack trace:
#0 /home/gathhnaw/public_html/mapi/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php(386): Automattic\WooCommerce\HttpClient\HttpClient->lookForErrors(Object(stdClass))
#1 /home/gathhnaw/public_html/mapi/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php(422): Automattic\WooCommerce\HttpClient\HttpClient->processResponse()
#2 /home/gathhnaw/public_html/mapi/vendor/automattic/woocommerce/src/WooCommerce/Client.php(56): Automattic\WooCommerce\HttpClient\HttpClient->request('orders', 'POST', Array)
#3 /home/gathhnaw/public_html/mapi/create_order.php(46): Automattic\WooCommerce\Client->post('orders', Array)
#4 {main}
thrown in /home/gathhnaw/public_html/mapi/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php on line 350
There seems to be a typo or documentation error on woo api. Just surround the total value between single quotes and run it
https://www.infocaptor.com/dashboard/woocommerce-rest-api-php-example-error-creating-order

Test every time is skipped by PHPUnit

I'm using PHPUnit with CakePHP to test a Custom Finder but test is every time skipped and I do not know what the reason
OK, but incomplete, skipped, or risky tests!
TestCase:
class UsersTableTest extends TestCase
{
public $fixtures = [
'app.users',
'app.user_types',
'app.bookings',
'app.stores'
];
public function setUp()
{
parent::setUp();
$this->Users = TableRegistry::get('Users');
}
public function testFindUser(){
$query = $this->Users->find('user', [
'fields' => ['Users.id', 'Users.email', 'Users.password',
'Users.username'],
'conditions' => ['Users.id' => 900000]
]);
$this->assertInstanceOf('Cake\ORM\Query', $query);
$result = $query->hydrate(false)->toArray();
$expected = [
[
'id' => 900000,
'email' => 'usuariocomum1#gmail.com',
'password' => 'usuariocomum1senha',
'username' => 'usuariocomum1username'
]
];
$this->assertEquals($expected, $result);
}
Method tested:
public function findUser(Query $query, array $options){
$query->where($options);
return $query;
}
Users Fixture:
public $records = [
[
'id' => 900000,
'email' => 'usuariocomum1#gmail.com',
'password' => 'usuariocomum1senha',
'username' => 'usuariocomum1username',
'user_type_id' => 900000,
'created' => '2015-07-17 18:46:47',
'modified' => '2015-07-17 18:46:47'
]
]
I'm Following this tutorial CakePHP 3.0 Testing
[EDIT 1]
With --verbose flag:
c:\xampp\htdocs\PROJETOS\Shopping>vendor\bin\phpunit --verbose tests\TestCase\Mo
del\Table\UsersTableTest
PHPUnit 4.8.6 by Sebastian Bergmann and contributors.
Runtime: PHP 5.6.3
Configuration: C:\xampp\htdocs\PROJETOS\Shopping\phpunit.xml.dist
III.
Time: 15.87 seconds, Memory: 7.50Mb
There were 3 incomplete tests:
1) App\Test\TestCase\Model\Table\UsersTableTest::testInitialize
Not implemented yet.
C:\xampp\htdocs\PROJETOS\Shopping\tests\TestCase\Model\Table\UsersTableTest.php:
58
2) App\Test\TestCase\Model\Table\UsersTableTest::testValidationDefault
Not implemented yet.
C:\xampp\htdocs\PROJETOS\Shopping\tests\TestCase\Model\Table\UsersTableTest.php:
71
3) App\Test\TestCase\Model\Table\UsersTableTest::testBuildRules
Not implemented yet.
C:\xampp\htdocs\PROJETOS\Shopping\tests\TestCase\Model\Table\UsersTableTest.php:
81
OK, but incomplete, skipped, or risky tests!
Tests: 4, Assertions: 2, Incomplete: 3.
[EDIT 2]
When I change test to:
public function testFindUser(){
$query = $this->Users->find('user', [
'fields' => ['Users.id', 'Users.email', 'Users.password',
'Users.username', 'Users.user_type_id', 'Users.created',
'Users.modified'],
'conditions' => ['Users.id' => 900000]
]);
$this->assertInstanceOf('Cake\ORM\Query', $query);
$result = $query->hydrate(false)->toArray();
$expected = [
[
'id' => 900000,
'email' => 'usuariocomum1#gmail.com',
'password' => 'usuariocomum1senha',
'username' => 'usuariocomum1username',
'user_type_id' => 900000,
'created' => '2015-07-17 18:46:47',
'modified' => '2015-07-17 18:46:47'
]
];
$this->assertEquals($expected, $result);
}
the test is executed but fails (hidrate(false) could make created and modified primitive objects)(Why now works? why 'user_type_id' => 900000 displayed)
my console:
c:\xampp\htdocs\PROJETOS\Shopping>vendor\bin\phpunit tests\TestCase\Model\Table\
UsersTableTest
PHPUnit 4.8.6 by Sebastian Bergmann and contributors.
IIIF
Time: 8.13 seconds, Memory: 7.75Mb
There was 1 failure:
1) App\Test\TestCase\Model\Table\UsersTableTest::testFindUser
Failed asserting that two arrays are equal.
--- Expected
+++ Actual
## ##
'user_type_id' => 900000
- 'created' => '2015-07-17 18:46:47'
- 'modified' => '2015-07-17 18:46:47'
+ 'created' => Cake\I18n\Time Object (...)
+ 'modified' => Cake\I18n\Time Object (...)
)
)
C:\xampp\htdocs\PROJETOS\Shopping\tests\TestCase\Model\Table\UsersTableTest.php:
107
FAILURES!
Tests: 4, Assertions: 2, Failures: 1, Incomplete: 3.
[EDIT 3]
I clean my TestCase and delete all not implemented test (created by bake) and this is the output:
c:\xampp\htdocs\PROJETOS\Shopping>vendor\bin\phpunit tests\TestCase\Model\Table\
UsersTableTest
PHPUnit 4.8.6 by Sebastian Bergmann and contributors.
.
Time: 6.06 seconds, Memory: 7.50Mb
OK (1 test, 2 assertions)
**NOTE** CakePHP 3.0.11 PHPUnit 4.8.6
We had this in your other question, hadn't we? The testFindUser test is not being skipped, it runs just fine as you can tell from the PHPUnit output, and from the fact that you receive a failure message when you change your code so that it produces and error, if it were skipped, there would have been no failures, and the output would have been IIIS.
OK, but incomplete, skipped, or risky tests!
Tests: 4, Assertions: 2, Incomplete: 3.
* emphasis mine
4 tests in total, 3 incomplete, = 1 test ran
The message just says that there are incomplete/non-implemented tests, additionally to the tests that ran OK.
The verbose level output makes this even more clear, in showing you exactly which tests are incomplete - none of them is your testFindUser test.
You may want to have a closer look at the docs, to get a grasp on how to interpret the output.
https://phpunit.de/manual/current/en/textui.html

Categories