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 service provider tests #81

Open
wants to merge 32 commits into
base: 49-cover-entity-generator-with-tests
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
8f76f20
chore: remove redundant logic.
Dec 15, 2023
aaf4e67
test: add Nova test generator test case.
Dec 15, 2023
76dba4c
test: separate tests for Nova Resources and Nova tests.
Dec 15, 2023
1605125
Merge branch '42-extend-nova-resource-generator' into 49-add-tests
Dec 15, 2023
dfb9d07
test: add tests for Nova Resource.
Dec 15, 2023
ac6845c
test: add fixture.
Dec 15, 2023
c20b26f
test: add tests for controller generator.
Dec 16, 2023
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
fa2c9f7
Merge branch 'master' into 49-add-tests
Dec 20, 2023
90e983c
test: add tests for factory generator.
Dec 20, 2023
5fa7683
chore: remove useless methods.
Dec 20, 2023
c3baf27
Merge branch '49-add-tests' into 49-add-factory-tests
Dec 20, 2023
c1f3a1e
test: add migration generation test.
Dec 20, 2023
8c7116b
test: add model generation test.
Dec 20, 2023
ae0b552
test: add repository generator test skeleton.
Dec 21, 2023
11a1c0c
Merge branch 'master' into 49-add-repository-generator-tests
Dec 21, 2023
db89113
chore: correct tests.
Dec 21, 2023
6071eda
test: add tests for repository generator.
Dec 21, 2023
f7f1b13
chore: remove fixture export.
Dec 21, 2023
6dbec55
tests: add requests generator tests.
Dec 21, 2023
ad5725c
tests: add resource generator tests.
Dec 21, 2023
740edbd
tests: add seeder generator tests.
Dec 22, 2023
8739be5
tests: add service generator tests.
Dec 22, 2023
9771fca
tests: add tests generator tests.
Dec 23, 2023
956b3a8
tests: add tests generator tests.
Dec 26, 2023
ed10827
Merge branch 'master' into 49-add-tests-generator-tests
Jan 18, 2024
2a8ad56
test: add tests for test generator.
Jan 19, 2024
b61599f
test: add tests for translation file generation generator.
Jan 19, 2024
7762c0d
test: add tests for service provider.
Jan 19, 2024
05251b6
chore: remove fixture export.
Jan 19, 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
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
{
}
9 changes: 9 additions & 0 deletions src/Exceptions/UnknownFieldTypeException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php

namespace RonasIT\Support\Exceptions;

use Exception;

class UnknownFieldTypeException extends Exception
{
}
4 changes: 0 additions & 4 deletions src/Generators/AbstractTestsGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -169,10 +169,6 @@ protected function getModelFields($model): array

protected function getMockModel($model): array
{
if (!$this->isFactoryExists($model)) {
return [];
}

$modelClass = $this->getModelClass($model);
$hasFactory = method_exists($modelClass, 'factory') && $this->classExists('factory', "{$model}Factory");
$factory = ($hasFactory) ? $modelClass::factory() : factory($modelClass);
Expand Down
8 changes: 8 additions & 0 deletions src/Generators/EntityGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,14 @@ protected function saveClass($path, $name, $content, $additionalEntityFolder = f
{
$entitiesPath = base_path($this->paths[$path]);

$pathParts = explode('/', $entitiesPath);

if (Str::endsWith(Arr::last($pathParts), '.php')) {
array_pop($pathParts);
}

$entitiesPath = implode('/', $pathParts);

if ($additionalEntityFolder) {
$entitiesPath = $entitiesPath . "/{$additionalEntityFolder}";
}
Expand Down
54 changes: 34 additions & 20 deletions src/Generators/FactoryGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@
use Faker\Generator as Faker;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use InvalidArgumentException;
use RonasIT\Support\Exceptions\FakerMethodNotFoundException;
use RonasIT\Support\Exceptions\ModelFactoryNotFound;
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 @@ -32,7 +33,7 @@ protected function generateSeparateClass(): string
$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'."
"Create a {$this->model} Model by itself or run command 'php artisan make:entity {$this->model} --only-model'."
);
}

Expand Down Expand Up @@ -74,7 +75,7 @@ protected function generateToGenericClass(): string

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

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

$this->prepareRelatedFactories();
} else {
Expand All @@ -86,13 +87,18 @@ protected function generateToGenericClass(): string

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

event(new SuccessCreateMessage($createMessage));
}

