Giter Site home page Giter Site logo

laravel-test-factory-helper's Introduction

Laravel Test Factory Generator

php artisan generate:model-factory

This package will generate factories from your existing models so you can get started with testing your Laravel application more quickly.

Example output

Migration and Model

Schema::create('users', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->string('username');
    $table->string('email')->unique();
    $table->string('password', 60);
    $table->integer('company_id');
    $table->rememberToken();
    $table->timestamps();
});

class User extends Model {
    public function company()
    {
        return $this->belongsTo(Company::class);
    }
}

Factory Result

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'name' => $faker->name,
        'username' => $faker->userName,
        'email' => $faker->safeEmail,
        'password' => bcrypt($faker->password),
        'company_id' => factory(App\Company::class),
        'remember_token' => Str::random(10),
    ];
});

Install

Require this package with composer using the following command:

composer require --dev mpociot/laravel-test-factory-helper

Usage

To generate multiple factories at once, run the artisan command:

php artisan generate:model-factory

This command will find all models within your application and create test factories. By default, this will not overwrite any existing model factories. You can force overwriting existing model factories by using the --force option.

To generate a factory for specific model or models, run the artisan command:

php artisan generate:model-factory User Team

By default, this command will search under the app folder for models. If your models are within a different folder, for example app/Models, you can specify this using --dir option. In this case, run the artisan command:

php artisan generate:model-factory --dir app/Models -- User Team

License

The Laravel Test Factory Helper is free software licensed under the MIT license.

laravel-test-factory-helper's People

Contributors

dontfreakout avatar dweineratl avatar edmandiesamonte avatar ilvsx avatar jasonmccreary avatar jeroen-g avatar jijoel avatar mpociot avatar oussama-tn avatar skeets23 avatar svenslijkoord avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

laravel-test-factory-helper's Issues

Does not work with Laravel 6.0 cannot install

Conflicts with fakerphp/faker, because it requires higher version if I understand correctly. I do not want to do any workarounds, because later upgrading to new Laravel LTS version might cause more headache.

After running:

composer require mpociot/laravel-apidoc-generator

This happens:

./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: remove laravel/framework v6.20.4
    - Conclusion: don't install laravel/framework v6.20.4
    - mpociot/laravel-apidoc-generator 2.1.8 requires laravel/framework ~5.4 -> satisfiable by laravel/framework[5.4.x-dev, 5.5.x-dev, 5.6.x-dev, 5.7.x-dev, 5.8.x-dev].
    - mpociot/laravel-apidoc-generator 2.x-dev requires laravel/framework ~5.4 -> satisfiable by laravel/framework[5.4.x-dev, 5.5.x-dev, 5.6.x-dev, 5.7.x-dev, 5.8.x-dev].
    - Can only install one of: laravel/framework[5.5.x-dev, v6.20.4].
    - Can only install one of: laravel/framework[5.6.x-dev, v6.20.4].
    - Can only install one of: laravel/framework[5.7.x-dev, v6.20.4].
    - Can only install one of: laravel/framework[5.8.x-dev, v6.20.4].
    - Can only install one of: laravel/framework[5.4.x-dev, v6.20.4].
    - Installation request for laravel/framework (locked at v6.20.4, required as ^6.20) -> satisfiable by laravel/framework[v6.20.4].
    - Installation request for mpociot/laravel-apidoc-generator ^2.1.8 -> satisfiable by mpociot/laravel-apidoc-generator[2.1.8, 2.x-dev].


Installation failed, reverting ./composer.json to its original content.

Rokas@DESKTOP MINGW64 ~/Desktop/lara-six/rest-pass
$ composer require mpociot/laravel-apidoc-generator

Rokas@DESKTOP MINGW64 ~/Desktop/lara-six/rest-pass
$ composer require mpociot/laravel-apidoc-generator
Using version ^4.8 for mpociot/laravel-apidoc-generator
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: don't install mpociot/laravel-apidoc-generator 4.8.2
    - Conclusion: don't install mpociot/laravel-apidoc-generator 4.8.1
    - Conclusion: don't install mpociot/laravel-apidoc-generator 4.8.0
    - Conclusion: remove fakerphp/faker v1.11.0
    - Installation request for mpociot/laravel-apidoc-generator ^4.8 -> satisfiable by mpociot/laravel-apidoc-generator[4.8.0, 4.8.1, 4.8.2, v4.x-dev].
    - Conclusion: don't install fakerphp/faker v1.11.0
    - mpociot/laravel-apidoc-generator v4.x-dev requires fzaninotto/faker ^1.8 -> satisfiable by fakerphp/faker[1.9.x-dev, v1.9.1], fzaninotto/faker[1.9.x-dev, v1.8.0, v1.9.0, v1.9.1].
    - Can only install one of: fakerphp/faker[1.9.x-dev, v1.11.0].
    - Can only install one of: fakerphp/faker[v1.9.1, v1.11.0].
    - fzaninotto/faker 1.9.x-dev conflicts with fakerphp/faker[v1.11.0].
    - fzaninotto/faker v1.8.0 conflicts with fakerphp/faker[v1.11.0].
    - fzaninotto/faker v1.9.0 conflicts with fakerphp/faker[v1.11.0].
    - fzaninotto/faker v1.9.1 conflicts with fakerphp/faker[v1.11.0].
    - Installation request for fakerphp/faker (locked at v1.11.0, required as ^1.9.1) -> satisfiable by fakerphp/faker[v1.11.0].


