Mock Middleware for route testing in Laravel - unit-testing

I am trying to write some unit tests to ensure my routes are not accidentally rewritten. I found already an answer to check whether a correct controller is assigned to particular route here.
However I would like to check as well that correct middlewares are assigned to route. I tried similar approach with
$tmp = new CorsService;
$corsMiddleware = Mockery::mock('Barryvdh\Cors\HandleCors[handle]', array($tmp))
->shouldReceive('handle')->once()
->andReturnUsing(function($request, Closure $next) {
return $next($request);
});
\App::instance('Barryvdh\Cors\HandleCors', $corsMiddleware);
For some reason the test is not picking this up. I am assuming that is because middleware instances are not stored using App::instance.
What am I doing wrong?

So I have found out there are 2 issues with above code
You can not chain ->shouldReceive directly with return value of Mockery::mock
there is missing \ from Closure
Working example:
$tmp = new CorsService;
$corsMiddleware = Mockery::mock('Barryvdh\Cors\HandleCors[handle]', array($tmp));
$corsMiddleware->shouldReceive('handle')->once()
->andReturnUsing(function($request, \Closure $next) {
return $next($request);
});
\App::instance('Barryvdh\Cors\HandleCors', $corsMiddleware);

Don't forget to to use ->getMock() at the end, if you are going to chain things like ->shouldReceive directly to your Mock object:
$corsMiddleware = Mockery::mock('Barryvdh\Cors\HandleCors[handle]', array($tmp))
->shouldReceive('handle')->once()
->andReturnUsing(function($request, Closure $next) {
return $next($request);
})
->getMock();

Try to get routes and check their middlewares
// Get Routes
foreach (Route::getRoutes() as $route) {
$middleware = $route->gatherMiddleware();
$name = $route->getName();
\Log::debug($name.'--');
\Log::debug($middleware);
}

Related

Symfony 3.2 - set environment variables in runtime [duplicate]

In my config.yml I have this:
parameters:
gitek.centro_por_defecto: 1
Now, I want to change this value from my controller using a form, like this:
public function seleccionAction(Request $request)
{
$entity = new Centro();
$form = $this->createForm(new SeleccionType(), $entity);
$centro = $this->container->getParameter('gitek.centro_por_defecto');
if ($this->getRequest()->getMethod() == 'POST') {
$form->bind($this->getRequest());
if ($form->isValid()) {
$miseleccion = $request->request->get('selecciontype');
$this->container->setParameter('gitek.centro_por_defecto', $miseleccion['nombre']);
// return $this->redirect($this->generateUrl('admin_centro'));
}
}
return $this->render('BackendBundle:Centro:seleccion.html.twig', array(
'entity' => $entity,
'form' => $form->createView(),
));
}
I´m getting Impossible to call set() on a frozen ParameterBag. error all the time.
Any help or clue?
You can't modify Container once it has been compiled, which is done before invoking the controller.
The DIC parameters are intended for configuration purposes - not a replacement for global variables. In addition it seems you want to persist some kind of permanent modification. In that case consider using session if it's a per-user modification or persisting it (e.g. into DB) if it's supposed to be application-wide.
If you need to modify DIC parameters or services, you can do so using a compiler pass. More info on how to write custom compiler passes can be found at:
http://symfony.com/doc/master/cookbook/service_container/compiler_passes.html
You can set $_ENV variables and get that after
putenv("VAR=1");
And to get
getenv("VAR");

Test JSON-returning controller method without MissingViewError

