Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add factory tests #68

Merged
merged 26 commits into from
Dec 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
474d057
test: add tests for factory generator.
Dec 18, 2023
0783b7c
Merge branch 'master' into 49-add-tests
Dec 19, 2023
a4d14e2
test: add factory generator tests.
Dec 20, 2023
90e983c
test: add tests for factory generator.
Dec 20, 2023
c3baf27
Merge branch '49-add-tests' into 49-add-factory-tests
Dec 20, 2023
32b1803
Merge branch 'master' into 49-add-factory-tests
Jan 17, 2024
798038d
Merge branch 'master' into 49-add-factory-tests
t0xas Nov 19, 2024
485b59f
chore: add factory tests
t0xas Nov 20, 2024
91e584b
chore: add factory tests
t0xas Nov 20, 2024
ea69440
chore: add factory tests
t0xas Nov 20, 2024
35d51f7
chore: add factory tests
t0xas Nov 20, 2024
67fd5fb
chore: add factory tests
t0xas Nov 20, 2024
a9f3ca2
chore: add factory tests
t0xas Nov 20, 2024
672aaef
chore: add factory tests
t0xas Nov 20, 2024
04dfc78
chore: add factory tests
t0xas Nov 20, 2024
0e1496b
feat: remove useless code
pirs1337 Nov 27, 2024
7aa73ba
feat: remove useless code
pirs1337 Nov 27, 2024
bbce08b
refactor: remove useless classes
pirs1337 Nov 27, 2024
0718d41
refactor: code
pirs1337 Nov 28, 2024
5188958
refactor: code
pirs1337 Nov 28, 2024
fac9425
refactor: code
pirs1337 Nov 28, 2024
fdb25c8
refactor: remove useless stubs
pirs1337 Nov 29, 2024
f6fa94c
Update tests/Support/Factory/FactoryMockTrait.php
DenTray Dec 2, 2024
171ab25
Merge remote-tracking branch 'origin/master' into 49-add-factory-tests
pirs1337 Dec 2, 2024
53f9fce
fix: conflicts
pirs1337 Dec 2, 2024
875c2fd
Merge remote-tracking branch 'origin/49-add-factory-tests' into 49-ad…
pirs1337 Dec 2, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 1 addition & 3 deletions config/entity-generator.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
'repositories' => 'app/Repositories',
'tests' => 'tests',
'routes' => 'routes/api.php',
'factory' => 'database/factories/ModelFactory.php',
'factories' => 'database/factories',
'translations' => 'resources/lang/en/validation.php',
'resources' => 'app/Http/Resources',
'nova' => 'app/Nova',
Expand All @@ -32,8 +32,6 @@
'routes' => 'entity-generator::routes',
'use_routes' => 'entity-generator::use_routes',
'factory' => 'entity-generator::factory',
'legacy_factory' => 'entity-generator::legacy_factory',
'legacy_empty_factory' => 'entity-generator::legacy_empty_factory',
'seeder' => 'entity-generator::seeder',
'legacy_seeder' => 'entity-generator::legacy_seeder',
'database_empty_seeder' => 'entity-generator::database_empty_seeder',
Expand Down
6 changes: 2 additions & 4 deletions src/Commands/MakeEntityCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace RonasIT\Support\Commands;

use Closure;
use Illuminate\Console\Command;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Config;
Expand Down Expand Up @@ -217,10 +216,9 @@ protected function outputNewConfig($packageConfigs, $projectConfigs)
}

$factories = 'database/factories';
$factories = (version_compare(app()->version(), '8', '>=')) ? $factories : "{$factories}/ModelFactory.php";

if ($newConfig['paths.factory'] !== $factories) {
$newConfig['paths.factory'] = $factories;
if ($newConfig['paths.factories'] !== $factories) {
$newConfig['paths.factories'] = $factories;
}

$differences = array_diff_key($newConfig, $flattenedProjectConfigs);
Expand Down
9 changes: 9 additions & 0 deletions src/Exceptions/FakerMethodNotFoundException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace RonasIT\Support\Exceptions;

use Exception;

class FakerMethodNotFoundException extends Exception
{
}
14 changes: 6 additions & 8 deletions src/Generators/AbstractTestsGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,11 @@ protected function getInserts(): array
}, $this->buildRelationsTree($arrayModels));
}

protected function isFactoryExists($modelName): bool
protected function isFactoryExists(string $modelName): bool
{
$factory = app(LegacyFactories::class);
$modelClass = $this->getModelClass($modelName);

$isNewStyleFactoryExists = $this->classExists('factory', "{$modelName}Factory") && method_exists($modelClass, 'factory');

return $isNewStyleFactoryExists || !empty($factory[$this->getModelClass($modelName)]);
return $this->classExists('factories', "{$modelName}Factory") && method_exists($modelClass, 'factory');
}

