Test every time is skipped by PHPUnit - php

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

Related

How to catch an exception in phpunit

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');
}

MongoDB error when using aggregation: "allowDiskUse" => true

I get the mongo error: Read timed out after reading 0 bytes, waited for 30.000000 seconds when I use aggregation sort.
In local it works correctly, but on the server it gives an error.
I am using mongo 3.2
This is my aggregation
$collection->aggregate(
[
array('$unwind' => '$skills.skill'),
array('$match' => array('skills.skill.name' => $str)),
array('$unwind' => '$skills.skill.value'),
array('$sort' => array('skills.skill.value.value' => -1) ),
array('$group' => array('_id' => null, 'updates' => array('$push' => '$skills.skill.value') )),
array('$project' => array('value' => '$updates'))
],
array("allowDiskUse" => true)
);
First, I use aggregation without the allowDiskUse option, and I get error: Sort exceeded memory limit of 104857600 bytes, then I added option: allowDiskUse : true and I get an error: Read timed out after reading 0 bytes, waited for 30.000000 seconds
How to solve this problem?
I tried $cursor->timeout(-1), but no results.

How do I deal with Class 'PHPUnit_Framework_TestCase' not found error?

I am trying to integrate to visa direct API. I decided to to it in PHP. However, as I am doing some tests from a sample code they have provided, I got stuck at Fatal error: Class 'PHPUnit_Framework_TestCase' not found error.
I have PHPUnit installed since when I check via phpunit --version ..I get PHPUnit 5.6.2 by Sebastian Bergmann and contributors.
Below is my code using PHPUnit, would someone direct me where my mistake is? Thank you.
<?php
class MVisaTest extends \PHPUnit_Framework_TestCase {
public function setUp() {
$this->visaAPIClient = new VisaAPIClient;
$strDate = date('Y-m-d\TH:i:s', time());
$this->mVisaTransactionRequest = json_encode ([
"acquirerCountryCode" => "643",
"acquiringBin" => "400171",
"amount" => "124.05",
"businessApplicationId" => "CI",
"cardAcceptor" => [
"address" => [
"city" => "Bangalore",
"country" => "IND"
],
"idCode" => "ID-Code123",
"name" => "Card Accpector ABC"
],
"localTransactionDateTime" => $strDate,
"merchantCategoryCode" => "4829",
"recipientPrimaryAccountNumber" => "4123640062698797",
"retrievalReferenceNumber" => "430000367618",
"senderAccountNumber" => "4541237895236",
"senderName" => "Mohammed Qasim",
"senderReference" => "1234",
"systemsTraceAuditNumber" => "313042",
"transactionCurrencyCode" => "USD",
"transactionIdentifier" => "381228649430015"
]);
}
public function testMVisaTransactions() {
$baseUrl = "visadirect/";
$resourcePath = "mvisa/v1/cashinpushpayments";
$statusCode = $this->visaAPIClient->doMutualAuthCall ( 'post', $baseUrl.$resourcePath, 'M Visa Transaction Test', $this->mVisaTransactionRequest );
$this->assertEquals($statusCode, "200");
}
}
You can just use TestCase class instead so you can say:
use PHPUnit\Framework\TestCase;
class MVisaTest extends TestCase {
// your tests goes here
}

Can't access CakePHP fixture db when triggering test with Travis CI

so I have a project in CakePHP. When pushing my code, Travis CI should run my test. My Test is named ToolTest and its Fixture is ToolFixture.
My .travis.yml looks as following:
language: php
php: 5.3
services:
- mysql
before_script:
- sh -c "mysql -e 'CREATE DATABASE test;'"
- chmod -R 777 project/tmp
- echo "<?php
class DATABASE_CONFIG {
public \$test = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'database' => 'test',
'host' => 'localhost',
'login' => 'travis'
);
}" > project/database.php
script:
sudo project/Console/cake test app Model/Tool --stderr
The error strack trace on travis says:
Fatal error: Uncaught exception 'MissingConnectionException' with message 'Database connection "Mysql" is missing, or could not be created.' in /home/travis/build/project/lib/Cake/Model/Datasource/Database/Mysql.php:194
Error: Database connection "Mysql" is missing, or could not be created.
I already tried '127.0.0.1' instead of localhost, same error messages. When running my test on the VM, the test passes.
What I've noticed:
If I'm not running the script command, travis is successful, so creating the db test and writing the database.php should work fine, right?
My test and fixture are pretty minimalistic.
ToolTest:
public function setUp()
{
parent::setUp();
$this->Tool = ClassRegistry::init('Tool');
}
public function testFindListById()
{
$result = $this->Tool->findListById(2);
$expected = array(
2 => 'Java'
);
$this->assertEquals($expected, $result);
}
ToolFixture:
class ToolFixture extends CakeTestFixture
{
public $useDbConfig = 'test';
public $fields = array(
'id' => 'string',
'name' => 'string'
);
public $records = array(
array(
'id' => 1,
'name' => 'HTML'
),
array(
'id' => 2,
'name' => 'Java'
)
);
}
What am I missing? I've been stuck with this problem for days..Any ideas? Glad for any help!
So I found out that I didn't write my database config in the correct folder..
Instead of
>project/database.php
It should have been
> project/Config/database.php
Jeez..

PHPUnit Strange behavior when mocking MongoCollection

Assume I have this test:
public function testStorage()
{
$collection = $this->getMockBuilder('MongoCollection')->disableOriginalConstructor()->getMock();
$collection->method('findOne')->will($this->returnValueMap([
[['_id' => 'aaa'], ['content'], 'ccc'],
]));
$this->assertEquals('ccc', $collection->findOne(['_id' => 'aaa'], ['content']));
}
When running unit test it says: Failed asserting that null matches expected 'ccc'.
I couldn't figure out why. But if I switch to mock another function, let's say: find it should work.
public function testStorage()
{
$collection = $this->getMockBuilder('MongoCollection')->disableOriginalConstructor()->getMock();
$collection->method('find')->will($this->returnValueMap([
[['_id' => 'aaa'], ['content'], 'ccc'],
]));
$this->assertEquals('ccc', $collection->find(['_id' => 'aaa'], ['content']));
}
OK (1 test, 1 assertion)
I really appreciate your help! Thank you very much!
I use getMock and it's work for me:
$collection = $this->getMock('MongoCollection', ['find', 'findOne'], [], '', false);
$collection->method('find')->will($this->returnValue([
[['_id' => 'aaa'], ['content'], 'ccc']
]));
$collection->method('findOne')->will($this->returnValue([
[['_id' => 'aaa'], ['content'], 'ccc']
]));

Categories