I am testing a Controller method that has only a JSON view. My method runs as expected, but the test method only returns "MissingViewException". Is there a solution to avoiding this exception in the unit test (besides inserting an empty file at View/People/map_leads.ctp)?
PeopleController.php
public function mapLeads($territory_id = null) {
$leads = $this->Person->getPeople([
'territory_id' => $territory_id
]);
$this->set('leads', $leads);
}
AppController.php
public $components = ['RequestHandler'];
routes.php
Router::parseExtensions('json');
PeopleControllerTest.php
public function testMapLeads() {
$id = 40;
$result = $this->testAction('/people/mapLeads/' . $id, array('return' => 'vars'));
}
View/People/json/map_leads.ctp exists and is properly utilized by CakePHP; it is only the test that wants to see View/People/map_leads.ctp.
I checked at CakePHP: calling testAction to a json-returning method causes missing view exception reminding about adding RequestHandler to $components. This does not resolve the exception.
You aren't issuing a JSON request/accessing a JSON endpoint, as neither your request URL does contain the .json extension, nor does your request send an appropriate Accept header (I don't remember whether the latter is possible with the 2.x controller test case class at all).
Use the .json extension and you should be good.
$this->testAction('/people/mapLeads/' . $id . '.json', array('return' => 'vars'));
Write this code inside your action.
$this->autoLayout = false;
$this->autoRender = false;
$this->response->type('application/javascript');

Issue testing Laravel Controller with Mockery | trying to get property of non-object

I'm very new to testing controllers and I'm running into a problem with a method(). I believe I'm either missing something in my test or my Controller / Repository is designed incorrectly.
The application I'm writing is basically one of those secure "one time" tools. Where you create a note, the system provides you with a URL, once that url is retrieved the note is deleted. I actually have the application written but I am going back to write tests for practice (I know that's backwards).
My Controller:
use OneTimeNote\Repositories\NoteRepositoryInterface as Note;
class NoteController extends \Controller {
protected $note;
public function __construct(Note $note)
{
$this->note = $note;
}
public function getNote($url_id, $key)
{
$note = $this->note->find($url_id, $key);
if (!$note) {
return \Response::json(array('message' => 'Note not found'), 404);
}
$this->note->delete($note->id);
return \Response::json($note);
}
...
I've injected my Note interface in to my controller and all is well.
My Test
use \Mockery as M;
class OneTimeNoteTest extends TestCase {
public function setUp()
{
parent::setUp();
$this->mock = $this->mock('OneTimeNote\Repositories\EloquentNoteRepository');
}
public function mock($class)
{
$mock = M::mock($class);
$this->app->instance($class, $mock);
return $mock;
}
public function testShouldReturnNoteObj()
{
// Should Return Note
$this->mock->shouldReceive('find')->once()->andReturn('test');
$note = $this->call('GET', '/note/1234567890abcdefg/1234567890abcdefg');
$this->assertEquals('test', $note->getContent());
}
}
...
The error I'm getting
1) OneTimeNoteTest::testShouldReturnNoteObj
ErrorException: Trying to get property of non-object
/Users/andrew/laravel/app/OneTimeNote/Controllers/NoteController.php:24
Line 24 is in reference to this line found in my controller:
$this->note->delete($note->id);
Basically my abstracted repository method delete() obviously can't find $note->id because it really doesn't exist in the testing environment. Should I create a Note within the test and try to actually deleting it? Or would that be something that should be a model test? As you can see I need help, thanks!
----- Update -----
I tried to stub the repository to return a Note object as Dave Marshall mentioned in his answer, however I'm now receiving another error.
1) OneTimeNoteTest::testShouldReturnNoteObj
BadMethodCallException: Method Mockery_0_OneTimeNote_Repositories_EloquentNoteRepository::delete() does not exist on this mock object
I do have a delete() method in my repository and I know it's working when I test my route in the browser.
public function delete($id)
{
Note::find($id)->delete();
}
You are stubbing the note repository to return a string, PHP is then trying to retrieve the id attribute of a string, hence the error.
You should stub the repository to return a Note object, something like:
$this->mock->shouldReceive('find')->once()->andReturn(new Note());
Building upon Dave's answer, I was able to figure out what my problem is. I wasn't mocking the delete() method. I didn't understand the need to mock each individual method in my controller that would be called.
I just added this line:
$mock->shouldReceive('delete')->once()->andReturnNull();
Since my delete method is just deleting the note after it is found, I went ahead and mocked it but set it to return null.

