How to use expectOutputString PHPunits? - phpunit

this my first question.
I install composer (1.10.5), fatfree-core(3.7) and phpunit (9.1.3) and go to TDD.
All working, but if i use $this->expectOutputString();
I've Assertions: 0 - not working.
I found it's:
> $f3 = Base::instance();
>
> $f3 -> mock ('GET /'); // <= it is problem
<?php
[...]
protected function setUp (): void
{
$this->f3 = Base::instance ();
$this->f3 -> set ('QUIET',TRUE);
$this->f3 -> config ('config.ini');
$this->f3 -> mock ('GET /ftp');
$this -> MainController = new MainController ($this->f3);
}
public function testExpectFooActualFoo ()
{
$this->expectOutputString ('foo');
print'foo';
}
[...]
CMD:
#php ./vendor/phpunit/phpunit/phpunit tests/MainControllerNoStaticTest.php
PHPUnit 9.1.3 by Sebastian Bergmann and contributors.
fooR
1 / 1 (100%)
Time: 00:00.052, Memory: 4.00 MB
There was 1 risky test:
1) MainControllerNoStaticTest::testExpectFooActualFoo
Test code or tested code did not (only) close its own output buffers
OK, but incomplete, skipped, or risky tests!
Tests: 1, Assertions: 0, Risky: 1.
Base heve finall class, before I mocked myself i edit base core and delete finall, but now this not good idea. Base (fat-free) have mock option.
Do you have an idea how to get it to be good?
- without modifying fat-free and phpunit files?
I want to use phpunit for testing, and I put the programming environment on fat-free.

Use getActualOutputForAssertion() to get the output and then use regular assertions on its return value. This will not help you, though, with misbehaving code under test that does not (only) close its own output buffers.

Related

Getting the build type/variant inside a bjam Jamfile / echo a feature?

So, let's say, I call bjam debug, or bjam release, or bjam clean, possibly with other target names, and I'd like to have the build action or type (debug, release, clean) available in a script.
Here https://android.googlesource.com/platform/external/boost/+/ac861f8c0f33538060790a8e50701464ca9982d3/Jamroot I found an example, that I modified like this:
import modules ;
tbuildcmd = "" ;
if clean in [ modules.peek : ARGV ]
{
tbuildcmd = clean ;
}
else if release in [ modules.peek : ARGV ]
{
tbuildcmd = release ;
}
else if debug in [ modules.peek : ARGV ]
{
tbuildcmd = debug ;
}
echo "tbuildcmd $(tbuildcmd)" ;
And this works fine, it seems - but I was wondering, is there a better method to get the build command/type as a variable? For instance, they say in https://www.boost.org/doc/libs/1_35_0/doc/html/bbv2/tutorial.html :
The release and debug that we've seen in bjam invocations are just a shorthand way to specify values of the variant feature. For example, the command above could also have been written this way:
bjam variant=release inlining=off debug-symbols=on
So, there is apparently a "variant" "feature" - but how can I use / echo it? I tried echo $(<variant>) and that failed.

PhpStorm with PHPUnit 8.4 gives exception Uncaught PHPUnit\Runner\Exception class ... could not be found

