Преглед на файлове

Remove RouteRules strategy

Shalvah преди 3 месеца
родител
ревизия
540f36ad59

+ 1 - 1
phpunit.xml

@@ -27,7 +27,7 @@
     </php>
     <testsuites>
         <testsuite name="Non-Unit Tests">
-            <directory>tests/GenerateDocumentation/OutputTest.php</directory>
+            <directory>tests/GenerateDocumentation</directory>
             <directory>tests/Strategies</directory>
         </testsuite>
         <testsuite name="Unit Tests">

+ 0 - 1
src/Config/Defaults.php

@@ -25,7 +25,6 @@ class Defaults
     ];
 
     public const HEADERS_STRATEGIES = [
-        Strategies\Headers\GetFromRouteRules::class,
         Strategies\Headers\GetFromHeaderAttribute::class,
         Strategies\Headers\GetFromHeaderTag::class,
     ];

+ 0 - 14
src/Extracting/Strategies/Headers/GetFromRouteRules.php

@@ -1,14 +0,0 @@
-<?php
-
-namespace Knuckles\Scribe\Extracting\Strategies\Headers;
-
-use Knuckles\Camel\Extraction\ExtractedEndpointData;
-use Knuckles\Scribe\Extracting\Strategies\Strategy;
-
-class GetFromRouteRules extends Strategy
-{
-    public function __invoke(ExtractedEndpointData $endpointData, array $routeRules = []): array
-    {
-        return $routeRules['headers'] ?? [];
-    }
-}

+ 24 - 54
tests/GenerateDocumentation/BehavioursTest.php

