浏览代码

Clean up tests

shalvah 2 年之前
父节点
当前提交
f9e5ba37ce

+ 3 - 1
src/Extracting/Strategies/UrlParameters/GetFromLaravelAPI.php

@@ -37,7 +37,9 @@ class GetFromLaravelAPI extends Strategy
 
         $parameters = $this->inferBetterTypesAndExamplesForEloquentUrlParameters($parameters, $endpointData);
 
-        $parameters = $this->inferBetterTypesAndExamplesForEnumUrlParameters($parameters, $endpointData);
+        if (version_compare(PHP_VERSION, '8.1.0', '>=')) {
+            $parameters = $this->inferBetterTypesAndExamplesForEnumUrlParameters($parameters, $endpointData);
+        }
 
         $parameters = $this->setTypesAndExamplesForOthers($parameters, $endpointData);
 

+ 4 - 1
src/Tools/AnnotationParser.php

@@ -6,9 +6,12 @@ class AnnotationParser
 {
     /**
      * Parse an annotation like 'status=400 when="things go wrong" {"message": "failed"}'.
-     * Attributes are always optional and may appear at the start or the end of the string.
+     * Fields are always optional and may appear at the start or the end of the string.
      *
      * @param string $annotationContent
+     * @param array $allowedFields List of fields to look for.
+     *
+     * @return array{content: string, attributes: string[]}
      */
     public static function parseIntoContentAndAttributes(string $annotationContent, array $allowedAttributes): array
     {

+ 0 - 2
tests/Fixtures/TestController.php

@@ -312,8 +312,6 @@ class TestController extends Controller
      */
     public function withResponseTag()
     {
-        ExtractorTest::$globalValue = rand();
-
         return '';
     }
 

+ 19 - 17
tests/Strategies/GetFromFormRequestTest.php

@@ -21,9 +21,7 @@ class GetFromFormRequestTest extends BaseLaravelTest
     public function can_fetch_bodyparams_from_form_request()
     {
         $method = new \ReflectionMethod(TestController::class, 'withFormRequestParameter');
-
-        $strategy = new BodyParameters\GetFromFormRequest(new DocumentationConfig([]));
-        $results = $strategy->getParametersFromFormRequest($method);
+        $results = $this->fetchViaBodyParams($method);
 
         $this->assertArraySubset([
             'user_id' => [
@@ -105,10 +103,8 @@ class GetFromFormRequestTest extends BaseLaravelTest
     /** @test */
     public function can_fetch_queryparams_from_form_request()
     {
-        $strategy = new QueryParameters\GetFromFormRequest(new DocumentationConfig([]));
-
         $method = new \ReflectionMethod(TestController::class, 'withFormRequestParameterQueryParams');
-        $results = $strategy->getParametersFromFormRequest($method);
+        $results = $this->fetchViaQueryParams($method);
 
         $this->assertArraySubset([
             'q_param' => [
@@ -120,7 +116,7 @@ class GetFromFormRequestTest extends BaseLaravelTest
         ], $results);
 
         $method = new \ReflectionMethod(TestController::class, 'withFormRequestParameterQueryParamsComment');
-        $results = $strategy->getParametersFromFormRequest($method);
+        $results = $this->fetchViaQueryParams($method);
 
         $this->assertArraySubset([
             'type' => 'integer',
@@ -132,19 +128,14 @@ class GetFromFormRequestTest extends BaseLaravelTest
     /** @test */
     public function will_ignore_not_relevant_form_request()
     {
-        $queryParamsStrategy = new QueryParameters\GetFromFormRequest(new DocumentationConfig([]));
         $method = new \ReflectionMethod(TestController::class, 'withFormRequestParameter');
-        $results = $queryParamsStrategy->getParametersFromFormRequest($method);
-        $this->assertEquals([], $results);
+        $this->assertEquals([], $this->fetchViaQueryParams($method));
 
-        $bodyParamsStrategy = new BodyParameters\GetFromFormRequest(new DocumentationConfig([]));
         $method = new \ReflectionMethod(TestController::class, 'withFormRequestParameterQueryParams');
-        $results = $bodyParamsStrategy->getParametersFromFormRequest($method);
-        $this->assertEquals([], $results);
+        $this->assertEquals([], $this->fetchViaBodyParams($method));
 
         $method = new \ReflectionMethod(TestController::class, 'withFormRequestParameterQueryParamsComment');
-        $results = $bodyParamsStrategy->getParametersFromFormRequest($method);
-        $this->assertEquals([], $results);
+        $this->assertEquals([], $this->fetchViaBodyParams($method));
     }
 
     /** @test */
@@ -159,9 +150,20 @@ class GetFromFormRequestTest extends BaseLaravelTest
             return new TestRequestQueryParams;
         };
 
-        $strategy = new BodyParameters\GetFromFormRequest(new DocumentationConfig([]));
-        $strategy->getParametersFromFormRequest($controllerMethod);
+        $this->fetchViaBodyParams($controllerMethod);
 
         Globals::$__instantiateFormRequestUsing = null;
     }
+
+    protected function fetchViaBodyParams(\ReflectionMethod $method): array
+    {
+        $strategy = new BodyParameters\GetFromFormRequest(new DocumentationConfig([]));
+        return $strategy->getParametersFromFormRequest($method);
+    }
+
+    protected function fetchViaQueryParams(\ReflectionMethod $method): array
+    {
+        $strategy = new QueryParameters\GetFromFormRequest(new DocumentationConfig([]));
+        return $strategy->getParametersFromFormRequest($method);
+    }
 }

+ 49 - 54
tests/Strategies/GetFromInlineValidatorTest.php

@@ -2,6 +2,7 @@
 
 namespace Knuckles\Scribe\Tests\Strategies;
 
+use Closure;
 use Knuckles\Camel\Extraction\ExtractedEndpointData;
 use Knuckles\Scribe\Extracting\Strategies\BodyParameters;
 use Knuckles\Scribe\Extracting\Strategies\QueryParameters;
@@ -91,15 +92,11 @@ class GetFromInlineValidatorTest extends BaseLaravelTest
     /** @test */
     public function can_fetch_from_request_validate_assignment()
     {
-        $endpoint = new class extends ExtractedEndpointData {
-            public function __construct(array $parameters = [])
-            {
-                $this->method = new \ReflectionMethod(TestController::class, 'withInlineRequestValidate');
-            }
-        };
+        $endpoint = $this->endpoint(function (ExtractedEndpointData $e) {
+            $e->method = new \ReflectionMethod(TestController::class, 'withInlineRequestValidate');
+        });
 
-        $strategy = new BodyParameters\GetFromInlineValidator(new DocumentationConfig([]));
-        $results = $strategy($endpoint, []);
+        $results = $this->fetchViaBodyParams($endpoint);
 
         $this->assertArraySubset(self::$expected, $results);
         $this->assertIsArray($results['ids']['example']);
@@ -108,15 +105,11 @@ class GetFromInlineValidatorTest extends BaseLaravelTest
     /** @test */
     public function can_fetch_from_request_validate_expression()
     {
-        $endpoint = new class extends ExtractedEndpointData {
-            public function __construct(array $parameters = [])
-            {
-                $this->method = new \ReflectionMethod(TestController::class, 'withInlineRequestValidateNoAssignment');
-            }
-        };
+        $endpoint = $this->endpoint(function (ExtractedEndpointData $e) {
+            $e->method = new \ReflectionMethod(TestController::class, 'withInlineRequestValidateNoAssignment');
+        });
 
-        $strategy = new BodyParameters\GetFromInlineValidator(new DocumentationConfig([]));
-        $results = $strategy($endpoint, []);
+        $results = $this->fetchViaBodyParams($endpoint);
 
         $this->assertArraySubset(self::$expected, $results);
         $this->assertIsArray($results['ids']['example']);
@@ -125,15 +118,11 @@ class GetFromInlineValidatorTest extends BaseLaravelTest
     /** @test */
     public function can_fetch_from_request_validatewithbag()
     {
-        $endpoint = new class extends ExtractedEndpointData {
-            public function __construct(array $parameters = [])
-            {
-                $this->method = new \ReflectionMethod(TestController::class, 'withInlineRequestValidateWithBag');
-            }
-        };
+        $endpoint = $this->endpoint(function (ExtractedEndpointData $e) {
+            $e->method = new \ReflectionMethod(TestController::class, 'withInlineRequestValidateWithBag');
+        });
 
-        $strategy = new BodyParameters\GetFromInlineValidator(new DocumentationConfig([]));
-        $results = $strategy($endpoint, []);
+        $results = $this->fetchViaBodyParams($endpoint);
 
         $this->assertArraySubset(self::$expected, $results);
         $this->assertIsArray($results['ids']['example']);
@@ -142,15 +131,11 @@ class GetFromInlineValidatorTest extends BaseLaravelTest
     /** @test */
     public function can_fetch_from_this_validate()
     {
-        $endpoint = new class extends ExtractedEndpointData {
-            public function __construct(array $parameters = [])
-            {
-                $this->method = new \ReflectionMethod(TestController::class, 'withInlineThisValidate');
-            }
-        };
+        $endpoint = $this->endpoint(function (ExtractedEndpointData $e) {
+            $e->method = new \ReflectionMethod(TestController::class, 'withInlineThisValidate');
+        });
 
-        $strategy = new BodyParameters\GetFromInlineValidator(new DocumentationConfig([]));
-        $results = $strategy($endpoint, []);
+        $results = $this->fetchViaBodyParams($endpoint);
 
         $this->assertArraySubset(self::$expected, $results);
         $this->assertIsArray($results['ids']['example']);
@@ -159,15 +144,11 @@ class GetFromInlineValidatorTest extends BaseLaravelTest
     /** @test */
     public function can_fetch_from_validator_make()
     {
-        $endpoint = new class extends ExtractedEndpointData {
-            public function __construct(array $parameters = [])
-            {
-                $this->method = new \ReflectionMethod(TestController::class, 'withInlineValidatorMake');
-            }
-        };
+        $endpoint = $this->endpoint(function (ExtractedEndpointData $e) {
+            $e->method = new \ReflectionMethod(TestController::class, 'withInlineValidatorMake');
+        });
 
-        $strategy = new BodyParameters\GetFromInlineValidator(new DocumentationConfig([]));
-        $results = $strategy($endpoint, []);
+        $results = $this->fetchViaBodyParams($endpoint);
 
         $this->assertArraySubset(self::$expected, $results);
         $this->assertIsArray($results['ids']['example']);
@@ -176,30 +157,44 @@ class GetFromInlineValidatorTest extends BaseLaravelTest
     /** @test */
     public function respects_query_params_comment()
     {
-        $queryParamsEndpoint = new class extends ExtractedEndpointData {
-            public function __construct(array $parameters = [])
-            {
-                $this->method = new \ReflectionMethod(TestController::class, 'withInlineRequestValidateQueryParams');
-            }
-        };
+        $queryParamsEndpoint = $this->endpoint(function (ExtractedEndpointData $e) {
+            $e->method = new \ReflectionMethod(TestController::class, 'withInlineRequestValidateQueryParams');
+        });
 
-        $strategy = new BodyParameters\GetFromInlineValidator(new DocumentationConfig([]));
-        $results = $strategy($queryParamsEndpoint, []);
+        $results = $this->fetchViaBodyParams($queryParamsEndpoint);
         $this->assertEquals([], $results);
 
-        $queryParamsStrategy = new QueryParameters\GetFromInlineValidator(new DocumentationConfig([]));
-        $results = $queryParamsStrategy($queryParamsEndpoint, []);
+        $results = $this->fetchViaQueryParams($queryParamsEndpoint);
         $this->assertArraySubset(self::$expected, $results);
         $this->assertIsArray($results['ids']['example']);
 
-        $bodyParamsEndpoint = new class extends ExtractedEndpointData {
+        $bodyParamsEndpoint = $this->endpoint(function (ExtractedEndpointData $e) {
+            $e->method = new \ReflectionMethod(TestController::class, 'withInlineRequestValidate');
+        });
+        $results = $this->fetchViaQueryParams($bodyParamsEndpoint);
+        $this->assertEquals([], $results);
+    }
+
+    protected function endpoint(Closure $configure): ExtractedEndpointData
+    {
+        $endpoint = new class extends ExtractedEndpointData {
             public function __construct(array $parameters = [])
             {
-                $this->method = new \ReflectionMethod(TestController::class, 'withInlineRequestValidate');
             }
         };
-        $results = $queryParamsStrategy($bodyParamsEndpoint, []);
-        $this->assertEquals([], $results);
+        $configure($endpoint);
+        return $endpoint;
     }
 
+    protected function fetchViaBodyParams(ExtractedEndpointData $endpoint): ?array
+    {
+        $strategy = new BodyParameters\GetFromInlineValidator(new DocumentationConfig([]));
+        return $strategy($endpoint, []);
+    }
+
+    protected function fetchViaQueryParams(ExtractedEndpointData $endpoint): ?array
+    {
+        $strategy = new QueryParameters\GetFromInlineValidator(new DocumentationConfig([]));
+        return $strategy($endpoint, []);
+    }
 }

+ 4 - 4
tests/Unit/AnnotationParserTest.php

@@ -9,7 +9,7 @@ class AnnotationParserTest extends TestCase
 {
     /**
      * @test
-     * @dataProvider contentAttributesAnnotations
+     * @dataProvider annotationsWithContentAndAttributes
      */
     public function can_parse_annotation_into_content_and_attributes(string $annotation, array $expected)
     {
@@ -18,7 +18,7 @@ class AnnotationParserTest extends TestCase
         $this->assertEquals($expected, $result);
     }
 
-    public function contentAttributesAnnotations()
+    public function annotationsWithContentAndAttributes()
     {
         return [
             "when attributes come first" => [
@@ -54,7 +54,7 @@ class AnnotationParserTest extends TestCase
 
     /**
      * @test
-     * @dataProvider attributesAnnotations
+     * @dataProvider annotationsWithAttributes
      */
     public function can_parse_annotation_into_attributes(string $annotation, array $expected)
     {
@@ -63,7 +63,7 @@ class AnnotationParserTest extends TestCase
         $this->assertEquals($expected, $result);
     }
 
-    public function attributesAnnotations()
+    public function annotationsWithAttributes()
     {
         return [
             "with or without quotes" => [

+ 13 - 16
tests/Unit/ExtractorPluginSystemTest.php

@@ -51,9 +51,7 @@ class ExtractorPluginSystemTest extends TestCase
                 'responses' => [], // Making this empty so the Laravel-dependent strategies are not called
             ],
         ];
-        $route = $this->createRoute('POST', '/api/test', 'dummy', true, TestController::class);
-        $generator = new Extractor(new DocumentationConfig($config));
-        $generator->processRoute($route);
+        $this->processRoute($config);
 
         $this->assertTrue(EmptyStrategy1::$called);
         $this->assertTrue(NotDummyMetadataStrategy::$called);
@@ -69,9 +67,7 @@ class ExtractorPluginSystemTest extends TestCase
                 'responses' => [DummyResponseStrategy200::class, DummyResponseStrategy400::class],
             ],
         ];
-        $route = $this->createRoute('GET', '/api/test', 'dummy', true, TestController::class);
-        $generator = new Extractor(new DocumentationConfig($config));
-        $parsed = $generator->processRoute($route);
+        $parsed = $this->processRoute($config);
 
         $this->assertCount(2, $parsed->responses->toArray());
         $responses = $parsed->responses->toArray();
@@ -99,9 +95,7 @@ class ExtractorPluginSystemTest extends TestCase
                 'responses' => [],
             ],
         ];
-        $route = $this->createRoute('GET', '/api/test', 'dummy', true, TestController::class);
-        $generator = new Extractor(new DocumentationConfig($config));
-        $parsed = $generator->processRoute($route);
+        $parsed = $this->processRoute($config);
 
         $expectedMetadata = [
             'groupName' => 'dummy',
@@ -123,9 +117,7 @@ class ExtractorPluginSystemTest extends TestCase
                 'responses' => [],
             ],
         ];
-        $route = $this->createRoute('GET', '/api/test', 'dummy', true, TestController::class);
-        $generator = new Extractor(new DocumentationConfig($config));
-        $parsed = $generator->processRoute($route);
+        $parsed = $this->processRoute($config);
 
         $expectedMetadata = [
             'groupName' => '',
@@ -147,9 +139,7 @@ class ExtractorPluginSystemTest extends TestCase
                 'responses' => [],
             ],
         ];
-        $route = $this->createRoute('GET', '/api/test', 'dummy', true, TestController::class);
-        $generator = new Extractor(new DocumentationConfig($config));
-        $parsed = $generator->processRoute($route);
+        $parsed = $this->processRoute($config);
 
         $expectedMetadata = [
             'groupName' => 'dummy',
@@ -161,7 +151,14 @@ class ExtractorPluginSystemTest extends TestCase
         $this->assertArraySubset($expectedMetadata, $parsed->metadata->toArray());
     }
 
-    public function createRoute(string $httpMethod, string $path, string $controllerMethod, $register = false, $class = TestController::class)
+    protected function processRoute(array $config): ExtractedEndpointData
+    {
+        $route = $this->createRoute('GET', '/api/test', 'dummy');
+        $extractor = new Extractor(new DocumentationConfig($config));
+        return $extractor->processRoute($route);
+    }
+
+    public function createRoute(string $httpMethod, string $path, string $controllerMethod, $class = TestController::class)
     {
         return new Route([$httpMethod], $path, ['uses' => [$class, $controllerMethod]]);
     }

+ 16 - 23
tests/Unit/ExtractorTest.php

@@ -14,10 +14,7 @@ class ExtractorTest extends TestCase
 {
     use ArraySubsetAsserts;
 
-    /**
-     * @var \Knuckles\Scribe\Extracting\Extractor
-     */
-    protected $generator;
+    protected Extractor $extractor;
 
     protected $config = [
         'strategies' => [
@@ -50,8 +47,6 @@ class ExtractorTest extends TestCase
         ],
     ];
 
-    public static $globalValue = null;
-
     /**
      * Setup the test environment.
      */
@@ -59,7 +54,7 @@ class ExtractorTest extends TestCase
     {
         parent::setUp();
 
-        $this->generator = new Extractor(new DocumentationConfig($this->config));
+        $this->extractor = new Extractor(new DocumentationConfig($this->config));
     }
 
     /** @test */
@@ -139,7 +134,7 @@ class ExtractorTest extends TestCase
     public function does_not_generate_values_for_excluded_params_and_excludes_them_from_clean_params()
     {
         $route = $this->createRoute('POST', '/api/test', 'withExcludedExamples');
-        $parsed = $this->generator->processRoute($route)->toArray();
+        $parsed = $this->extractor->processRoute($route)->toArray();
         $cleanBodyParameters = $parsed['cleanBodyParameters'];
         $cleanQueryParameters = $parsed['cleanQueryParameters'];
         $bodyParameters = $parsed['bodyParameters'];
@@ -172,19 +167,19 @@ class ExtractorTest extends TestCase
     public function can_parse_route_methods()
     {
         $route = $this->createRoute('GET', '/get', 'withEndpointDescription');
-        $parsed = $this->generator->processRoute($route);
+        $parsed = $this->extractor->processRoute($route);
         $this->assertEquals(['GET'], $parsed->httpMethods);
 
         $route = $this->createRoute('POST', '/post', 'withEndpointDescription');
-        $parsed = $this->generator->processRoute($route);
+        $parsed = $this->extractor->processRoute($route);
         $this->assertEquals(['POST'], $parsed->httpMethods);
 
         $route = $this->createRoute('PUT', '/put', 'withEndpointDescription');
-        $parsed = $this->generator->processRoute($route);
+        $parsed = $this->extractor->processRoute($route);
         $this->assertEquals(['PUT'], $parsed->httpMethods);
 
         $route = $this->createRoute('DELETE', '/delete', 'withEndpointDescription');
-        $parsed = $this->generator->processRoute($route);
+        $parsed = $this->extractor->processRoute($route);
         $this->assertEquals(['DELETE'], $parsed->httpMethods);
     }
 
@@ -209,11 +204,11 @@ class ExtractorTest extends TestCase
 
         $paramName = 'room_id';
         $results = [];
-        $results[$this->generator->processRoute($route)->cleanBodyParameters[$paramName]] = true;
-        $results[$this->generator->processRoute($route)->cleanBodyParameters[$paramName]] = true;
-        $results[$this->generator->processRoute($route)->cleanBodyParameters[$paramName]] = true;
-        $results[$this->generator->processRoute($route)->cleanBodyParameters[$paramName]] = true;
-        $results[$this->generator->processRoute($route)->cleanBodyParameters[$paramName]] = true;
+        $results[$this->extractor->processRoute($route)->cleanBodyParameters[$paramName]] = true;
+        $results[$this->extractor->processRoute($route)->cleanBodyParameters[$paramName]] = true;
+        $results[$this->extractor->processRoute($route)->cleanBodyParameters[$paramName]] = true;
+        $results[$this->extractor->processRoute($route)->cleanBodyParameters[$paramName]] = true;
+        $results[$this->extractor->processRoute($route)->cleanBodyParameters[$paramName]] = true;
         // Examples should have different values
         $this->assertNotEquals(1, count($results));
 
@@ -232,7 +227,7 @@ class ExtractorTest extends TestCase
     {
         $route = $this->createRouteUsesArray('GET', '/api/array/test', 'withEndpointDescription');
 
-        $parsed = $this->generator->processRoute($route);
+        $parsed = $this->extractor->processRoute($route);
 
         $this->assertSame('Example title.', $parsed->metadata->title);
         $this->assertSame("This will be the long description.\nIt can also be multiple lines long.", $parsed->metadata->description);
@@ -249,12 +244,10 @@ class ExtractorTest extends TestCase
          * @queryParam location_id required The id of the location.
          * @bodyParam name required Name of the location
          */
-        $handler = function () {
-            return 'hi';
-        };
+        $handler = fn () =>  'hi';
         $route = $this->createRouteUsesCallable('POST', '/api/closure/test', $handler);
 
-        $parsed = $this->generator->processRoute($route);
+        $parsed = $this->extractor->processRoute($route);
 
         $this->assertSame('A short title.', $parsed->metadata->title);
         $this->assertSame("A longer description.\nCan be multiple lines.", $parsed->metadata->description);
@@ -268,7 +261,7 @@ class ExtractorTest extends TestCase
     public function endpoint_metadata_supports_custom_declarations()
     {
         $route = $this->createRoute('POST', '/api/test', 'dummy');
-        $parsed = $this->generator->processRoute($route);
+        $parsed = $this->extractor->processRoute($route);
         $this->assertSame('some custom metadata', $parsed->metadata->custom['myProperty']);
     }
 

+ 13 - 14
tests/Unit/OpenAPISpecWriterTest.php

@@ -31,8 +31,7 @@ class OpenAPISpecWriterTest extends TestCase
         $endpointData2 = $this->createMockEndpointData();
         $groups = [$this->createGroup([$endpointData1, $endpointData2])];
 
-        $writer = new OpenAPISpecWriter(new DocumentationConfig($this->config));
-        $results = $writer->generateSpecContent($groups);
+        $results = $this->generate($groups);
 
         $this->assertEquals(OpenAPISpecWriter::VERSION, $results['openapi']);
         $this->assertEquals($this->config['title'], $results['info']['title']);
@@ -51,8 +50,7 @@ class OpenAPISpecWriterTest extends TestCase
         $endpointData3 = $this->createMockEndpointData(['uri' => 'path1/path2']);
         $groups = [$this->createGroup([$endpointData1, $endpointData2, $endpointData3])];
 
-        $writer = new OpenAPISpecWriter(new DocumentationConfig($this->config));
-        $results = $writer->generateSpecContent($groups);
+        $results = $this->generate($groups);
 
         $this->assertIsArray($results['paths']);
         $this->assertCount(2, $results['paths']);
@@ -140,8 +138,7 @@ class OpenAPISpecWriterTest extends TestCase
         $endpointData2 = $this->createMockEndpointData(['uri' => 'path1', 'httpMethods' => ['POST']]);
         $groups = [$this->createGroup([$endpointData1, $endpointData2])];
 
-        $writer = new OpenAPISpecWriter(new DocumentationConfig($this->config));
-        $results = $writer->generateSpecContent($groups);
+        $results = $this->generate($groups);
 
         $this->assertArrayNotHasKey('parameters', $results['paths']['/path1']);
         $this->assertCount(2, $results['paths']['/path1/{param}/{optionalParam}']['parameters']);
@@ -174,8 +171,7 @@ class OpenAPISpecWriterTest extends TestCase
         $endpointData2 = $this->createMockEndpointData(['uri' => 'path1', 'httpMethods' => ['GET'], 'headers' => []]);
         $groups = [$this->createGroup([$endpointData1, $endpointData2])];
 
-        $writer = new OpenAPISpecWriter(new DocumentationConfig($this->config));
-        $results = $writer->generateSpecContent($groups);
+        $results = $this->generate($groups);
 
         $this->assertEquals([], $results['paths']['/path1']['get']['parameters']);
         $this->assertCount(2, $results['paths']['/path1']['post']['parameters']);
@@ -215,8 +211,7 @@ class OpenAPISpecWriterTest extends TestCase
         $endpointData2 = $this->createMockEndpointData(['headers' => [], 'httpMethods' => ['POST'], 'uri' => '/path1',]);
         $groups = [$this->createGroup([$endpointData1, $endpointData2])];
 
-        $writer = new OpenAPISpecWriter(new DocumentationConfig($this->config));
-        $results = $writer->generateSpecContent($groups);
+        $results = $this->generate($groups);
 
         $this->assertEquals([], $results['paths']['/path1']['post']['parameters']);
         $this->assertArrayHasKey('parameters', $results['paths']['/path1']['get']);
@@ -323,8 +318,7 @@ class OpenAPISpecWriterTest extends TestCase
         ]);
         $groups = [$this->createGroup([$endpointData1, $endpointData2, $endpointData3])];
 
-        $writer = new OpenAPISpecWriter(new DocumentationConfig($this->config));
-        $results = $writer->generateSpecContent($groups);
+        $results = $this->generate($groups);
 
         $this->assertArrayNotHasKey('requestBody', $results['paths']['/path1']['get']);
         $this->assertArrayHasKey('requestBody', $results['paths']['/path1']['post']);
@@ -461,8 +455,7 @@ class OpenAPISpecWriterTest extends TestCase
         ]);
         $groups = [$this->createGroup([$endpointData1, $endpointData2])];
 
-        $writer = new OpenAPISpecWriter(new DocumentationConfig($this->config));
-        $results = $writer->generateSpecContent($groups);
+        $results = $this->generate($groups);
 
         $this->assertCount(2, $results['paths']['/path1']['post']['responses']);
         $this->assertArraySubset([
@@ -550,4 +543,10 @@ class OpenAPISpecWriterTest extends TestCase
             'endpoints' => $endpoints,
         ];
     }
+
+    protected function generate(array $groups): array
+    {
+        $writer = new OpenAPISpecWriter(new DocumentationConfig($this->config));
+        return $writer->generateSpecContent($groups);
+    }
 }

+ 28 - 35
tests/Unit/PostmanCollectionWriterTest.php

@@ -14,18 +14,19 @@ class PostmanCollectionWriterTest extends TestCase
 {
     use ArraySubsetAsserts;
 
-    public function testCorrectStructureIsFollowed()
+    /** @test */
+    public function correct_structure_is_followed()
     {
         $config = ['title' => 'Test API', 'description' => 'A fake description', 'base_url' => 'http://localhost'];
 
-        $writer = new PostmanCollectionWriter(new DocumentationConfig($config));
-        $collection = $writer->generatePostmanCollection([]);
+        $collection = $this->generate($config);
 
         $this->assertSame('Test API', $collection['info']['name']);
         $this->assertSame('A fake description', $collection['info']['description']);
     }
 
-    public function testEndpointIsParsed()
+    /** @test */
+    public function endpoint_is_parsed()
     {
         $endpointData = $this->createMockEndpointData('some/path');
 
@@ -33,10 +34,7 @@ class PostmanCollectionWriterTest extends TestCase
         $endpointData->httpMethods = ['GET'];
 
         $endpoints = $this->createMockEndpointGroup([$endpointData], 'Group');
-
-        $config = ['base_url' => 'fake.localhost', 'title' => 'Test API'];
-        $writer = new PostmanCollectionWriter(new DocumentationConfig($config));
-        $collection = $writer->generatePostmanCollection([$endpoints]);
+        $collection = $this->generate(endpoints: [$endpoints]);
 
         $this->assertSame('Group', data_get($collection, 'item.0.name'), 'Group name exists');
 
@@ -53,16 +51,14 @@ class PostmanCollectionWriterTest extends TestCase
         ], data_get($item, 'request.header'), 'JSON Accept header is added');
     }
 
-    public function testHeadersArePulledFromRoute()
+    /** @test */
+    public function headers_are_pulled_from_route()
     {
         $endpointData = $this->createMockEndpointData('some/path');
-
         $endpointData->headers = ['X-Fake' => 'Test'];
 
-        $endpoints = $this->createMockEndpointGroup([$endpointData], 'Group');
-        $config = ['base_url' => 'fake.localhost', 'title' => 'Test API'];
-        $writer = new PostmanCollectionWriter(new DocumentationConfig($config));
-        $collection = $writer->generatePostmanCollection([$endpoints]);
+        $endpoints = $this->createMockEndpointGroup([$endpointData]);
+        $collection = $this->generate(endpoints: [$endpoints]);
 
         $this->assertContains([
             'key' => 'X-Fake',
@@ -80,11 +76,9 @@ class PostmanCollectionWriterTest extends TestCase
             'required' => true,
             'example' => 'foobar',
         ]);
-        $endpoints = $this->createMockEndpointGroup([$endpointData]);
 
-        $config = ['base_url' => 'fake.localhost', 'title' => 'Test API'];
-        $writer = new PostmanCollectionWriter(new DocumentationConfig($config));
-        $collection = $writer->generatePostmanCollection([$endpoints]);
+        $endpoints = $this->createMockEndpointGroup([$endpointData]);
+        $collection = $this->generate(endpoints: [$endpoints]);
 
         $item = data_get($collection, 'item.0.item.0');
         $this->assertSame('fake/{param}', $item['name'], 'Name defaults to URL path');
@@ -124,9 +118,7 @@ class PostmanCollectionWriterTest extends TestCase
         $endpointData->cleanQueryParameters = Extractor::cleanParams($endpointData->queryParameters);
 
         $endpoints = $this->createMockEndpointGroup([$endpointData]);
-        $config = ['base_url' => 'fake.localhost', 'title' => 'Test API'];
-        $writer = new PostmanCollectionWriter(new DocumentationConfig($config));
-        $collection = $writer->generatePostmanCollection([$endpoints]);
+        $collection = $this->generate(endpoints: [$endpoints]);
 
         $variableData = data_get($collection, 'item.0.item.0.request.url.query');
 
@@ -151,7 +143,8 @@ class PostmanCollectionWriterTest extends TestCase
         ], $variableData[2]);
     }
 
-    public function testUrlParametersAreNotIncludedIfMissingFromPath()
+    /** @test */
+    public function url_parameters_are_not_included_if_missing_from_path()
     {
         $endpointData = $this->createMockEndpointData('fake/path');
 
@@ -163,9 +156,7 @@ class PostmanCollectionWriterTest extends TestCase
         ]);
 
         $endpoints = $this->createMockEndpointGroup([$endpointData]);
-        $config = ['base_url' => 'fake.localhost', 'title' => 'Test API'];
-        $writer = new PostmanCollectionWriter(new DocumentationConfig($config));
-        $collection = $writer->generatePostmanCollection([$endpoints]);
+        $collection = $this->generate(endpoints: [$endpoints]);
 
         $variableData = data_get($collection, 'item.0.item.0.request.url.query');
 
@@ -195,9 +186,7 @@ class PostmanCollectionWriterTest extends TestCase
         $endpointData->cleanQueryParameters = Extractor::cleanParams($endpointData->queryParameters);
 
         $endpoints = $this->createMockEndpointGroup([$endpointData]);
-        $config = ['base_url' => 'fake.localhost', 'title' => 'Test API'];
-        $writer = new PostmanCollectionWriter(new DocumentationConfig($config));
-        $collection = $writer->generatePostmanCollection([$endpoints]);
+        $collection = $this->generate(endpoints: [$endpoints]);
 
         $variableData = data_get($collection, 'item.0.item.0.request.url.query');
 
@@ -216,9 +205,7 @@ class PostmanCollectionWriterTest extends TestCase
         ], $variableData);
     }
 
-    /**
-     * @test
-     */
+    /** @test */
     public function auth_info_is_added_correctly()
     {
         $endpointData1 = $this->createMockEndpointData('some/path');
@@ -235,8 +222,7 @@ class PostmanCollectionWriterTest extends TestCase
             ],
         ];
         $config['auth']['in'] = 'bearer';
-        $writer = new PostmanCollectionWriter(new DocumentationConfig($config));
-        $collection = $writer->generatePostmanCollection([$endpoints]);
+        $collection = $this->generate($config, [$endpoints]);
 
         $this->assertEquals(['type' => 'bearer'], $collection['auth']);
         $this->assertArrayNotHasKey('auth', $collection['item'][0]['item'][0]['request']);
@@ -244,8 +230,7 @@ class PostmanCollectionWriterTest extends TestCase
 
         $config['auth']['in'] = 'query';
         $config['auth']['name'] = 'tokennnn';
-        $writer = new PostmanCollectionWriter(new DocumentationConfig($config));
-        $collection = $writer->generatePostmanCollection([$endpoints]);
+        $collection = $this->generate($config, [$endpoints]);
 
         $this->assertEquals([
             'type' => 'apikey',
@@ -296,4 +281,12 @@ class PostmanCollectionWriterTest extends TestCase
             'endpoints' => $endpoints,
         ];
     }
+
+    protected function generate(
+        array $config = ['base_url' => 'fake.localhost', 'title' => 'Test API'], array $endpoints = []
+    ): array
+    {
+        $writer = new PostmanCollectionWriter(new DocumentationConfig($config));
+        return $writer->generatePostmanCollection($endpoints);
+    }
 }