I tried to use PHPUnit v8. However I was not succeeded with PhpStorm. When I run simple test (class method) in PhpStorm I got the following message:
PHP Fatal error: Uncaught PHPUnit\Runner\Exception: Class 'Mrself\\TreeType\\Tests\\Functional\\BuildingTest' could not be found in '/vagrant/symfony-tree-type/tests/Functional/BuildingTest.php'. in /vagrant/symfony-tree-type/vendor/phpunit/phpunit/src/Runner/StandardTestSuiteLoader.php:65
Yes, I have that class and yes I have psr configured properly:
"autoload": {
"psr-4": {
"Mrself\\TreeType\\": "./src/"
}
},
"autoload-dev": {
"psr-4": {
"Mrself\\TreeType\\Tests\\": "./tests/"
}
}
The proof the I have everything correctly setup is that when I run vendor/bin/phpunit it gives me correct result.
When I run method in PhpStorm I got the following call:
/usr/bin/php /vagrant/symfony-tree-type/vendor/phpunit/phpunit/phpunit --configuration /vagrant/symfony-tree-type/phpunit.xml --filter "/(::testFormCanBeBuild)( .*)?$/" Mrself\\TreeType\\Tests\\Functional\\BuildingTest /vagrant/symfony-tree-type/tests/Functional/BuildingTest.php --teamcity
However if I prepend class namespace with \\ everything works correctly as well. I can not get a clue what's going on. PHPUnit version 7 works as well.
Same thing happened to me. All of the sudden I started getting the following error:
PHP Fatal error: Uncaught PHPUnit\Runner\Exception: Class 'Tests\\Feature\\ExampleTest' could not be found
And after I have read #frank-vue's comment I noticed the same thing and he did: If I run tests on the entire folder it runs normally, but if I run test on a specific class/method I get that error.
I tried earlier version of PHPStorm, downgraded PHP plugin etc... and nothing worked.
In my case, when I checked the stacktrace looks like:
#0 /var/www/vendor/phpunit/phpunit/src/Runner/BaseTestRunner.php(145): PHPUnit\Runner\StandardTestSuiteLoader->load('Tests\\\\Unit\\\\Ex...', '/var/www/tests/...')
#1 /var/www/vendor/phpunit/phpunit/src/Runner/BaseTestRunner.php(105): PHPUnit\Runner\BaseTestRunner->loadSuiteClass('Tests\\\\Unit\\\\Ex...', '/var/www/tests/...')
#2 /var/www/vendor/phpunit/phpunit/src/TextUI/Command.php(177): PHPUnit\Runner\BaseTestRunner->getTest('Tests\\\\Unit\\\\Ex...', '/var/www/tests/...', Array)
#3 /var/www/vendor/phpunit/phpunit/src/TextUI/Command.php(159): PHPUnit\TextUI\Command->run(Array, true)
#4 /var/www/vendor/phpunit/phpunit/phpunit(61): PHPUnit\TextUI\Command::main()
#5 {main}
thrown in /var/www/vendor/phpunit/phpunit/src/Runner/StandardTestSuiteLoader.php on line 69
Notice Tests\\\\Unit\\\\Ex... instead of Tests\\Unit\\Ex....
So in the end I broke the rule and I've modified vendor file, which should be avoided at any cost, but as a temporary solution it solves my problem.
So I added 1 line to the vendor/phpunit/phpunit/src/Runner/BaseTestRunner.php on line 98 (PHPUnit version 8.4.1), which replaces unnecessary '\'s.
if (empty($suiteClassFile) && \is_dir($suiteClassName) && !\is_file($suiteClassName . '.php')) {
/** #var string[] $files */
$files = (new FileIteratorFacade)->getFilesAsArray(
$suiteClassName,
$suffixes
);
$suite = new TestSuite($suiteClassName);
$suite->addTestFiles($files);
return $suite;
}
$suiteClassName = str_replace('\\\\', '\\', $suiteClassName); // THIS IS THE LINE I ADDED
try {
$testClass = $this->loadSuiteClass(
$suiteClassName,
$suiteClassFile
);
} catch (Exception $e) {
$this->runFailed($e->getMessage());
return null;
}

SBT terminates silently when Git repository for build plugin can't be downloaded

SBT is silently failing when it can't download a plugin via SSH from a Git repository.
This is the output of SBT when it's trying to download the repository:
[info] Updating ProjectRef(uri("ssh://git#repository.com/plugin.git"), "plugin")...
# (nothing after that line)
And it just terminates after that with no explanation. This is very likely a bug with SBT's downloading of plugins via SSH from a Git repository.
When downloading the plugin succeeds, this line is printed:
[info] Done updating.
So for some reason, SBT isn't stating what's wrong, even when executed like this:
sbt -Xdebug test
Here are the relevant configuration files:
# project/build-properties
sbt.version=1.1.5
# project/plugins.sbt
lazy val buildPlugin = RootProject(uri("ssh://git#repository.com/plugin.git"))
lazy val root = (project in file(".")).dependsOn(buildPlugin)
Questions:
1. How can I get SBT to print more debugging information?
2. Where in the SBT code could I fix this bug?
3. How can I build and use my own version of SBT?
How can I get SBT to print more debugging information?
Using the latest launching script available from https://www.scala-sbt.org/download.html (1.2.1 as of August, 2018), you can run:
$ sbt -debug
Where in the SBT code could I fix this bug?
See my answer here https://github.com/sbt/sbt/issues/1120#issuecomment-415553592:
Here are some of the relevant code:
Load.builtinLoader - https://github.com/sbt/sbt/blob/v1.2.1/main/src/main/scala/sbt/internal/Load.scala#L480-L488
RetrieveUnit - https://github.com/sbt/sbt/blob/v1.2.1/main/src/main/scala/sbt/internal/RetrieveUnit.scala
Resolvers.git - https://github.com/sbt/sbt/blob/v1.2.1/main/src/main/scala/sbt/Resolvers.scala#L82-L101
Resolvers.creates - https://github.com/sbt/sbt/blob/v1.2.1/main/src/main/scala/sbt/Resolvers.scala#L145-L155
val git: Resolver = (info: ResolveInfo) => {
val uri = info.uri.withoutMarkerScheme
val localCopy = uniqueSubdirectoryFor(uri.copy(scheme = "git"), in = info.staging)
val from = uri.withoutFragment.toASCIIString
if (uri.hasFragment) {
val branch = uri.getFragment
Some { () =>
creates(localCopy) {
run("git", "clone", from, localCopy.getAbsolutePath)
run(Some(localCopy), "git", "checkout", "-q", branch)
}
}
} else
Some { () =>
creates(localCopy) {
run("git", "clone", "--depth", "1", from, localCopy.getAbsolutePath)
}
}
}
....
def creates(file: File)(f: => Unit) = {
if (!file.exists)
try {
f
} catch {
case NonFatal(e) =>
IO.delete(file)
throw e
}
file
}
How can I build and use my own version of SBT?
https://github.com/sbt/sbt/blob/1.x/CONTRIBUTING.md#build-from-source
For this, you just need sbt/sbt, and publishLocal.

