├── .php_cs ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE.md ├── README.md ├── SECURITY.md ├── composer.json ├── config └── test_generator.php ├── psalm.xml └── src ├── Commands └── GeneratorCommand.php ├── Filter.php ├── Generator.php ├── Generators └── PHPUnitGenerator.php ├── LaravelTestGeneratorServiceProvider.php ├── RouteParser.php ├── TestGeneratorManager.php └── TestMethod.php /.php_cs: -------------------------------------------------------------------------------- 1 | notPath('bootstrap/*') 5 | ->notPath('storage/*') 6 | ->notPath('resources/view/mail/*') 7 | ->in([ 8 | __DIR__ . '/src', 9 | __DIR__ . '/tests', 10 | ]) 11 | ->name('*.php') 12 | ->notName('*.blade.php') 13 | ->ignoreDotFiles(true) 14 | ->ignoreVCS(true); 15 | 16 | return PhpCsFixer\Config::create() 17 | ->setRules([ 18 | '@PSR2' => true, 19 | 'array_syntax' => ['syntax' => 'short'], 20 | 'single_quote' => true, 21 | 'ordered_imports' => ['sortAlgorithm' => 'alpha'], 22 | 'no_unused_imports' => true, 23 | 'not_operator_with_successor_space' => false, 24 | 'trailing_comma_in_multiline_array' => true, 25 | 'phpdoc_scalar' => true, 26 | 'unary_operator_spaces' => true, 27 | 'binary_operator_spaces' => true, 28 | 'blank_line_before_statement' => [ 29 | 'statements' => ['break', 'continue', 'declare', 'return', 'throw', 'try'], 30 | ], 31 | 'phpdoc_single_line_var_spacing' => true, 32 | 'phpdoc_var_without_name' => true, 33 | 'method_argument_space' => [ 34 | 'on_multiline' => 'ensure_fully_multiline', 35 | 'keep_multiple_spaces_after_comma' => true, 36 | ] 37 | ]) 38 | ->setFinder($finder); 39 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to `laravel-test-generator` will be documented in this file 4 | 5 | ## 0.1.0 - 2020-07-31 6 | 7 | - initial release 8 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Contributions are **welcome** and will be fully **credited**. 4 | 5 | Please read and understand the contribution guide before creating an issue or pull request. 6 | 7 | ## Etiquette 8 | 9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code 10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be 11 | extremely unfair for them to suffer abuse or anger for their hard work. 12 | 13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the 14 | world that developers are civilized and selfless people. 15 | 16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient 17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used. 18 | 19 | ## Viability 20 | 21 | When requesting or submitting new features, first consider whether it might be useful to others. Open 22 | source projects are used by many developers, who may have entirely different needs to your own. Think about 23 | whether or not your feature is likely to be used by other users of the project. 24 | 25 | ## Procedure 26 | 27 | Before filing an issue: 28 | 29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident. 30 | - Check to make sure your feature suggestion isn't already present within the project. 31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress. 32 | - Check the pull requests tab to ensure that the feature isn't already in progress. 33 | 34 | Before submitting a pull request: 35 | 36 | - Check the codebase to ensure that your feature doesn't already exist. 37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix. 38 | 39 | ## Requirements 40 | 41 | If the project maintainer has any additional requirements, you will find them listed here. 42 | 43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer). 44 | 45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests. 46 | 47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date. 48 | 49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option. 50 | 51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests. 52 | 53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting. 54 | 55 | **Happy coding**! 56 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) Jarek Tkaczyk 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in 13 | all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | THE SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Laravel feature test generator 2 | 3 | [![Latest Version on Packagist](https://img.shields.io/packagist/v/sofa/laravel-test-generator.svg?style=flat-square)](https://packagist.org/packages/jarektkaczyk/laravel-test-generator) 4 | [![GitHub Tests Action Status](https://github.com/jarektkaczyk/laravel-test-generator/workflows/Tests/badge.svg)](https://github.com/jarektkaczyk/laravel-test-generator/actions?query=workflow%3Atests+branch%3Amaster) 5 | [![Total Downloads](https://img.shields.io/packagist/dt/sofa/laravel-test-generator.svg?style=flat-square)](https://packagist.org/packages/jarektkaczyk/laravel-test-generator) 6 | 7 | 8 | Don't write boilerplate for your feature tests! This package scans all the routes in your Laravel app and generates skeleton for testing them. 9 | 10 | ## Installation 11 | 12 | You can install the package via composer: 13 | 14 | ```bash 15 | composer require jarektkaczyk/package-laravel-test-generator-laravel 16 | ``` 17 | 18 | You can publish the config file with and customize it afterwards in `config/test_generator.php`: 19 | ```bash 20 | php artisan vendor:publish --provider="Sofa\LaravelTestGenerator\LaravelTestGeneratorServiceProvider" --tag="config" 21 | ``` 22 | 23 | ## Usage 24 | 25 | ``` php 26 | php artisan generate:feature-tests 27 | ``` 28 | 29 | ## Roadmap 30 | 31 | - [x] support for PHPUnit driver 32 | * [x] generate new test classes 33 | * [x] bare happy path case 34 | * [x] bare failing path case 35 | * [ ] parse route model binding and build setup for tests accordingly 36 | * [ ] (OPTIONAL) parse requests and build setup for tests accordingly - might be too complex in many cases 37 | * [ ] (OPTIONAL) update existing test classes with new methods (not trivial with `nette/php-generator`, find better way?) 38 | - [x] support for different drivers 39 | - [ ] (OPTIONAL) other drivers 40 | 41 | ## Testing 42 | 43 | ``` bash 44 | composer test 45 | ``` 46 | 47 | ## Changelog 48 | 49 | Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently. 50 | 51 | ## Contributing 52 | 53 | Please see [CONTRIBUTING](CONTRIBUTING.md) for details. 54 | 55 | ## Security 56 | 57 | If you discover any security related issues, please email jarek@softonsofa.com instead of using the issue tracker. 58 | 59 | ## Credits 60 | 61 | - [Jarek Tkaczyk](https://github.com/jarektkaczyk) 62 | - [All Contributors](../../contributors) 63 | 64 | ## License 65 | 66 | The MIT License (MIT). Please see [License File](LICENSE.md) for more information. 67 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Reporting a Vulnerability 4 | 5 | If you discover any security related issues, please email freek@spatie.be instead of using the issue tracker. 6 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "sofa/laravel-test-generator", 3 | "description": "Don't write boilerplate for your feature tests in a Laravel project", 4 | "keywords": [ 5 | "laravel-test-generator" 6 | ], 7 | "homepage": "https://github.com/jarektkaczyk/laravel-test-generator", 8 | "license": "MIT", 9 | "authors": [ 10 | { 11 | "name": "Jarek Tkaczyk", 12 | "email": "jarek@softonsofa.com", 13 | "homepage": "https://softonsofa.com", 14 | "role": "Developer" 15 | } 16 | ], 17 | "require": { 18 | "php": "^7.4", 19 | "illuminate/routing": "7.*", 20 | "nette/php-generator": "^3.4" 21 | }, 22 | "require-dev": { 23 | "friendsofphp/php-cs-fixer": "^2.16", 24 | "phpunit/phpunit": "^9.0" 25 | }, 26 | "autoload": { 27 | "psr-4": { 28 | "Sofa\\LaravelTestGenerator\\": "src" 29 | } 30 | }, 31 | "autoload-dev": { 32 | "psr-4": { 33 | "Sofa\\LaravelTestGenerator\\Tests\\": "tests", 34 | "App\\Http\\Controllers\\": "tests/__fixtures__/Controllers", 35 | "LaravelTestGeneratorTests\\": "tests/__fixtures__/Tests" 36 | } 37 | }, 38 | "scripts": { 39 | "psalm": "vendor/bin/psalm", 40 | "test": "vendor/bin/phpunit", 41 | "test-coverage": "vendor/bin/phpunit --coverage-html coverage", 42 | "format": "vendor/bin/php-cs-fixer fix --allow-risky=yes" 43 | }, 44 | "config": { 45 | "sort-packages": true 46 | }, 47 | "extra": { 48 | "laravel": { 49 | "providers": [ 50 | "Sofa\\LaravelTestGenerator\\LaravelTestGeneratorServiceProvider" 51 | ], 52 | "aliases": { 53 | "LaravelTestGenerator": "Sofa\\LaravelTestGenerator\\LaravelTestGeneratorFacade" 54 | } 55 | } 56 | }, 57 | "minimum-stability": "dev", 58 | "prefer-stable": true 59 | } 60 | -------------------------------------------------------------------------------- /config/test_generator.php: -------------------------------------------------------------------------------- 1 | 'phpunit', 12 | 13 | 'drivers' => [ 14 | 'phpunit' => [ 15 | /** 16 | * PHPUnit test method naming @link https://phpunit.readthedocs.io/en/9.2/writing-tests-for-phpunit.html 17 | * - `prefix` -> create methods with 'test' prefix 18 | * - `annotation` -> create methods with '@test' annotation 19 | */ 20 | 'method_naming' => 'prefix', 21 | 22 | /** 23 | * Test method naming case 24 | * - `snake` -> 'test_some_method()' 25 | * - `camel` -> 'testSomeMethod()' 26 | */ 27 | 'method_case' => 'snake', 28 | 29 | /** 30 | * Your base application root namespace 31 | */ 32 | 'base_namespace' => 'App', 33 | 34 | /** 35 | * Base namespace for generated Feature tests 36 | */ 37 | 'tests_namespace' => 'Tests\Feature', 38 | 39 | /** 40 | * Base path where tests will be generated 41 | */ 42 | 'tests_base_path' => base_path('tests/Feature'), 43 | 44 | /** 45 | * Default TestCase class in a Laravel app that generated tests will extend 46 | */ 47 | 'base_test_case' => 'Tests\TestCase', 48 | ], 49 | ], 50 | ]; 51 | -------------------------------------------------------------------------------- /psalm.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /src/Commands/GeneratorCommand.php: -------------------------------------------------------------------------------- 1 | getRoutes()->getRoutes()); 22 | 23 | $routes 24 | // 1. build configuration for tests 25 | ->map(fn (Route $route): RouteParser => new RouteParser($route)) 26 | ->map(fn (RouteParser $route) => [ 27 | $generator->generateHappyPath($route), 28 | $route->needsFailingPath() ? $generator->generateFailingPath($route) : null, 29 | ]) 30 | ->collapse()->filter() 31 | // 2. filter out non-applicable routes 32 | ->filter(new Filter) 33 | // 4. group by test class 34 | ->groupBy(fn (TestMethod $test) => $test->classname) 35 | ->each(fn (Collection $tests, string $classname) => $generator->generateTestFile($classname, $tests)); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/Filter.php: -------------------------------------------------------------------------------- 1 | classname); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/Generator.php: -------------------------------------------------------------------------------- 1 | $tests 28 | */ 29 | public function generateTestFile(string $fqcn, Collection $tests): void; 30 | } 31 | -------------------------------------------------------------------------------- /src/Generators/PHPUnitGenerator.php: -------------------------------------------------------------------------------- 1 | config = $config + [ 21 | 'method_naming' => 'prefix', 22 | 'method_case' => 'snake', 23 | 'base_namespace' => 'App', 24 | 'tests_namespace' => 'Tests\Feature', 25 | 'tests_base_path' => __DIR__ . '/../../../../tests/Feature', 26 | 'base_test_case' => 'Tests\TestCase', 27 | ]; 28 | } 29 | 30 | public function generateHappyPath(RouteParser $route): TestMethod 31 | { 32 | return $this->generateTestMethod($route); 33 | } 34 | 35 | public function generateFailingPath(RouteParser $route): TestMethod 36 | { 37 | return $this->generateTestMethod($route, false); 38 | } 39 | 40 | private function generateHappyPathExpression(RouteParser $route): string 41 | { 42 | // TODO add setup for test method 43 | $setup = ''; 44 | $uri = str_replace('{user}', '0', $route->getUri()); 45 | 46 | $payload = in_array($route->getHttpMethod(), ['POST', 'PUT', 'PATCH']) 47 | ? ', [/* valid payload here */]' 48 | : ''; 49 | 50 | return trim(vsprintf("%s\n\n\$this->%s('%s'%s)->assertStatus(%d);", [ 51 | $setup, 52 | strtolower($route->getHttpMethod()), 53 | $uri, 54 | $payload, 55 | $route->getSuccessHttpCode(), 56 | ])); 57 | } 58 | 59 | private function generateFailingExpression(RouteParser $route): string 60 | { 61 | $setup = ''; 62 | $uri = str_replace('{user}', '0', $route->getUri()); 63 | 64 | $payload = in_array($route->getHttpMethod(), ['POST', 'PUT', 'PATCH']) 65 | ? ', [/* invalid payload here */]' 66 | : ''; 67 | 68 | return trim(vsprintf("%s\n\n\$this->%s('%s'%s)->assertStatus(%d);", [ 69 | $setup, 70 | strtolower($route->getHttpMethod()), 71 | $uri, 72 | $payload, 73 | $route->getErrorHttpCode(), 74 | ])); 75 | } 76 | 77 | /** 78 | * @param RouteParser $route 79 | * @param bool $happy 80 | * @return TestMethod 81 | */ 82 | private function generateTestMethod(RouteParser $route, bool $happy = true): TestMethod 83 | { 84 | $test = new TestMethod; 85 | 86 | // test class name 87 | $test->classname = str_replace( 88 | $this->config['base_namespace'], 89 | $this->config['tests_namespace'], 90 | $route->getControllerClassname() . 'Test', 91 | ); 92 | 93 | // test method name 94 | $case = $this->config['method_case']; 95 | $testMethod = $route->getControllerMethod(); 96 | 97 | if (!$happy) { 98 | $testMethod .= '_failing'; 99 | } 100 | 101 | if ($this->config['method_naming'] === 'annotation') { 102 | $test->test_annotation = true; 103 | $test->name = Str::$case($testMethod); 104 | } else { 105 | $test->name = Str::$case('test_' . $testMethod); 106 | } 107 | 108 | $test->expression = $happy 109 | ? $this->generateHappyPathExpression($route) 110 | : $this->generateFailingExpression($route); 111 | 112 | return $test; 113 | } 114 | 115 | public function getTestFilePath(string $classname): string 116 | { 117 | $relativePath = str_replace($this->config['tests_namespace'], '', $classname) . '.php'; 118 | 119 | return sprintf( 120 | '%s/%s', 121 | $this->config['tests_base_path'], 122 | trim(str_replace('\\', '/', $relativePath), '/'), 123 | ); 124 | } 125 | 126 | /** 127 | * @param string $fqcn 128 | * @param Collection|TestMethod[] $tests 129 | * @psalm-param Collection $tests 130 | */ 131 | public function generateTestFile(string $fqcn, Collection $tests): void 132 | { 133 | $path = $this->getTestFilePath($fqcn); 134 | 135 | $directory = pathinfo($path, PATHINFO_DIRNAME); 136 | 137 | if (!file_exists($directory)) { 138 | mkdir($directory, 0777, true); 139 | } 140 | 141 | $testClassname = class_basename($fqcn); 142 | $namespace = trim(str_replace($testClassname, '', $fqcn), '\\'); 143 | $ns = new PhpNamespace($namespace); 144 | $ns->addUse($this->config['base_test_case']); 145 | $class = $ns->addClass($testClassname); 146 | $class->setExtends($this->config['base_test_case']); 147 | 148 | // parse existing file and check which methods need to be added 149 | foreach ($tests as $test) { 150 | if (!$class->hasMethod($test->name)) { 151 | $method = $class->addMethod($test->name); 152 | $method->addBody($test->expression); 153 | if ($test->test_annotation) { 154 | $method->addComment('@test'); 155 | } 156 | } 157 | } 158 | 159 | $printer = new PsrPrinter; 160 | 161 | file_put_contents($path, "printNamespace($ns)); 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /src/LaravelTestGeneratorServiceProvider.php: -------------------------------------------------------------------------------- 1 | app->runningInConsole()) { 13 | $this->publishes([ 14 | __DIR__.'/../config/test_generator.php' => config_path('test_generator.php'), 15 | ], 'config'); 16 | 17 | $this->commands([ 18 | GeneratorCommand::class, 19 | ]); 20 | } 21 | 22 | $this->loadViewsFrom(__DIR__.'/../resources/views', 'laravel-test-generator'); 23 | } 24 | 25 | public function register() 26 | { 27 | $this->mergeConfigFrom(__DIR__ . '/../config/test_generator.php', 'laravel-test-generator'); 28 | 29 | $this->app->bind(Generator::class, fn (): Generator => app(TestGeneratorManager::class)->driver()); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/RouteParser.php: -------------------------------------------------------------------------------- 1 | route = $route; 17 | } 18 | 19 | public function getControllerClassname(): string 20 | { 21 | return get_class($this->route->getController()); 22 | } 23 | 24 | public function getControllerMethod(): string 25 | { 26 | return $this->route->getActionMethod(); 27 | } 28 | 29 | public function getHttpMethod(): string 30 | { 31 | return strtoupper(Arr::first($this->route->methods())); 32 | } 33 | 34 | public function getUri(): string 35 | { 36 | return $this->route->uri(); 37 | } 38 | 39 | public function getSuccessHttpCode(): int 40 | { 41 | return $this->getHttpMethod() === 'POST' 42 | ? Response::HTTP_CREATED 43 | : Response::HTTP_OK; 44 | } 45 | 46 | public function getErrorHttpCode(): int 47 | { 48 | return in_array($this->getHttpMethod(), ['POST', 'PUT', 'PATCH']) 49 | ? Response::HTTP_UNPROCESSABLE_ENTITY 50 | : Response::HTTP_NOT_FOUND; 51 | } 52 | 53 | public function needsFailingPath(): bool 54 | { 55 | return $this->getErrorHttpCode() === Response::HTTP_UNPROCESSABLE_ENTITY 56 | || Str::contains($this->getUri(), '{'); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/TestGeneratorManager.php: -------------------------------------------------------------------------------- 1 | config->get('test_generator.driver'); 13 | } 14 | 15 | protected function createPhpunitDriver(): PHPUnitGenerator 16 | { 17 | return new PHPUnitGenerator( 18 | $this->config->get('test_generator.drivers.phpunit') 19 | ); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/TestMethod.php: -------------------------------------------------------------------------------- 1 | classname = $classname; 23 | $this->name = $name; 24 | $this->expression = $expression; 25 | $this->test_annotation = $test_annotation; 26 | } 27 | } 28 | --------------------------------------------------------------------------------