How to quickly write debug output from within a PHP Spec test method - phpspec

I have inherited some phpspec tests.
The test is testing the value of a method called "getFatalErrors" and reporting failure with:
expected [array:1], but got [array:1].
I would like to see the actual contents of the array.
I have tried to hack the phpspec test class by adding lines like:
<?php
namespace spec;
use MyClass;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class MyClassSpec extends ObjectBehavior
{
public function it_returns_a_path_problem($args,\XMLFileWrapperTest $testWrapper)
{
echo "foo";
...
var_dump(print_r($this->getFatalErrors()->getWrappedObject(), true));
...
fwrite(STDOUT, "foo");
print_r($this->getFatalErrors()->getWrappedObject(), true)
$this->display("foo");
}
}
--
But I can never get any output to show on my CLI output.
How can I make some arbitrary text appear in my test output so that I 'see' what is going on as I become more familiar with PHPSpec?

Try a different formatter.
When the formatter pretty is selected either in phpspec.yml using the line
formatter.name: pretty
or when executing the test runner with format flag
vendor/bin/phpspec run --format=pretty
then echo output is visible in the terminal.

Have you tried to tail the error log and in your function to add something like
error_log( print_r( $this->getFatalErrors()->getWrappedObject(), 1 ) ); or error_log( print_r( $this->getFatalErrors(), 1 ) ); ?
Usually, it works, as the output is written in your server error log and you can use the terminal or console to tail on that file and see in real time the result.

Just run phpspec with the -v flag, it will be more verbose.

According to the phpspec documentation on Matchers > Inline Matcher, it is possible...
to print a more verbose error message
to do this you can throw
FailureException
So, this implies that it is possible to throw FailureException to output custom messages from within your PHPSpec Example methods.
I tried this and it let me write the phrase "foo message" to my test output:
<?php
namespace spec;
use PhpSpec\ObjectBehavior;
[...]
use PhpSpec\Exception\Example\FailureException;
class MyClassSpec extends ObjectBehavior
{
public function it_tests_something()
{
[...]
throw new FailureException("foo message");
}
}

Related

How to pass arguments to a test function in laravel throw console

I'm playing around with test in Laravel, and I want to test the same function with different users I've created. Is there a way to pass the id as an argument throw laravel console? I mean, writing something like:
/** #test */
public function my_test_function($id)
{
$user = User::find($id);
..........................}
And then calling with:
php artisan test --filter my_test_function ....... plus something to pass the id.
The cli arguments are accesible in the global namespace. You can retrieve and dump them with something like:
/** #test */
public function my_test()
{
global $argv;
var_dump($argv);
$this->assertTrue(true);
}
However, phpunit shouldn't allow for arbitrary parameters
$ vendor/bin/phpunit -u 1
PHPUnit 9.5.4 by Sebastian Bergmann and contributors.
Unknown option "-u"
You can resort to piggyback on a harmless option. For example, if you mean to pass an integer to match the user_id (as you probably do), you could probably do
$ vendor/bin/phpunit --exclude-group 14
As long as you don't have a real test group called '14', and have the dump display:
array (3) [
0 => string (15) "vendor/bin/pest"
1 => string (15) "--exclude-group"
2 => string (2) "14"
]
You don't need to write your own parsing rules to handle those arguments, but it's still -as I said- piggybacking and it could break in several ways. Before going further with that approach, I'd reccomend using an environment variable defined right before the executable
$ APP_USER_ID=14 vendor/bin/phpunit
which you can retrieve with
/** #test */
public function my_test()
{
var_dump(getenv('APP_USER_ID'));
$this->assertTrue(true);
}
the dump will display the value you're looking for without involving arguments parsing
string (2) "14"

How can my command pass through optional arguments to another Artisan command?