SBT Subprojects do not recognize plugin commands

I'm having an issue with getting SBT Subprojects to recognize commands provided by plugins. I have the following plugin source:
object DemoPlugin extends AutoPlugin {
override lazy val projectSettings = Seq(commands += demoCommand)
lazy val demoCommand =
Command.command("demo") { (state: State) =>
println("Demo Plugin!")
state
}
}
Which is used by a project configured as follows:
lazy val root = project in file(".")
lazy val sub = (project in file("sub")).
enablePlugins(DemoPlugin).
settings(
//...
)
The plugin is, of course, listed in project/plugins.sbt. However, when I open up sbt in the project, I see the following:
> sub/commands
[info] List(sbt.SimpleCommand#413d2cd1)
> sub/demo
[error] Expected ':' (if selecting a configuration)
[error] Not a valid key: demo (similar: doc)
[error] sub/demo
Even stranger, using consoleProject, I can see that the command in the project is the one defined by DemoPlugin!
scala> (commands in sub).eval.map { c => c.getClass.getMethod("name").invoke(c) }
res0: Seq[Object] = List(demo)
I'm looking to be able to type sub/demo, and have it perform the demo command. Any help would be much appreciated!
Commands aren't per-project. They only work for the top-level project.
It's also recommended to try and use tasks, or if needed input tasks where you might want to use a command.
If you really need a command, there's a way to have a sort of "holder" task, see the answer to Can you access a SBT SettingKey inside a Command?

ZendFramework 2 - PHPUnit - command line works, NetBeans states "No tests executed"

I seem to have a slight problem with executing PHPUnit tests for own modules in the Zend Framework 2.
OS: Mac OS 10.8.3
Zend Framework 2.1.4
PHPUnit Version 3.7.19 (installed via pear)
PHP Version 5.3.15 (xdebug enabled, version 2.1.3)
I followed the instructions of the Zend guideline, to create the module "Album" (http://framework.zend.com/manual/2.1/en/user-guide/modules.html)
Instead of putting the unit tests into the module folders, I want to have them all in one centralized folder. This is the base structure of my application:
-config
-data
-module
-public
-tests
--Modules
---Album
----AlbumTest.php
--Bootstrap.php
--phpunit.xml
-vendor
...(license, readme, composers and init_autoloader.php)
-> The test for the Module Album resides in a folder "Modules/Album" in "tests". The folder "tests" contains also the Bootstrap.php and phpunit.xml.
Here is the content of the files:
Bootstrap.php
<?php
/*
* Set error reporting to the level to which Zend Framework code must comply.
*/
error_reporting( E_ALL | E_STRICT );
/*
* The first run required me to fix some constants
*/
defined('TESTS_ZEND_FORM_RECAPTCHA_PUBLIC_KEY') || define('TESTS_ZEND_FORM_RECAPTCHA_PUBLIC_KEY', 'public key');
defined('TESTS_ZEND_FORM_RECAPTCHA_PRIVATE_KEY') || define('TESTS_ZEND_FORM_RECAPTCHA_PRIVATE_KEY', 'private key');
defined('TESTS_ZEND_LDAP_PRINCIPAL_NAME') || define('TESTS_ZEND_LDAP_PRINCIPAL_NAME', 'someUser#example.com');
defined('TESTS_ZEND_LDAP_ALT_USERNAME') || define('TESTS_ZEND_LDAP_ALT_USERNAME', 'anotherUser');
chdir(dirname(__DIR__));
/*
* autoload the application
*/
include __DIR__ . '/../init_autoloader.php';
Zend\Mvc\Application::init(include 'config/test.config.php');
phpunit.xml
<phpunit bootstrap="./Bootstrap.php" colors="true">
<testsuites>
<testsuite name="Zend Module Tests">
<directory>./Modules</directory>
</testsuite>
</testsuites>
</phpunit>
AlbumTest.php
<?php
namespace AlbumTest\Model;
use Album\Model\Album;
use PHPUnit_Framework_TestCase;
/**
* #category Module
* #package Album
* #subpackage UnitTests
* #group Module_Album
*/
class AlbumTest extends PHPUnit_Framework_TestCase {
public function testAlbumInitialState() {
$album = new Album();
$this->assertNull($album->artist, '"artist" should initially be null');
$this->assertNull($album->id, '"id" should initially be null');
$this->assertNull($album->title, '"title" should initially be null');
}
public function testExchangeArraySetsPropertiesCorrectly() {
$album = new Album();
$data = array('artist' => 'some artist',
'id' => 123,
'title' => 'some title');
$album->exchangeArray($data);
$this->assertSame($data['artist'], $album->artist, '"artist" was not set correctly');
$this->assertSame($data['id'], $album->id, '"id" was not set correctly');
$this->assertSame($data['title'], $album->title, '"title" was not set correctly');
}
public function testExchangeArraySetsPropertiesToNullIfKeysAreNotPresent() {
$album = new Album();
$album->exchangeArray(array('artist' => 'some artist',
'id' => 123,
'title' => 'some title'));
$album->exchangeArray(array());
$this->assertNull($album->artist, '"artist" should have defaulted to null');
$this->assertNull($album->id, '"id" should have defaulted to null');
$this->assertNull($album->title, '"title" should have defaulted to null');
}
public function testGetArrayCopyReturnsAnArrayWithPropertyValues() {
$album = new Album();
$data = array('artist' => 'some artist',
'id' => 123,
'title' => 'some title');
$album->exchangeArray($data);
$copyArray = $album->getArrayCopy();
$this->assertSame($data['artist'], $copyArray['artist'], '"artist" was not set correctly');
$this->assertSame($data['id'], $copyArray['id'], '"id" was not set correctly');
$this->assertSame($data['title'], $copyArray['title'], '"title" was not set correctly');
}
public function testInputFiltersAreSetCorrectly() {
$album = new Album();
$inputFilter = $album->getInputFilter();
$this->assertSame(3, $inputFilter->count());
$this->assertTrue($inputFilter->has('artist'));
$this->assertTrue($inputFilter->has('id'));
$this->assertTrue($inputFilter->has('title'));
}
}
NetBeans knows, where to find the phpunit binaries:
(I wanted to post images here, don't have the reputation though :), I will try to explain it)
The paths to are configured in the options - php - unit testing
/usr/local/pear/bin/phpunit and
/usr/local/pear/bin/phpunit-skelgen
In the properties of the project I set the "Use XML Configuration" and pasted the path to the phpunit.xml. I also checked "Ask for Test Groups Before Running Tests" - I gave the test above the group "Module_Album" - like this I make sure, that PHPUnit finds the right test.
I right click on Project and choose "Test", it shows me the group "Module_Album", I check it and click "Ok". It runs something, tells me it located the right phpunit.xml ("Configuration read from FULL_PATH/tests/phpunit.xml"). After running, it tells me, that it didn't execute any tests.
This is the full output in NetBeans:
PHPUnit 3.7.19 by Sebastian Bergmann.
Configuration read from FULL_PATH/tests/phpunit.xml
Time: 9 seconds, Memory: 348.25Mb
[2KNo tests executed!
[2K
Generating code coverage report in Clover XML format ... done
Anyway, I can do the same successfully via shell (terminal). It doesn't matter, if I directly mount the tests directory and run phpunit, use the full path to the phpunit binary (to make sure, that I don't use different version), specifying the full path of the phpunit.xml, and so on. Here are some samples:
phpunit
phpunit -c FULL_PATH/tests/phpunit.xml
/usr/local/pear/bin/phpunit -c FULL_PATH/tests/phpunit.xml
All of these commands give me, what I expect:
PHPUnit 3.7.19 by Sebastian Bergmann.
Configuration read from FULL_PATH/tests/phpunit.xml
.....
Time: 0 seconds, Memory: 12.75Mb
OK (5 tests, 16 assertions)
I don't get, why this works in shell but not via NetBeans
NetBeans uses 350MB, while in shell it uses only 12.75MB
In case I remove the option "Ask for Test Groups Before Running Tests", it seems to try running all ZendTests. Don't know how this is possible, from the phpunit.xml it should not find them.
Any help is appreciated, thanks!
I finally figured out, what is going on. I ran previously the ZendTests with the phpunit.xml, which is inside vendor/zendframework/zendframework/tests
For some reason NetBeans saves the testfile-directory, which it finds in the first test run and doesn't release them, if the a different phpunit.xml is chosen. I had to change the path of my "new" tests directory via "Right click on project" - "Properties" - "Sources" - "Test Folder".
Now NetBeans runs the test and gives exactly the same output like CLI.

Resources