I want to functional-test a Symfony's command I'm creating. I'm taking advantage of the Question helper class, by associating a personal validator:
$helper = $this->getHelper('question');
$question = new Question('Enter a valid IP: ');
$question->setValidator($domainValidator);
$question->setMaxAttempts(2);
the tests I'm performing are functionals, so in order to mock the interaction I added something like the following to my PHPUnit's test class. Here's an excerpt:
public function testBadIpRaisesError()
{
$question = $this->createMock('Symfony\Component\Console\Helper\QuestionHelper');
$question
->method('ask')
->will($this->onConsecutiveCalls(
'<IP>',
true
));
...
}
protected function createMock($originalClassName)
{
return $this->getMockBuilder($originalClassName)
->disableOriginalConstructor()
->disableOriginalClone()
->disableArgumentCloning()
->disallowMockingUnknownTypes()
->getMock();
}
of course this mock is more than ok when I'm testing something that goes beyond the Question helper, but in this case what I'd like to do is testing the whole thing in order to make sure the validator is well written.
What's the best option in this case? Unit testing my validator is OK, but I would like to functional-testing it as a black box by the user point of view
The Console component provides a CommandTester for precisely this use case: https://symfony.com/doc/current/console.html#testing-commands. You probably want to do something like this:
<?php
class ExampleCommandTest extends \PHPUnit\Framework\TestCase
{
public function testBadIpRaisesError()
{
// For a command 'bin/console example'.
$commandName = 'example';
// Set up your Application with your command.
$application = new \Symfony\Component\Console\Application();
// Here's where you would inject any mocked dependencies as needed.
$createdCommand = new WhateverCommand();
$application->add($createdCommand);
$foundCommand = $application->find($commandName);
// Create a CommandTester with your Command class processed by your Application.
$tester = new \Symfony\Component\Console\Tester\CommandTester($foundCommand);
// Respond "y" to the first prompt (question) when the command is invoked.
$tester->setInputs(['y']);
// Execute the command. This example would be the equivalent of
// 'bin/console example 127.0.0.1 --ipv6=true'
$tester->execute([
'command' => $commandName,
// Arguments as needed.
'ip-address' => '127.0.0.1',
// Options as needed.
'--ipv6' => true,
]);
self::assert('Example output', $tester->getDisplay());
self::assert(0, $tester->getStatusCode());
}
}
You can see some more sophisticated working examples in a project I'm working on: https://github.com/php-tuf/composer-stager/blob/v0.1.0/tests/Unit/Console/Command/StageCommandTest.php
Related
I am using dingo/api in my api and I want to unit test the endpoint:
class MyApiTest extends TestCase
{
public function testEndpoint()
{
$dispatcher = app('Dingo\Api\Dispatcher');
$fake_token = 'cndksjonsdcnsod';
$dispatcher->header('Authorization', 'Bearer: '.$fake_token);
$dispatcher->version($version)->get('/my-endpoint');
}
}
In my app.php I have the following configuration:
'auth' => [
'jwt' => Dingo\Api\Auth\Provider\JWT::class,
],
Is there a way to mock/fake/set default values to the Dingo\Api\Auth\Provider\JWT provider of jwt authentication?
An approach that worked for me, is via testing the controller itself and mock JWT authentication service by bypassing the Dingo and any middleware used by routing itself.
Example:
Let us suppose we have the following controller:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Tymon\JWTAuth\Facades\JWTAuth;
class ProfileController extends Controller
{
public function getProfile(Request $request,$profile_id)
{
$user = JWTAuth::parseToken()->authenticate();
$language = App::getLocale();
// Do stuff Here
}
}
You can write a simple test:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;
use Tymon\JWTAuth\Facades\JWTAuth;
// Set a test class for speed is ommited
public function testMyApiCall()
{
/**
* $user is an instance of a User
*/
JWTAuth::shouldReceive('parseToken->authenticate')->andReturn($user);
App::setlocale('el');
$request = new Request();
$request->initialize([],['token' => 'AAABBBCCC' ],[],[],[],[],[]);
$controller = new ProfileController();
// I ommit the profile_id value it is just a demonstration
$response = $controller->getProfile($request,$profile_id)
$response_dody = $response->getData(false);
// Perform assertions upon $response_dody
}
In our case we do not care about what routing is used and how it is set up. Therefore, are no mentioning any routing and anything regarding Dingo in this example, we just forget it.
Cons and pros
Though it is not a silver bullet, it is an approach that will give a reliable result focusing on the actual code. Keep in mind though that you bypass many middlewares that may you also want to test as well eg. Authentication ones.
On the other hand you are able to test the logic inside the controller, in cases where the logic is rather small to create a seperate class/method for it eg. selecting data from DB.
I have this situation:
Symfony 4.4.8, in the controller, for some users, I change some properties of an entity before displaying it:
public function viewAction(string $id)
{
$em = $this->getDoctrine()->getManager();
/** #var $offer Offer */
$offer = $em->getRepository(Offer::class)->find($id);
// For this user the payout is different, set the new payout
// (For displaying purposes only, not intended to be stored in the db)
$offer->setPayout($newPayout);
return $this->render('offers/view.html.twig', ['offer' => $offer]);
}
Then, I have a onKernelTerminate listener that updates the user language if they changed it:
public function onKernelTerminate(TerminateEvent $event)
{
$request = $event->getRequest();
if ($request->isXmlHttpRequest()) {
// Don't do this for ajax requests
return;
}
if (is_object($this->user)) {
// Check if language has changed. If so, persist the change for the next login
if ($this->user->getLang() && ($this->user->getLang() != $request->getLocale())) {
$this->user->setLang($request->getLocale());
$this->em->persist($this->user);
$this->em->flush();
}
}
}
public static function getSubscribedEvents()
{
return [
KernelEvents::TERMINATE => [['onKernelTerminate', 15]],
];
}
Now, there is something very weird happening here, if the user changes language, the offer is flushed to the db with the new payout, even if I never persisted it!
Any idea how to fix or debug this?
PS: this is happening even if I remove $this->em->persist($this->user);, I was thinking maybe it's because of some relationship between the user and the offer... but it's not the case.
I'm sure the offer is persisted because I've added a dd('beforeUpdate'); in the Offer::beforeUpdate() method and it gets printed at the bottom of the page.
alright, so by design, when you call flush on the entity manager, doctrine will commit all the changes done to managed entities to the database.
Changing values "just for display" on an entity that represents a record in database ("managed entity") is really really bad design in that case. It begs the question what the value on your entity actually means, too.
Depending on your use case, I see a few options:
create a display object/array/"dto" just for your rendering:
$display = [
'payout' => $offer->getPayout(),
// ...
];
$display['payout'] = $newPayout;
return $this->render('offers/view.html.twig', ['offer' => $display]);
or create a new non-persisted entity
use override-style rendering logic
return $this->render('offers/view.html.twig', [
'offer' => $offer,
'override' => ['payout' => $newPayout],
]);
in your template, select the override when it exists
{{ override.payout ?? offer.payout }}
add a virtual field (meaning it's not stored in a column!) to your entity, maybe call it "displayPayout" and use the content of that if it exists
I'm a bit of noob when it comes to OOP PHP, so please forgive me if I make this sound more complicated then it is.
Basically I am trying to clean up my controller as it's starting to get too cluttered.
I have my entities set up and I have also created a repository to add methods for some db queries to a sqlite database.
But now I also have to manipulate this data before outputting it, I've created a separate connector class that fetches additional info (from an XML web source) for each item being queried and then this gets added to the doctrine query data before being outputted.
I could manipulate this data in the repository but the data I am adding obviously doesn't originate from my entity. So I have therefore created a separate model class to add this data.
Please tell me if I'm on the right track.
In my entity repository I will have a custom method like this:
public function queryTop10All()
{
$query = $this->getEntityManager($this->em)
->createQueryBuilder('u')
->select('u.ratingkey, u.origTitle, u.origTitleEp, u.episode, u.season, u.year, u.xml, count(u.title) as playCount')
->from($this->class, 'u')
->groupBy('u.title')
->orderBy('playCount', 'desc')
->addOrderBy('u.ratingkey', 'desc')
->setMaxResults(10)
->getQuery();
return $query->getResult();
}
Now I created a new class in \Model\ChartsDataModel.php and I am injecting doctrine into it using a service and calling the custom method, getting the results and then adding the additional data from the web connector to it, like so:
namespace PWW\DataFactoryBundle\Model;
use Doctrine\ORM\EntityManager;
use PWW\DataFactoryBundle\Connector\XMLExtractor;
use PWW\DataFactoryBundle\Connector\WebConnector;
use PWW\ContentBundle\Entity\Settings;
class ChartsDataModel {
private $settings;
private $repository;
private $em;
public function __construct(EntityManager $em)
{
$this->settings = new Settings();
$this->repository = $this->settings->getGroupingCharts() ? 'PWWDataFactoryBundle:Grouped' : 'PWWDataFactoryBundle:Processed';
$this->em = $em;
}
public function getChartsTop10All()
{
$xmlExtractor = new XMLExtractor();
$webConnector = new WebConnector();
$results = $this->em->getRepository($this->repository)->queryTop10All();
$xml = $xmlExtractor->unXmlArray($results);
$outputArray = array();
foreach($xml as $item) {
$outputArray[] = array(
"ratingKey" => $item['ratingkey'],
"origTitle" => $item['origTitle'],
"origTitleEp" => $item['origTitleEp'],
"playCount" => $item['playCount'],
"episode" => $item['episode'],
"season" => $item['season'],
"year" => $item['year'],
"type" => $item['media']['type'],
"parent" => $webConnector->getMetaData($webConnector->getMetaDataParentKey($item['ratingkey'])),
"metadata" => $webConnector->getMetaData($item['ratingkey'])
);
}
return $outputArray;
}
}
The xmlExtractor class is used to pull out certain xml fields stored in a database field as a raw xml dump.
My config.yml:
services:
pww.datafactorybundle.model.charts_data_model:
class: PWW\DataFactoryBundle\Model\ChartsDataModel
arguments: [ #doctrine.orm.entity_manager ]
Then in my controller, I just instantiate a new ChartsDataModel and call the method like so:
namespace PWW\ContentBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
...
use PWW\DataFactoryBundle\Model\ChartsDataModel;
public function chartsAction()
{
$charts = new ChartsDataModel($this->getDoctrine()->getManager());
$top10Array = $charts->getChartsTop10All();
return $this->render('PWWContentBundle:Default:charts.html.twig', array('page' => 'charts', 'top10' => $top10Array));
}
I just want to know if I am doing this correctly and is there a better way of doing this (or right way)?
I'm also very new to Symfony and still getting my head around it. I just don't want to get into bad habits so I'm trying to do things right from the start.
I hope I explained this well enough :)
TIA
Just detected two things that are in the top of my head.
1 If you define the service like:
services:
pww.datafactorybundle.model.charts_data_model:
class: PWW\DataFactoryBundle\Model\ChartsDataModel
arguments: [ #doctrine.orm.entity_manager ]
Then you can inject it in the controller like described here, so you keep the service arguments out of the Controller:
public function chartsAction()
{
$myservice = $this->get('pww.datafactorybundle.model.charts_data_model');
$top10Array = $myservice->getChartsTop10All();
}
Secondly, I would not put this standard queries in the Model, I think is better to keep the models clean with their setters, getters and put this custom queries elsewhere like in a service that will handle all related Chart queries and you can instance from anywhere else.
is there any possibility to get the service-container of symfony2 within an SQLFilter or can i maybe directly use a service as SQLFilter?
I know that this isn't a "clean" way, but i have to perform several checks directly before the final submit of the query gets fired (as i have to append conditions to the WHERE-statement, i can't use lifecycle-events at this point).
it's not clean but you could try this:
<?php
class MyBundle extends Bundle
{
public function boot()
{
$em = $this->container->get('doctrine.orm.default_entity_manager');
$conf = $em->getConfiguration();
$conf->addFilter(
'test',
'Doctrine\Filter\TestFilter'
);
$em->getFilters()->enable('test')->setContainer($this->container);
}
}
In symfony 1.4, how to call an action of another application from the current action?
There's a blog post about that here:
http://symfony.com/blog/cross-application-links
There's a plugin for it:
https://github.com/rande/swCrossLinkApplicationPlugin
And there are some blogposts explaining it:
http://rabaix.net/en/articles/2009/05/30/cross-link-application-with-symfony
http://rabaix.net/en/articles/2009/07/13/cross-link-application-with-symfony-part-2
(Note: both are for symfony 1.2, but they should also work in 1.4)
To route to your frontend to your backend, there are three easy steps:
1. Add to your backend configuration the following two methods
These methods read the backend routing, and use it to generate routes. You'll need to supply the link to it, since php does not know how you configured your webserver for the other application.
.
// apps/backend/config/backendConfiguration.class.php
class backendConfiguration extends sfApplicationConfiguration
{
protected $frontendRouting = null;
public function generateFrontendUrl($name, $parameters = array())
{
return 'http://frontend.example.com'.$this->getFrontendRouting()->generate($name, $parameters);
}
public function getFrontendRouting()
{
if (!$this->frontendRouting)
{
$this->frontendRouting = new sfPatternRouting(new sfEventDispatcher());
$config = new sfRoutingConfigHandler();
$routes = $config->evaluate(array(sfConfig::get('sf_apps_dir').'/frontend/config/routing.yml'));
$this->frontendRouting->setRoutes($routes);
}
return $this->frontendRouting;
}
// ...
}
2. You can link to your application in such a fashion now:
$this->redirect($this->getContext()->getConfiguration()->generateFrontendUrl('hello', array('name' => 'Bar')));
3. Since it's a bit tedious to write, you can create a helper
function link_to_frontend($name, $parameters)
{
return sfProjectConfiguration::getActive()->generateFrontendUrl($name, $parameters);
}
The sfCrossLinkApplicationPlugin does this , this, but in a bit simpler fashion, you would be able to use a syntax similar to this:
<?php if($sf_user->isSuperAdmin()):?>
<?php link_to('Edit Blog Post', '#backend.edit_post?id='.$blog->getId()) ?>
<?php endif ?>
It would be something like this:
public function executeActionA(sfWebRequest $request)
{
$this->redirect("http:://host/app/url_to_action");
}
In Symfony each application is independent from the others, so if you need to call an action of another app, you need to request it directly.
Each app is represented by one main controller (frontend, backend, webapp), this controller takes care of the delivery of each request to the corresponding action (and lots of other things like filters, etc.).
I really recommend you to read this, it would be quite more explanatory: Symfony - Inside the Controller Layer