Installation failed, reverting ./composer.json to its original content.

Error when upgrading laravel 7 to laravel 8

When upgrading from larvel 7 to laravel 8:

    - mpociot/laravel-test-factory-helper v2.1.0 requires illuminate/filesystem ^6.0|^7.0 -> satisfiable by illuminate/filesystem[v6.0.0, ..., 6.x-dev, v7.0.0, ..., 7.x-dev].
    - Only one of these can be installed: illuminate/filesystem[v5.5.0, ..., 5.8.x-dev, v6.0.0, ..., 6.x-dev, v7.0.0, ..., 7.x-dev, v8.0.0, ..., 8.x-dev], laravel/framework[v8.0.0, ..., 8.x-dev]. laravel/framework replaces illuminate/filesystem and thus cannot coexist with it.

Installation fails with an error

I have tried to install this package (on a fresh Laravel 5.2.27 installation) using composer require, but I get an error:

[Symfony\Component\Debug\Exception\FatalErrorException]
Class 'Mpociot\LaravelTestFactoryHelper\TestFactoryHelperServiceProvider' not found

Script php artisan optimize handling the post-update-cmd event returned with an error

Installation failed, reverting ./composer.json to its original content.

[RuntimeException]
Error Output:

the same happens when I run
php artisan test-factory-helper:generate

[Symfony\Component\Debug\Exception\FatalErrorException]

Class 'Mpociot\LaravelTestFactoryHelper\TestFactoryHelperServiceProvider' not found

Doesn't find Models

This package doesn't find models in namespace "App". shows : PHP Fatal error: Class 'Bear' not found in /opt/lampp/htdocs/blog/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 790

Why it searches in vendor folder ??

Custom date attributes are currently being set as `\Carbon\Carbon`

Currently, if you have any custom date attributes as part of your models - such as deleted_at or any other custom dates, their model factory attributes are set as \Carbon\Carbon.

If we use a custom date field of viewed_at, as example - this is what is set:

    'viewed_at' =>  '\Carbon\Carbon' ,
    'deleted_at' =>  '\Carbon\Carbon' ,

Additionally, perhaps there should also be a check that if the attribute is deleted_at we can assume this suggests the user is implementing soft deletes, so this should be set to null? Otherwise any factories will be created as a deleted record.

So the expected behaviour for dates might be the following:

    'viewed_at' =>  $faker->dateTime(),
    'deleted_at => null

PHP Fatal error: Cannot declare class ... because the name is already in use

Complete error message:
(occurs when running php artisan generate:model-factory)

PHP Fatal error:  Cannot declare class PragmaRX\Tracker\Data\Repositories\Session, because the name is already in use in /app/VendorOverrides/PragmaRX/Tracker/Data/Repositories/Session.php on line 330

Symfony\Component\Debug\Exception\FatalErrorException: Cannot declare class PragmaRX\Tracker\Data\Repositories\Session, because the name is already in use

Background:
The PragmaRX Tracker package hasn't merged an important fix, so I've had to override it in my app with composer magic.

composer.json:

    "autoload": {
        "classmap": [
            "database/seeds",
            "database/factories"
        ],
+        "files": ["app/VendorOverrides/PragmaRX/Tracker/Data/Repositories/Session.php"],
        "psr-4": {
            "App\\": "app/"
        }
    },

So, yes, my app does actually re-declare that class, but composer knows how to handle it.

Possible Solutions:

  1. Bandage: add an "exclude" flag to the generate:model-factory command, where we can list the things (ie: directories probably) to ignore.
  2. Auto-ignore things listed in composer.json's autoload.files key.
  3. Catch the error and just ignore it, instead of fatal abort.
  4. Tell the user (me!) I'm doing it wrong! (ie: I guess I could put these overrides outside app)

Laravel 4.2

Any change for a laravel 4.2 version? A lot of projects are still using it and are still under active development.

SmallInteger

Migration:
$table->smallInteger('small');

Factory:
'small'=> $faker->numberBetween($min = 0, $max = 32767),

Tried with different location

Hi,

I tried to store the factory in different location, but it doesn't write in the appropriate file, instead always write to default file ModelFactory.php

Though I have created the TestFactory.php under factories.

php artisan test-factory-helper:generate --filename="database/factories/TestFactory.php"
and
php artisan test-factory-helper:generate --filename=database/factories/TestFactory.php

