How do I get assertTrue method? My file phpunit_test.php is
<?php
class phptest extends PHPUnit_Framework_TestCase
{
public function test_something()
{
$this->assertTrue{ 1 > 0 };
}
}
?>
but phpunit phpunit_test.php returns
There was 1 error:
1) phptest::test_something
Undefined property: phptest::$assertTrue
$this->assertTrue{ 1 > 0 };
should be
$this->assertTrue( 1 > 0 );
Related
I need to compare two arrays in phpunit. I am using asserequals() but output shows No Tests Executed! I am mentioning my arrays below and code too:
$expected_arr = array('success' => 1);
$result_array =(output of print_r($result_array))
Array
(
[success] => 1
)
$this->assertEquals($arr_data,$expected_arr);
My PHPUnit version is 5.1.3. I am running is on Ubuntu 16
UPDATED:
<?php
require_once ('PHPUnit/Framework/TestCase.php');
class abc_auto_testing_test extends PHPUnit_Framework_TestCase
{
public $abc_id;
public $abc_answer;
public function __construct($ABC_id, $ABC_answer)
{
$this->abc_id = $ABC_id;
$this->abc_answer = $ABC_answer;
$this->test_Abc_Validate($this->abc_id, $this->abc_answer);
}
public function setUp()
{
}
public function tearDown()
{
}
public function test_Abc_Validate($abcId, $abcAnswer)
{
$expected_arr = array('success' => 1);
// var_dump($expected_arr);
$arr_data = ABC_Validate($abcId, $abcAnswer);
// var_dump($arr_data);
$this->assertEquals($arr_data,$expected_arr);
}
}
require'/var/www/data.abc.in/abc_server_crons/abc_auto_testing_bkp.php';
$ABC_identifier = $abcIdentifier;
$ABC_answer = $abcAnswer;
$validObj = new abc_auto_testing_test($ABC_identifier, $ABC_answer);
?>
Your test code makes no sense. Go here to learn the basics of writing and running tests.
After upgrading my project from Symfony 3.4.0 BETA 2 to 3.4.0 BETA 4 I get the following error in every request and every cli command:
[Doctrine\ORM\ORMException]
It's a requirement to specify a Metadata Driver and pass it to Doctrine\ORM\Configuration::setMetadataDriverImpl().
Exception trace:
Doctrine\ORM\ORMException::missingMappingDriverImpl() at D:\jinya-gallery-cms\vendor\doctrine\orm\lib\Doctrine\ORM\EntityManager.php:830
Doctrine\ORM\EntityManager::create() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:952
Container3xxrjsx\appDevDebugProjectContainer->getDoctrine_Orm_DefaultEntityManagerService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:2164
Container3xxrjsx\appDevDebugProjectContainer->getJinyaGallery_Monolog_MySqlHandlerService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:2299
Container3xxrjsx\appDevDebugProjectContainer->getMonolog_Logger_CacheService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:1508
Container3xxrjsx\appDevDebugProjectContainer->getCache_AnnotationsService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:1409
Container3xxrjsx\appDevDebugProjectContainer->getAnnotationReaderService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:940
Container3xxrjsx\appDevDebugProjectContainer->getDoctrine_Orm_DefaultEntityManagerService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:2164
Container3xxrjsx\appDevDebugProjectContainer->getJinyaGallery_Monolog_MySqlHandlerService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:2330
Container3xxrjsx\appDevDebugProjectContainer->getMonolog_Logger_EventService() at D:\jinya-gallery-cms\var\cache\dev\Container3xxrjsx\appDevDebugProjectContainer.php:1703
Container3xxrjsx\appDevDebugProjectContainer->getDebug_EventDispatcherService() at D:\jinya-gallery-cms\vendor\symfony\symfony\src\Symfony\Component\DependencyInjection\Container.php:299
Symfony\Component\DependencyInjection\Container->get() at D:\jinya-gallery-cms\vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Console\Application.php:65
Symfony\Bundle\FrameworkBundle\Console\Application->doRun() at D:\jinya-gallery-cms\vendor\symfony\symfony\src\Symfony\Component\Console\Application.php:129
Symfony\Component\Console\Application->run() at D:\jinya-gallery-cms\bin\console:27
After checking the generated cache code I found out, that the code that instantiates the EntityManager is completely different than in BETA 2.
This is the code from BETA 2:
<?php
use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
// This file has been auto-generated by the Symfony Dependency Injection Component for internal use.
// Returns the public 'doctrine.orm.default_entity_manager' shared service.
$a = ${($_ = isset($this->services['annotation_reader']) ? $this->services['annotation_reader'] : $this->load(__DIR__.'/getAnnotationReaderService.php')) && false ?: '_'};
$b = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($a, array(0 => 'D:\\jinya-gallery-cms\\src\\HelperBundle\\Entity', 1 => 'D:\\jinya-gallery-cms\\src\\DataBundle\\Entity'));
$c = new \Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain();
$c->addDriver($b, 'HelperBundle\\Entity');
$c->addDriver($b, 'DataBundle\\Entity');
$c->addDriver(new \Doctrine\ORM\Mapping\Driver\XmlDriver(new \Doctrine\Common\Persistence\Mapping\Driver\SymfonyFileLocator(array('D:\\jinya-gallery-cms\\vendor\\friendsofsymfony\\user-bundle\\Resources\\config\\doctrine-mapping' => 'FOS\\UserBundle\\Model'), '.orm.xml')), 'FOS\\UserBundle\\Model');
$d = new \Doctrine\ORM\Configuration();
$d->setEntityNamespaces(array('HelperBundle' => 'HelperBundle\\Entity', 'DataBundle' => 'DataBundle\\Entity'));
$d->setMetadataCacheImpl(${($_ = isset($this->services['doctrine_cache.providers.doctrine.orm.default_metadata_cache']) ? $this->services['doctrine_cache.providers.doctrine.orm.default_metadata_cache'] : $this->load(__DIR__.'/getDoctrineCache_Providers_Doctrine_Orm_DefaultMetadataCacheService.php')) && false ?: '_'});
$d->setQueryCacheImpl(${($_ = isset($this->services['doctrine_cache.providers.doctrine.orm.default_query_cache']) ? $this->services['doctrine_cache.providers.doctrine.orm.default_query_cache'] : $this->load(__DIR__.'/getDoctrineCache_Providers_Doctrine_Orm_DefaultQueryCacheService.php')) && false ?: '_'});
$d->setResultCacheImpl(${($_ = isset($this->services['doctrine_cache.providers.doctrine.orm.default_result_cache']) ? $this->services['doctrine_cache.providers.doctrine.orm.default_result_cache'] : $this->load(__DIR__.'/getDoctrineCache_Providers_Doctrine_Orm_DefaultResultCacheService.php')) && false ?: '_'});
$d->setMetadataDriverImpl($c);
$d->setProxyDir(($this->targetDirs[0].'/doctrine/orm/Proxies'));
$d->setProxyNamespace('Proxies');
$d->setAutoGenerateProxyClasses(true);
$d->setClassMetadataFactoryName('Doctrine\\ORM\\Mapping\\ClassMetadataFactory');
$d->setDefaultRepositoryClassName('Doctrine\\ORM\\EntityRepository');
$d->setNamingStrategy(new \Doctrine\ORM\Mapping\UnderscoreNamingStrategy());
$d->setQuoteStrategy(new \Doctrine\ORM\Mapping\DefaultQuoteStrategy());
$d->setEntityListenerResolver(${($_ = isset($this->services['doctrine.orm.default_entity_listener_resolver']) ? $this->services['doctrine.orm.default_entity_listener_resolver'] : $this->load(__DIR__.'/getDoctrine_Orm_DefaultEntityListenerResolverService.php')) && false ?: '_'});
$this->services['doctrine.orm.default_entity_manager'] = $instance = \Doctrine\ORM\EntityManager::create(${($_ = isset($this->services['doctrine.dbal.default_connection']) ? $this->services['doctrine.dbal.default_connection'] : $this->load(__DIR__.'/getDoctrine_Dbal_DefaultConnectionService.php')) && false ?: '_'}, $d);
${($_ = isset($this->services['doctrine.orm.default_manager_configurator']) ? $this->services['doctrine.orm.default_manager_configurator'] : $this->services['doctrine.orm.default_manager_configurator'] = new \Doctrine\Bundle\DoctrineBundle\ManagerConfigurator(array(), array())) && false ?: '_'}->configure($instance);
return $instance;
This is the code from BETA 4
<?php
namespace ContainerXo2t2t9;
use Symfony\Component\DependencyInjection\Argument\RewindableGenerator;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\Exception\InvalidArgumentException;
use Symfony\Component\DependencyInjection\Exception\LogicException;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;
use Symfony\Component\DependencyInjection\ParameterBag\FrozenParameterBag;
/**
* This class has been auto-generated
* by the Symfony Dependency Injection Component.
*
* #final since Symfony 3.3
*/
class appDevDebugProjectContainer extends Container
{
/**
* Gets the public 'doctrine.orm.default_entity_manager' shared service.
*
* #return \Doctrine\ORM\EntityManager
*/
protected function getDoctrine_Orm_DefaultEntityManagerService($lazyLoad = true)
{
$a = ${($_ = isset($this->services['doctrine.dbal.default_connection']) ? $this->services['doctrine.dbal.default_connection'] : $this->getDoctrine_Dbal_DefaultConnectionService()) && false ?: '_'};
$b = ${($_ = isset($this->services['annotation_reader']) ? $this->services['annotation_reader'] : $this->getAnnotationReaderService()) && false ?: '_'};
if (isset($this->services['doctrine.orm.default_entity_manager'])) {
return $this->services['doctrine.orm.default_entity_manager'];
}
$c = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($b, array(0 => 'D:\\jinya-gallery-cms\\src\\HelperBundle\\Entity', 1 => 'D:\\jinya-gallery-cms\\src\\DataBundle\\Entity'));
$d = new \Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain();
$e = new \Doctrine\ORM\Configuration();
$this->services['doctrine.orm.default_entity_manager'] = $instance = \Doctrine\ORM\EntityManager::create($a, $e);
$d->addDriver($c, 'HelperBundle\\Entity');
$d->addDriver($c, 'DataBundle\\Entity');
$d->addDriver(new \Doctrine\ORM\Mapping\Driver\XmlDriver(new \Doctrine\Common\Persistence\Mapping\Driver\SymfonyFileLocator(array('D:\\jinya-gallery-cms\\vendor\\friendsofsymfony\\user-bundle\\Resources\\config\\doctrine-mapping' => 'FOS\\UserBundle\\Model'), '.orm.xml')), 'FOS\\UserBundle\\Model');
$e->setEntityNamespaces(array('HelperBundle' => 'HelperBundle\\Entity', 'DataBundle' => 'DataBundle\\Entity'));
$e->setMetadataCacheImpl(${($_ = isset($this->services['doctrine_cache.providers.doctrine.orm.default_metadata_cache']) ? $this->services['doctrine_cache.providers.doctrine.orm.default_metadata_cache'] : $this->getDoctrineCache_Providers_Doctrine_Orm_DefaultMetadataCacheService()) && false ?: '_'});
$e->setQueryCacheImpl(${($_ = isset($this->services['doctrine_cache.providers.doctrine.orm.default_query_cache']) ? $this->services['doctrine_cache.providers.doctrine.orm.default_query_cache'] : $this->getDoctrineCache_Providers_Doctrine_Orm_DefaultQueryCacheService()) && false ?: '_'});
$e->setResultCacheImpl(${($_ = isset($this->services['doctrine_cache.providers.doctrine.orm.default_result_cache']) ? $this->services['doctrine_cache.providers.doctrine.orm.default_result_cache'] : $this->getDoctrineCache_Providers_Doctrine_Orm_DefaultResultCacheService()) && false ?: '_'});
$e->setMetadataDriverImpl($d);
$e->setProxyDir(($this->targetDirs[0].'/doctrine/orm/Proxies'));
$e->setProxyNamespace('Proxies');
$e->setAutoGenerateProxyClasses(true);
$e->setClassMetadataFactoryName('Doctrine\\ORM\\Mapping\\ClassMetadataFactory');
$e->setDefaultRepositoryClassName('Doctrine\\ORM\\EntityRepository');
$e->setNamingStrategy(new \Doctrine\ORM\Mapping\UnderscoreNamingStrategy());
$e->setQuoteStrategy(new \Doctrine\ORM\Mapping\DefaultQuoteStrategy());
$e->setEntityListenerResolver(${($_ = isset($this->services['doctrine.orm.default_entity_listener_resolver']) ? $this->services['doctrine.orm.default_entity_listener_resolver'] : $this->services['doctrine.orm.default_entity_listener_resolver'] = new \Doctrine\Bundle\DoctrineBundle\Mapping\ContainerAwareEntityListenerResolver($this)) && false ?: '_'});
${($_ = isset($this->services['doctrine.orm.default_manager_configurator']) ? $this->services['doctrine.orm.default_manager_configurator'] : $this->services['doctrine.orm.default_manager_configurator'] = new \Doctrine\Bundle\DoctrineBundle\ManagerConfigurator(array(), array())) && false ?: '_'}->configure($instance);
return $instance;
}
}
The result is, that in BETA 4 the EntityManager is created before the config values are set. Does anyone know how I can affect the cache generation to create a working cache?
The solution which worked for me:
Install Lazy Services with composer require ocramius/proxy-manager
For each listener set additional parameter lazy: true in tags
app.service_doctrine.foo_listerner:
class: AppBundle\Service\Doctrine\FooListener
...
tags:
- { name: doctrine.orm.entity_listener, entity_manager: default, lazy: true }
Hi All below Drupal 8 EventSubscriber class supposed to attach drupalSettings into Drupal 8 javascript settings. But unfortunately this \Drupal::service('renderer')->renderRoot($js_data); not attaching the drupal javascript settings.
namespace Drupal\ejectorseat\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Drupal\Core\Url;
class EjectorseatSubscriber implements EventSubscriberInterface {
public function customEjector(GetResponseEvent $event) {
$account = \Drupal::currentUser();
$ejectorseat_interval = \Drupal::config('ejectorseat.settings')->get('ejectorseat_interval');
if(empty($ejectorseat_interval)){
$ejectorseat_interval = 60;
}
$ejectorseat_background = \Drupal::config('ejectorseat.settings')->get('ejectorseat_background');
if(empty($ejectorseat_background)){
$ejectorseat_background = 0;
}
if ($account->id() > 0 && (int) $ejectorseat_interval) {
$js_data = array();
$js_data['#attached']['drupalSettings']['ejectorSeat']['interval'] = $ejectorseat_interval;
$js_data['#attached']['drupalSettings']['ejectorSeat']['url'] = Url::fromRoute('ejectorseat/check');
$js_data['#attached']['drupalSettings']['ejectorSeat']['ignoreFocus'] = $ejectorseat_background ? TRUE : FALSE;
\Drupal::service('renderer')->renderRoot($js_data);
}
}
public static function getSubscribedEvents() {
$events[KernelEvents::REQUEST][] = array('customEjector');
return $events;
}
}
I was facing the same issue and i didn't find a OOP solution.
In your case just place your logic form the customEjector Method in a HOOK called hook_js_settings_alter in your ejectorseat.module file. This way you can be sure all variables are avaiable in the drupalSettings Object.
E.g just for demonstration:
<?php
/**
* Implements hook_js_settings_alter().
*
*/
function ejectorseat_js_settings_alter(array &$settings,
\Drupal\Core\Asset\AttachedAssetsInterface $assets
) {
...
$settings['all_settings'] = $globalSettings->getAll();
//if you want to push only a single value
$settings['custom_link'] = $globalSettings->get('custom_link')
$settings['ejectorSeat']['interval'] = $ejectorseat_interval;
$settings['ejectorSeat']['url'] = Url::fromRoute('ejectorseat/check');
$settings['ejectorSeat']['ejectorSeat']['ignoreFocus'] = $ejectorseat_background ? TRUE : FALSE;
}
We have issues with memory leak when loading Doctrine in our phpunit tests
Starting for Symfony's documentation :
http://symfony.com/doc/2.7/cookbook/testing/doctrine.html we have written this test :
use Symfony\Bundle\FrameworkBundle\Test\KernelTestCase;
class memoryleakTest extends KernelTestCase
{
private $em;
protected function setUp()
{
self::bootKernel();
$this->em = static::$kernel->getContainer()
->get('doctrine')
->getManager();
}
protected function tearDown()
{
parent::tearDown();
$this->em->close();
}
function testEEE1() {
}
function testEEE2() {
}
function testEEE3() {
}
function testEEE4() {
}
function testEEE5() {
}
function testEEE6() {
}
function testEEE7() {
}
function testEEE8() {
}
function testEEE9() {
}
function testEEE10() {
}
function testEEE11() {
}
function testEEE12() {
}
function testEEE13() {
}
function testEEE14() {
}
function testEEE15() {
}
function testEEE16() {
}
}
we got this result (php_memory_usage between parenthesis) :
testEEE1: . (42M)
testEEE2: . (42.7M)
testEEE3: . (43.3M)
testEEE4: . (44M)
testEEE5: . (44.8M)
testEEE6: . (45.5M)
testEEE7: . (46.1M)
testEEE8: . (46.8M)
testEEE9: . (47.4M)
testEEE10: . (48.1M)
testEEE11: . (48.7M)
testEEE12: . (49.4M)
testEEE13: . (50.1M)
testEEE14: . (50.7M)
testEEE15: . (51.4M)
testEEE16: . (52M)
If we remove the doctrine manager loading in setup, we got (32,7M) for each test
Is it a proper way to unload doctrine after each test in the teardown function ?
The full solution as been found here:
https://github.com/symfony/symfony/issues/18236
For each service used in the phpunit test, you have to free it by assigning null to the variable if you want the garbage collector to free memory.
protected function tearDown()
{
parent::tearDown();
$this->em->close();
$this->em=null;
gc_collect_cycles();
}
To make this even easier for you, you can have a BaseTestCase.php with a teardown function and put this inside:
// Remove properties defined during the test
$refl = new \ReflectionObject($this);
foreach ($refl->getProperties() as $prop) {
if (!$prop->isStatic() && 0 !== strpos($prop->getDeclaringClass()->getName(), 'PHPUnit_')) {
$prop->setAccessible(true);
$prop->setValue($this, null);
}
}
That piece of code will save you from some headaches :)
I want to make an instant redirection in my controller in Laravel.
I know I can use
public function show($page)
{
return Redirect::url('http://example.com');
}
but I want to repeat this code in many controllers adding condition for example I would like to do something like this:
public function show($page)
{
$totalPages = 100; // here calculating maximum page
if ($page < 2 || $page > $totalPages) {
return Redirect::url('http://example.com');
}
// rest of code here - should be run if condition is false
}
but I don't want to repeat code in each controller.
If I try put redirection code in other method (that could exist in base controller) it won't work because it doesn't return anything in main controller:
public function show($page)
{
$totalPages = 100; // here calculating maximum page
$this->checkPages($page, $totalPages, 'http://example.com');
// rest of code here - should be run if condition is false
}
public function checkPages($page, $totalPages, $url)
{
if ($page < 2 || $page > $totalPages) {
return Redirect::url($url);
}
}
How can I solve this issue?
After a while of digging it seems that for this purposes you should use send() method from Symfony\Component\HttpFoundation (Laravel RedirectResponse inherits from this class).
So you can modify checkPages method this way:
public function checkPages($page, $totalPages, $url)
{
if ($page < 2 or $page > $totalPages) {
Redirect::url($url)->send();
}
}
and it will make instant redirection.
You have to return the results of the method in the base controller.
return $this->checkPages($page, $totalPages, 'http://example.com');
I'd probably suggest that your checkPages method is trying to do too much. Would I expect checkPages (which maybe should be validatePageNumber() or similar) to return a redirect? No, I'd expect it to return true or false.
That gives you this as your logic:
/**
* Make sure the current page is between 1 and $lastPage
*
* #param int $page
* #param int $lastPage
* #return bool
*/
protected function validatePageNumber( $page, $lastPage ) {
return $page < 2 || $page > $lastPage;
}
and now your controller logic is trivial:
public function show( $page ) {
$totalPages = 100;
if ( ! $this->validatePageNumber( $page, $totalPages ) ) {
return Redirect::url( 'http://example.com' );
}
// rest of code here - should be run if condition is false
}
Now if we use quasi-English to read your code, you have a public method show($page) which shows a page: it sets the total number of pages, checks that $page is valid, and if not, redirects somewhere. All of this is control logic, and only control logic, which is what a controller should be doing.
Your validatePageNumber() can now be abstracted into a model, or better yet, a ServiceProvider, and it does one job: validates that a number is between 1 and n.