phpunit - Help needed about risky tests - php

i'm implementing some tests for a site.
In a particular test, this result occurred:
{
"event": "test",
"suite": "Example_V_test",
"test": "Example_V_test::test_3",
"status": "error",
"time": 13.469105958939,
"trace": [
{
"file": "\/opt\/lampp\/htdocs\/buy\/application\/tests\/phpunit.phar",
"line": 569,
"function": "main",
"class": "PHPUnit_TextUI_Command",
"type": "::"
}
],
"message": "Risky Test: Test code or tested code did not (only) close its own output buffers",
"output": ""
}R 3 / 3 (100%)
Time: 25.76 seconds, Memory: 59.25MB
There was 1 risky test:
1) Example_V_test::test_3
Test code or tested code did not (only) close its own output buffers
/opt/lampp/htdocs/buy/application/tests/phpunit.phar:569
OK, but incomplete, skipped, or risky tests!
My question is this: how to find the line of code that cause this 'issue'?

The message is reported if PHPUnit detects that the output buffering level at the end of a test method is different from the level at the beginning. This is due to the fact that it uses its own output buffer and checks that the test produces no output.
Because there is no option in PHPUnit to ignore this, you need to find the reason why the output buffering in your code was started but not ended (or ended too much) and fix that.
That might be really difficult to achieve because there is no hint, where output buffering is started, but you could use a full-text search on your source code (and libs) to identify candidates. Then look for Exceptions, which might break the normal program flow and so prevent ob_end_flush() (or similar) to be called.

Specifically to Test code or tested code did not (only) close its own output buffers
Recently ran into this.
Originally this SO question, and the answer was a solution for me. However, I didnt like the solution. There was a deeper reason as to why this was happening, and only on one test out of hundreds I have written...
After doing a little bit more digging, I was able to locate my issue stemmed from a #section() and #endsection call within my blade template.
Some how, through mistake the keyboard was struck and a random key was left there. This didn't cause issues visually, or any red flags to the end user when page rendered so it went unnoticed.
In my case -- My error was
#section('sudo')
...
#endsection2
removing the 2 fixed the original issue and allowed me to remove the hacky solution for
// // start hacky
// ob_start();
// ob_end_flush();
// ob_get_clean();
// // end hacky
ps. this may only fix a percentage of peoples issues that trip across this SO question. Sorry if it doesnt solve your issue :)

Mine is fixed by using:
ob_end_flush();
ob_get_clean();
At end of tests.

I ran into this error also:
Test code or tested code did not (only) close its own output buffers
It's useful to use ob_get_level() to determine the output buffer level at the start and end of the affected test. I put breakpoints in the test then used the console in PHPStorm to check this.
In my case, I was testing a method that opened a Symfony\Component\HttpFoundation\StreamedResponse. The level was 1 at the start of the test, but 0 at the end - so for me the solution was to add ob_start() at the end of the test.

Related

Trapping line of code that emits first character

Suddenly, an application isn't any longer able to output ZIP files. An inspection revealed the cause: The first character of the ZIP is a blank, which breaks the ZIP format spec.
To track down this problem, I enabled CStatementTracer, which prints each line of executed code to a log file. Didn't help. [Remark: declare(ticks=1); doesn't seem to trap each line of executed code]
I then set an output handler like so:
function callback( $buffer ) {
$deb = print_r( debug_backtrace(), TRUE );
file_put_contents( './statementTrager.log', $deb );
return $buffer;
}
ob_start("callback", 1 );
Unfortunately, this handler isn't called at all.
Q: Does a generic / canonical solution exists, which identifies the file / line of PHP-code, which emits the first character.
A solution, that finds the loc whatever other code gets executed.
Remarks:
Not even a single PHP file is closed using ?>
Meanwhile I found the suspicious like of code: A blank in front of a starting
Still, I'd like to get hints regarding a programmatic solution. Preferrably a solution written in pure PHP.
https://linux.die.net/man/1/strace is probably the most reliable tool to find out where the output comes from. Assuming you are on Linux. There must be similar tools for other platforms.
Although it will not give you the line of the php code, you can analyse the context of system calls made before and after the offensive character was sent. Usually it is enough to identify where the problem originates.
It is quite time consuming process though. Should be used as the last resort.

PHP's exec() printing output -- doesn't seem to follow specs

One of my users is experiencing odd behavior that doesn't seem to follow the PHP exec() specs.
I'm invoking like so:
exec($cmd, $out, $ret);
I would expect this not to generate any output, but the user is seeing an error stack trace from $cmd printed when it errors out. Nothing in my code outputs anything, so it has to be coming out of exec(), but how? Am I misinterpreting the documentation?
I expect I could trap this inside of an output buffer then dispose of it, but I would rather prevent it... And whatever I do, I want to understand why this is happening first.
NOTE: I'm working on getting more specifics on PHP version and other d etails from the users, but do not have that information at this time. All I can say is that it is >= 5.2.4.
What you experience is the normal unix behaviour:
An executed command always has two output pipes: standard out and error out. The documentation states that all output is given back. That does not include stuff written to the error output. That is using a separate pipe py purpose to separate error and normal output. If you want to capture that too you have to change the command you execute, typically you map the error output to the standard output by appending a 2>&1.

Output Buffering? Why not?