+ 16 - 8
tests/Unit/RouteMatcherDingoTest.php

@@ -19,7 +19,8 @@ class RouteMatcherDingoTest extends BaseLaravelTest
         ];
     }
 
-    public function testRespectsDomainsRuleForDingoRouter()
+    /** @test */
+    public function respects_domains_rule_for_dingo_router()
     {
         $this->registerDingoRoutes();
         $routeRules[0]['match']['versions'] = ['v1'];
@@ -52,7 +53,8 @@ class RouteMatcherDingoTest extends BaseLaravelTest
         }
     }
 
-    public function testRespectsPrefixesRuleForDingoRouter()
+    /** @test */
+    public function respects_prefixes_rule_for_dingo_router()
     {
         $this->registerDingoRoutes();
         $routeRules[0]['match']['versions'] = ['v1'];
@@ -85,7 +87,8 @@ class RouteMatcherDingoTest extends BaseLaravelTest
         }
     }
 
-    public function testRespectsVersionsRuleForDingoRouter()
+    /** @test */
+    public function respects_versions_rule_for_dingo_router()
     {
         $this->registerDingoRoutes();
 
@@ -107,7 +110,8 @@ class RouteMatcherDingoTest extends BaseLaravelTest
         $this->assertCount(18, $routes);
     }
 
