Browse Source

More test cleanup

Shalvah 6 months ago
parent
commit
11b8216e52

+ 2 - 16
src/Extracting/Strategies/Responses/ResponseCalls.php

@@ -30,12 +30,8 @@ class ResponseCalls extends Strategy
 
     public function __invoke(ExtractedEndpointData $endpointData, array $settings = []): ?array
     {
-        return $this->makeResponseCallIfConditionsPass($endpointData, $settings);
-    }
-
-    public function makeResponseCallIfConditionsPass(ExtractedEndpointData $endpointData, array $settings): ?array
-    {
-        if (!$this->shouldMakeApiCall($endpointData)) {
+        // Don't attempt a response call if there are already successful responses
+        if ($endpointData->responses->hasSuccessResponse()) {
             return null;
         }
 
@@ -262,16 +258,6 @@ class ResponseCalls extends Strategy
         return $response;
     }
 
-    protected function shouldMakeApiCall(ExtractedEndpointData $endpointData): bool
-    {
-        // Don't attempt a response call if there are already successful responses
-        if ($endpointData->responses->hasSuccessResponse()) {
-            return false;
-        }
-
-        return true;
-    }
-
     /**
      * Transform headers array to array of $_SERVER vars with HTTP_* format.
      */

+ 62 - 1
tests/BaseLaravelTest.php

@@ -3,8 +3,12 @@
 namespace Knuckles\Scribe\Tests;
 
 use DMS\PHPUnitExtensions\ArraySubset\ArraySubsetAsserts;
+use Knuckles\Scribe\Config\AuthIn;
 use Knuckles\Scribe\ScribeServiceProvider;
 use Orchestra\Testbench\TestCase;
+use function Knuckles\Scribe\Config\withConfiguredStrategy;
+use Knuckles\Scribe\Config;
+use Knuckles\Scribe\Extracting\Strategies;
 
 class BaseLaravelTest extends TestCase
 {
@@ -41,11 +45,68 @@ class BaseLaravelTest extends TestCase
         return $providers;
     }
 
+    protected function setUp(): void
+    {
+        parent::setUp();
+
+        $this->setConfig(Config\Factory::make(
+            extracting: Config\Extracting::with(
+                routes: Config\Routes::match(prefixes: ['*']),
+                defaultGroup: 'Endpoints',
+                databaseConnectionsToTransact: [],
+                fakerSeedForExamples: 1234,
+                auth: Config\Extracting::auth(
+                    enabled: false,
+                    default: false,
+                    in: AuthIn::BEARER,
+                    useValue: env('SCRIBE_AUTH_KEY'),
+                    placeholder: '{YOUR_AUTH_KEY}',
+                ),
+                strategies: Config\Extracting::strategies(
+                    metadata: Config\Defaults::METADATA_STRATEGIES,
+                    urlParameters: Config\Defaults::URL_PARAMETERS_STRATEGIES,
+                    queryParameters: Config\Defaults::QUERY_PARAMETERS_STRATEGIES,
+                    headers: Config\Defaults::HEADERS_STRATEGIES,
+                    bodyParameters: Config\Defaults::BODY_PARAMETERS_STRATEGIES,
+                    responses: withConfiguredStrategy(
+                        Config\Defaults::RESPONSES_STRATEGIES,
+                        Strategies\Responses\ResponseCalls::withSettings(
+                            only: [],
+                            except: ['*'], // Disabled to speed up tests
+                            config: [
+                                'app.env' => 'documentation',
+                                // 'app.debug' => false,
+                            ],
+                            queryParams: [],
+                            bodyParams: [],
+                            fileParams: [],
+                            cookies: [],
+                        )),
+                    responseFields: Config\Defaults::RESPONSE_FIELDS_STRATEGIES,
+                )
+            ),
+            output: Config\Output::with(
+                type: Config\Output::staticType(
+                    theme: Config\InHouseTheme::Legacy,
+                ),
+                baseUrls: [
+                    "production" => config("app.base_url"),
+                ],
+                // Skip these for faster tests
+                postman: Config\Output::postman(
+                    enabled: false,
+                ),
+                openApi: Config\Output::openApi(
+                    enabled: false,
+                ),
+            )
+        ));
+    }
+
     protected function setConfig($configValues): void
     {
         foreach ($configValues as $key => $value) {
             config(["scribe.$key" => $value]);
-            config(["scribe_new.$key" => $value]);
         }
     }
 }

