PHPUnit - does nothing, no errors, no output - phpunit

Sorry for another 'phpunit doesn't work' question. It used to work for years now. Today I reinstalled PEAR and phpunit for reasons not connected to this problem. Now when I run phpunit as I usually did. Nothing happens. The cli just shows me a new line, no output whatsoever.
Has anyone encountered this problem or has an idea what could have caused it.
PHPUnit Version: 3.5.15
PEAR Version: 1.9.4
PHP Version: 5.3.8
Windows 7

I'm on OSX and MAMP. To get error messages I had to adjust the following entries in php.ini:
display_errors = On
display_startup_errors = On
Please not that this has to go into /Applications/MAMP/bin/php/php5.3.6/conf/php.ini .

For future reference, for those who are facing any problem with PHPUnit, and PHPUnit is failing silently, just add this three lines inside phpunit.xml:
<phpunit ....... >
...
...
<php>
<ini name="display_errors" value="true"/>
</php>
</phpunit>
After that run the tests again, and now you can see why PHPUnit is failing,
AND ... ENJOY UNIT TESTING :)

I know the orignal poster's question is already answered, but just for any people searching in the future: one thing that can cause PHPUnit to fail silently (i.e. it just stops running tests without telling you why) is that it has an error handler that it set up before each test run, which is intended to capture errors and display them at the end of the test run. The problem is that certain errors halt execution of the whole test run.
What I generally do when this happens, as a first step, is reset the error handler to something that will immediately output the error message. In my base test class I have a method called setVerboseErrorHandler, which I'll call at the top of the test (or in setUp) when this happens. The below requires php 5.3 or higher (due to the closure), so if you're on 5.2 or lower you can make it a regular function.
protected function setVerboseErrorHandler()
{
$handler = function($errorNumber, $errorString, $errorFile, $errorLine) {
echo "
ERROR INFO
Message: $errorString
File: $errorFile
Line: $errorLine
";
};
set_error_handler($handler);
}

Create the simplest test class you can without a bootstrap.php or phpunit.xml to first verify that your new installation works. PHPUnit will stop without any message if it cannot instantiate all of the test cases--one for each test method and data provider--before running any tests.

You have already figured out how to get it to work, but my solution was a little different.
First thing you can do is check the exit status. If it's not 0, then PHP exited and because of the INI configuration settings set, none of the PHP error messages were outputted. What I did was to enable the "display_errors" INI setting, and set "error_reporting" to E_ALL. I was then able to identify errors such as PHP not being able to parse a certain script. Once I fixed that, PHPUnit ran properly.

I managed to spectacularly paint myself in a corner with a custom "fatal error handler" that in certain rare conditions turned out to output nothing. Those conditions, in accordance with Murphy's Law, materialized once I had forgotten the handler was in place.
Since it wasn't really a "PHPunit problem", none of the other answers helped [although #David's problem was at the bottom the same thing], even though the symptoms were the same - phpunit terminating with no output, no errors, no log and no clue.
In the end I had to resort to a step-by-step tracing of the whole test suite by adding this in the bootstrap code:
register_shutdown_function(function() {
foreach ($GLOBALS['lastStack'] as $i => $frame) {
print "{$i}. {$frame['file']} +{$frame['line']} in function {$frame['function']}\n";
}
});
register_tick_function(function() {
$GLOBALS['lastStack'] = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 8);
});
declare(ticks=1);
If anyone ever manages to do worse than this, and somehow block stdout as well, this modification should work:
register_shutdown_function(function() {
$fp = fopen("/tmp/path-to-debugfile.txt", "w");
foreach ($GLOBALS['lastStack'] as $i => $frame) {
fwrite($fp, "{$i}. {$frame['file']} +{$frame['line']} in function {$frame['function']}\n");
}
fclose($fp);
});

an old thread this one, but one I stumbled across when having the same problem.
I had the same problem, nothing being returned to console including print, print_r, echo etc.
solved it by using --stderr as a test-runner option.

Check that you haven't written any logic into your code that just dies, with no output. For example,
<?php
if (!array_key_exists('SERVER_NAME', $_SERVER)) {
die();
}
This was exactly my case; I'd made some assumptions about the environment which were correct when running the code via Apache, but weren't fulfilled when running from CLI and the code did not echo any output.
PHPUnit tried to include the bootstrap file before giving the usual init output, but died during the bootstrapping proccess, hence exiting with status 0 and no output.