Need to add opening php tag to ModelFactory.php (when file doesn't already exist)

Currently, if you run the php artisan test-factory-helper:generate command, and the database/factories/ModelFactory.php does not exist before running the command, the model factories are generated correctly, but there is no opening <?php on the newly created database/factories/ModelFactory.php file.

I don't have an example to show but I have tested it on 2 separate projects, without the ModelFactory.php pre-existing in both projects.

SQLSTATE[HY000] [2002] No such file or directory

I have solved this issue, but thought to share in case someone else will face it:
After downloading this package and running
php artisan generate:model-factory
I got empty factory files and the following exception for each factory file :
SQLSTATE[HY000] [2002] No such file or directory
I am using 'mysql' and I haven't had any problem with DB connection before while working with my Laravel application.
The exception was related to dbal connection, and the solution was to add :
'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',
To my mysql driver in Laravel 'config->database.php'

[Proposal Solution] Exception: SQLSTATE[IM001]: Driver does not support this function: driver does not support that attribute Could not analyze class Modules\Pdm\Models\PickingList\PickingListItem

Hello @mpociot

Hope to find you well!

So, with DBAL, for SQL server, is needed to set some option. Already solver this before.
For such connections, to work out of the box, something similar to this will work.

protected function setNeededPdoSettings()
    {
        $connectionsSqlServer = [
            'x3db_v11',
            'roots_sql_server',
            'imos',
        ];

        collect($connectionsSqlServer)
            ->each(function ($item, $key) {
                config()->set("database.connections.{$item}.options",[
                    \PDO::ATTR_PERSISTENT => true
                ]);
            });

    }

It puts that option on the fly, for the current execution.
I could rewrite above snipper to apply such setting to every SQL Server connection, and make a PR.
What do you think?

Not Support in laravel 5.4

Problem - mpociot/laravel-test-factory-helper 0.3.1 requires illuminate/support 5.0.x|5.1.x|5.2.x|5.3.x
and - mpociot/laravel-test-factory-helper 0.3.1 requires illuminate/filesystem 5.0.x|5.1.x|5.2.x|5.3.x
don't install laravel/framework v5.4.0

Not working on laravel 5.3

Problem 1
- Installation request for mpociot/laravel-test-factory-helper ^0.2.1 -> satisfiable by mpociot/laravel-test-factory-helper[0.2.1].
- Conclusion: remove laravel/framework 5.3.x-dev
- mpociot/laravel-test-factory-helper 0.2.1 requires illuminate/filesystem 5.0.x|5.1.x|5.2.x -> satisfiable by laravel/framework[5.2.x-dev], illuminate/filesystem[5.0.x-dev, 5.1.x-dev, 5.2.x-dev, v5.0.0, v5.0.22, v5.0.25, v5.0.26, v5.0.28, v5.0.33, v5.0.4, v5.1.1, v5.1.13, v5.1.16, v5.1.2, v5.1.20, v5.1.22, v5.1.25, v5.1.28, v5.1.30, v5.1.31, v5.1.6, v5.1.8, v5.2.0, v5.2.19, v5.2.21, v5.2.24, v5.2.25, v5.2.26, v5.2.27, v5.2.28, v5.2.31, v5.2.32, v5.2.37, v5.2.6, v5.2.7].
- Can only install one of: laravel/framework[5.3.x-dev, 5.2.x-dev].
- don't install illuminate/filesystem 5.2.x-dev|don't install laravel/framework 5.3.x-dev

lumen 5.4

The JSON field type that does not seem to support mysql5.7

Exception: Unknown database type json requested, Doctrine\DBAL\Platforms\MySQL57Platform may not support it.

Mongodb doesn't seem to support either

Exception: call_user_func_array() expects parameter 1 to be a valid callback, class 'MongoDB\Database' does not have a method 'getDoctrineDriver'

Convert relation column id to closure

Instead of

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'company_id' => factory(App\Company::class)->create()->id,
    ];
});

it should be

$factory->define(App\User::class, function (Faker\Generator $faker) {
    return [
        'company_id' => function() {
              return factory(App\Company::class)->create();
         },
    ];
});

For ENUM

Migration:
$table->enum('status',['ACTIVE','DISABLED','EXPIRED','WAITING','CONSUMED']);

Factory:
'status'=> $faker->randomElement($array = array ('ACTIVE','DISABLED','EXPIRED','WAITING','CONSUMED')),

Generate Seeking Non-Existent Model

I have a Model called Address that utilizes several lookup tables named with _type (eg. Address_type, Region_type, etc.) Upon running php artisan test-factory-helper:generate, the package errors out with the message:

[Symfony\Component\Debug\Exception\FatalThrowableError]  
Class 'App\Models\Region' not found  

It appears to be expecting a Model that doesn't exist: Region to associate with Region_type.

Postgres / sqlite support

is postgres or sqlite support available? Just tried both with no luck at 'SHOW COLUMNS... ' 😢

If so, maybe there should be a message in README

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.