InvalidArgumentException: Unable to locate factory with name [default] - laravel, faker, phpunit - laravel

Since I am developing package, so I put my factories to custom path like this:
-- app
-- packages
-----mockizart
-------blog
---------database
--------------factories
----------------- PageModelFactory.php
---------src
this is how i load factory in my service provider (I already make sure the path is correct by clicking it on phpstorm):
function boot()
{
Factory::construct($this->app->make(\Faker\Generator::class), __DIR__."/../database/factories");
}
this is my page model factory (I already made sure this file was really loaded):
<?php
/** #var \Illuminate\Database\Eloquent\Factory $factory */
use Mockizart\Blog\Dodols\PageModel;
use Faker\Generator as Faker;
$factory->define(PageModel::class, function (Faker $faker) {
return [
'name' => "retretre",
'slug' => "retretret",
'type' => 0,
'category' => 0,
'tags' => "",
'content' => "",
];
});
and this is my script test :
use Mockizart\Blog\Dodols\PageModel;
.....
.....
/** #test */
public function edit_page()
{
dd(PageModel::find(1)); <-- this return was NULL so I think my class and namespace does exist.
factory(PageModel::class)->make(); <-- this cause error "unable to locate factory......"
$response = $this->get('/blog/page/edit/15');
$response->assertStatus(200);
}

so if you are using orchestra\Testbench, the correct way to load custom factories is in the setUp() method of your Test class or TestCase NOT in your Service Provider.
the code would be like this:
class TestCase extends \Orchestra\Testbench\TestCase
{
public function setUp(): void
{
parent::setUp();
// additional setup
$this->loadMigrationsFrom(__DIR__ . '/../database/migrations');
$this->withFactories(__DIR__.'/../database/factories');
}
protected function getPackageProviders($app)
{
return BlogServiceProvider::class;
}
}

Related

Static model class is null in feature test laravel

I have this test in my feature folder and I've imported model on top of the class but it keeps failing and I think $event is null!
namespace Tests\Feature\Events;
use App\Models\Event;
use Tests\TestCase;
use Illuminate\Foundation\Testing\RefreshDatabase;
class EventManagementTest extends TestCase
{
use RefreshDatabase;
/**
* #test
* #group event
* A basic feature test to check event registration
*
*/
public function an_event_can_be_registered()
{
$this->withoutExceptionHandling();
$response = $this->post('/events',$this->data());
$event = Event::first();
$this->assertCount(1,Event::all());
$response->assertRedirect('/events/' . $event->event_id);
}
private function data()
{
return[
'event_title' => 'Internet Businesses',
'event_location' => 'Milad Tower',
'event_description' => 'In this event Amin will present you the most recent methods in Internet Businesses',
'event_start_date' => '2020-06-01',
'event_end_date' => '2020-06-05',
];
}
...
}
And this is the results:
FAIL Tests\Feature\Events\EventManagementTest ✕ an event can be registered
Tests: 1 failed
Failed asserting that two strings are equal.
....
--- Expected
+++ Actual
## ##
-'http://localhost/events/1'
+'http://localhost/events'
these two URIs are different and I think that's because $event is null and I don't know why?!
UPDATE: I've added the Route and the controller:
Route::post('/events','Web\EventsController#store');
and the controller is:
public function store(){
$event = Event::create($this->validateRequest());
return redirect('/events/'.$event->event_id);
}
protected function validateRequest(){
return request()->validate([
'event_title' => 'required',
'event_location' => 'required',
'event_description' => 'required',
'event_start_date' => 'required',
'event_end_date' => 'required',
]);
}
Your do not use the standard primary id column, therefor you need to define it in your model. If it is not defined, it will not set it on create().
class Event extends Model {
protected $primaryKey = 'event_id';
}

Faker get streetAddress throwing ErrorException