I found few articles on the Internet that are suggesting use of ob_ functions, all of these emphase benefits, and there are no downsides of using functions mentioned.
My question is what are the downsides of using ob_ functions, or setting ini_set('output_buffering', '1'); ?
The cons of using output buffering entirely depend on the context of your usage.
One of the biggest cons of output buffering is your runtime error messages or warnings may get suppressed, and you may sometimes end up with erroneous data.
Consider this example:
<?php
function render_template() {
ob_start();
// Do some processing
fetch_template_and_render();
do_render();
// end capture
$output = ob_get_clean();
return $output;
}
memchace::set( $some_key, render_template() );
?>
If either of fetch_template_and_render or do_render throw run time errors, they will get dumped into your output, and eventually in this example will end up in the database or cache.
Here are 2 snippets that demonstrate what I mean which you can try for yourself
#1
<?php
echo 1/0;
?>
outputs
Warning: Division by zero on line 1
#2
<?php
ob_start();
echo 1/0;
$var = ob_get_clean();
?>
outputs nothing.
To avoid such cases, you will need to be diligent about error checking and take precautions.
When used diligently, ob_* functions are very powerful and super useful.
There are no major drawbacks, with proper implementation, to the use of output buffering.
Output buffering can allow errors/warnings/notices (except stop errors) to appear in the output without being readily apparent. This is typically resolved with proper error checking, better configuration of the php environment and the implementation of a good error handler (such as one that converts errors to ErrorExceptions which can be caught with try/catch - see Whoops! as an example of an error handler using ErrorExceptions).
Memory can possibly be a drawback, but the output size is typically insignificant for most scripts. An exception to this may be when sending large amounts of data, such as using fpassthru to deliver file content. This can be resolved by turning off the output buffering (ob_end_clean or ob_end_flush) before writing this content to the output.
Memory consumption is the most important drawback. I've recently built a PHP script that outputs a large chunk of XML data of several megabytes. The framework this 'page' was part of used output buffering. With output buffering, you need a memory buffer large enough to contain all the data. In my case it wasn't and the script failed.
If you output the data directly to the client, you don't have this problem. This is escpecially important in cases like this and when throughputting files. In case of generating a 'normal' HTML page, you will likely not use up the whole buffer, although you still need a lot of memory if you have many simultaneous requests.
Without buffering, the data is gone and doesn't trouble your server anymore. As long as the data is buffered, it can be changed or flushed, but actually puts a load on your server.
Here's a pretty good use for ob_ functions:
ob_start("ob_gzhandler");
Provided that the zlib extension is enabled in PHP, that should ensure your output is gz-compressed. It noticably speeds up page transfers for large pages.

Omnicompletion stops giving useful predictions

I am trying to set up omni completion for PHP in vim 7.3 with ctags 5.9~svn20110310 on Ubuntu 12.04.1 (LTS) but I am running into a very strange issue where completion provides radically different predictions for instances of the same class.
I have the following two files:
// Foo.php
class Foo {
public function do_stuff() {
echo 'Working...';
}
}
// index.php
require 'Foo.php';
$f = new Foo();
$f->[cursor position 1]
$g = new Foo();
$g->[cursor position 2]
When the cursor is in position 1 and I press CTRL+X CTRL+O it comples the line with do_stuff( as we would expect. But when I press CTRL+X CTRL+O in the second position I get a list of predictions that starts with key, next, rewind. What am I doing wrong?
Edit: With regard to your specific issue, if you have an old version of phpcomplete.vim, it's possible that you can only properly complete off a variable either by marking it with a special phpdoc tag (see this question) or by regenerating your tags file after declaring the variable.
In all probability, you are doing nothing wrong; the PHP support in ctags is extremely basic and not very rigorous, which unfortunately means the Vim support is lacking, too. A quick look at the ctags module illustrates the problem:
ctags/php.c
That's it. Just a couple of relatively basic regular expressions. That parser stuff at the bottom is not used any longer, and tragically hasn't been for a very long time.
Compounding the issue is the fact that the standard omnicomplete function for PHP in Vim is hackish at best; suffice it to say that it involves switching between all the open windows as part of its completion process (a practise explicitly condemned by Vim documentation). Take a look for yourself:
phpcomplete.vim/autoload/phpcomplete.vim
I have struggled with terrible PHP completion in Vim for a long time now and have determined that nothing short of a complete overhaul will produce a satisfactory result. I've joined the ctags dev mailing list, and I plan to improve the PHP support there before moving on to making Vim's omnicompletion thereof work as properly as it can in an interpreted language. For now, unfortunately, the solution is to wait until the support is better, or fix it yourself.

Why might my PHP log file not entirely be text?

I'm trying to debug a plugin-bloated Wordpress installation; so I've added a very simple homebrew logger that records all the callbacks, which are basically listed in a single, ultimately 250+ row multidimensional array in Wordpress (I can't use print_r() because I need to catch them right before they are called).
My logger line is $logger->log("\t" . $callback . "\n");
The logger produces a dandy text file in normal situations, but at two points during this particular task it is adding something which causes my log file to no longer be encoded properly. Gedit (I'm on Ubuntu) won't open the file, claiming to not understand the encoding. In vim, the culprit corrupt callback (which I could not find in the debugger, looking at the array) is about in the middle and printed as ^#lambda_546 and at the end of file there's this cute guy ^M. The ^M and ^# are blue in my vim, which has no color theme set for .txt files. I don't know what it means.
I tried adding an is_string($callback) condition, but I get the same results.
Any ideas?
^# is a NUL character (\0) and ^M is a CR (\r). No idea why they're being generated though. You'd have to muck through the source and database to find out. geany should be able to open the file easily enough though.
Seems these cute guys are a result of your callback formatting for windows.
Mystery over. One of the callbacks was an anonymous function. Investigating the PHP create_function documentation, I saw that a commenter had noted that the created function has a name like so: chr(0) . lambda_n. Thanks PHP.
As for the \r. Well, that is more embarrassing. My logger reused some older code that I previously written which did end lines in \r\n.

Categories