protected function isMethodExists($modelName, $method): bool
Expand Down Expand Up @@ -170,13 +167,14 @@ protected function getModelFields($model): array

protected function getMockModel($model): array
{
if (!$this->isFactoryExists($model)) {
$hasFactory = $this->isFactoryExists($model);

if (!$hasFactory) {
return [];
}

$modelClass = $this->getModelClass($model);
$hasFactory = method_exists($modelClass, 'factory') && $this->classExists('factory', "{$model}Factory");
$factory = ($hasFactory) ? $modelClass::factory() : factory($modelClass);
$factory = $modelClass::factory();

return $factory
->make()
Expand Down
175 changes: 25 additions & 150 deletions src/Generators/FactoryGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@
use Faker\Generator as Faker;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use RonasIT\Support\Exceptions\ModelFactoryNotFound;
use InvalidArgumentException;
use RonasIT\Support\Exceptions\FakerMethodNotFoundException;
use RonasIT\Support\Exceptions\ClassNotExistsException;
use RonasIT\Support\Exceptions\ModelFactoryNotFoundedException;
use RonasIT\Support\Exceptions\ClassAlreadyExistsException;
use RonasIT\Support\Events\SuccessCreateMessage;
use Exception;

class FactoryGenerator extends EntityGenerator
{
Expand All @@ -26,109 +25,33 @@ class FactoryGenerator extends EntityGenerator
'json' => '[]',
];

protected function generateSeparateClass(): string
public function generate(): void
{
if (!$this->classExists('models', $this->model)) {
$this->throwFailureException(
ClassNotExistsException::class,
"Cannot create {$this->model}Factory cause {$this->model} Model does not exists.",
"Create a {$this->model} Model by himself or run command 'php artisan make:entity {$this->model} --only-model'."
exceptionClass: ClassNotExistsException::class,
failureMessage: "Cannot create {$this->model}Factory cause {$this->model} Model does not exists.",
recommendedMessage: "Create a {$this->model} Model by itself or run command 'php artisan make:entity {$this->model} --only-model'.",
);
}

if ($this->classExists('factory', "{$this->model}Factory")) {
if ($this->classExists('factories', "{$this->model}Factory")) {
$this->throwFailureException(
ClassAlreadyExistsException::class,
"Cannot create {$this->model}Factory cause {$this->model}Factory already exists.",
"Remove {$this->model}Factory."
exceptionClass: ClassAlreadyExistsException::class,
failureMessage: "Cannot create {$this->model}Factory cause {$this->model}Factory already exists.",
recommendedMessage: "Remove {$this->model}Factory.",
);
}

$factoryContent = $this->getStub('factory', [
'namespace' => $this->getOrCreateNamespace('factory'),
'namespace' => $this->getOrCreateNamespace('factories'),
'entity' => $this->model,
'fields' => $this->prepareFields()
'fields' => $this->prepareFields(),
]);

$this->saveClass('factory', "{$this->model}Factory", $factoryContent);

return "Created a new Factory: {$this->model}Factory";
}

protected function generateToGenericClass(): string
{
if (!file_exists($this->paths['factory'])) {
$this->prepareEmptyFactory();
}

if (!$this->checkExistModelFactory() && $this->checkExistRelatedModelsFactories()) {
$stubPath = config("entity-generator.stubs.legacy_factory");

$content = view($stubPath)->with([
'entity' => $this->model,
'fields' => $this->prepareFields(),
'modelsNamespace' => $this->getOrCreateNamespace('models')
])->render();

$content = "\n\n" . $content;

$createMessage = "Created a new Test factory for {$this->model} model in '{$this->paths['factory']}'";

file_put_contents($this->paths['factory'], $content, FILE_APPEND);

$this->prepareRelatedFactories();
} else {
$createMessage = "Factory for {$this->model} model has already created, so new factory not necessary create.";
}

return $createMessage;
}
$this->saveClass('factories', "{$this->model}Factory", $factoryContent);

public function generate(): void
{
$createMessage = (version_compare(app()->version(), '8', '>='))
? $this->generateSeparateClass()
: $this->generateToGenericClass();

event(new SuccessCreateMessage($createMessage));
}

protected function prepareEmptyFactory(): void
{
$stubPath = config('entity-generator.stubs.legacy_empty_factory');
$content = "<?php \n\n" . view($stubPath, [
'modelsNamespace' => $this->getOrCreateNamespace('models')
])->render();

list($basePath, $databaseFactoryDir) = extract_last_part(config('entity-generator.paths.factory'), '/');

if (!is_dir($databaseFactoryDir)) {
mkdir($databaseFactoryDir);
}

file_put_contents($this->paths['factory'], $content);
}

protected function checkExistRelatedModelsFactories(): bool
{
$modelFactoryContent = file_get_contents($this->paths['factory']);
$relatedModels = $this->getRelatedModels($this->model, "{$this->model}Factory");
$modelNamespace = $this->getOrCreateNamespace('models');

foreach ($relatedModels as $relatedModel) {
$relatedFactoryClass = "{$modelNamespace}\\$relatedModel::class";
$existModelFactory = strpos($modelFactoryContent, $relatedFactoryClass);

if (!$existModelFactory) {
$this->throwFailureException(
ModelFactoryNotFoundedException::class,
"Not found $relatedModel factory for $relatedModel model in '{$this->paths['factory']}",
"Please declare a factory for $relatedModel model on '{$this->paths['factory']}' path and run your command with option '--only-tests'."
);
}
}

return true;
event(new SuccessCreateMessage("Created a new Factory: {$this->model}Factory"));
}

protected static function getFakerMethod($field): string
Expand All @@ -146,42 +69,10 @@ protected static function getCustomMethod($field): string
return self::CUSTOM_METHODS[$field['type']];
}

$message = $field['type'] . 'not found in CUSTOM_METHODS variable CUSTOM_METHODS = ' . self::CUSTOM_METHODS;
throw new Exception($message);
}

protected function prepareRelatedFactories(): void
{
$relations = array_merge(
$this->relations['hasOne'],
$this->relations['hasMany']
);

foreach ($relations as $relation) {
$modelFactoryContent = file_get_contents($this->paths['factory']);

if (!Str::contains($modelFactoryContent, $this->getModelClass($relation))) {
$this->throwFailureException(
ModelFactoryNotFound::class,
"Model factory for mode {$relation} not found.",
"Please create it and after thar you can run this command with flag '--only-tests'."
);
}

$matches = [];

preg_match($this->getFactoryPattern($relation), $modelFactoryContent, $matches);

foreach ($matches as $match) {
$field = Str::snake($this->model) . '_id';

$newField = "\n \"{$field}\" => 1,";
$message = "Cannot generate fake data for unsupported {$field['type']} field type. "
. "Supported custom field types are " . implode(', ', array_keys(self::CUSTOM_METHODS));

$modelFactoryContent = str_replace($match, $match . $newField, $modelFactoryContent);
}

file_put_contents($this->paths['factory'], $modelFactoryContent);
}
throw new FakerMethodNotFoundException($message);
}

public static function getFactoryFieldsContent($field): string
Expand All @@ -193,49 +84,33 @@ public static function getFactoryFieldsContent($field): string
return 1;
}