I'm building a laravel application, and I've created a FakerServiceProvider to populate factories for testing and local dev.
<?php
namespace App\Providers;
use Faker\Factory;
use Faker\Generator;
use Faker\Provider\en_GB\Address;
use Faker\Provider\en_GB\Person;
use Faker\Provider\en_GB\PhoneNumber;
use Illuminate\Contracts\Support\DeferrableProvider;
use Illuminate\Support\ServiceProvider;
/**
* Class FakerServiceProvider
* #package App\Providers
*/
class FakerServiceProvider extends ServiceProvider implements DeferrableProvider
{
/**
*
*/
public function register()
{
$this->app->singleton(Generator::class, function ($app) {
$factory = Factory::create('en_GB');
$factory->addProvider(Person::class);
$factory->addProvider(Address::class);
$factory->addProvider(PhoneNumber::class);
return $factory;
});
}
/**
* #return array
*/
public function provides()
{
return [Generator::class];
}
}
I have created an address factory:
<?php
use App\Address;
use App\Country;
$factory->define(Address::class, function (Faker\Generator $faker) {
return [
'line_1' => $faker->secondaryAddress,
'line_2' => $faker->streetAddress,
'town' => $faker->city,
'county' => $faker->county,
'country_id' => factory(Country::class)->make()->id,
'postcode' => $faker->postcode,
'phone' => $faker->phoneNumber,
];
});
When I try to use this factory I get the following error:
ErrorException: call_user_func_array() expects parameter 1 to be a valid callback, non-static method Faker\Provider\Address::streetAddress() should not be called statically
I have checked the source for the Faker library and there is a streetAddress method here
I have tried calling both $faker->streetAddress and $faker->streetAddress()with no luck. I would expect$faker->streetAddressto produce something like ` or something similar.
Can anyone shed a bit of light on this for me
Removing the added providers in the Faker Service Provider fixed the issue

How to change hard coded Eloquent $connection only in phpunit tests?

I have an Eloquent Model like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SomeModel extends Model
{
protected $connection = 'global_connection';
......................
The problem is that this $connection has to be hard coded because I have a multi tenant web platform and all the tenants should read from this Database.
But when now in tests I am hitting the Controller route store() and I don't have access to the model!
I just do this:
public function store()
{
SomeModel::create($request->validated());
return response()->json(['msg' => 'Success']);
}
Which works great when using it as a user through browser...
But now I want to somehow force that model NOT to use that hard coded $connection and set it to Testing database connection...
And this is my Test
/** #test */
public function user_can_create_some_model(): void
{
$attributes = [
'name' => 'Some Name',
'title' => 'Some Title',
];
$response = $this->postJson($this->route, $attributes)->assertSuccessful();
}
Is there any way to achieve this with some Laravel magic maybe :)?
Because you asked for Laravel magic... Here it goes. Probably an overkill and over engineered way.
Let's first create an interface whose sole purpose is to define a function that returns a connection string.
app/Connection.php
namespace App;
interface Connection
{
public function getConnection();
}
Then let's create a concrete implementation that we can use in real world (production).
app/GlobalConnection.php
namespace App;
class GlobalConnection implements Connection
{
public function getConnection()
{
return 'global-connection';
}
}
And also another implementation we can use in our tests.
app/TestingConnection.php (you can also put this in your tests directory, but make sure to change the namespace to the appropriate one)
namespace App;
class TestingConnection implements Connection
{
public function getConnection()
{
return 'testing-connection';
}
}
Now let's go ahead and tell Laravel which concrete implementation we want to use by default. This can be done by going to the app/Providers/AppServiceProvider.php file and adding this bit in the register method.
app/Providers/AppServiceProvider.php
namespace App\Providers;
use App\Connection;
use App\GlobalConnection;
// ...
public function register()
{
// ...
$this->app->bind(Connection::class, GlobalConnection::class);
// ...
}
Let's use it in our model.
app/SomeModel.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class SomeModel extends Model
{
public function __construct(Connection $connection, $attributes = [])
{
parent::__construct($attributes);
$this->connection = $connection->getConnection();
}
// ...
}
Almost there. Now in our tests, we can replace the GlobalConnection implementation with the TestingConnection implementation. Here is how.
tests/Feature/ExampleTest.php
namespace Tests\Feature;
use Tests\TestCase;
use App\Connection;
use App\TestingConnection;
class ExampleTest extends TestCase
{
public function setUp(): void
{
parent::setUp();
$this->app->instance(Connection::class, TestingConnection::class);
}
/** #test */
public function your_test()
{
// $connection is 'testing-connection' in here
}
}
Code is untested, but should work. You can also create a facade to access the method statically then use Mockery to mock the method call and return a desired connection string while in testing.
Unfortunately for me, none of these answers didn't do the trick because of my specific DB setup for multi tenancy. I had a little help and this is the right solution for this problem:
Create a custom class ConnectionResolver somewhere under tests/ directory in laravel
<?php
namespace Tests;
use Illuminate\Database\ConnectionResolverInterface;
use Illuminate\Database\ConnectionResolver as IlluminateConnectionResolver;
class ConnectionResolver extends IlluminateConnectionResolver
{
protected $original;
protected $name;
public function __construct(ConnectionResolverInterface $original, string $name)
{
$this->original = $original;
$this->name = $name;
}
public function connection($name = null)
{
return $this->original->connection($this->name);
}
public function getDefaultConnection()
{
return $this->name;
}
}
In test use it like this
create a method called create() inside tests/TestCase.php
protected function create($attributes = [], $model = '', $route = '')
{
$this->withoutExceptionHandling();
$original = $model::getConnectionResolver();
$model::setConnectionResolver(new ConnectionResolver($original, 'testing'));
$response = $this->postJson($route, $attributes)->assertSuccessful();
$model = new $model;
$this->assertDatabaseHas('testing_db.'.$model->getTable(), $attributes);
$model::setConnectionResolver($original);
return $response;
}
and in actual test you can simply do this:
/** #test */
public function user_can_create_model(): void
{
$attributes = [
'name' => 'Test Name',
'title' => 'Test Title',
'description' => 'Test Description',
];
$model = Model::class;
$route = 'model_store_route';
$this->create($attributes, $model, $route);
}
Note: that test method can have only one line when using setUp() method and $this-> notation
And that's it. What this does is forcing the custom connection name (which should be written inside config/database.php) and the model during that call will work with that connection no matter what you specify inside the model, therefore it will store the data into DB which you have specified in $model::setConnectionResolver(new ConnectionResolver($original, 'HERE'));
This is tested for Laravel 8 & 9 and Super Simple.
Here is an example of switching the connection while testing.
In your model ->
class YourModel extends Model {
protected $connection = 'remote';
public function __construct(array $attributes = [])
{
if(config('app.env') === 'testing') {
$this->connection = 'sqlite';
}
parent::__construct($attributes);
}
}
In the Eloquent Model you have the following method.
/**
* Set the connection associated with the model.
*
* #param string|null $name
* #return $this
*/
public function setConnection($name)
{
$this->connection = $name;
return $this;
}
So you can just do
$user = new User();
$user->setConnection('connectionName')
One option would be to create a new environment file just for testing, that way you can overwrite the connection credentials only for your tests and you would not have to touch your models:
tests/CreatesApplication.php
public function createApplication()
{
$app = require __DIR__ . '/../bootstrap/app.php';
$app->loadEnvironmentFrom('.env.testing'); // add this
$app->make(Kernel::class)->bootstrap();
return $app;
}
Copy your .env file to .env.testing and change your database credentials for the connection global_connection to your test database credentials.
I am not sure how you configured your connection but it probably looks something like the following.
database.php
'global_connection' => [
'database' => env('DB_GLOBAL_DATABASE', ''),
'username' => env('DB_GLOBAL_USERNAME', ''),
'password' => env('DB_GLOBAL_PASSWORD', ''),
],
.env.testing:
DB_GLOBAL_DATABASE=database
DB_GLOBAL_USERNAME=username
DB_GLOBAL_PASSWORD=secret
Now you can use the global_connection connection but it will use your test database.
Additionally you could then remove all environment values from the phpunit.xml file and move them into the .env.testing file so you have all environment values for your tests in one place.
If you don't want to create a new environment file you could of course just update the values in your phpunit.xml file:
<php>
<server name="DB_GLOBAL_DATABASE" value="database"/>
<server name="DB_GLOBAL_USERNAME" value="username"/>
<server name="DB_GLOBAL_PASSWORD" value="password"/>
</php>
The most "magical" thing I suggest you could do is focus exclusively on the test and try to not modify the model at all:
/** #test */
public function user_can_create_some_model(): void
{
config([ "database.connections.global_connection" => [
'driver' => 'mysql', 'host' => x // basically override everything that is in config/database.php
]);
$attributes = [
'name' => 'Some Name',
'title' => 'Some Title',
];
$response = $this->postJson($this->route, $attributes)->assertSuccessful();
}
Hopefully when the configuration needs to be read the new one will be used.
If your global_connection configuration is read from the .env file you can also override the env variables in your test runner configuration (e.g. phpunit.xml)

Invalid Argument Exception - Laravel Unit Testing

I am running a unit test to check that
View page exists
AssertSee that text appears on the page and with a string limit
I am getting an invalid argument exception:
1) Tests\Feature\ViewAllPostTest::testCanViewAllPosts
InvalidArgumentException: You requested 1 items, but there are only 0 items available.
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Support\Arr.php:472
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Support\Collection.php:1486
C:\projects\car-torque-laravel\database\factories\PostFactory.php:12
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:274
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:292
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\GuardsAttributes.php:122
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:300
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:219
C:\projects\car-torque-laravel\vendor\laravel\framework\src\Illuminate\Database\Eloquent\FactoryBuilder.php:178
C:\projects\car-torque-laravel\tests\Feature\ViewAllPostTest.php:19
My source code is as follows:
Test Function
namespace Tests\Feature;
use App\Post;
use Tests\TestCase;
class ViewAllPostTest extends TestCase
{
/**
* #group posts
*
* #return void
*/
public function testCanViewAllPosts()
{
//arrange
$post = factory(Post::class)->create();
//action
$response = $this->get('/posts');
//assert
$response->assertStatus(200);
$response->assertSee($post->body);
$response->assertSee(str_limit($post->body));
}
}
Factory Class
use App\Post;
use App\User;
use Faker\Generator as Faker;
$factory->define(Post::class, function (Faker $faker) {
return [
'body' => $faker->text,
'user_id' => User::all()->random()->id,
'created_at' => now(),
'updated_at' => now(),
];
});
'user_id' => User::all()->random()->id,
In the above line of your factory, you want random id form your users table. But have you created any User before running the test. At least a user should be created before creating post using post factory.

How to create a Custom Auth Guard / Provider for Laravel 5.7

I'm migrating from Laravel 4 to 5.7 and having trouble with my custom auth provider. I've followed various walkthroughs (e.g. 1, 2, 3) as well as quite a bit of googling.
I've attempted to get this working by the following:
Set the guards and providers and link to my target model.
'defaults' => [
'guard' => 'custom_auth_guard',
'passwords' => 'users',
],
'guards' => [
'custom_auth_guard' => [
'driver' => 'session',
'provider' => 'custom_auth_provider',
],
],
'providers' => [
'custom_auth_provider' => [
'driver' => 'custom',
'model' => App\UserAccount::class,
],
],
Register the driver defined in the above provider. I'm piggybacking off AuthServiceProvider for ease
...
public function boot()
{
$this->registerPolicies();
\Auth::provider('custom',function() {
return new App\Auth\CustomUserProvider;
});
}
...
Created my custom provider which has my retrieveByCredentials, etc. I've replaced the logic with some die() to validate if it is making it here. In Laravel 4, it used to go to validateCredentials().
class CustomUserProvider implements UserProviderInterface {
public function __construct()
{
die('__construct');
}
public function retrieveByID($identifier)
{
die('retrieveByID');
}
public function retrieveByCredentials(array $credentials)
{
die('retrieveByCredentials');
}
public function validateCredentials(\Illuminate\Auth\UserInterface $user, array $credentials)
{
die('validateCredentials');
}
For reference, App/UserAccount looks like so
class UserAccount extends Authenticatable
{
use Notifiable;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'public.user_account';
// no updated_at, created_at
public $timestamps = false;
private $_roles = [];
private $_permissions = [];
}
Finally, I am calling it via my controller.
if(\Auth::attempt($credentials){
return \Redirect::intended('/dashboard');
}
I have also tried to call the guard direct
if(\Auth::guard('custom_auth_guard')->attempt($credentials){
return \Redirect::intended('/dashboard');
}
This results in the following error: "Auth guard [custom_auth_guard] is not defined."
I've tried a few other commands to make sure there is no cache issue:
composer update
php artisan cache:clear
The results: when I call Auth::attempt($credentials) Laravel is trying to run a query on the users table. the expected result is that it would hit one of the die()'s in CustomUserProvider... or at lease try and query public.user_account as defined in the model.
I've been messing with this for some time and I must be missing something simple... hopefully someone with a bit more experience in Laravel 5 can see what I am doing wrong.
Thanks in advance!!
Managed to work it out. Couple little problems but the main one was that I was trying to piggyback on AuthServiceProvider as opposed to my own provider. Below is what I did to get a custom auth provider working in Laravel 5.7
Set the provider in config.auth.php.
'providers' => [
'user' => [
'driver' => 'eloquent',
'model' => \UserAccount::class,
],
],
Create a new provider in app/providers/ . This links the listed provider above with the correct User Provider Code.
namespace App\Providers;
use Auth;
use App\Auth\CustomUserProvider;
use Illuminate\Support\ServiceProvider;
class CustomAuthProvider extends ServiceProvider
{
public function register()
{
//
}
public function boot()
{
Auth::provider('eloquent',function()
{
return new CustomUserProvider(new \UserAccount());
});
}
}
Created my custom provider in app/auth/. This is the logic for validating the user and replaces the laravel functions for auth. I had an issue here where it was validating but not populating the user object. I originally had a test to see if the object was null and if it was, populate... however it was always populated with an empty object. removing the test allowed me to call Auth::user() functions.
namespace App\Auth;
use Illuminate\Contracts\Auth\Authenticatable as UserContract;
use Illuminate\Auth\EloquentUserProvider;
class CustomUserProvider implements EloquentUserProvider{
public function __construct()
{
$this->user = $user;
}
public function retrieveByID($identifier)
{
$this->user = \UserAccount::find($identifier);
return $this->user;
}
public function retrieveByCredentials(array $credentials)
{
// find user by username
$user = \UserAccount::where('name', $credentials['username'])->first();
// validate
return $user;
}
public function validateCredentials(\Illuminate\Auth\UserInterface $user, array $credentials)
{
//logic to validate user
}
Updated App/Models/UserAccount looks like so
use Illuminate\Foundation\Auth\User as Authenticatable;
class UserAccount extends Authenticatable
{
protected $table = 'public.user_account';
// no updated_at, created_at
public $timestamps = false;
private $_roles = [];
private $_permissions = [];
}
That's it. I can now validate via the below call
if(\Auth::attempt($credentials){
return \Redirect::intended('/dashboard');
}

Resources