(Updated question to show that it's not like the linked questions)
I wrote a Laravel command (shown in its entirety below) that basically is a wrapper for Dusk so that I can be sure to call certain other functions beforehand. (Otherwise, I inevitably would forget to reset my testing environment.)
It works perfectly when I run php artisan mydusk.
namespace App\Console\Commands;
class DuskCommand extends BaseCommand {
protected $signature = 'mydusk {file?} {--filter=?}';
protected $description = 'refreshAndSeedTestingDb, then run Dusk suite of tests';
public function handle() {
$this->consoleOutput($this->description);
$resetTestingEnv = new ResetTestingEnv();
$resetTestingEnv->refreshAndSeedTestingDb();
$this->consoleOutput('refreshAndSeedTestingDb finished. Now will run Dusk...');
$file = $this->argument('file');//What to do with this?
return \Artisan::call('dusk', ['--filter' => $this->option('filter')]);
}
}
As you can see, I've already read these docs and understand how to write the $signature to accept optional arguments.
My goal is to be able to sometimes run php artisan mydusk and also be able to optionally add arguments such as when I might want to call something like php artisan mydusk tests/Browser/MailcheckTest.php --filter testBasicValidCaseButtonClick (which would pass the tests/Browser/MailcheckTest.php --filter testBasicValidCaseButtonClick arguments through to the normal dusk command).
How can I edit the last 2 lines of my handle() function so that $file gets passed to dusk?
You can have a look at these links too it might help you.
Stack Answer 1
Stack Answer 2
I was surprised to learn from my experiments that my original function actually works as I desired, and I can remove the inert line ($file = $this->argument('file');).
Passing the file argument through \Artisan::call() actually does not seem to be necessary at all.
#fubar's answer seems to have made the same mistaken assumptions as I originally did.
As #Jonas Staudenmeir hinted in a comment, Laravel\Dusk\Console\DuskCommand uses arguments from $_SERVER['argv'].
Use signature without '--' to provide arguments
return \Artisan::call('dusk', ['file' => $file , '--filter' => $this->option('filter')]);
The documentation does give an example but it is not stated clearly (it assumes you followed all the statements in the sections above)
For the signature below
protected $signature = 'email:send {user} {--queue}';
It gives (on very far below) this example as calling an Artisan command from other commands
public function handle()
{
$this->call('email:send', [
'user' => 1, '--queue' => 'default'
]);
}
https://laravel.com/docs/5.6/artisan#calling-commands-from-other-commands

Is it possible to print the created query, like shows up in error messages?

I really like how the error messages include a text string representing what the ReQL code looks like. Is it possible to get at this without forcing an error?
Example Error message:
RqlRuntimeError: No attribute `colors` in object:
{...}
in:
r.db("r_g").table("items").group("collection").ungroup().map(function(var_0) { return var_0("group").object(var_0("reduction")); }).concatMap(function(var_1) { return var_1("colors"); })
I'm wanting to get at the value after "in:" shown before I run() the query.
You can use .toString() like query.toString() (without .run(...))
It should use the same code as the one used to generate backtraces.
I opened an issue this morning to add it in the docs, it is somehow missing -- https://github.com/rethinkdb/docs/issues/354

Error while executing perl application in locate.pl

This is the error:
No 'new' for class 'Spec::Benchmark::bzip2401' in 'C:/Users/Tester/Documents/SpecINT2k6_WoT/benchspec/CPU2006/401.bzip2/Spec/object.pm'
point of error in locate.pl file:
my $class="Spec::Benchmark::${name}${num}";
if (!$class->can('new')) {
Log(0, "\nNo 'new' for class '$class' in '$pm'\n");
next;
}
here is the link to the whole locate.pl file http://ks.tier2.hep.manchester.ac.uk/Repositories/other-software/SPEC_CPU2006v1.1/bin/locate.pl
This is the object.pm file http://codepad.org/O196ykIq
I am getting this error while running Specint2006 suite, but this error is not related to the suite. Can anyone tell me what does !$class->can('new') do and why is it returning true here?
Thanks.
Can checks if the Class has the method. The return value is always the coderef. If the class dont know the method, the return value is undef.
The Class dont know the new method, so its false. But you call it with not
!$class->can('new')
Quote from HERE
Again, the same rule about having a valid invocand applies -- use an eval block or blessed if you need to be extra paranoid.

Print debug messages to console from a PowerShell function that returns

Is there a way to print debug messages to the console from a PowerShell function that returns a value?
Example:
function A
{
$output = 0
# Start of awesome algorithm
WriteDebug # Magic function that prints debug messages to the console
#...
# End of awesome algorithm
return $output
}
# Script body
$result = A
Write-Output "Result=" $result
Is there a PowerShell function that fits this description?
I'm aware of Write-Output and Write-*, but in all my tests using any of those functions inside a function like the one above will not write any debug messages. I'm also aware that just calling the function without using the returned value will indeed cause the function to write debug messages.
Sure, use the Write-Debug cmdlet to do so. Note that by default you will not see debug output. In order to see the debug output, set $DebugPreference to Continue (instead of SilentlyContinue). For simple functions I will usually do something like this:
function A ([switch]$Debug) {
if ($Debug) { $DebugPreference = 'Continue' }
Write-Debug "Debug message about something"
# Generate output
"Output something from function"
}
Note that I would not recommend using the form return $output. Functions output anything that isn't captured by a variable, redirected to a file (or Out-Null) or cast to [void]. If you need to return early from a function then by all means use return.
For advanced functions you can get debug functionality a bit more easily because PowerShell provides the ubiquitous parameters for you, including -Debug:
function A {
[CmdletBinding()]
param()
End {
$pscmdlet.WriteDebug("Debug message")
"Output something from cmdlet"
}
}
FYI, it's the [CmdletBinding()] attribute on the param() statement is what makes this an advanced function.
Also don't forget about Write-Verbose and $pscmdlet.WriteVerbose() if you just want a way to output additional information that isn't debug related.

Resources