protected function allowedToCreateFactoryInSeparateClass(): bool
{
return version_compare(app()->version(), '8', '>=');
}

protected function prepareEmptyFactory(): void
{
$stubPath = config('entity-generator.stubs.legacy_empty_factory');
Expand All @@ -102,16 +108,18 @@ protected function prepareEmptyFactory(): void

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

$databaseFactoryDir = base_path($databaseFactoryDir);

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

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

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

Expand All @@ -122,8 +130,9 @@ protected function checkExistRelatedModelsFactories(): bool
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'."
"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'."
);
}
}
Expand All @@ -146,8 +155,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);
$message = "Cannot generate fake data for unsupported {$field['type']} field type. "
. "Supported custom field types are " . implode(', ', array_keys(self::CUSTOM_METHODS));

throw new FakerMethodNotFoundException($message);
}

protected function prepareRelatedFactories(): void
Expand All @@ -158,12 +169,12 @@ protected function prepareRelatedFactories(): void
);

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

if (!Str::contains($modelFactoryContent, $this->getModelClass($relation))) {
$this->throwFailureException(
ModelFactoryNotFound::class,
"Model factory for mode {$relation} not found.",
"Model factory for model {$relation} not found.",
"Please create it and after thar you can run this command with flag '--only-tests'."
);
}
Expand All @@ -180,7 +191,7 @@ protected function prepareRelatedFactories(): void
$modelFactoryContent = str_replace($match, $match . $newField, $modelFactoryContent);
}

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

Expand All @@ -193,20 +204,23 @@ 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']);
$modelFactoryContent = file_get_contents(base_path($this->paths['factory']));
$modelNamespace = $this->getOrCreateNamespace('models');
$factoryClass = "{$modelNamespace}\\$this->model::class";

Expand Down Expand Up @@ -262,8 +276,8 @@ protected function getModelClassContent($model): string
if (!$this->classExists('models', $model)) {
$this->throwFailureException(
ClassNotExistsException::class,
"Cannot create {$model} Model cause {$model} Model does not exists.",
"Create a {$model} Model by himself or run command 'php artisan make:entity {$model} --only-model'."
"Cannot get {$model} Model class content cause {$model} Model does not exists.",
"Create a {$model} Model by itself or run command 'php artisan make:entity {$model} --only-model'."
);
}

Expand Down
7 changes: 4 additions & 3 deletions src/Generators/MigrationGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
namespace RonasIT\Support\Generators;

use Carbon\Carbon;
use Exception;
use Illuminate\Support\Arr;
use RonasIT\Support\Events\SuccessCreateMessage;
use RonasIT\Support\Exceptions\UnknownFieldTypeException;

class MigrationGenerator extends EntityGenerator
{
Expand Down Expand Up @@ -34,7 +35,7 @@ protected function isJson($typeName): bool

protected function isRequired($typeName): bool
{
return !empty(explode('-', $typeName)[1]);
return Arr::get(explode('-', $typeName), 1) === 'required';
}

protected function isNullable($typeName): bool
Expand Down Expand Up @@ -96,6 +97,6 @@ protected function getTableRow($fieldName, $typeName): string
return $this->getNonRequiredLine($fieldName, $typeName);
}

throw new Exception('Unknown fieldType in MigrationGenerator');
throw new UnknownFieldTypeException("Unknown field type {$typeName} in MigrationGenerator.");
}
}
6 changes: 3 additions & 3 deletions src/Generators/ModelGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ public function prepareRelatedModels(): void
if (!$this->classExists('models', $relation)) {
$this->throwFailureException(
ClassNotExistsException::class,
"Cannot create {$relation} Model cause {$relation} Model does not exists.",
"Create a {$relation} Model by himself or run command 'php artisan make:entity {$relation} --only-model'."
"Cannot create {$this->model} Model cause relation model {$relation} does not exist.",
"Create the {$relation} Model by himself or run command 'php artisan make:entity {$relation} --only-model'."
);
}

Expand Down Expand Up @@ -115,7 +115,7 @@ protected function getCasts($fields): array
$result = [];