@@ -24,14 +24,6 @@ class BehavioursTest extends BaseLaravelTest
     {
         parent::setUp();
 
-        $this->setConfig([
-            'database_connections_to_transact' => [],
-            'routes.0.match.prefixes' => ['api/*'],
-            // Skip these for faster tests
-            'openapi.enabled' => false,
-            'postman.enabled' => false,
-        ]);
-
         $factory = app(\Illuminate\Database\Eloquent\Factory::class);
         $factory->define(TestUser::class, function () {
             return [
@@ -52,20 +44,21 @@ class BehavioursTest extends BaseLaravelTest
     /** @test */
     public function can_process_traditional_laravel_route_syntax_and_callable_tuple_syntax()
     {
+        dump(config('scribe'));
         RouteFacade::get('/api/test', [TestController::class, 'withEndpointDescription']);
         RouteFacade::get('/api/array/test', [TestController::class, 'withEndpointDescription']);
 
-        $this->generateAndExpectConsoleOutput(
+        $this->generateAndExpectConsoleOutput(expected: [
             'Processed route: [GET] api/test',
             'Processed route: [GET] api/array/test'
-        );
+        ]);
     }
 
     /** @test */
     public function processes_head_routes_as_head_not_get()
     {
         RouteFacade::addRoute('HEAD', '/api/test', [TestController::class, 'withEndpointDescription']);
-        $this->generateAndExpectConsoleOutput('Processed route: [HEAD] api/test');
+        $this->generateAndExpectConsoleOutput(expected: ['Processed route: [HEAD] api/test']);
     }
 
     /**
@@ -74,10 +67,8 @@ class BehavioursTest extends BaseLaravelTest
      */
     public function can_process_closure_routes()
     {
-        RouteFacade::get('/api/closure', function () {
-            return 'hi';
-        });
-        $this->generateAndExpectConsoleOutput('Processed route: [GET] api/closure');
+        RouteFacade::get('/api/closure', fn() => 'hi');
+        $this->generateAndExpectConsoleOutput(expected: ['Processed route: [GET] api/closure']);
     }
 
     /** @test */
@@ -111,7 +102,7 @@ class BehavioursTest extends BaseLaravelTest
     {
         $commandInstance = null;
 
-        Scribe::bootstrap(function (GenerateDocumentation $command) use (&$commandInstance){
+        Scribe::bootstrap(function (GenerateDocumentation $command) use (&$commandInstance) {
             $commandInstance = $command;
         });
 
@@ -131,33 +122,34 @@ class BehavioursTest extends BaseLaravelTest
         RouteFacade::get('/api/skipClass', TestIgnoreThisController::class . '@dummy');
         RouteFacade::get('/api/test', [TestController::class, 'withEndpointDescription']);
 
-        $this->generateAndExpectConsoleOutput(
+        $this->generateAndExpectConsoleOutput(expected: [
             'Skipping route: [GET] api/skip',
             'Skipping route: [GET] api/skipClass',
             'Processed route: [GET] api/test'
-        );
+        ]);
     }
 
     /** @test */
     public function warns_of_nonexistent_response_files()
     {
         RouteFacade::get('/api/non-existent', [TestController::class, 'withNonExistentResponseFile']);
-        $this->generateAndExpectConsoleOutput('@responseFile i-do-not-exist.json does not exist');
+        $this->generateAndExpectConsoleOutput(expected: ['@responseFile i-do-not-exist.json does not exist']);
     }
 
     /** @test */
     public function can_parse_resource_routes()
     {
-        RouteFacade::resource('/api/users', TestResourceController::class)
-            ->only(['index', 'store']);
-
-        $output = $this->generate();
-
-        $this->assertStringContainsString('Processed route: [GET] api/users', $output);
-        $this->assertStringContainsString('Processed route: [POST] api/users', $output);
+        RouteFacade::resource('/api/users', TestResourceController::class)->only(['index', 'store']);
 
-        $this->assertStringNotContainsString('Processed route: [PUT,PATCH] api/users/{user}', $output);
-        $this->assertStringNotContainsString('Processed route: [DELETE] api/users/{user}', $output);
+        $this->generateAndExpectConsoleOutput(
+            expected: [
+                'Processed route: [GET] api/users',
+                'Processed route: [POST] api/users'
+            ],
+            notExpected: [
+                'Processed route: [PUT,PATCH] api/users/{user}',
+                'Processed route: [DELETE] api/users/{user}',]
+        );
     }
 
     /** @test */
@@ -165,10 +157,10 @@ class BehavioursTest extends BaseLaravelTest
     {
         RouteFacade::resource('/api/users', TestPartialResourceController::class);
 
-        $this->generateAndExpectConsoleOutput(
+        $this->generateAndExpectConsoleOutput(expected: [
             'Processed route: [GET] api/users',
             'Processed route: [PUT,PATCH] api/users/{user}'
-        );
+        ]);
     }
 
     /** @test */
@@ -186,35 +178,13 @@ class BehavioursTest extends BaseLaravelTest
         Utils::deleteDirectoryAndContents('static/');
     }
 
-    /** @test */
-    public function checks_for_upgrades_after_run_unless_disabled()
-    {
-        file_put_contents("config/scribe_test.php", str_replace("'logo' => false,", "", file_get_contents("config/scribe.php")));
-        config(["scribe_test" => require "config/scribe_test.php"]);
-
-        $output = $this->artisan('scribe:generate', ['--config' => 'scribe_test']);
-
-        if (! FileFacade::exists(config_path("scribe.php"))) {
-            $this->assertStringContainsString("No config file to upgrade.", $output);
-        } else {
-            $this->assertStringContainsString("Checking for any pending upgrades to your config file...", $output);
-            $this->assertStringContainsString("`logo` will be added", $output);
-        }
-
-        $output = $this->artisan('scribe:generate', ['--config' => 'scribe_test', '--no-upgrade-check' => true]);
-        $this->assertStringNotContainsString("Checking for any pending upgrades to your config file...", $output);
-
-        unlink("config/scribe_test.php");
-        Utils::deleteDirectoryAndContents(".scribe_test");
-    }
-
     /** @test */
     public function can_generate_with_apiresource_tag_but_without_apiresourcemodel_tag()
     {
         RouteFacade::get('/api/test', [TestController::class, 'withEmptyApiResource']);
-        $this->generateAndExpectConsoleOutput(
+        $this->generateAndExpectConsoleOutput(expected: [
             "Couldn't detect an Eloquent API resource model",
             'Processed route: [GET] api/test'
-        );
+        ]);
     }
 }

+ 47 - 85
tests/GenerateDocumentation/OutputTest.php

@@ -22,6 +22,8 @@ use Knuckles\Scribe\Tools\Utils;
 use Symfony\Component\DomCrawler\Crawler;
 use Symfony\Component\Yaml\Yaml;
 use Knuckles\Scribe\Extracting\Strategies;
+use function Knuckles\Scribe\Config\overrideResults;
+use function Knuckles\Scribe\Config\withConfiguredStrategy;
 
 class OutputTest extends BaseLaravelTest
 {
@@ -31,32 +33,6 @@ class OutputTest extends BaseLaravelTest
     {
         parent::setUp();
 
-        $this->setConfig(['strategies' => [
-            'metadata' => Defaults::metadataStrategies()->toArray(),
-            'urlParameters' => Defaults::urlParametersStrategies()->toArray(),
-            'queryParameters' => Defaults::queryParametersStrategies()->toArray(),
-            'headers' => Defaults::headersStrategies()->toArray(),
-            'bodyParameters' => Defaults::bodyParametersStrategies()->toArray(),
-            'responses' => Defaults::responsesStrategies()
-                ->configure(Strategies\Responses\ResponseCalls::withSettings(
-                    only: ['GET *'],
-                    config: [
-                        'app.env' => 'documentation',
-                        // 'app.debug' => false,
-                    ],
-                ))
-                ->toArray(),
-            'responseFields' => Defaults::responseFieldsStrategies()->toArray(),
-        ],
-        ]);
-        $this->setConfig(['database_connections_to_transact' => []]);
-        $this->setConfig(['routes.0.match.prefixes' => ['api/*']]);
-        // Skip these ones for faster tests
-        $this->setConfig(['openapi.enabled' => false]);
-        $this->setConfig(['postman.enabled' => false]);
-        // We want to have the same values for params each time
-        $this->setConfig(['examples.faker_seed' => 1234]);
-
         $factory = app(\Illuminate\Database\Eloquent\Factory::class);
         $factory->define(TestUser::class, function () {
             return [
@@ -74,37 +50,35 @@ class OutputTest extends BaseLaravelTest
         Utils::deleteDirectoryAndContents('.scribe');
     }
 
-    protected function usingLaravelTypeDocs($app)
-    {
-        $this->setConfig([
-            'type' => 'laravel',
-            'laravel.add_routes' => true,
-            'laravel.docs_url' => '/apidocs',
-        ]);
-    }
-
     /**
      * @test
-     * @define-env usingLaravelTypeDocs
      */
     public function generates_laravel_type_output()
     {
         RouteFacade::post('/api/withQueryParameters', [TestController::class, 'withQueryParameters']);
+        // This test breaks because the routes are not added, since the service provider has already been loaded.
+        // However, since we've switched default to Laravel type, we should switch default for tests as well
+        // TODO
+        $this->setConfig([
+            'type' => 'laravel',
+            'laravel.add_routes' => true,
+            'laravel.docs_url' => '/apidocs',
+        ]);
         $this->setConfig(['postman.enabled' => true]);
         $this->setConfig(['openapi.enabled' => true]);
 
-        $this->generateAndExpectConsoleOutput(
+        $this->generateAndExpectConsoleOutput(expected: [
             "Wrote Blade docs to: vendor/orchestra/testbench-core/laravel/resources/views/scribe",
             "Wrote Laravel assets to: vendor/orchestra/testbench-core/laravel/public/vendor/scribe",
             "Wrote Postman collection to: vendor/orchestra/testbench-core/laravel/storage/app/scribe/collection.json",
             "Wrote OpenAPI specification to: vendor/orchestra/testbench-core/laravel/storage/app/scribe/openapi.yaml",
-        );
+        ]);
 
         $this->assertFileExists($this->postmanOutputPath(true));
         $this->assertFileExists($this->openapiOutputPath(true));
         $this->assertFileExists($this->bladeOutputPath());
 
-        $response = $this->get('/apidocs/');
+        $response = $this->get('/apidocs');
         $response->assertStatus(200);
         $response = $this->get('/apidocs.postman');
         $response->assertStatus(200);
@@ -142,19 +116,12 @@ class OutputTest extends BaseLaravelTest
         if ($intermediateOutputDirectory) {
             $pathOptions["--scribe-dir"] = $intermediateOutputDirectory;
         }
-        $output = $this->generate($pathOptions);
-        $this->assertStringContainsString(
-            "Wrote Blade docs to: vendor/orchestra/testbench-core/laravel/resources/views/{$configName}", $output
-        );
-        $this->assertStringContainsString(
-            "Wrote Laravel assets to: vendor/orchestra/testbench-core/laravel/public/vendor/{$configName}", $output
-        );
-        $this->assertStringContainsString(
-            "Wrote Postman collection to: vendor/orchestra/testbench-core/laravel/storage/app/{$configName}/collection.json", $output
-        );
-        $this->assertStringContainsString(
-            "Wrote OpenAPI specification to: vendor/orchestra/testbench-core/laravel/storage/app/{$configName}/openapi.yaml", $output
-        );
+        $this->generateAndExpectConsoleOutput($pathOptions, [
+            "Wrote Blade docs to: vendor/orchestra/testbench-core/laravel/resources/views/{$configName}",
+            "Wrote Laravel assets to: vendor/orchestra/testbench-core/laravel/public/vendor/{$configName}",
+            "Wrote Postman collection to: vendor/orchestra/testbench-core/laravel/storage/app/{$configName}/collection.json",
+            "Wrote OpenAPI specification to: vendor/orchestra/testbench-core/laravel/storage/app/{$configName}/openapi.yaml",
+        ]);
 
         $paths = collect([
             Storage::disk('local')->path("{$configName}/collection.json"),
@@ -174,7 +141,6 @@ class OutputTest extends BaseLaravelTest
         if (phpversion() < 8.3) {
             // See https://github.com/FakerPHP/Faker/issues/694
             $this->markTestSkipped('Faker seeding changed in PHP 8.3');
-            return;
         }
 
         RouteFacade::post('/api/withBodyParametersAsArray', [TestController::class, 'withBodyParametersAsArray']);
@@ -190,15 +156,16 @@ class OutputTest extends BaseLaravelTest
             'postman.overrides' => [
                 'info.version' => '3.9.9',
             ],
-            'routes.0.apply.headers' => [
+            'strategies.headers' => overrideResults(config('scribe.strategies.headers'), [
                 'Custom-Header' => 'NotSoCustom',
-            ],
+            ]),
         ]);
+        $this->enableResponseCalls();
 
-        $this->generateAndExpectConsoleOutput(
+        $this->generateAndExpectConsoleOutput(expected: [
             "Wrote HTML docs and assets to: public/docs/",
             "Wrote Postman collection to: public/docs/collection.json"
-        );
+        ]);
 
         $generatedCollection = json_decode(file_get_contents($this->postmanOutputPath()), true);
         // The Postman ID varies from call to call; erase it to make the test data reproducible.
@@ -214,7 +181,6 @@ class OutputTest extends BaseLaravelTest
         if (phpversion() < 8.3) {
             // See https://github.com/FakerPHP/Faker/issues/694
             $this->markTestSkipped('Faker seeding changed in PHP 8.3');
-            return;
         }
 
         RouteFacade::post('/api/withBodyParametersAsArray', [TestController::class, 'withBodyParametersAsArray']);
@@ -229,15 +195,16 @@ class OutputTest extends BaseLaravelTest
             'openapi.overrides' => [
                 'info.version' => '3.9.9',
             ],
-            'routes.0.apply.headers' => [
+            'strategies.headers' => overrideResults(Defaults::HEADERS_STRATEGIES, [
                 'Custom-Header' => 'NotSoCustom',
-            ],
+            ]),
         ]);
+        $this->enableResponseCalls();
 
-        $this->generateAndExpectConsoleOutput(
+        $this->generateAndExpectConsoleOutput(expected: [
             "Wrote HTML docs and assets to: public/docs/",
             "Wrote OpenAPI specification to: public/docs/openapi.yaml"
-        );
+        ]);
 
         $generatedSpec = Yaml::parseFile($this->openapiOutputPath());
         $fixtureSpec = Yaml::parseFile(__DIR__ . '/../Fixtures/openapi.yaml');
@@ -249,10 +216,11 @@ class OutputTest extends BaseLaravelTest
     {
         RouteFacade::get('/api/headers', [TestController::class, 'checkCustomHeaders']);
         $this->setConfig([
-            'routes.0.apply.headers' => [
-                'Authorization' => 'customAuthToken',
-                'Custom-Header' => 'NotSoCustom',
-            ],
+            'strategies.headers' => overrideResults(Defaults::HEADERS_STRATEGIES, [
+                    'Authorization' => 'customAuthToken',
+                    'Custom-Header' => 'NotSoCustom',
+                ]
+            ),
         ]);
         $this->generate();
 
@@ -268,8 +236,7 @@ class OutputTest extends BaseLaravelTest
 
         $this->generate();
 
-        $generatedHtml = file_get_contents($this->htmlOutputPath());
-        $this->assertStringContainsString('Лорем ипсум долор сит амет', $generatedHtml);
+        $this->assertFileContainsString($this->htmlOutputPath(), 'Лорем ипсум долор сит амет');
     }
 
     /** @test */
@@ -420,7 +387,6 @@ class OutputTest extends BaseLaravelTest
         RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
         RouteFacade::get('/api/action2', [TestGroupController::class, 'action2']);
         $this->setConfig([
-            'routes.0.apply.response_calls.methods' => [],
             'groups.order' => [
                 '1. Group 1',
                 '5. Group 5',
@@ -468,7 +434,6 @@ class OutputTest extends BaseLaravelTest
     {
         RouteFacade::get('/api/action1', [TestGroupController::class, 'action1']);
         RouteFacade::get('/api/action1b', [TestGroupController::class, 'action1b']);
-        $this->setConfig(['routes.0.apply.response_calls.methods' => []]);
 
         $this->generate();
 
@@ -501,14 +466,14 @@ class OutputTest extends BaseLaravelTest
         $group = Yaml::parseFile($firstGroupFilePath);
         $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
         $this->assertEquals(['a_param' => $extraParam], $group['endpoints'][0]['urlParameters']);
-        $this->assertStringContainsString('Some other useful stuff.', file_get_contents($authFilePath));
+        $this->assertFileContainsString($authFilePath, 'Some other useful stuff.');
 
         $this->generate(['--force' => true]);
 
         $group = Yaml::parseFile($firstGroupFilePath);
         $this->assertEquals('api/action1', $group['endpoints'][0]['uri']);
         $this->assertEquals([], $group['endpoints'][0]['urlParameters']);
-        $this->assertStringNotContainsString('Some other useful stuff.', file_get_contents($authFilePath));
+        $this->assertFileNotContainsString($authFilePath, 'Some other useful stuff.');
     }
 
     /** @test */
@@ -519,8 +484,6 @@ class OutputTest extends BaseLaravelTest
                 'addresses' => 'address:uuid',
             ]);
         });
-        $this->setConfig(['routes.0.match.prefixes' => ['*']]);
-        $this->setConfig(['routes.0.apply.response_calls.methods' => []]);
 
         $this->generate();
 
@@ -536,9 +499,6 @@ class OutputTest extends BaseLaravelTest
         RouteFacade::resource('posts', TestPostController::class)->only('update');
         RouteFacade::resource('posts.users', TestPostUserController::class)->only('update');
 
-        $this->setConfig(['routes.0.match.prefixes' => ['*']]);
-        $this->setConfig(['routes.0.apply.response_calls.methods' => []]);
-
         $this->generate();
 
         $group = Yaml::parseFile('.scribe/endpoints/00.yaml');
@@ -553,9 +513,6 @@ class OutputTest extends BaseLaravelTest
 
         RouteFacade::resource('posts', TestPostBoundInterfaceController::class)->only('update');
 
-        $this->setConfig(['routes.0.match.prefixes' => ['*']]);
-        $this->setConfig(['routes.0.apply.response_calls.methods' => []]);
-
         $this->generate();
 
         $group = Yaml::parseFile('.scribe/endpoints/00.yaml');
@@ -568,9 +525,6 @@ class OutputTest extends BaseLaravelTest
         RouteFacade::get('posts/{post}/users', function (TestPost $post) {
         });
 
-        $this->setConfig(['routes.0.match.prefixes' => ['*']]);
-        $this->setConfig(['routes.0.apply.response_calls.methods' => []]);
-
         $this->generate();
 
         $group = Yaml::parseFile('.scribe/endpoints/00.yaml');
@@ -615,8 +569,6 @@ class OutputTest extends BaseLaravelTest
          * @bodyParam data.a_file file
          */
         RouteFacade::post('nested-file', fn() => null);
-        $this->setConfig(['routes.0.match.prefixes' => ['*']]);
-        $this->setConfig(['routes.0.apply.response_calls.methods' => []]);
 
         $this->generate();
 
@@ -651,4 +603,14 @@ class OutputTest extends BaseLaravelTest
     {
         return View::getFinder()->find('scribe/index');
     }
+
+    protected function enableResponseCalls(): void
+    {
+        $this->setConfig([
+            'strategies.responses' => withConfiguredStrategy(
+                config('scribe.strategies.responses'),
+                Strategies\Responses\ResponseCalls::withSettings(only: ['GET *'], except: [])
+            )
+        ]);
+    }
 }