phpunit testable livewire fails with Undefined array key "fingerprint" - phpunit

When trying a test that came with Laravel and Jetstream/Livewire libraries, I get an undefined array key "fingerprint" error message
Undefined array key "fingerprint"
at vendor/livewire/livewire/src/Testing/TestableLivewire.php:181
public function pretendWereSendingAComponentUpdateRequest($message, $payload)
{
$result = $this->callEndpoint('POST', '/livewire/message/'.$this->componentName, [
'fingerprint' => $this->payload['fingerprint'],
'serverMemo' => $this->payload['serverMemo'],
'updates' => [['type' => $message, 'payload' => $payload]],
]);
This happens for any out of the box feature tests that ship with Laravel9 with Jetstream when used against my project.
Here is one example that fails at the Livewire::test.... line.
The user is created and authenticating without issue and confirmed in other phpunit tests.
class BrowserSessionsTest extends TestCase
{
use RefreshDatabase;
public function test_other_browser_sessions_can_be_logged_out(): void
{
$this->actingAs($user = User::factory()->create());
Livewire::test(LogoutOtherBrowserSessionsForm::class)
->set('password', $user->password)
->call('logoutOtherBrowserSessions')
->assertSuccessful();
}
}
I stood up a fresh Laravel 9 project which works and began inserting various areas from my project into the fresh project as a way of hopefully identifying the issue. Session parameters, events, migrations, factories, models, were not the issue as it continued to work in the fresh project.
One thing I noticed is that the generic routes are not accepted in my project within he test cases. I have to insert 'https://realtor.host' in front of every test route (e.g. $response = $this->get('https://realtor.host/register');
I was curious if it was not evaluating the livewire route and I tried to add my domain into the vendor's livewire component in which the test still failed and that did not cause it to work.
Any ideas on where else I can look?

Related

Lighthouse auto model detection doesn't work with unit tests

I seem to be facing the general problem that directive driven mutations won't properly work when unit testing them. Using GraphQL Playground everything works as expected and the User model is auto detected. But if unit testing the same functionality it fails.
All config values are properly set (as I can see from regular requests not failing):
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => ClientName\PackageName\Models\User::class,
],
...
]
And lighthouse config values also set to the namespace above!
So for example this mutation would trigger the UserPolicy class and after that automatically call the create method of the User class:
type Mutation #protect(guards: ["api"]) {
"Create user"
createUser(data: NewUserInput! #spread): User
#can(ability: "create")
#create
}
But calling the same request via phpunit would result in errors:
for #can it returns a not authorized error and if I remove #can it only updates the email field of the user model as if mass assignment is not properly set.
When I now change the above schema definition to:
type Mutation #protect(guards: ["api"]) {
"Create user"
createUser(data: NewUserInput! #spread): User
#can(ability: "create" model: "ClientName\\PackageName\\Models\\User")
#create(model: "ClientName\\PackageName\\Models\\User")
}
And it works as expected within phpunit tests!
Now I suspect that within tests there is not User model found or not the appropriate but I cannot understand why this is.
Does anyone have any idea?

Laravel Dusk testing with sqlite drops file busy exception

T try to write a laravel dusk login (with sqlite) test but I still kepp getting
Tests\Browser\LoginTest::employee_can_login
ErrorException: unlink(/var/www/laravel/database/database.sqlite): Text file busy
my test looks like
/** #test research analyst login **/
public function employee_can_login()
{
$user = factory(User::class)->create([
'email' => 'login#gmail.com',
'password' => bcrypt('password'),
]);
$this->browse(function (Browser $browser) use ($user) {
$browser->visit(new Login())
->type('email', 'login#gmail.com')
->type('password', 'password')
->press('Login')
->assertSee('Dashboard')
->assertSee('You are logged in!')
->assertSee($user->name);
});
}
on migration the sqlite tables were created,
What does that mean how do I fix this error?
As answered in similar thread, this is common problem (at least for me) with virtual machines. You can try not to share this file (so probably better move this file to not shared directory) or to solve this temporary you need to restart your virtual machine to make it work.