foreach ($fields as $fieldType => $names) {
if (empty($casts[$fieldType])) {
if (!array_key_exists($fieldType, $casts)) {
continue;
}

Expand Down
4 changes: 0 additions & 4 deletions src/Generators/NovaTestGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,6 @@ protected function getActions(): array
{
$actions = $this->loadNovaActions();

if (empty($actions)) {
return [];
}

$actions = array_unique(array_map(function ($action) {
return get_class($action);
}, $actions));
Expand Down
23 changes: 15 additions & 8 deletions src/Generators/SeederGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,28 +15,30 @@ public function __construct()
{
parent::__construct();

$this->seedsPath = Arr::get($this->paths, 'seeders', 'database/seeders');
$this->databaseSeederPath = Arr::get($this->paths, 'database_seeder', 'database/seeders/DatabaseSeeder.php');
$this->seedsPath = base_path(Arr::get($this->paths, 'seeders', 'database/seeders'));
$this->databaseSeederPath = base_path(Arr::get($this->paths, 'database_seeder', 'database/seeders/DatabaseSeeder.php'));
}

public function generate(): void
{
$this->checkConfigs();

if (!file_exists($this->seedsPath)) {
mkdir($this->seedsPath);
}

if (!file_exists($this->databaseSeederPath)) {
list($basePath, $databaseSeederDir) = extract_last_part($this->databaseSeederPath, '/');

$databaseSeederDir = base_path($databaseSeederDir);

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

$this->createDatabaseSeeder();
}

if (!is_dir($this->seedsPath)) {
mkdir($this->seedsPath);
}

$this->createEntitySeeder();

$this->appendSeederToList();
Expand All @@ -59,7 +61,7 @@ protected function createDatabaseSeeder(): void

protected function createEntitySeeder(): void
{
$seeder = (version_compare(app()->version(), '8', '>=')) ? 'seeder' : 'legacy_seeder';
$seeder = ($this->useClassStyleSeeder()) ? 'seeder' : 'legacy_seeder';

$stubPath = config("entity-generator.stubs.{$seeder}");

Expand All @@ -70,7 +72,7 @@ protected function createEntitySeeder(): void
'modelsNamespace' => $this->getOrCreateNamespace('models')
])->render();

$seederPath = base_path("{$this->seedsPath}/{$this->model}Seeder.php");
$seederPath = "{$this->seedsPath}/{$this->model}Seeder.php";

file_put_contents($seederPath, $content);

Expand All @@ -79,6 +81,11 @@ protected function createEntitySeeder(): void
event(new SuccessCreateMessage($createMessage));
}

protected function useClassStyleSeeder(): bool
{
return version_compare(app()->version(), '8', '>=');
}

protected function appendSeederToList(): void
{
$content = file_get_contents($this->databaseSeederPath);
Expand Down
18 changes: 0 additions & 18 deletions src/Generators/TestsGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,6 @@ public function getTestClassName(): string
return "{$this->model}Test";
}

protected function generateExistedEntityFixture()
{
$object = $this->getFixtureValuesList($this->model);
$entity = Str::snake($this->model);

foreach (self::FIXTURE_TYPES as $type => $modifications) {
if ($this->isFixtureNeeded($type)) {
foreach ($modifications as $modification) {
$excepts = [];
if ($modification === 'request') {
$excepts = ['id'];
}
$this->generateFixture("{$type}_{$entity}_{$modification}.json", Arr::except($object, $excepts));
}
}
}
}

protected function isFixtureNeeded($type): bool
{
$firstLetter = strtoupper($type[0]);
Expand Down
6 changes: 3 additions & 3 deletions src/Generators/TranslationsGenerator.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ public function __construct()
{
parent::__construct();

$this->translationPath = Arr::get($this->paths, 'translations', 'resources/lang/en/validation.php');
$this->translationPath = base_path(Arr::get($this->paths, 'translations', 'resources/lang/en/validation.php'));
}

public function generate(): void
Expand All @@ -29,7 +29,7 @@ public function generate(): void

protected function isTranslationMissed($translation) : bool
{
return __($translation) === 'validation.exceptions.not_found';
return __($translation) !== 'validation.exceptions.not_found';
}

protected function createTranslate(): void
Expand Down Expand Up @@ -57,4 +57,4 @@ protected function appendNotFoundException(): void

file_put_contents($this->translationPath, $fixedContent);
}
}
}
Loading