+ 44 - 89
tests/Strategies/Responses/ResponseCallsTest.php

@@ -17,34 +17,21 @@ use Symfony\Component\HttpFoundation\Request;
 
 class ResponseCallsTest extends BaseLaravelTest
 {
-    protected function setUp(): void
-    {
-        parent::setUp();
-        $this->setConfig(['database_connections_to_transact' => []]);
-    }
-
     /** @test */
     public function can_call_route_and_fetch_response()
     {
         $route = LaravelRouteFacade::post('/shouldFetchRouteResponse', [TestController::class, 'shouldFetchRouteResponse']);
 
-        $rules = [
-            'response_calls' => [
-                'methods' => ['*'],
-            ],
-        ];
-
-        $strategy = new ResponseCalls(new DocumentationConfig([]));
-        $results = $strategy(ExtractedEndpointData::fromRoute($route), $this->convertRules($rules));
+        $responses = $this->invokeStrategy($route, settings: ['methods' => '*']);
 
-        $this->assertEquals(200, $results[0]['status']);
+        $this->assertEquals(200, $responses[0]['status']);
         $this->assertArraySubset([
             'id' => 4,
             'name' => 'banana',
             'color' => 'red',
             'weight' => '1 kg',
             'delicious' => true,
-        ], json_decode($results[0]['content'], true));
+        ], json_decode($responses[0]['content'], true));
     }
 
     /** @test */