-    public function testWillIncludeRouteIfListedExplicitlyForDingoRouter()
+    /** @test */
+    public function includes_route_if_listed_explicitly_for_dingo_router()
     {
         $this->registerDingoRoutes();
 
@@ -130,7 +134,8 @@ class RouteMatcherDingoTest extends BaseLaravelTest
         $this->assertCount(1, $oddRuleOut);
     }
 
-    public function testWillIncludeRouteIfMatchForAnIncludePatternForDingoRouter()
+    /** @test */
+    public function includes_route_if_match_for_an_include_pattern_for_dingo_router()
     {
         $this->registerDingoRoutes();
 
@@ -154,7 +159,8 @@ class RouteMatcherDingoTest extends BaseLaravelTest
         $this->assertCount(count($mustInclude), $oddRuleOut);
     }
 
-    public function testWillExcludeRouteIfListedExplicitlyForDingoRouter()
+    /** @test */
+    public function excludes_route_if_listed_explicitly_for_dingo_router()
     {
         $this->registerDingoRoutes();
 
@@ -177,7 +183,8 @@ class RouteMatcherDingoTest extends BaseLaravelTest
         $this->assertCount(0, $oddRuleOut);
     }
 
-    public function testWillExcludeRouteIfMatchForAnExcludePatterForDingoRouter()
+    /** @test */
+    public function excludes_route_if_match_for_an_exclude_patter_for_dingo_router()
     {
         $this->registerDingoRoutes();
 
@@ -201,7 +208,8 @@ class RouteMatcherDingoTest extends BaseLaravelTest
         $this->assertCount(0, $oddRuleOut);
     }
 