Virtual Filesystem for PHPUnit tests in Laravel 5.4

i'm having a bit of a problem with my PHPUnit integration tests, i have a method which handles a form upload for a video file as well as a preview image for that video.
public function store($request)
{
/** #var Video $resource */
$resource = new $this->model;
// Create a new Content before creating the related Photo
$contentRepo = new ContentRepository();
$content = $contentRepo->store($request);
if($content->isValid()) {
$resource->content_id = $content->id;
$directory = 'frontend/videos/assets/'.date("Y").'/'.date('m').'/'.time();
\File::makeDirectory($directory, 0755, true);
$request->video->move($directory.'/', $request->video->getClientOriginalName());
$resource->video = '/'.$directory.'/'.$request->video->getClientOriginalName();
$request->preview_image->move($directory.'/', $request->preview_image->getClientOriginalName());
$resource->preview_image = '/'.$directory.'/'.$request->preview_image->getClientOriginalName();
$resource->highlighted = intval($request->input('highlighted') == 'on');
$resource->save();
return $resource;
}
else {
return $content;
}
}
The important part to keep is the $request->video->move() call which i probably need to replace in order to use Virtual Filesystem.
and then the test
public function testVideoUpload(){
File::put(__DIR__.'/frontend/videos/assets/image.mp4', 'test');
$file = new UploadedFile(__DIR__.'/frontend/videos/assets/image.mp4', 'foofile.mp4', 'video/mp4', 100023, null, $test=true);
File::put(__DIR__.'/frontend/images/assets/image.jpg', 'test');
$preview = new UploadedFile(__DIR__.'/frontend/images/assets/image.jpg', 'foofile.jpg', 'image/jpeg', 100023, null, $test=true);
$this->post('/admin/videos', [
'title' => 'My Video #12',
'description' => 'This is a description',
'actors' => [$this->actor->id, $this->actor2->id],
'scenes' => [$this->scene->id, $this->scene2->id],
'payment_methods' => [$this->paymentMethod->id],
'video' => $file,
'preview_image' => $preview
])->seeInDatabase('contents', [
'title' => 'My Video #12',
'description' => 'This is a description'
]);
}
As you can see, i need to create a dummy file in some local directory and then use that in the HTTP request to the form's endpoint, then after that, that file would be moved and i need to delete the created folder and the new moved file... it's an authentic mess.
As such i want to use Virtual Filesystem instead, but i have no idea how to set it up in this particular case, i've already downloaded a package and set it up, but the questions are, first, which package have you used/recommend and how would you tweak the class and the test to support the Virtual Filesystem? Would i need to switch over to using the Storage facade instead of the $request->video->move() call? If so how would that be done exactly?
Thank you in advance for your help
I couldn't figure out the VFS system, however i do have somewhat of an alternative that's still kinda messy but gets the job done.
Basically i set up two methods on my PHPUnit base class to setup and teardown the temp folders i need on any test that requires them, because i'm using Database Transactions the files get deleted on every test run and i need to create new dummy files every time i run the test.
So i have two methods setupTempDirectories and teardownTempDirectories which i will call at the beginning and at the end of each test that requires those temporary directories.
I put my temp files in the Storage directory because sometimes i run my tests individually through PHPStorm and the __DIR__ command gets messed up and points to different directories when i do that, i also tried __FILE__ with the same result, so i just resorted to using Laravel's storage_path instead and that works fine.
Then that leaves the problem of my concrete class which tries to move files around and create directories in the public folder for them... so in order to fix that i changed the code to use the Storage facade, then i Mock the Storage facade in my tests
So in my concrete class
$directory = 'frontend/videos/assets/'.date("Y").'/'.date('m').'/'.time();
Storage::makeDirectory($directory, 0755, true);
Storage::move($request->video, $directory . '/' . $request->video->getClientOriginalName());
$resource->video = '/'.$directory.'/'.$request->video->getClientOriginalName();
Storage::move($request->preview_image, $directory . '/' . $request->preview_image->getClientOriginalName());
$resource->preview_image = '/'.$directory.'/'.$request->preview_image->getClientOriginalName();
And then in my test i mock both the makeDirectory and the move methods like such
// Override the Storage facade with a Mock version so that we don't actually try to move files around...
Storage::shouldReceive('makeDirectory')->once()->andReturn(true);
Storage::shouldReceive('move')->twice()->andReturn(true);
That makes my tests work and does not actually leave files behind after it's done...i hope someone has a better solution but for the time being this is what i came up with.
I was actually trying to use VFS but it never worked out... i keep getting errors that the original file in the storage directory is not found even though it's right there...
I'm not even sure the Storage facade was using VFS in the background to begin with even though it should...