if (property_exists($faker, $field['name'])) {
return "\$faker-\>{$field['name']}";
try {
$faker->{$field['name']};
$hasFormatter = true;
} catch (InvalidArgumentException $e) {
$hasFormatter = false;
}

if (method_exists($faker, $field['name'])) {
return "\$faker-\>{$field['name']}()";
if ($hasFormatter) {
return "\$faker->{$field['name']}";
}

return self::getFakerMethod($field);
}

protected function checkExistModelFactory(): int
{
$modelFactoryContent = file_get_contents($this->paths['factory']);
$modelNamespace = $this->getOrCreateNamespace('models');
$factoryClass = "{$modelNamespace}\\$this->model::class";

return strpos($modelFactoryContent, $factoryClass);
}

protected function prepareFields(): array
{
$result = [];

foreach ($this->fields as $type => $fields) {
foreach ($fields as $field) {
$explodedType = explode('-', $type);

$result[] = [
'name' => $field,
'type' => head($explodedType)
'type' => Str::before($type, '-'),
];
}
}

return $result;
}

protected function getFactoryPattern($model): string
{
$modelNamespace = "App\\\\Models\\\\" . $model;
$return = "return \\[";

return "/{$modelNamespace}.*{$return}/sU";
}
}
2 changes: 1 addition & 1 deletion stubs/factory.blade.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,4 @@ public function definition(): array
@endforeach
];
}
}
}
30 changes: 0 additions & 30 deletions stubs/legacy_empty_factory.blade.php

This file was deleted.

7 changes: 0 additions & 7 deletions stubs/legacy_factory.blade.php

This file was deleted.

Loading