If when you run from command line a recent version of phpunit like this
> php phpunit
or
> ./phpunit
or
> php ./phpunit.phar
or
> ./phpunit.phar
And you immediatly return to the prompt with no messages, this is probably due to a "suhosin secutiry" setup.
phpunit is now a "phar" package including all libraries. To be able to run such file when php has the suhosin security module enabled, you must first set this
suhosin.executor.include.whitelist = phar
into you php.ini file (for example, with debian/ubuntu, you may have to edit file /etc/php5/conf.d/suhosin.ini

i tried everything here, but nothing worked until i tried phpunit --no-configuration simpletest.php. that finally gave me some output, which implies that my phpunit.xml.dist file is broken. (i'll come back and update this once i debug it.)
the contents of simpletest.php are below, but any test file should work.
<?php
use PHPUnit\Framework\TestCase;
final class FooTest extends TestCase
{
public function testFoo()
{
$this->assertEquals('x', 'y');
}
}

Check if the phpunit you're running and the one you installed are the same:
$ pear list phpunit/phpunit
...
script /path/to/phpunit
...
Try to execute exactly that phpunit with the full path.
Then check your PATH variable and see if the correct directory is in it. If not, fix that.
If that does not help, use write something into the phpunit executable, e.g. "echo 123;" and run phpunit. Check if you see that.

For me the conflict was with Xdebug's directive
xdebug.remote_enable=1

If you are using composer, check to make sure your included PHP files are not ending the code executions. The same goes for when you included certain PHP files explicitly.
In my case, I was working on a WordPress plugin and one of the PHP files I included directly in composer.json (which I don't want to load through PSR-4 because WordPress's coding standards don't support it yet) had this code on top;
if (!defined('ABSPATH')) {
exit(); // exit if accessed directly
}
And since ABSPATH will not be defined when I run the tests directly, the code was exiting.
This is because, since I told Composer to always load these files each time, this part of the code will execute, while the other files included though autoload PSR will load on demand.
So check to make sure any of the files you included are not stopping the code execution. If it happens, then even when you run phpunit --info the code will still exit and you won't see any output.

I was facing a seems problem. I could run phpunit from root directory but not from anywhere else. so I put the "--configuration" tag, and point it to my xml configuration.
$ ./<path_to_phpunit>phpunit --configuration <path_to_phpunitxml>/phpunit.xml
The path to phpunit is optinal, I used it because I installed locally by composer.

In /composer/vendor/phpunit/phpunit/src/TextUI/Command.php in main() function in catch (Throwable $t) {} block var_dump (echo / print_r) exception. If an exception exists, you, probably, will solve the current problem.

Related

Grunt error with fs.unlinkSync on Sails

I'm using skipper to receive the files, sharp to resize (and save) and fs unlink to remove the old image. But I got a very weird error this time that concerns me a lot:
error: ** Grunt :: An error occurred. **
error:
Aborted due to warnings.
Running "copy:dev" (copy) task
Warning: Unable to read "assets/images/users/c8e303ca-1036-4f52-88c7-fda7e01b6bba.jpg" file (Error code: ENOENT).
error: Looks like a Grunt error occurred--
error: Please fix it, then restart Sails to continue running tasks (e.g. watching for changes in assets)
error: Or if you're stuck, check out the troubleshooting tips below.
error: Troubleshooting tips:
error:
error: *-> Are "grunt" and related grunt task modules installed locally? Run npm install if you're not sure.
error:
error: *-> You might have a malformed LESS, SASS, CoffeeScript file, etc.
error:
error: *-> Or maybe you don't have permissions to access the .tmp directory?
error: e.g., (edited for privacy)/sails/.tmp ?
error:
error: If you think this might be the case, try running:
error: sudo chown -R 1000 (edited for privacy)/sails/.tmp
Grunt stopped running and to have that in production is a big NoNo... I believe that this is caused because of concurrency with fs.unlinkSync(fname). The error is also intermittent and very hard to reproduce in some machines (IO ops/sec maybe?).
I have the following controller action:
var id = 1; // for example
req.file('avatar').upload({
dirname: require('path').resolve(sails.config.appPath, 'assets/images')
}, function(err, files){
var avatar = files.pop();
//file name operations here. output is defined as the path + id + filetype
//...
sharp(avatar.fd)
.resize(800, 800)
.toFile(output, (err, info)=>{
if(err){
res.badRequest();
} else {
fs.unlinkSync(avatar.fd);
res.ok();
}
});
});
Now I've been thinking about a few solutions:
Output the new image directly to .temp
Unlink when files exists on .tmp. Explanation: Grunt already copied the old file so removing it would be safe!
But I don't know if this is some spaghetti code or even if a better solution exists.
EDIT: My solution was, as proposed by arbuthnott, wrap a controller like this:
get : function(req, res){
var filepath = req.path.slice(1,req.path.length);
//remove '/' root identifier. path.resolve() could be used
if(fs.existsSync(path.resolve(filepath))){
return res.sendfile(filepath);
} else {
return res.notFound();
}
}
I think you are on the right track about the error. You are making some rapid changes to in the assets folder. If I read your code right:
Add an image with user-generated filename to assets/images (ex cat.jpg)
Copy/resize the file to an id filename in assets/images (ex abc123.jpg)
Delete the original upload (cat.jpg)
(I don't know the details of sharp, there may be more under the hood there)
If sails is running in dev mode, then Grunt will be trying to watch the whole assets/ folder, and copy all the changes to .tmp/public/. It's easy to imagine Grunt may register a change, but when it gets around to copying the added file (assets/images/cat.jpg) it is already gone.
I have two suggestions for the solution:
One:
Like you suggested, upload your original to the .tmp folder (maybe even a custom subfolder of .tmp). Still place your sized copy into /assets/images/, and it will be copied to /.tmp/public/ where it can be accessed as an asset by the running app. But Grunt will ignore the quick add-then-delete in the .tmp folder.
Two:
Do a bit of general thinking about both what you want to include in version control, and what Grunt tasks you want to be running in production. Note that if you use sails lift --prod then Grunt watch is turned off by default, and this error would not even occur. Generally, I don't feel like we want Grunt to do too much in production, it is more of a development shortcut. Specifically, Grunt watch can use a lot of resources on a production server.
The note about version control is just that you probably want some of the contents of assets/images/ to be in version control (images used by the site, etc), but maybe not in the case of user-uploaded avatars. Make sure you have a way to differentiate these contents (subdirectories or whatever). Then they can be easily .git-ignore'd or whatever is appropriate.
Hope this helps, good luck!

Sudden syntax error after deployment

I have a working symfony project. I have it on a private bitbucked repository and locally the website works without an issue.
Today I tried to deploy the project onto an external server linuxpl.com.
Steps taken include:
Istalling composer
Adding the mysql database
Running git clone to get the data into a proper location
Running composer install on the folder to install everything and connect to the db
Cleared the cache
Set the project root as ....domain/project_name/web
However after completing all these steps, when running the website with regular server:run I'm getting this odd error:
Parse error: syntax error, unexpected '.' in /home/spirifer/domains/surowcewobiektywie.pl/konkurs/vendor/twig/twig/lib/Twig/Extension/Core.php on line 1571
Not sure if this is of any importance but the mentioned code partion looks like this in my local files:
// Some objects throw exceptions when they have __call, and the method we try
// to call is not supported. If ignoreStrictCheck is true, we should return null.
try {
$ret = $object->$method(...$arguments);
} catch (BadMethodCallException $e) {
if ($call && ($ignoreStrictCheck || !$env->isStrictVariables())) {
return;
}
throw $e;
}
The local version does not differ from the one on the server.
My local machine has PHP 7.0.9 and the remove server has PHP 7.0.14
How could I fix this issue?
PHP 5.6 adds Variadic functions, with "...". However, Twig v1.x only required the use of PHP 5.2.7 or above.
If you didn't explicitly update to Twig 2.0, it's very possible you have used the 'death star' version constraint in the composer file - '*'. which allows uncontrolled version updates to the latest version. If this is the case, you will need to either update your version of PHP, or at least require just a previous version of Twig/twig, "^1.32" would be the latest in the version 1 series of Twig.

non cli PHPUnit - Running and collecting results in a php script

I am trying to get the results of a php unit tests folder , but not using the CLI, and instead using a php file.
I would like to get the answer ( OK, 4 tests passed ) in a variable or something so I can decide whether the script should execute or not, what's the best way to do this? i don't want to use batch files, I want to force the execution of the tests, inside the library itself.
I started with
require_once 'PHPUnit/Autoload.php';
When I included the tests, don't know how to start them thought.
Any advice?
You can check PHPUnits exit code, 0 means no test failed.
To run the tests from a php file, then to check the exit code, try something like this:
//Composer installs phpunit to /vendor/bin/phpunit
exec('/vendor/bin/phpunit', $result, $exitCode);
if ($exitCode == 0) {
// continue exiting the script
} else {
// there was a test failure, more info will be in $result
}
If you're looking for an enterprise quality solution, look into a Continuous Integration product like Jenkins or Bamboo.

Why does Symfony2 set the error_reporting?

I've been trying to remove the E_NOTICE and E_STRICT error levels to avoid this error:
Runtime Notice: Only variables should be passed by reference
I tried modifying php.ini but didn't work, error_reporting always is -1. Then I tried setting it dynamically in the current action, and worked fine. Then I also tried the same in the first line in app_dev.php and didn't work. Which means Symfony2 is setting it dynamically somewhere.
What should I do?
EDIT
For those who are not familiar with the error:
$user = $this->('security.context')->getToken()->getUser();
$first = reset($user->getRoles()); // error
$roles = $user->getRoles();
$first = reset($roles); // works fine
Whilst the notice is not 'retarded', this is a reasonable question in other contexts so: this is set in the Kernel instance, instantiated in app_dev.php (or app.php).
The second parameter to the construct is a boolean debug flag, and if true then error_reporting is set to -1 and display_errors to 1, otherwise default and 0 respectively.
$kernel = new AppKernel('dev', false);
symfony documentation
Hope this helps.
I got the same error in the following scenario i.e.
Scenario:
I lost the development environment for my existing LIVE project. But I got the whole code from GIT repo and then installed the symfony 2.4.2 (same version as on LIVE site) in my new development environment. Then I found that the web-application pages working on the LIVE site are broken in my new DEV environment.
Solution:
I spent quit a lot time to understand why the problem is then I found that i.e.
When I installed symfony 2.4.2 in my development environment using composer.phar then it created a new web/app_dev.php file in my development environment and it has the following entry to turn it off i.e.
Debug::enable();
Just comment the above line then the php notices will be off and then all the pages that were giving me notices are fixed.
I hope this will be helpful for someone having the same problem like me. Good Luck!
Cheers.
PS: But I will recommend to enable the above line in your new development projects so that you can see the PHP notices and then remove them during development.

How to Determine if PHPUnit Tests are Running?

I currently have a problem that I have to work around in legacy code to get our interaction with a PHP Extension to work properly (Singleton Testing Question).
As such, I do not want to execute this code when running our normal production code with the application. Therefore, I need to check in regular PHP code if the code being executed is being executed as part of a test or not.
Any suggestions on how to determine this? I thought about a defined variable tied to the presence of the test files themselves (we do not ship the tests to customers) but our developers need the Extension to work normally, while the CI server needs to run the tests.
Would a Global set in the PHPUnit.xml file be recommended? Other thoughts?
An alternative approach is to set a constant in the PHP section of your phpunit.xml.*:
<php>
<const name="PHPUNIT_YOURAPPLICATION_TESTSUITE" value="true"/>
</php>
In your PHP application, you might then use the following check:
if (defined('PHPUNIT_YOURAPPLICATION_TESTSUITE') && PHPUNIT_YOURAPPLICATION_TESTSUITE)
{
echo 'TestSuite running!';
}
Define a constant in your PHPUnit bootstrap.php file. This is executed before loading or running any tests. This shouldn't impact developers running the application normally--just the unit tests.
If you're using Laravel than use App::runningUnitTests()
You could check the $argv different ways.
if(PHP_SAPI == 'cli') {
if(strpos($_SERVER['argv'][0], 'phpunit') !== FALSE) { ... }
// or
if($_SERVER['argv'][0] == '/usr/bin/phpunit') { ... }
}
Use PHPUnit Constants
You can either define constant, but that requires your work, no typos and it's not generic. How to do it better?
PHPUnit defines 2 constants by itself:
if (! defined('PHPUNIT_COMPOSER_INSTALL') && ! defined('__PHPUNIT_PHAR__')) {
// is not PHPUnit run
return;
}
// is PHPUnit

Resources