PhpUnit dataProviders vs Coverage - phpunit

I decided, that it will be fine if I use data providers but when i try to generate code coverage whole tested class has 0% coverage.. Can someone tell me why?
Test class:
class AuthorDbManagerTest extends AbstractDbManagerTest
{
public function setUp()
{
parent::setUp();
}
/**
* #dataProvider instanceOfProvider
* #param bool $isInstanceOf
*/
public function testInstances(bool $isInstanceOf)
{
$this->assertTrue($isInstanceOf);
}
public function instanceOfProvider()
{
$manager = new AuthorDbManager($this->getEntityManagerMock());
return [
"create()" => [$manager->create() instanceof Author],
"save()" => [$manager->save(new Author()) instanceof AuthorDbManager],
"getRepository" => [$manager->getRepository() instanceof EntityRepository],
];
}
}
Tested class:
class AuthorDbManager implements ManagerInterface
{
protected $entityManager;
protected $repository;
public function __construct(EntityManager $entityManager)
{
$this->entityManager = $entityManager;
$this->repository = $entityManager->getRepository(Author::class);
}
public function create(array $data = [])
{
return new Author();
}
public function getRepository(): EntityRepository
{
return $this->repository;
}
public function save($object): ManagerInterface
{
$this->entityManager->persist($object);
$this->entityManager->flush();
return $this;
}
}
Why my code coverage is 0% on AuthorDbManager?
Screen

The data in the DataProvider is collected before the actual tests start - and there is nothing useful being tested within the testInstances() method.
If you passed the classname and expected class into testInstances($methodName, $expectedClass):
public function testInstances(callable $method, $expectedClass)
{
$this->assertInstanceOf($expectedClass, $method());
}
The dataprovider could return a callable, and the expected result:
"create()" => [[$manager,'create'], Author::class],
then you'd at least be running the code with in the actual test. You may also be better to just pass back a string methodname - 'create', and run that with a locally created $manager instance - $manager->$method() in the test.
In general, it's best to test something as specific as you can - not just letting it convert to a true/false condition.

Related

How to use VichUploaderBundle in CrudController's configureFields