@@ -52,17 +39,8 @@ class ResponseCallsTest extends BaseLaravelTest
     {
         $route = RouteFacade::post('/withFormDataParams', [TestController::class, 'withFormDataParams']);
 
-        $this->setConfig([
-            'routes.0.apply.response_calls' => [],
-            'strategies.responses' => [
-                [ResponseCalls::class,
-                    ['only' => 'POST *']
-                ],
-            ]
-        ]);
-        $parsed = (new Extractor())->processRoute($route, config('scribe.routes.0.apply'));
+        $responses = $this->invokeStrategy($route, settings: ['methods' => 'POST *']);
 
-        $responses = $parsed->responses->toArray();
         $this->assertCount(1, $responses);
         $this->assertArraySubset([
             "status" => 200,
@@ -76,18 +54,6 @@ class ResponseCallsTest extends BaseLaravelTest
     {
         $route = LaravelRouteFacade::post('/echo/{id}', [TestController::class, 'echoesRequestValues']);
 
-        $rules = [
-            'response_calls' => [
-                'methods' => ['*'],
-                'queryParams' => [
-                    'queryParam' => 'queryValue',
-                ],
-                'bodyParams' => [
-                    'bodyParam' => 'bodyValue',
-                ],
-            ],
-        ];
-
         $endpointData = ExtractedEndpointData::fromRoute($route, [
             'auth' => ['headers', 'Authorization', 'Bearer bearerToken'],
             'headers' => [
@@ -97,13 +63,19 @@ class ResponseCallsTest extends BaseLaravelTest
             ],
         ]);
 
-        $strategy = new ResponseCalls(new DocumentationConfig([]));
-        $results = $strategy($endpointData,
-            $this->convertRules($rules));
+        $responses = $this->invokeStrategy($endpointData, settings: [
+            'methods' => ['*'],
+            'queryParams' => [
+                'queryParam' => 'queryValue',
+            ],
+            'bodyParams' => [
+                'bodyParam' => 'bodyValue',
+            ],
+        ]);
 
-        $this->assertEquals(200, $results[0]['status']);
+        $this->assertEquals(200, $responses[0]['status']);
 
-        $responseContent = json_decode($results[0]['content'], true);
+        $responseContent = json_decode($responses[0]['content'], true);
         $this->assertEquals('queryValue', $responseContent['queryParam']);
         $this->assertEquals('bodyValue', $responseContent['bodyParam']);
         $this->assertEquals('headerValue', $responseContent['header']);
@@ -114,29 +86,17 @@ class ResponseCallsTest extends BaseLaravelTest
     public function can_override_application_config_during_response_call()
     {
         $route = LaravelRouteFacade::post('/echoesConfig', [TestController::class, 'echoesConfig']);
-
-        $rules = [
-            'response_calls' => [
-                'methods' => ['*'],
-            ],
-        ];
-
-        $strategy = new ResponseCalls(new DocumentationConfig([]));
-        $results = $strategy(ExtractedEndpointData::fromRoute($route), $this->convertRules($rules));
-        $originalValue = json_decode($results[0]['content'], true)['app.env'];
+        $responses = $this->invokeStrategy($route, settings: ['methods' => '*']);
+        $originalValue = json_decode($responses[0]['content'], true)['app.env'];
 
         $now = time();
-        $rules = [
-            'response_calls' => [
-                'methods' => ['*'],
-                'config' => [
-                    'app.env' => $now,
-                ],
+        $responses = $this->invokeStrategy($route, settings: [
+            'methods' => ['*'],
+            'config' => [
+                'app.env' => $now,
             ],
-        ];
-
-        $results = $strategy(ExtractedEndpointData::fromRoute($route), $this->convertRules($rules));
-        $newValue = json_decode($results[0]['content'], true)['app.env'];
+        ],);
+        $newValue = json_decode($responses[0]['content'], true)['app.env'];
         $this->assertEquals($now, $newValue);
         $this->assertNotEquals($originalValue, $newValue);
     }
@@ -153,18 +113,6 @@ class ResponseCallsTest extends BaseLaravelTest
 
         $route = LaravelRouteFacade::post('/echo/{id}', [TestController::class, 'echoesRequestValues']);
 
-        $rules = [
-            'response_calls' => [
-                'methods' => ['*'],
-                'queryParams' => [
-                    'queryParam' => 'queryValue',
-                ],
-                'bodyParams' => [
-                    'bodyParam' => 'bodyValue',
-                ],
-            ],
-        ];
-
         $endpointData = ExtractedEndpointData::fromRoute($route, [
             'auth' => ['headers', 'Authorization', 'Bearer bearerToken'],
             'headers' => [
@@ -173,13 +121,19 @@ class ResponseCallsTest extends BaseLaravelTest
                 'header' => 'headerValue',
             ],
         ]);
+        $responses = $this->invokeStrategy($endpointData, settings: [
+            'methods' => ['*'],
+            'queryParams' => [
+                'queryParam' => 'queryValue',
+            ],
+            'bodyParams' => [
+                'bodyParam' => 'bodyValue',
+            ],
+        ]);
 
-        $strategy = new ResponseCalls(new DocumentationConfig([]));
-        $results = $strategy($endpointData, $this->convertRules($rules));
-
-        $this->assertEquals(200, $results[0]['status']);
+        $this->assertEquals(200, $responses[0]['status']);
 
-        $responseContent = json_decode($results[0]['content'], true);
+        $responseContent = json_decode($responses[0]['content'], true);
         $this->assertEquals('overridden_queryValue', $responseContent['queryParam']);
         $this->assertEquals('overridden_headerValue', $responseContent['header']);
         $this->assertEquals('overridden_Bearer bearerToken', $responseContent['auth']);
@@ -193,12 +147,6 @@ class ResponseCallsTest extends BaseLaravelTest
     {
         $route = LaravelRouteFacade::post('/shouldFetchRouteResponse', [TestController::class, 'shouldFetchRouteResponse']);
 
-        $rules = [
-            'response_calls' => [
-                'methods' => ['*'],
-            ],
-        ];
-
         $endpointData = ExtractedEndpointData::fromRoute($route, [
             'responses' => new ResponseCollection([
                 [
@@ -207,14 +155,21 @@ class ResponseCallsTest extends BaseLaravelTest
                 ],
             ]),
         ]);
-        $strategy = new ResponseCalls(new DocumentationConfig([]));
-        $results = $strategy($endpointData, $this->convertRules($rules));
+        $responses = $this->invokeStrategy($endpointData, settings: ['methods' => '*']);
 
-        $this->assertNull($results);
+        $this->assertNull($responses);
     }
 
     protected function convertRules(array $rules): mixed
     {
         return Extractor::transformOldRouteRulesIntoNewSettings('responses', $rules, ResponseCalls::class);
     }
+
+    protected function invokeStrategy(ExtractedEndpointData|Route $route, $settings): ?array
+    {
+        $strategy = new ResponseCalls(new DocumentationConfig([]));
+        return $strategy(
+            $route instanceof ExtractedEndpointData ? $route : ExtractedEndpointData::fromRoute($route), $settings
+        );
+    }
 }

+ 16 - 5
tests/TestHelpers.php

@@ -28,19 +28,30 @@ trait TestHelpers
         );
     }
 
-    protected function generateAndExpectConsoleOutput(string ...$expectedOutput): void
+    protected function generateAndExpectConsoleOutput(
+        array $options = [], array $expected = [], array $notExpected = []
+    ): void
     {
-        $output = $this->generate();
+        $output = $this->generate($options);
 
-        foreach ($expectedOutput as $expected) {
-            $this->assertStringContainsString($expected, $output);
+        foreach ($expected as $string) {
+            $this->assertStringContainsString($string, $output);
+        }
+
+        foreach ($notExpected as $string) {
+            $this->assertStringNotContainsString($string, $output);
         }
     }
 
     protected function assertFileContainsString(string $filePath, string $string)
     {
-        $this->assertFileExists($filePath);
         $fileContents = file_get_contents($filePath);
         $this->assertStringContainsString($string, $fileContents);
     }
+
+    protected function assertFileNotContainsString(string $filePath, string $string)
+    {
+        $fileContents = file_get_contents($filePath);
+        $this->assertStringNotContainsString($string, $fileContents);
+    }
 }

+ 0 - 15
tests/Unit/ExtractorTest.php

@@ -28,7 +28,6 @@ class ExtractorTest extends BaseLaravelTest
                 Strategies\QueryParameters\GetFromQueryParamTag::class,
             ],
             'headers' => [
-                Strategies\Headers\GetFromRouteRules::class,
                 Strategies\Headers\GetFromHeaderTag::class,
             ],
             'bodyParameters' => [
@@ -208,20 +207,6 @@ class ExtractorTest extends BaseLaravelTest
         $this->assertNotEmpty($parsed->responses);
     }
 
-    /** @test */
-    public function adds_override_for_headers_based_on_deprecated_route_apply_rules()
-    {
-        $this->config['strategies']['headers'] = [Strategies\Headers\GetFromRouteRules::class];
-
-        $extractor = $this->makeExtractor();
-        $route = $this->createRoute('GET', '/get', 'dummy');
-        $parsed = $extractor->processRoute($route, ['headers' => ['content-type' => 'application/json+vnd']]);
-        $this->assertArraySubset($parsed->headers, ['content-type' => 'application/json+vnd']);
-
-        $parsed = $extractor->processRoute($route);
-        $this->assertEmpty($parsed->headers);
-    }
-
     /** @test */
     public function adds_override_for_headers_based_on_strategy_configs()
     {