- Using the Symfony2 Dependency Injection Container as a standalone component
- Launching PHPUnit tests from a browser with Symfony2
- Using the Console component to write an interactive installer for Composer
This post is part of the ”Symfony2 components in your own userland” series; here is a list of all the articles contained this series:
Today we are going to launch interactive PHPUnit tests thanks to the Symfony2 Process component.
Premise
This article will show you how to build a script to run your unit tests from a browser and render the output to the webpage: since the aim of this series of articles is to show you how easily you can integrate Symfony2 code into your own projects, I will use nasty scripts to accomplish our requirements.
The approach
Our approach will be very basic and dummy: we are goint to execute a shell command from PHP, write each output buffers into a file and poll the file from the frontend to progressively read its content.
Into the mix
To do so, let’s create a JS-loving index.php
file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|
As you see, as you click on the Run tests
link you will fire an event that:
- makes a
GET
call toprocess.php
- makes a recursive
GET
request tooutput.php
, until the output object does not contain thestop
attribute
The output script is really easy:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
|
As you see, each time we call this script, it reads the content of the test.output.txt
file in the temporary directory of your system: if it doesn’t find it, it reads the
test.output.txt.f
file1.
Enter Process
In our final step, let’s install the Process component:
1 2 3 4 5 6 |
|
1 2 3 |
|
then we can create our process.php
script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
|
As you see we are launching the test suite and, at each buffer, thanks to a
lambda, we write a new chunk to the file: at the end of the process the
txt
file gets renamed, so the output.php
script knows that it needs to
notify the frontend that he’s not required to poll it anymore, adding
the stop
attribute to the JSON object it outputs:
1 2 3 |
|
Benefits from the Process component
I can do that crap with shell_exec() too!
There are some advantages of using Process instead of writing your own command executor: first of all, if you don’t want to take care of the subtle differences between the different platforms everything is done for you; then error handling becomes very easy since you are able to catch all the buffers:
1 2 3 4 5 6 7 8 9 10 11 |
|
- Flaw here: no error handling when the .f file is not found ↩