Images aren't saving with settings below
public function configureFields(string $pageName): iterable
{
return [
ImageField::new('imageFile')->setBasePath('%app.path.product_images%'),
];
}
This working for me...
First create VichImageField
use EasyCorp\Bundle\EasyAdminBundle\Contracts\Field\FieldInterface;
use EasyCorp\Bundle\EasyAdminBundle\Field\FieldTrait;
use Vich\UploaderBundle\Form\Type\VichImageType;
class VichImageField implements FieldInterface
{
use FieldTrait;
public static function new(string $propertyName, ?string $label = null)
{
return (new self())
->setProperty($propertyName)
->setTemplatePath('')
->setLabel($label)
->setFormType(VichImageType::class);
}
}
And
public function configureFields(string $pageName): iterable
{
return [
ImageField::new('imagename')->setBasePath($this->getParameter('app.path.product_images'))->onlyOnIndex(),
VichImageField::new('imageFile')->hideOnIndex()
];
}
More info here
https://symfony.com/doc/master/bundles/EasyAdminBundle/fields.html#creating-custom-fields
Make sure to change at least 1 doctrine mapped field in your setter, otherwise doctrine won't dispatch events. Here is an example from the docs:
/**
* #ORM\Column(type="datetime")
* #var \DateTime
*/
private $updatedAt;
public function setImageFile(File $image = null)
{
$this->imageFile = $image;
// VERY IMPORTANT:
// It is required that at least one field changes if you are using Doctrine,
// otherwise the event listeners won't be called and the file is lost
if ($image) {
// if 'updatedAt' is not defined in your entity, use another property
$this->updatedAt = new \DateTime('now');
}
}
You need the resolve the parameter first.
Instead of
ImageField::new('imageFile')->setBasePath('%app.path.product_images%')
Try
...
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
class ProductCrudController extends AbstractCrudController
{
private $params;
public function __construct(ParameterBagInterface $params)
{
$this->params = $params;
}
public function configureFields(string $pageName): iterable
{
return [
ImageField::new('imageFile')>setBasePath($this->params->get('app.path.product_images'))
];
}
More info on getting the parameter here:
https://symfony.com/blog/new-in-symfony-4-1-getting-container-parameters-as-a-service

Token Storage Problems Symfony 5 Custom Login Authenticator

When the user logs in to the system, I need to fill a class variable (Login-> testInfo) with information, but in the controller the variable always returns null.
Here is a generic example.
The Login class
class Login extends UserInterface
{
private $testInfo = null;
public function setTestInfo(string $testInfo)
{
$this->testInfo = $testInfo;
}
public function getTestInfo() : ?string
{
return $this->testInfo;
}
}
The Authenticator:
class FormAuthenticator extends AbstractFormLoginAuthenticator
{
...
public function getUser($credentials, UserProviderInterface $userProvider)
{
$user = $this->entityManager->getRepository(Login::class)->findByUsername(credentials['username']);
if (!$user)
{
throw new CustomUserMessageAuthenticationException('Username could not be found.');
}
//this prints NULL
dd($user->getTestInfo());
$user->setTestInfo('testing the string');
//this prints 'testing the string'
dd($user->getTestInfo());
return $user;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
//this prints 'testing the string'
dd($token->getUser()->getTestInfo());
}
...
}
The Controller Class:
class MyController extends AbstractController
{
private $login = null;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->login = $tokenStorage->getToken() ? $tokenStorage->getToken()->getUser() : null;
}
public function home()
{
//this prints null
dd($this->login->getTestInfo());
}
}
If $user goes to the tokenStorage with the new value ('testing the string'), why, when I try to use it on the controller, does the variable always return null? what am I doing wrong?
Is testInfo a transient variable? Because you gotta know that there is UserProvider that tries to refresh user from token (maybe it could be "changed" somehow between requests). I'm pretty sure you're losing those infos right in this process.
Are you sure your controller constructor isn't being executed too soon, prior to the authentication success event writing the token to the token storage service? I'd dd() the token in the constructor to verify if the token and Login instance are present at that point.
You may need to use setContainer() instead of __construct() in your controller to retrieve the authenticated token, which would look something like this:
private $tokenStorage = null;
private $login = null;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
/**
* #param ContainerInterface $container Symfony service container interface
* #return ContainerInterface|null
*/
public function setContainer(\Psr\Container\ContainerInterface $container): ?\Psr\Container\ContainerInterface
{
if ($this->tokenStorage instanceof TokenStorageInterface && $this->tokenStorage->getToken() instanceof TokenInterface && $this->tokenStorage->getToken()->getUser() instanceof Login) {
$this->login = $this->tokenStorage->getToken()->getUser();
}
return $container;
}

Workflow enter place listener