Symfony2 : Handling error on a single controller

I made a controller to provide some webservices in JSON and i would like to provide some errors informations when Symfony throw an exception ( Error 500 ) , how can i write such a thing ?
The main purpose of the webservice is to update informations in Symfony DB provided by the caller in POST values.
in my controller i return response in JSON and i would like to handle Symfony exception ( like when the values provided or not fitting the schema designed ) to return details informations about errors .
i thought about making a test of every values but it would be a long time to write and not e easy code to read or using a try / catch system , but i think Symfony already provide such a function .
What do you think ?
Thx :)
I think you should use an EventListener to catch errors and return the proper response.
You can place it inside your SomethingBundle/EventListener folder and also you need to define a service in order to be loaded by Symfony.
More info: Event Listener
I hope I helped you, if you think I might be wrong, let me know. Good luck!
EDIT
If you only want to catch the errors inside a specific controller (for example) a controller called Webservice inside your SomethingBundle, you must check it before doing anything:
public function onKernelException(GetResponseForExceptionEvent $event)
{
$request = $event->getRequest();
if($this->getBundle($request) == "Something" && $this->getController($request) == "Webservice")
{
// Do your magic
//...
}
}
private function getBundle(Request $request)
{
$pattern = "#([a-zA-Z]*)Bundle#";
$matches = array();
preg_match($pattern, $request->get('_controller'), $matches);
return (count($matches)) ? $matches[0] : null;
}
private function getController(Request $request)
{
$pattern = "#Controller\\\([a-zA-Z]*)Controller#";
$matches = array();
preg_match($pattern, $request->get('_controller'), $matches);
return (count($matches)) ? $matches[1] : null;
}
DANGER This code is not tested, is only an approach for you to build your own code. But, if I have something wrong on it, tell me. I'd like to keep my examples clean.
Use JsonResponse Symfony class in sandbox:
use Symfony\Component\HttpFoundation\JsonResponse;
$data = array(); // array of returned response, which encode to JSON
$data['error_message'] = 'Bad request or your other error...');
$response = new JsonResponse($data, 500); // 500 - response status
return $response;

Symfony 2 Controller as a Service: container not injected

I want to be able to inject services into my controllers, so I had a look at http://symfony.com/doc/current/cookbook/controller/service.html and after some fiddling with the notation (could be a little more consistent but whatever) I have my WebTestCase using the service definition entry.
But the controller needs the container itself injected (and does indeed extend ContainerAware via the default framework controller), and the ControllerResolver in the FrameworkBundle does not do that.
Looking at the code (Symfony\Bundle\FrameworkBundle\Controller\ControllerResolver::createController()) this is not suprising:
protected function createController($controller)
{
if (false === strpos($controller, '::')) {
$count = substr_count($controller, ':');
if (2 == $count) {
// controller in the a:b:c notation then
$controller = $this->parser->parse($controller);
} elseif (1 == $count) {
// controller in the service:method notation
list($service, $method) = explode(':', $controller, 2);
return array($this->container->get($service), $method);
} else {
throw new \LogicException(sprintf('Unable to parse the controller name "%s".', $controller));
}
}
list($class, $method) = explode('::', $controller, 2);
if (!class_exists($class)) {
throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
}
$controller = new $class();
if ($controller instanceof ContainerAwareInterface) {
$controller->setContainer($this->container);
}
return array($controller, $method);
}
Apparently when using service:method notation,, it directly returns the controller from the container, not injecting the container itself.
Is this is a bug or am I missing something?
This is not a bug. It works as expected. This workflow generally "protects" the Controller as a Service concept. This way You need to look at Controller as a regular Service. In regular Service You inject everything what You need - if You need the controller itself - inject it explicitly.
To explain it more clearly, this "protection" I mentioned helps to avoid using service:method notation in one place and controller::method or bundle:controller:method in another.
So if not this "protection" it would be difficult to state that particular Controller is described as a Service or not as this would depend on which notation will be called first in Container build-up.