-    public function testMergesRoutesFromDifferentRuleGroupsForDingoRouter()
+    /** @test */
+    public function merges_routes_from_different_rule_groups_for_dingo_router()
     {
         $this->registerDingoRoutes();
         $routeRules = [

+ 38 - 51
tests/Unit/RouteMatcherTest.php

@@ -9,71 +9,62 @@ use Knuckles\Scribe\Tests\BaseLaravelTest;
 
 class RouteMatcherTest extends BaseLaravelTest
 {
-    public function testRespectsDomainsRuleForLaravelRouter()
+    /** @test */
+    public function respects_domains_rule_for_laravel_router()
     {
         $this->registerLaravelRoutes();
 
         $routeRules[0]['match']['prefixes'] = ['*'];
         $routeRules[0]['match']['domains'] = ['*'];
-        $matcher = new RouteMatcher();
-        $routes = $matcher->getRoutes($routeRules);
-        $this->assertCount(12, $routes);
+        $this->assertCount(12, $this->matchRoutes($routeRules));
 
         $routeRules[0]['match']['domains'] = ['domain1.*', 'domain2.*'];
-        $matcher = new RouteMatcher();
-        $routes = $matcher->getRoutes($routeRules);
-        $this->assertCount(12, $routes);
+        $this->assertCount(12, $this->matchRoutes($routeRules));
 
         $routeRules[0]['match']['domains'] = ['domain1.*'];
-        $matcher = new RouteMatcher();
-        $routes = $matcher->getRoutes($routeRules);
+        $routes = $this->matchRoutes($routeRules);
         $this->assertCount(6, $routes);
         foreach ($routes as $route) {
             $this->assertStringContainsString('domain1', $route['route']->getDomain());
         }
 
         $routeRules[0]['match']['domains'] = ['domain2.*'];
-        $matcher = new RouteMatcher();
-        $routes = $matcher->getRoutes($routeRules);
+        $routes = $this->matchRoutes($routeRules);
         $this->assertCount(6, $routes);
         foreach ($routes as $route) {
             $this->assertStringContainsString('domain2', $route['route']->getDomain());
         }
     }
 
-    public function testRespectsPrefixesRuleForLaravelRouter()
+    /** @test */
+    public function respects_prefixes_rule_for_laravel_router()
     {
         $this->registerLaravelRoutes();
         $routeRules[0]['match']['domains'] = ['*'];
 
         $routeRules[0]['match']['prefixes'] = ['*'];
-        $matcher = new RouteMatcher();
-        $routes = $matcher->getRoutes($routeRules);
-        $this->assertCount(12, $routes);
+        $this->assertCount(12, $this->matchRoutes($routeRules));
 
         $routeRules[0]['match']['prefixes'] = ['prefix1/*', 'prefix2/*'];
-        $matcher = new RouteMatcher();
-        $routes = $matcher->getRoutes($routeRules);
-        $this->assertCount(8, $routes);
+        $this->assertCount(8, $this->matchRoutes($routeRules));
 
         $routeRules[0]['match']['prefixes'] = ['prefix1/*'];
-        $matcher = new RouteMatcher();
-        $routes = $matcher->getRoutes($routeRules);
+        $routes = $this->matchRoutes($routeRules);
         $this->assertCount(4, $routes);
         foreach ($routes as $route) {
             $this->assertTrue(Str::is('prefix1/*', $route['route']->uri()));
         }
 
         $routeRules[0]['match']['prefixes'] = ['prefix2/*'];
-        $matcher = new RouteMatcher();
-        $routes = $matcher->getRoutes($routeRules);
+        $routes = $this->matchRoutes($routeRules);
         $this->assertCount(4, $routes);
         foreach ($routes as $route) {
             $this->assertTrue(Str::is('prefix2/*', $route['route']->uri()));
         }
     }
 
-    public function testWillIncludeRouteIfListedExplicitlyForLaravelRouter()
+    /** @test */
+    public function includes_route_if_listed_explicitly_for_laravel_router()
     {
         $this->registerLaravelRoutes();
         $mustInclude = 'domain1-1';
@@ -81,15 +72,13 @@ class RouteMatcherTest extends BaseLaravelTest
 
         $routeRules[0]['match']['domains'] = ['domain1.*'];
         $routeRules[0]['match']['prefixes'] = ['prefix1/*'];
-        $matcher = new RouteMatcher();
-        $routes = $matcher->getRoutes($routeRules);
-        $oddRuleOut = collect($routes)->filter(function ($route) use ($mustInclude) {
-            return $route['route']->getName() === $mustInclude;
-        });
+        $routes = $this->matchRoutes($routeRules);
+        $oddRuleOut = collect($routes)->filter(fn($route) => $route['route']->getName() === $mustInclude);
         $this->assertCount(1, $oddRuleOut);
     }
 
-    public function testWillIncludeRouteIfMatchForAnIncludePatternForLaravelRouter()
+    /** @test */
+    public function includes_route_if_match_for_an_include_pattern_for_laravel_router()
     {
         $this->registerLaravelRoutes();
         $mustInclude = ['domain1-1', 'domain1-2'];
@@ -98,15 +87,13 @@ class RouteMatcherTest extends BaseLaravelTest
 
         $routeRules[0]['match']['domains'] = ['domain1.*'];
         $routeRules[0]['match']['prefixes'] = ['prefix1/*'];
-        $matcher = new RouteMatcher();
-        $routes = $matcher->getRoutes($routeRules);
-        $oddRuleOut = collect($routes)->filter(function ($route) use ($mustInclude) {
-            return in_array($route['route']->getName(), $mustInclude);
-        });
+        $routes = $this->matchRoutes($routeRules);
+        $oddRuleOut = collect($routes)->filter(fn($route) => in_array($route['route']->getName(), $mustInclude));
         $this->assertCount(count($mustInclude), $oddRuleOut);
     }
 
-    public function testWillExcludeRouteIfListedExplicitlyForLaravelRouter()
+    /** @test */
+    public function exclude_route_if_listed_explicitly_for_laravel_router()
     {
         $this->registerLaravelRoutes();
         $mustNotInclude = 'prefix1.domain1-1';
@@ -114,15 +101,13 @@ class RouteMatcherTest extends BaseLaravelTest
 
         $routeRules[0]['match']['domains'] = ['domain1.*'];
         $routeRules[0]['match']['prefixes'] = ['prefix1/*'];
-        $matcher = new RouteMatcher();
-        $routes = $matcher->getRoutes($routeRules);
-        $oddRuleOut = collect($routes)->filter(function ($route) use ($mustNotInclude) {
-            return $route['route']->getName() === $mustNotInclude;
-        });
+        $routes = $this->matchRoutes($routeRules);
+        $oddRuleOut = collect($routes)->filter(fn($route) => $route['route']->getName() === $mustNotInclude);
         $this->assertCount(0, $oddRuleOut);
     }
 
-    public function testWillExcludeRouteIfMatchForAnExcludePatternForLaravelRouter()
+    /** @test */
+    public function exclude_route_if_match_for_an_exclude_pattern_for_laravel_router()
     {
         $this->registerLaravelRoutes();
         $mustNotInclude = ['prefix1.domain1-1', 'prefix1.domain1-2'];
@@ -131,15 +116,13 @@ class RouteMatcherTest extends BaseLaravelTest
 
         $routeRules[0]['match']['domains'] = ['domain1.*'];
         $routeRules[0]['match']['prefixes'] = ['prefix1/*'];
-        $matcher = new RouteMatcher();
-        $routes = $matcher->getRoutes($routeRules);
-        $oddRuleOut = collect($routes)->filter(function ($route) use ($mustNotInclude) {
-            return in_array($route['route']->getName(), $mustNotInclude);
-        });
+        $routes = $this->matchRoutes($routeRules);
+        $oddRuleOut = collect($routes)->filter(fn($route) => in_array($route['route']->getName(), $mustNotInclude));
         $this->assertCount(0, $oddRuleOut);
     }
 
-    public function testMergesRoutesFromDifferentRuleGroupsForLaravelRouter()
+    /** @test */
+    public function merges_routes_from_different_rule_groups_for_laravel_router()
     {
         $this->registerLaravelRoutes();
 
@@ -158,11 +141,9 @@ class RouteMatcherTest extends BaseLaravelTest
             ],
         ];
 
-        $matcher = new RouteMatcher();
-        $routes = $matcher->getRoutes($routeRules);
-        $this->assertCount(4, $routes);
+        $this->assertCount(4, $this->matchRoutes($routeRules));
 
-        $routes = collect($routes);
+        $routes = collect($this->matchRoutes($routeRules));
         $firstRuleGroup = $routes->filter(function ($route) {
             return Str::is('prefix1/*', $route['route']->uri())
                 && Str::is('domain1.*', $route['route']->getDomain());
@@ -219,4 +200,10 @@ class RouteMatcherTest extends BaseLaravelTest
             })->name('prefix2.domain2-2');
         });
     }
+
+    protected function matchRoutes(array $routeRules): array
+    {
+        $matcher = new RouteMatcher();
+        return $matcher->getRoutes($routeRules);
+    }
 }