I have what I think is an uncommon issue but I'll try to explain as clear as I can. I have created a simple artisan command that does this
/**
* Execute the console command.
*/
public function handle()
{
$this->info("==> Cleaning up reports and docs...");
$command = new Process("rm -f tests/docs/* && rm -rf test/reports/*");
$command->run();
$this->warn("==> Reports and docs are clean");
$this->info("==> Executing Tests Suite...");
$command = new Process("vendor/bin/phpunit --coverage-html tests/reports --testdox-html tests/docs/reports.html -v --debug");
$command->run();
$this->info($command->getIncrementalOutput());
$this->warn("==> report generated >> test/reports. Documentation generated >> test/docs/reports.html");
}
This could seems kinda odd but it is actually pretty useful, it launch the PHPUnit with the coverage support and other stuff. The problem is that if I run this command like php artisan ludo237:full-test it will completely ignore the phpunit.xml in fact it will display and error saying that the MySQL database does not exists, even though I've set the sqlite connection inside my phpunit.xml speaking of which you can clearly see that is correct:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="bootstrap/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Application Test Suite">
<directory suffix="Test.php">./tests</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./app</directory>
</whitelist>
</filter>
<php>
<env name="APP_ENV" value="testing"/>
<env name="APP_DEBUG" value="true"/>
<env name="APP_URL" value="http://localhost:8000"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:" />
<env name="CACHE_DRIVER" value="array"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
<env name="MAIL_DRIVER" value="log"/>
<env name="MAIL_PRETEND" value="true"/>
</php>
</phpunit>
I know that I can simply create a bash alias for that command line, in fact this is my current hot fix, but at this point I'm just curious to understand why when I launch the phpunit command from the artisan command it ignores the XML file.
Does anyone have a clue about this? Thank you!
It took me really a lot to debug this, but in the end I found why it is not working.
First of all, let me clarify that is nothing wrong with your code, even there is nothing wrong with the Process class, you will get the same behavior even by using native exec function.
Second, the phpunit.xml file is totally being read, no issues at all.
Said that, the real issue resides, on PHPUnit that doesn't allow you to re-define ( or override ) any env variable, because there is a check that prevents that.
This is because Laravel is not parsing the phpunit.xml file itself, and in the moment you're calling it, it's already too late and the environment variables are defined, either via putenv, $_SERVER and/or $_ENV.
Because of this, I created an Issue on PHPUnit, which even in latest versions ( as of today ), this issue persist, even if this was already asked in the past.
Unfortunately I have no solution yet for you, but let's cross our fingers and let's wait for PHPUnit to add the proposed force attribute :)
Best regards,
Julian
Related
I have an API method that is called by clicking a buttom in a form and inside that API method there is a request to another API of another project using guzzle. That works fine.
My problem is I'm doing behat tests and I want to test my API method, but I need to mock the request to the external API (because I don't need to test it). Is there any way Laravel detects if I am in a test environment and mock the request and if I'm in a normal environment leave it without mock?
There should be a file in your project called phpunit.xml and you can set the APP_ENV there.
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
...
processIsolation="false"
stopOnFailure="false">
<testsuites>
...
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./app</directory>
</whitelist>
</filter>
<php>
<!-- HERE -->
<env name="APP_ENV" value="testing"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
</php>
Then you can use whatever logic you like with if(env('APP_ENV') == 'testing')
I have a pretty big Laravel 5.6 application I'm currently developing. By default, Larvel comes with a tests directory along with a tests/Unit and tests/Feature sub directories.
When I first started developing my app, any test I wrote that didn't require a full HTTP life cycle to take place, I would put in the tests/Unit directory.
Example: Testing a custom local query scope on a model.
Similarly, any test that did require a full HTTP life cycle I would put in the tests/Feature directory.
Example: Testing controllers using a GET, POST, etc request and making sure I got back a 200 response or equivalent.
Now that my application has grown to be quite massive, I'm starting to think that there should be a better way to organize my tests directory. I'm also noticing that parts of my code base do not have test coverage based on reports from codecov.io.
In my mind, it would make sense to create a tests/App directory and have that mirror all my files and classes in the app directory of the project root. Each class and/or file would have a corresponding test. This way, I'll have a better idea of which parts of my app have test coverage and which ones do not. I haven't seen any other projects that do this so I'm hesitant to apply this approach.
So, to summarize my question:
Are there any pitfalls with structuring the tests directory exactly like the app directory?
Is there an alternative way to structure your test directory so that you can tell with ease which classes/files have corresponding tests?
Side Note: I'm well aware that my unit tests don't adhere to the "normal" convention of mocking out your dependencies and testing in isolation. This is a separate issue but in short I feel that mocking doesn't allow you to refactor you code with ease. More info on what I'm talking about in my defense: https://www.youtube.com/watch?v=LdUKfbG713M
I'm also using the structure that Laravel provided. but I have made little changes. for example for functional testing, I have added an admin folder so I can write tests for admin APIs or for unit testing I have added (unit/cron, unit/middleware, unit/jobs, ...) this way I can control the directories.
tests/functional/admin
tests/unit/cron
tests/unit/middleware
tests/unit/jobs
tests/unit/policy
tests/unit/models
...
And also to see which API or function has a test or not it's a little hard to have it. If you are following the TDD principle then no need to worry about this part because you know that everyone who writes a piece of code he/she will write the test for it. but if you are not following the TDD and you have just started with writing tests for your project then you need to run PHPUnit coverage with --HTML tag and it'll return for you the HTML graph which can tell you how much code coverage your project has.
All Laravel projects start from an initial template,
if you check the phpunit.xml which the template normally includes, you should find:
...
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
</testsuites>
All this does is tell PHPUnit to execute/run Unit folder's tests before Feature folder's tests.
The reason for that being;
If a normally small Unit is failing any test,
Then it makes no sense to search for the bug in normally large Feature(s),
And PHPUnit's report shows Unit folder's test-results at top,
which suggests that those should be fixed first, because debugging an entire Feature is normally harder than debugging a small Unit.
Example
Knowing above should help you decide for yourself;
But if you ask me, I would simply create an App folder in Unit folder, or add an additional testsuite to phpunit.xml file, right after Unit entry, like:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="./vendor/phpunit/phpunit/phpunit.xsd"
backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
>
<testsuites>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
<testsuite name="App">
<directory suffix="Test.php">./tests/App</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./app</directory>
</whitelist>
</filter>
<php>
<server name="APP_ENV" value="testing"/>
<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_DRIVER" value="array"/>
<!-- <server name="DB_CONNECTION" value="sqlite"/> -->
<!-- <server name="DB_DATABASE" value=":memory:"/> -->
<server name="MAIL_MAILER" value="array"/>
<server name="QUEUE_CONNECTION" value="sync"/>
<server name="SESSION_DRIVER" value="array"/>
<server name="TELESCOPE_ENABLED" value="false"/>
</php>
</phpunit>
Because having one test-file beside each php-file is a Unit-testing style, not Feature-testing, even if the test requires "full HTTP life cycle".
I am using Laravel 5.5, phpunit 6.5.5 on Homestead-7 (I think).
I am trying this tutorial: https://laravel-news.com/your-first-laravel-application (And this should tell you a lot about my experience with the framework)
Testing fails (due to TokenMismatchException) and I have managed to track down the root cause to the APP_ENV variable being set to local, although I've tried many ways of setting it to testing.
At the end, what allowed me to overcome the problem was to set the variable like this:
APP_ENV=testing vendor/bin/phpunit
Then, the tests completed successfully.
My question is, what am I doing wrong? The above hack is obviously not the best way to do it. There must be a way to properly do this.
Update
Contents of phpunit.xml:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="vendor/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="false"
stopOnFailure="false">
<testsuites>
<testsuite name="Feature">
<directory suffix="Test.php">./tests/Feature</directory>
</testsuite>
<testsuite name="Unit">
<directory suffix="Test.php">./tests/Unit</directory>
</testsuite>
</testsuites>
<filter>
<whitelist processUncoveredFilesFromWhitelist="true">
<directory suffix=".php">./app</directory>
</whitelist>
</filter>
<php>
<env name="APP_ENV" value="testing"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
</php>
</phpunit>
Thank you in advance for your time.
From the Laravel docs:
When running tests via phpunit, Laravel will automatically set the configuration environment to testing because of the environment variables defined in the phpunit.xml file.
...so I would bet that your phpunit.xml file is missing or misconfigured. It should be in your project's root directory and should contain the following:
<php>
<env name="APP_ENV" value="testing"/>
...
</php>
If you do have a phpunit.xml file in the right place and it does contain the part above, and it's still not working, then try clearing your config cache:
php artisan config:clear
If that still doesn't fix it, then I'd check for something odd with the phpunit.xml file, such as being misnamed or containing a syntax error.
And here's a link to the original phpunit.xml file, to help you restore it if needed.
I managed to find the problem with my system. In my homestead box, I had included in Homestead.yaml setting of global environment variable APP_ENV:
variables:
- key: APP_ENV
- value: local
This was provided as an example in the instructions for Homestead set up. I followed that without realising what I was doing.
Setting again the variable through .env or phpunit.xml just did not work. I removed the definition from Homestead.yaml and it works as I would have expected.
i am new in Laravel. Using local development environment with Homestead
Try to run simple test
namespace Tests\Feature;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
class UserTest extends TestCase
{
/**
* A basic test example.
*
* #return void
*/
public function testBasicTest()
{
$response = $this->get('/');
$response->assertStatus(200);
}
}
routes/web.php :
Route::get('/', function () {
return view('main');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
running phpunit returns 404 error
vagrant#homestead:~/code/laravel$ phpunit PHPUnit 6.4.3 by Sebastian
Bergmann and contributors.
.F. 3
/ 3 (100%)
Time: 1.07 seconds, Memory: 10.00MB
There was 1 failure:
1) Tests\Feature\UserTest::testBasicTest Expected status code 200 but
received 404. Failed asserting that false is true.
/home/vagrant/code/laravel/vendor/laravel/framework/src/Illuminate/Foundation/Testing/TestResponse.php:78
/home/vagrant/code/laravel/tests/Feature/UserTest.php:25
I have tried to fix it with these ways
1.
Laravel phpunit always 404
updateTestCase.php
protected $baseUrl = 'http://localhost'
change with
protected $baseUrl = 'http://laravel.local'
2.
https://github.com/dingo/api/issues/540 and next to it
https://github.com/dingo/api/issues/571
use Illuminate\Foundation\Testing\WithoutMiddleware;
class BankTest extends TestCase {
use WithoutMiddleware;
Changing APP_URL in .env to
APP_URL=laravel.local
none of this helped
'laravel.local' works fine in browser
Please, help me fix it
I was running my application with following URL in browser.
http://localhost/app/public/
The default unit test having below line was failing. It was getting 404 response instead of 200.
$response = $this->get('/');
$response->assertStatus(200);
I changed APP_URL in .env file as below after reading above comments.
APP_URL=http://localhost
But I was still getting 404 error. After some trial and errors, I found that I needed to clear config cache.
php artisan config:cache
This did the trick and my test started working!!
I had the same problem, and if I run laravel with php artisan serve, it has to be:
APP_URL=http://127.0.0.1:8000/
The APP_URL, has to be exactly the URL of the website.
The website was working, but I didn't have that constant correctly, and PHPUnit was saying all time 404.
Don't forget to clear the cache, after change the config
php artisan config:cache
Have you tried with process isolation set to true in your phpunit.xml file? Our functional tests fail with 404 errors all over the place if we do not have process isolation:
<phpunit backupGlobals="false"
backupStaticAttributes="false"
bootstrap="bootstrap/autoload.php"
colors="true"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
processIsolation="true"
stopOnFailure="false">
For anyone having this problem, use APP_URL=http://localhost, this happens if you use vagrant I am not sure for other envs, still investigating.
Laravel tests run and expect environment variables. They expect variables like ENV_URL, ENV_KEY,... depending on your test case.
It is important that the ENV_URL variable is set to http://localhost disregarding your laravel/server setup. Tests work differently here.
Inside phpunit.xml, the line <server name="APP_ENV" value="testing"/> specifies which testing file to use. value="testing" expects a to use the .env.testing file, if it exists and fallbacks to .env.
There are two approaches that you can do from here on:
Approach A - Using .env.testing:
Create a copy of .env and name it .env.testing.
Verfiy that phpunit.xml includes the .env.testing file, like following <server name="APP_ENV" value="testing"/>
IMPORTANT Edit the .env.testing to use APP_URL=http://localhost as its URL. It doesn't matter under which URL you usually serve your application.
Edit other values to reflect your testing environment
Delete cache using php artisan cache:clear
Approach B - ENV values in phpunit.xml:
You can harcode all ENV values inside the phpunit.xml, like below
...
<php>
<server name="APP_URL" value="http://localhost"/>
<server name="APP_KEY" value="base64:e8+BZAzKrSR/LprdHQ2TfMaw+DOTWYmgpkFkEJHV+zw="/>
<server name="DB_CONNECTION" value="mysql"/>
<server name="DB_HOST" value="127.0.0.1"/>
<!-- More ENV values -->
...
<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_DRIVER" value="array"/>
<!-- <server name="DB_CONNECTION" value="sqlite"/> -->
<!-- <server name="DB_DATABASE" value=":memory:"/> -->
<server name="MAIL_MAILER" value="array"/>
<server name="QUEUE_CONNECTION" value="sync"/>
<server name="SESSION_DRIVER" value="array"/>
<server name="TELESCOPE_ENABLED" value="false"/>
</php>
</phpunit>
Bonus - Hybrid Approach:
Use the main .env file and overwrite the APP_URL inside the phpunit.xml.
For this, there should not exist an .env.testing file or remove <server name="APP_ENV" value="testing"/> if it does exist.
...
<php>
<server name="APP_ENV" value="testing"/>
<!-- IMPORTANT - Overwrite the APP_URL -->
<server name="APP_URL" value="http://localhost"/>
<server name="BCRYPT_ROUNDS" value="4"/>
<server name="CACHE_DRIVER" value="array"/>
<!-- <server name="DB_CONNECTION" value="sqlite"/> -->
<!-- <server name="DB_DATABASE" value=":memory:"/> -->
<server name="MAIL_MAILER" value="array"/>
<server name="QUEUE_CONNECTION" value="sync"/>
<server name="SESSION_DRIVER" value="array"/>
<server name="TELESCOPE_ENABLED" value="false"/>
</php>
</phpunit>
The solution is to simply test using the url returned by
php artisan serve
as base url then run the tests
For example:
$response = $this->post('http://127.0.0.1:8001/api/register', [
'email' => '',
'phone' => '',
'password' => '',
'c_password' => '',
'role_id' => '',
]);
$response->assertStatus(401);
As #TooCooL mentioned, one could set APP_URL=http://localhost even if your project might be something as APP_URL=http://localhost/myproject.
Even better is to create another .env, it shall be called env.testing and there one can change APP_URL or even another database for testing purposes only and so on.
Phpunit will look for configuration at that file .env.testing
Although phpunit works fine even when APP_URL is set on my vhost name on my lamp stack.
Check out your /etc/hosts file as well.
Just for Laravel 8 devs.
Use full url inside get method
$response = $this->get('http://127.0.0.1:8000');
Leave APP_URL blank in .env file ie
APP_URL=
I want to seperate my tests from the actual database. I configuted it following a tutorial from laracasts but it does not seem to actually use the configured stuff. This is my phpunit.xml (relevant part)
<php>
<env name="APP_ENV" value="testing"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<env name="CACHE_DRIVER" value="array"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="QUEUE_DRIVER" value="sync"/>
</php>
I noticed it will always use my actual database instead of this configured one.
I run tests by going into vendor/bin and executing phpunit ../../tests for some reason I can not figure out it won't run out of my root directory even though i ve installed phpunit globally
I've found it myself. The problem is that I', starting from vendor/bin folder. My starting point must be the root. So I now use
call vendor/bin/phpunit
From my root directory