ZF2 unit-testing authentication

I was learning about unit testing and I attempted to resolve the following issue:
Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for zfcUserAuthentication
... using the only answer given at:
Simple ZF2 Unit Tests for a controller using ZfcUser
So my setUp function looks the same. Unfortunately, I get the error message:
Zend\Mvc\Exception\InvalidPluginException: Plugin of type Mock_ZfcUserAuthentication_868bf824 is invalid; must implement Zend\Mvc\Controller\Plugin\PluginInterface
It is caused at this part of the code (split up in my code in the same way):
$this -> controller->getPluginManager()
->setService('zfcUserAuthentication', $authMock); // Error refers to this line.
The $authMock object is apparently not implementing plugininterface, which I need to implement to pass into setService.
Is $authMock not meant to be passed there for it's use in unit testing? Should I be using a different (unit-testing oriented) setService method?
I need a way to handle logging into my application, or my unit testing is pointless.
Thanks for any advice.
=== Edit (11/02/2013) ===
I wanted to focus on this part for clarification, as I think this is the problem area:
// Getting mock of authentication object, which is used as a plugin.
$authMock = $this->getMock('ZfcUser\Controller\Plugin\ZfcUserAuthentication');
// Some expectations of the authentication service.
$authMock -> expects($this->any())
-> method('hasIdentity')
-> will($this->returnValue(true));
$authMock -> expects($this->any())
-> method('getIdentity')
-> will($this->returnValue($ZfcUserMock));
// At this point, PluginManager disallows mock being assigned as plugin because
// it will not implement plugin interface, as mentioned.
$this -> controller->getPluginManager()
->setService('zfcUserAuthentication', $authMock);
If the mock doesn't handle necessary implementations, how else am I to pretend to login?
You have a problem with name-spacing or your autoloader.
When you are creating your mock, the class definition of ZfcUser\Controller\Plugin\ZfcUserAuthentication is not being found. So PHPUnit creates a mock that only extends this class for your test. If the class was available then PHPUnit will use the actual class to extend when making its mock, which will then use the parent classes/interfaces.
You can see this logic here: https://github.com/sebastianbergmann/phpunit-mock-objects/blob/master/PHPUnit/Framework/MockObject/Generator.php
if (!class_exists($mockClassName['fullClassName'], $callAutoload) &&
!interface_exists($mockClassName['fullClassName'], $callAutoload)) {
$prologue = 'class ' . $mockClassName['originalClassName'] . "\n{\n}\n\n";
if (!empty($mockClassName['namespaceName'])) {
$prologue = 'namespace ' . $mockClassName['namespaceName'] .
" {\n\n" . $prologue . "}\n\n" .
"namespace {\n\n";
$epilogue = "\n\n}";
}
$cloneTemplate = new Text_Template(
$templateDir . 'mocked_clone.tpl'
);
So if there is no class or interface, PHPUnit will actually create one itself so that the mock will meet the type hinting of original class name. However, any parent classes or interfaces will not be included because PHPUnit is not aware of them.
This would be due to not including the proper namespace in your test or having a problem in your autoloader. It is difficult to tell without actually seeing the entire test file.
Alternatively rather than mocking ZfcUser\Controller\Plugin\ZfcUserAuthentication, you could mock the Zend\Mvc\Controller\Plugin\PluginInterface in your test and pass that into the plugin manager. Though if you are type-hinting for the plugin in your code, your test still won't work.
//Mock the plugin interface for checking authorization
$authMock = $this->getMock('Zend\Mvc\Controller\Plugin\PluginInterface');
// Some expectations of the authentication service.
$authMock -> expects($this->any())
-> method('hasIdentity')
-> will($this->returnValue(true));
$authMock -> expects($this->any())
-> method('getIdentity')
-> will($this->returnValue($ZfcUserMock));
$this -> controller->getPluginManager()
->setService('zfcUserAuthentication', $authMock);
I just made an example for the FlashMessenger plugin. You should just use the ControllerPluginManager to override the ControllerPlugin. Make sure that your application bootstrap calls setApplicationConfig();
<?php
namespace SimpleTest\Controller;
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
class SimpleControllerTest extends AbstractHttpControllerTestCase {
public function testControllerWillAddErrorMessageToFlashMessenger()
{
$flashMessengerMock = $this->getMockBuilder('\Zend\Mvc\Controller\Plugin\FlashMessenger', array('addErrorMessage'))->getMock();
$flashMessengerMock->expects($this->once())
->method('addErrorMessage')
->will($this->returnValue(array()));
$serviceManager = $this->getApplicationServiceLocator();
$serviceManager->setAllowOverride(true);
$serviceManager->get('ControllerPluginManager')->setService('flashMessenger', $flashMessengerMock);
$this->dispatch('/error/message');
}
}?>

webdriver-test is unusable

On a virtual machine (clean, fresh Ubuntu server 11.04) I created a test website as described in Creating Your First Yii Application and now I want to create simple test using webdriver-test.
I set up proper TEST_BASE_URL in protected/tests/WebTestCase.php and created protected/tests/functional/MySimpleTest.php
<?php
Yii::import( 'ext.webdriver-bindings.CWebDriverTestCase' );
class MySimpleTest extends CWebDriverTestCase {
protected function setUp() {
parent::setUp( '192.168.57.1', 4444, 'firefox' );
}
public function testMySite() {
$this->get( TEST_BASE_URL );
$qElem = $this->findElementBy( LocatorStrategy::linkText, 'Users' );
$this->assertNotNull( $qElem, 'There is no "Users" link!' );
$qElem->clickAndWait();
$this->assertTrue( $this->isTextPresent( 'test1#example.com' ), 'The is no "test1#example.com" text on result page!' );
}
}
Running it looks like this:
etam#ubuntu:/var/www/test/protected/tests$ phpunit functional/MySimpleDbTest.php
PHPUnit 3.5.15 by Sebastian Bergmann.
E
Time: 5 seconds, Memory: 5.25Mb
There was 1 error:
1) MySimpleTest::testMySite
PHPUnit_Framework_Exception: setBrowserUrl() needs to be called before start().
/opt/yii-1.1.8.r3324/framework/test/CWebTestCase.php:61
/var/www/test/protected/extensions/webdriver-bindings/CWebDriverTestCase.php:156
FAILURES!
Tests: 1, Assertions: 0, Errors: 1.
Notice that it's complaining about setBrowserUrl() from PHPUnit_Extensions_SeleniumTestCase_Driver, which is not the same as one from CWebDriverTestCase.
I tried to find out what's going on, but it's too complicated to me. It looks like problems with old and new selenium API existing together, but I'm not sure about it.
I'm using:
Ubuntu server 11.04
yii 1.1.8.r3324
webdriver-test 1.1b
phpunit 3.5.15 (repaired as described in bugs.launchpad.net/ubuntu/+source/phpunit/+bug/701544)
Please help!
You need to call the setBrowseUrl() method right after the parent::setup() method because selenium requires this url to resolve relative paths on your test cases. So this way you could call open('full.url.com/someAction') or just open('/someAction') and both would go to the same page.

Resources