I'm working with the Workflow component in symfony 4.3. For my entity I have a marking property and a transition_contexts property. The transition_contexts is of JSON type like
[{"time": ..., "context":[all info I want], "new_marking" : "some_place", {etc...}]
for every transition made.
I want to set a transition_context also for the initial place called creation. For now, when I create a new object my transition_contexts looks like :
[{"time": ..., "context":[], "new_marking" : "creation"}]
For all other transitions I use the apply() function where I can set the context array, but for the initialisation with the initial place, I don't know how to do it.
I've read about listeners, so I tried
class FicheSyntheseTransitionListener implements EventSubscriberInterface
{
private $security;
private $connection;
public function __construct(Security $security, ManagerRegistry $em)
{
$this->security = $security;
//ManagerRegistry au lieu de EntityManagerInterface car on a plusieurs entityManager
$this->connection = $em->getManager('fichesynthese');
}
public function addRedacteur(Event $event)
{
$context = $event->getContext();
$user = $this->tokenStorage->getToken()->getUser();
if ($user instanceof UserInterface) {
$context['user'] = $user->getUsername();
}
$event->setContext($context);
$this->get('doctrine')->getManager('fichesynthese')->flush();
}
public static function getSubscribedEvents()
{
return [
'workflow.fiche.entered.creation' => ['addRedacteur'],
];
}
}
But it seems that it is not taken into account. Is there a way to achieve this ? A manual call to the function that set the initial marking ?
Thanks

Symfony Request Not Available in EventSubscriber

Changes to my Entities are logged using an EventSubscriber for Doctrine lifecycle events. I want to log a request id alognside the entity change log entries to see what's happened in one single user action.
Adding the request id is as easy as this:
class RequestIdSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [KernelEvents::REQUEST => 'addRequestId'];
}
public function addRequestId(GetResponseEvent $event): void
{
$request = $event->getRequest();
$request->attributes->set('RequestId', Uuid::uuid1()->toString());
}
}
The problem is that the request does not seem to be available in the Doctrine EventSubscribers in a reliable way:
class EntityEventSubscriber implements EventSubscriber
{
public function __construct(DelayedEventDispatcher $dispatcher, RequestStack $requestStack, LoggerInterface $logger)
{
$this->dispatcher = $dispatcher;
$this->inventory = new EntityInventory();
$this->requestStack = $requestStack;
$this->logger = $logger;
}
public function getSubscribedEvents(): array
{
return [
Events::postUpdate,
];
}
public function postUpdate(LifecycleEventArgs $args): void
{
// works
$this->logger->debug($this->requestStack->getCurrentRequest()->get('RequestId'));
$entity = $args->getEntity();
$changes = $this->inventory->getChangeSet($entity);
$event = new EntityUpdatedEvent($entity, $changes);
$this->triggerAuditLogEvent($event);
}
public function triggerAuditLogEvent(EntityEvent $event): void
{
// request.CRITICAL: Uncaught PHP Exception Error: "Call to a member function get() on null"
$event->setRequestId($this->requestStack->getCurrentRequest()->get('RequestId'));
$this->dispatcher->dispatch(FhrEvents::GENERIC_ENTITY_EVENT, $event);
}
}
So what really bothers me is that the request seems to be available in one method and if I call the next one, it's already gone.

Too many connection during unit testing

I have a project with a lot of tests class like
class MyTest extends BaseTestCase
{
public function __construct()
{
parent::__construct();
$this->em = $this->get('doctrine')->getManager();
}
public function setUp() {
$this->init();
//load sql data for the tests
$path = $this->get('kernel')->locateResource('#Bundle/Data/Test.sql');
$content_file_sql_data = file_get_contents($path);
$stmt = $this->em->getConnection()->prepare($content_file_sql_data);
$stmt->execute();
$stmt->closeCursor();
}
/*
* Then we do a lot of tests using the database
*/
}
They all extends my BaseTestCase:
abstract class BaseTestCase extends \PHPUnit_Framework_TestCase {
protected $_container;
protected $kernel;
public function __construct() {
parent::__construct();
$this->kernel = new \AppKernel("test", true);
$this->kernel->boot();
$this->_container = $this->kernel->getContainer();
$this->init();
}
//empty the database before each test class
public function init() {
$this->_application = new Application($this->kernel);
$this->_application->setAutoExit(false);
//rebuild and empty the database
$this->runConsole("doctrine:schema:drop", array("--force" => true));
$this->runConsole("doctrine:schema:create");
}
Since I have a lot of tests, i have recently got some errors PDOException: SQLSTATE[08004] [1040] Too many connections. It's like phpunit never close database connection, and around 100 tests I get this error for all the other tests.
How can i fix it?
I tried to put a last test doing $this->em->close() at the end of each test class but it didn't solve it
Some additional information: i'm pretty sure I don't have an issue with ONE test, because if I change the order of the test suite, the error appears around the same amount of tests class passed
My solution was to override shutdown method in my Bundle class:
public function shutdown()
{
if ('test' == $this->container->getParameter('kernel.environment')) {
/* #var EntityManager $em */
$em = $this->container->get('doctrine.orm.default_entity_manager');
$em->getConnection()->close();
}
}

Resources