diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 23e18cd327..8b18e8df1e 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -71,7 +71,7 @@ jobs: composer update ${{ matrix.composer-options }} --no-interaction --prefer-dist --with-all-dependencies composer update psr/http-message guzzlehttp/psr7 guzzlehttp/guzzle --with-all-dependencies --no-interaction if [[ "${{ matrix.php-versions }}" == "8.4" ]]; then - composer update phpunit/phpunit:^9.6.18 --with-all-dependencies --no-interaction + composer update phpunit/phpunit:^10.0 --with-all-dependencies --no-interaction fi else composer update ${{ matrix.composer-options }} --no-interaction --prefer-dist --with-all-dependencies diff --git a/Makefile b/Makefile index 47df0e7d74..5782039b43 100644 --- a/Makefile +++ b/Makefile @@ -24,8 +24,12 @@ clear-cache: php build/aws-clear-cache.php test: - @AWS_ACCESS_KEY_ID=foo AWS_SECRET_ACCESS_KEY=bar AWS_SESSION_TOKEN= AWS_CSM_ENABLED=false AWS_REGION= AWS_ENDPOINT_URL= AWS_SUPPRESS_PHP_DEPRECATION_WARNING=true \ - vendor/bin/phpunit --testsuite=unit $(TEST) + AWS_ACCESS_KEY_ID=foo AWS_SECRET_ACCESS_KEY=bar AWS_SESSION_TOKEN= \ + AWS_CSM_ENABLED=false \ + AWS_REGION= \ + AWS_ENDPOINT_URL= \ + AWS_SUPPRESS_PHP_DEPRECATION_WARNING=true \ + vendor/bin/phpunit --no-coverage --testsuite=unit $(TEST) test-phar: package [ -f build/artifacts/behat.phar ] || (cd build/artifacts && \ diff --git a/composer.json b/composer.json index 3820ded327..ac95667707 100644 --- a/composer.json +++ b/composer.json @@ -33,7 +33,7 @@ "ext-openssl": "*", "ext-dom": "*", "ext-sockets": "*", - "phpunit/phpunit": "^9.6", + "phpunit/phpunit": "^10.0", "behat/behat": "~3.0", "doctrine/cache": "~1.4", "aws/aws-php-sns-message-validator": "~1.0", @@ -42,7 +42,7 @@ "psr/simple-cache": "^2.0 || ^3.0", "sebastian/comparator": "^1.2.3 || ^4.0 || ^5.0", "yoast/phpunit-polyfills": "^2.0", - "dms/phpunit-arraysubset-asserts": "^0.4.0" + "dms/phpunit-arraysubset-asserts": "^v0.5.0" }, "suggest": { "ext-openssl": "Allows working with CloudFront private distributions and verifying received SNS messages", diff --git a/phpunit.xml.dist b/phpunit.xml.dist index d32051d2b7..5987d7c487 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,17 +1,6 @@ - + - - src - - - src/data - @@ -26,4 +15,12 @@ + + + src + + + src/data + + diff --git a/src/AwsClient.php b/src/AwsClient.php index a19b794119..d7683f0ffa 100644 --- a/src/AwsClient.php +++ b/src/AwsClient.php @@ -737,29 +737,6 @@ protected function isUseEndpointV2() return $this->endpointProvider instanceof EndpointProviderV2; } - public static function emitDeprecationWarning() { - trigger_error( - "This method is deprecated. It will be removed in an upcoming release." - , E_USER_DEPRECATED - ); - - $phpVersion = PHP_VERSION_ID; - if ($phpVersion < 70205) { - $phpVersionString = phpversion(); - @trigger_error( - "This installation of the SDK is using PHP version" - . " {$phpVersionString}, which will be deprecated on August" - . " 15th, 2023. Please upgrade your PHP version to a minimum of" - . " 7.2.5 before then to continue receiving updates to the AWS" - . " SDK for PHP. To disable this warning, set" - . " suppress_php_deprecation_warning to true on the client constructor" - . " or set the environment variable AWS_SUPPRESS_PHP_DEPRECATION_WARNING" - . " to true.", - E_USER_DEPRECATED - ); - } - } - /** * Returns a service model and doc model with any necessary changes diff --git a/src/ClientResolver.php b/src/ClientResolver.php index d8751b1148..4e41bd6389 100644 --- a/src/ClientResolver.php +++ b/src/ClientResolver.php @@ -1247,12 +1247,6 @@ public static function _apply_suppress_php_deprecation_warning($value, &$args) $args['suppress_php_deprecation_warning'] = \Aws\boolean_value($_ENV["AWS_SUPPRESS_PHP_DEPRECATION_WARNING"]); } - - if ($args['suppress_php_deprecation_warning'] === false - && PHP_VERSION_ID < 80100 - ) { - self::emitDeprecationWarning(); - } } public static function _default_endpoint(array &$args) @@ -1440,21 +1434,4 @@ private static function isValidApiVersion($service, $apiVersion) __DIR__ . "/data/{$service}/$apiVersion" ); } - - private static function emitDeprecationWarning() - { - $phpVersionString = phpversion(); - trigger_error( - "This installation of the SDK is using PHP version" - . " {$phpVersionString}, which will be deprecated on January" - . " 13th, 2025.\nPlease upgrade your PHP version to a minimum of" - . " 8.1.x to continue receiving updates for the AWS" - . " SDK for PHP.\nTo disable this warning, set" - . " suppress_php_deprecation_warning to true on the client constructor" - . " or set the environment variable AWS_SUPPRESS_PHP_DEPRECATION_WARNING" - . " to true.\nMore information can be found at: " - . "https://aws.amazon.com/blogs/developer/announcing-the-end-of-support-for-php-runtimes-8-0-x-and-below-in-the-aws-sdk-for-php/\n", - E_USER_DEPRECATED - ); - } } diff --git a/tests/AbstractConfigurationProviderTest.php b/tests/AbstractConfigurationProviderTest.php index 80a4fbbc4b..32c13f523c 100644 --- a/tests/AbstractConfigurationProviderTest.php +++ b/tests/AbstractConfigurationProviderTest.php @@ -2,24 +2,26 @@ namespace Aws\Test; +use Aws\AbstractConfigurationProvider; use Aws\LruArrayCache; use Aws\Result; use Aws\ResultInterface; use GuzzleHttp\Promise; +use PHPUnit\Framework\MockObject\MockObject; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\AbstractConfigurationProvider - */ +#[CoversClass(AbstractConfigurationProvider::class)] class AbstractConfigurationProviderTest extends TestCase { - /** @var \PHPUnit_Framework_MockObject_MockObject */ + /** @var MockObject */ private $provider; - public function __construct() + protected function setUp(): void { - parent::__construct(); - $this->provider = $this->getMockForAbstractClass('\Aws\AbstractConfigurationProvider'); + $this->provider = $this->getMockForAbstractClass( + '\Aws\AbstractConfigurationProvider' + ); } public function testGetsHomeDirectoryForWindowsUsers() diff --git a/tests/Api/ApiProviderTest.php b/tests/Api/ApiProviderTest.php index 350daa7f6c..5212137986 100644 --- a/tests/Api/ApiProviderTest.php +++ b/tests/Api/ApiProviderTest.php @@ -4,10 +4,9 @@ use Aws\Api\ApiProvider; use Aws\Exception\UnresolvedApiException; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Api\ApiProvider - */ +#[CoversClass(ApiProvider::class)] class ApiProviderTest extends TestCase { /** @@ -25,7 +24,9 @@ private function getTestApiProvider($useManifest = true) public function testCanResolveProvider() { - $p = function ($a, $b, $c) {return [];}; + $p = function ($a, $b, $c) { + return []; + }; $result = ['metadata'=> ['serviceIdentifier' => 's']]; $this->assertEquals($result, ApiProvider::resolve($p, 't', 's', 'v')); diff --git a/tests/Api/DateTimeResultTest.php b/tests/Api/DateTimeResultTest.php index f8fe015904..53eba9cb8c 100644 --- a/tests/Api/DateTimeResultTest.php +++ b/tests/Api/DateTimeResultTest.php @@ -3,10 +3,10 @@ use Aws\Api\DateTimeResult; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Api\DateTimeResult - */ +#[CoversClass(DateTimeResult::class)] class DateTimeResultTest extends TestCase { public function testCreatesFromEpoch() @@ -50,18 +50,14 @@ public function testJsonSerialzesAsIso8601() $this->assertSame('"' . gmdate('c', $t). '"', json_encode($d)); } - /** - * @return void - * - * @dataProvider nanosecondPrecisionProvider - */ + #[DataProvider('nanosecondPrecisionProvider')] public function testIso8601NanosecondPrecision($timestamp, $expected) { $parsed = DateTimeResult::fromISO8601($timestamp); $this->assertEquals($expected, (string) $parsed); } - public function nanosecondPrecisionProvider() + public static function nanosecondPrecisionProvider(): array { return [ ['2024-07-31T19:05:47.1234567Z', '2024-07-31T19:05:47+00:00'], diff --git a/tests/Api/ErrorParser/JsonRpcErrorParserTest.php b/tests/Api/ErrorParser/JsonRpcErrorParserTest.php index 0149db699c..97048c801d 100644 --- a/tests/Api/ErrorParser/JsonRpcErrorParserTest.php +++ b/tests/Api/ErrorParser/JsonRpcErrorParserTest.php @@ -2,35 +2,46 @@ namespace Aws\Test\Api\ErrorParser; use Aws\Api\ErrorParser\JsonRpcErrorParser; -use Aws\Api\ErrorParser\RestJsonErrorParser; -use Aws\Api\StructureShape; +use Aws\Api\ErrorParser\JsonParserTrait; use Aws\Test\TestServiceTrait; -use GuzzleHttp\Promise\Promise; use GuzzleHttp\Psr7; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Api\ErrorParser\JsonRpcErrorParser - * @covers \Aws\Api\ErrorParser\JsonParserTrait - */ +#[CoversClass(JsonRpcErrorParser::class)] +#[CoversClass(JsonParserTrait::class)] class JsonRpcErrorParserTest extends TestCase { use TestServiceTrait; - /** - * @dataProvider errorResponsesProvider - * - * @param $response - * @param $command - * @param $parser - * @param $expected - */ + #[DataProvider('errorResponsesProvider')] public function testParsesClientErrorResponses( - $response, - $command, - $parser, - $expected + string $response, + ?string $commandName, + bool $parserWithService, + array $expected ) { + $service = $this->generateTestService('json'); + $awsQueryCompatibleService = $this->generateTestService( + 'json', + ['awsQueryCompatible' => true] + ); + $shapes = $service->getErrorShapes(); + $errorShape = $shapes[0]; + $client = $this->generateTestClient($service); + $command = $commandName === null + ? null + : $client->getCommand($commandName); + $parser = $parserWithService + ? new JsonRpcErrorParser($awsQueryCompatibleService) + : new JsonRpcErrorParser(); + + // If error shape required in the expected + if ($expected['error_shape'] ?? false) { + $expected['error_shape'] = $errorShape; + } + $response = Psr7\Message::parseResponse($response); $parsed = $parser($response, $command); $this->assertCount( @@ -49,18 +60,8 @@ public function testParsesClientErrorResponses( } } - public function errorResponsesProvider() + public static function errorResponsesProvider(): array { - $service = $this->generateTestService('json'); - $awsQueryCompatibleService = $this->generateTestService( - 'json', - ['awsQueryCompatible' => true] - ); - $shapes = $service->getErrorShapes(); - $errorShape = $shapes[0]; - $client = $this->generateTestClient($service); - $command = $client->getCommand('TestOperation', []); - return [ // Non-modeled exception, mixed casing [ @@ -68,7 +69,7 @@ public function errorResponsesProvider() "x-amzn-requestid: xyz\r\n\r\n" . '{ "__Type": "foo", "Message": "lorem ipsum" }', null, - new JsonRpcErrorParser(), + false, [ 'code' => 'foo', 'message' => 'lorem ipsum', @@ -89,8 +90,8 @@ public function errorResponsesProvider() "x-meta-bar: bar-meta\r\n" . "x-amzn-requestid: xyz\r\n\r\n" . '{ "TestString": "foo", "TestInt": 123, "NotModeled": "bar", "__type": "TestException", "message": "Test Message" }', - $command, - new JsonRpcErrorParser($service), + 'TestOperation', + true, [ 'code' => 'TestException', 'type' => 'client', @@ -113,7 +114,7 @@ public function errorResponsesProvider() 'TestStatus' => 400, ], 'message' => 'Test Message', - 'error_shape' => $errorShape + 'error_shape' => true ] ], // Unmodeled shape, with service @@ -125,7 +126,7 @@ public function errorResponsesProvider() "x-amzn-requestid: xyz\r\n\r\n" . '{ "TestString": "foo", "TestInt": 123, "NotModeled": "bar", "__type": "NonExistentException", "message": "Test Message" }', null, - new JsonRpcErrorParser($service), + true, [ 'code' => 'NonExistentException', 'message' => 'Test Message', @@ -148,7 +149,7 @@ public function errorResponsesProvider() "x-amzn-query-error: NonExistentException;Sender\r\n\r\n" . '{ "__Type": "foo", "Message": "lorem ipsum" }', null, - new JsonRpcErrorParser($awsQueryCompatibleService), + true, [ 'code' => 'NonExistentException', 'message' => 'lorem ipsum', @@ -168,7 +169,7 @@ public function errorResponsesProvider() "x-amzn-query-error: ;Sender\r\n\r\n" . '{ "__Type": "foo", "Message": "lorem ipsum" }', null, - new JsonRpcErrorParser($awsQueryCompatibleService), + true, [ 'code' => 'foo', 'message' => 'lorem ipsum', @@ -188,7 +189,7 @@ public function errorResponsesProvider() "x-amzn-query-error: \r\n\r\n" . '{ "__Type": "foo", "Message": "lorem ipsum" }', null, - new JsonRpcErrorParser(), + false, [ 'code' => 'foo', 'message' => 'lorem ipsum', diff --git a/tests/Api/ErrorParser/RestJsonErrorParserTest.php b/tests/Api/ErrorParser/RestJsonErrorParserTest.php index 800a2dc3ed..3ab86c6371 100644 --- a/tests/Api/ErrorParser/RestJsonErrorParserTest.php +++ b/tests/Api/ErrorParser/RestJsonErrorParserTest.php @@ -2,32 +2,42 @@ namespace Aws\Test\Api\ErrorParser; use Aws\Api\ErrorParser\RestJsonErrorParser; +use Aws\Api\ErrorParser\JsonParserTrait; use Aws\Test\TestServiceTrait; use GuzzleHttp\Psr7; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Api\ErrorParser\RestJsonErrorParser - * @covers \Aws\Api\ErrorParser\JsonParserTrait - */ +#[CoversClass(RestJsonErrorParser::class)] +#[CoversClass(JsonParserTrait::class)] class RestJsonErrorParserTest extends TestCase { use TestServiceTrait; - /** - * @dataProvider errorResponsesProvider - * - * @param $response - * @param $command - * @param $parser - * @param $expected - */ + #[DataProvider('errorResponsesProvider')] public function testParsesClientErrorResponses( - $response, - $command, - $parser, - $expected + string $response, + ?string $commandName, + bool $parserWithService, + array $expected ) { + $service = $this->generateTestService('rest-json'); + $shapes = $service->getErrorShapes(); + $errorShape = $shapes[0]; + $client = $this->generateTestClient($service); + $command = $commandName === null + ? null + : $client->getCommand($commandName); + $parser = $parserWithService + ? new RestJsonErrorParser($service) + : new RestJsonErrorParser(); + + // If error shape required in the expected + if ($expected['error_shape'] ?? false) { + $expected['error_shape'] = $errorShape; + } + $response = Psr7\Message::parseResponse($response); $parsed = $parser($response, $command); $this->assertCount( @@ -46,14 +56,8 @@ public function testParsesClientErrorResponses( } } - public function errorResponsesProvider() + public static function errorResponsesProvider(): array { - $service = $this->generateTestService('rest-json'); - $shapes = $service->getErrorShapes(); - $errorShape = $shapes[0]; - $client = $this->generateTestClient($service); - $command = $client->getCommand('TestOperation', []); - return [ // Error code in body [ @@ -61,7 +65,7 @@ public function errorResponsesProvider() "x-amzn-requestid: xyz\r\n\r\n" . '{ "type": "client", "message": "lorem ipsum", "code": "foo" }', null, - new RestJsonErrorParser(), + false, [ 'code' => 'foo', 'message' => 'lorem ipsum', @@ -82,7 +86,7 @@ public function errorResponsesProvider() "x-amzn-ErrorType: foo:bar\r\n\r\n" . '{"message": "lorem ipsum"}', null, - new RestJsonErrorParser(), + false, [ 'code' => 'foo', 'message' => 'lorem ipsum', @@ -102,8 +106,8 @@ public function errorResponsesProvider() "x-meta-bar: bar-meta\r\n" . "x-amzn-requestid: xyz\r\n\r\n" . '{ "TestString": "foo", "TestInt": 123, "NotModeled": "bar", "code": "TestException" }', - $command, - new RestJsonErrorParser($service), + 'TestOperation', + true, [ 'code' => 'TestException', 'type' => 'client', @@ -128,7 +132,7 @@ public function errorResponsesProvider() 'TestStatus' => 400, ], 'message' => null, - 'error_shape' => $errorShape + 'error_shape' => true ] ], // Error code in header, with service, modeled exception @@ -140,8 +144,8 @@ public function errorResponsesProvider() "x-amzn-ErrorType: TestException\r\n" . "x-amzn-requestid: xyz\r\n\r\n" . '{ "TestString": "foo", "TestInt": 123, "NotModeled": "bar"}', - $command, - new RestJsonErrorParser($service), + 'TestOperation', + true, [ 'code' => 'TestException', 'type' => 'client', @@ -165,7 +169,7 @@ public function errorResponsesProvider() 'TestStatus' => 400, ], 'message' => null, - 'error_shape' => $errorShape + 'error_shape' => true ] ], // Error code in header, with service, unmodeled code @@ -175,7 +179,7 @@ public function errorResponsesProvider() "x-amzn-ErrorType: NonExistentException\r\n\r\n" . '{"message": "lorem ipsum"}', null, - new RestJsonErrorParser($service), + true, [ 'code' => 'NonExistentException', 'message' => 'lorem ipsum', @@ -193,7 +197,7 @@ public function errorResponsesProvider() "x-amzn-requestid: xyz\r\n\r\n" . '{ "type": "client", "message": "lorem ipsum", "code": "NonExistentException" }', null, - new RestJsonErrorParser($service), + true, [ 'code' => 'NonExistentException', 'message' => 'lorem ipsum', @@ -213,7 +217,7 @@ public function errorResponsesProvider() "x-amzn-requestid: xyz\r\n\r\n" . '{ "type": "client", "Message": "lorem ipsum", "code": "NonExistentException" }', null, - new RestJsonErrorParser($service), + true, [ 'code' => 'NonExistentException', 'message' => 'lorem ipsum', @@ -234,8 +238,8 @@ public function errorResponsesProvider() "TestHeader: 0\r\n" . "x-amzn-requestid: xyz\r\n\r\n" . '{ "code": "TestException" }', - $command, - new RestJsonErrorParser($service), + 'TestOperation', + true, [ 'code' => 'TestException', 'type' => 'client', @@ -247,7 +251,7 @@ public function errorResponsesProvider() 'TestStatus' => 400, ], 'message' => null, - 'error_shape' => $errorShape + 'error_shape' => true ] ], // Test false value in header @@ -256,8 +260,8 @@ public function errorResponsesProvider() "TestHeader: false\r\n" . "x-amzn-requestid: xyz\r\n\r\n" . '{ "code": "TestException" }', - $command, - new RestJsonErrorParser($service), + 'TestOperation', + true, [ 'code' => 'TestException', 'type' => 'client', @@ -269,7 +273,7 @@ public function errorResponsesProvider() 'TestStatus' => 400, ], 'message' => null, - 'error_shape' => $errorShape + 'error_shape' => true ] ], // Test empty string in header (should be skipped) @@ -278,8 +282,8 @@ public function errorResponsesProvider() "TestHeader: \r\n" . "x-amzn-requestid: xyz\r\n\r\n" . '{ "code": "TestException" }', - $command, - new RestJsonErrorParser($service), + 'TestOperation', + true, [ 'code' => 'TestException', 'type' => 'client', @@ -291,7 +295,7 @@ public function errorResponsesProvider() 'TestStatus' => 400, ], 'message' => null, - 'error_shape' => $errorShape + 'error_shape' => true ] ] ]; diff --git a/tests/Api/ErrorParser/XmlErrorParserTest.php b/tests/Api/ErrorParser/XmlErrorParserTest.php index 3bc73e5f19..7c86b40b13 100644 --- a/tests/Api/ErrorParser/XmlErrorParserTest.php +++ b/tests/Api/ErrorParser/XmlErrorParserTest.php @@ -6,30 +6,37 @@ use DMS\PHPUnitExtensions\ArraySubset\ArraySubsetAsserts; use GuzzleHttp\Psr7; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Api\ErrorParser\XmlErrorParser - */ +#[CoversClass(XmlErrorParser::class)] class XmlErrorParserTest extends TestCase { use ArraySubsetAsserts; use TestServiceTrait; /** - * @dataProvider errorResponsesProvider + * @param string $response + * @param string $protocol + * @param string $parser + * @param array $expected + * @param string|null $expectedParsedType * - * @param $response - * @param $command - * @param $parser - * @param $expected + * @throws \Exception */ + #[DataProvider('errorResponsesProvider')] public function testParsesClientErrorResponses( - $response, - $command, - $parser, - $expected, - $expectedParsedType + string $response, + string $protocol, + string $parser, + array $expected, + ?string $expectedParsedType ) { + $service = $this->generateTestService($protocol); + $client = $this->generateTestClient($service); + $command = $client->getCommand('TestOperation'); + $parser = new $parser($service); + $response = Psr7\Message::parseResponse($response); $result = $parser($response, $command); $this->assertArraySubset($expected, $result); @@ -41,20 +48,8 @@ public function testParsesClientErrorResponses( } } - public function errorResponsesProvider() + public static function errorResponsesProvider(): array { - $ec2Service = $this->generateTestService('ec2'); - $ec2Client = $this->generateTestClient($ec2Service); - $ec2Command = $ec2Client->getCommand('TestOperation', []); - - $queryService = $this->generateTestService('query'); - $queryClient = $this->generateTestClient($queryService); - $queryCommand = $queryClient->getCommand('TestOperation', []); - - $restXmlService = $this->generateTestService('query'); - $restXmlClient = $this->generateTestClient($restXmlService); - $restXmlCommand = $restXmlClient->getCommand('TestOperation', []); - return [ // ec2, modeled exception [ @@ -75,8 +70,8 @@ public function errorResponsesProvider() ' ' . ' xyz' . '', - $ec2Command, - new XmlErrorParser($ec2Service), + 'ec2', + XmlErrorParser::class, [ 'type' => 'client', 'request_id' => 'xyz', @@ -114,8 +109,8 @@ public function errorResponsesProvider() ' ' . ' xyz' . '', - $ec2Command, - new XmlErrorParser($ec2Service), + 'ec2', + XmlErrorParser::class, [ 'type' => 'client', 'request_id' => 'xyz', @@ -141,8 +136,8 @@ public function errorResponsesProvider() ' ' . ' xyz' . '', - $queryCommand, - new XmlErrorParser($queryService), + 'query', + XmlErrorParser::class, [ 'type' => 'client', 'request_id' => 'xyz', @@ -178,8 +173,8 @@ public function errorResponsesProvider() ' ' . ' xyz' . '', - $queryCommand, - new XmlErrorParser($queryService), + 'query', + XmlErrorParser::class, [ 'type' => 'client', 'request_id' => 'xyz', @@ -205,8 +200,8 @@ public function errorResponsesProvider() ' ' . ' xyz' . '', - $restXmlCommand, - new XmlErrorParser($restXmlService), + 'query', + XmlErrorParser::class, [ 'type' => 'client', 'request_id' => 'xyz', @@ -242,8 +237,8 @@ public function errorResponsesProvider() ' ' . ' xyz' . '', - $restXmlCommand, - new XmlErrorParser($restXmlService), + 'query', + XmlErrorParser::class, [ 'type' => 'client', 'request_id' => 'xyz', @@ -268,8 +263,8 @@ public function errorResponsesProvider() ' 456' . ' baz' . '', - $restXmlCommand, - new XmlErrorParser($restXmlService), + 'query', + XmlErrorParser::class, [ 'type' => 'client', 'request_id' => 'xyz', @@ -304,8 +299,8 @@ public function errorResponsesProvider() ' 456' . ' baz' . '', - $restXmlCommand, - new XmlErrorParser($restXmlService), + 'query', + XmlErrorParser::class, [ 'type' => 'client', 'request_id' => 'xyz', @@ -321,8 +316,8 @@ public function errorResponsesProvider() "x-meta-foo: foo-meta\r\n" . "x-meta-bar: bar-meta\r\n" . "x-amz-request-id: xyz\r\n\r\n", - $restXmlCommand, - new XmlErrorParser($restXmlService), + 'query', + XmlErrorParser::class, [ 'type' => 'client', 'request_id' => 'xyz', diff --git a/tests/Api/ListShapeTest.php b/tests/Api/ListShapeTest.php index 9b42c50aef..ff46e07fe7 100644 --- a/tests/Api/ListShapeTest.php +++ b/tests/Api/ListShapeTest.php @@ -4,11 +4,10 @@ use Aws\Api\Shape; use Aws\Api\ShapeMap; use Aws\Api\ListShape; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Api\ListShape - */ +#[CoversClass(ListShape::class)] class ListShapeTest extends TestCase { public function testReturnsMember() diff --git a/tests/Api/MapShapeTest.php b/tests/Api/MapShapeTest.php index d1e0df7707..f78fea4e2d 100644 --- a/tests/Api/MapShapeTest.php +++ b/tests/Api/MapShapeTest.php @@ -4,11 +4,10 @@ use Aws\Api\Shape; use Aws\Api\ShapeMap; use Aws\Api\MapShape; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Api\MapShape - */ +#[CoversClass(MapShape::class)] class MapShapeTest extends TestCase { public function testReturnsValue() diff --git a/tests/Api/OperationTest.php b/tests/Api/OperationTest.php index 76c393779e..aa6e505c84 100644 --- a/tests/Api/OperationTest.php +++ b/tests/Api/OperationTest.php @@ -4,11 +4,10 @@ use Aws\Api\Shape; use Aws\Api\ShapeMap; use Aws\Api\Operation; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Api\Operation - */ +#[CoversClass(Operation::class)] class OperationTest extends TestCase { public function testCreatesDefaultMethodAndUri() diff --git a/tests/Api/Parser/ComplianceTest.php b/tests/Api/Parser/ComplianceTest.php index 5a63710c5c..f6aae88950 100644 --- a/tests/Api/Parser/ComplianceTest.php +++ b/tests/Api/Parser/ComplianceTest.php @@ -11,17 +11,25 @@ use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; +use Aws\Api\Parser\AbstractParser; +use Aws\Api\Parser\AbstractRestParser; +use Aws\Api\Parser\JsonRpcParser; +use Aws\Api\Parser\JsonParser; +use Aws\Api\Parser\RestJsonParser; +use Aws\Api\Parser\RestXmlParser; +use Aws\Api\Parser\QueryParser; +use Aws\Api\Parser\XmlParser; -/** - * @covers \Aws\Api\Parser\AbstractParser - * @covers \Aws\Api\Parser\AbstractRestParser - * @covers \Aws\Api\Parser\JsonRpcParser - * @covers \Aws\Api\Parser\JsonParser - * @covers \Aws\Api\Parser\RestJsonParser - * @covers \Aws\Api\Parser\RestXmlParser - * @covers \Aws\Api\Parser\QueryParser - * @covers \Aws\Api\Parser\XmlParser - */ +#[CoversClass(AbstractParser::class)] +#[CoversClass(AbstractRestParser::class)] +#[CoversClass(JsonRpcParser::class)] +#[CoversClass(JsonParser::class)] +#[CoversClass(RestJsonParser::class)] +#[CoversClass(RestXmlParser::class)] +#[CoversClass(QueryParser::class)] +#[CoversClass(XmlParser::class)] class ComplianceTest extends TestCase { use UsesServiceTrait; @@ -47,8 +55,7 @@ class ComplianceTest extends TestCase 'legacy query Flattened list with location name' => true ]; - /** @doesNotPerformAssertions */ - public function testCaseProvider(): \Generator + public static function caseProvider(): \Generator { $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( @@ -105,17 +112,7 @@ public function testCaseProvider(): \Generator } } - /** - * @dataProvider testCaseProvider - * - * @param $about - * @param Service $service - * @param $name - * @param array $expectedResult - * @param $res - * @param string|null $errorCode - * @param string|null $errorMessage - */ + #[DataProvider('caseProvider')] public function testPassesComplianceTest( string $about, Service $service, diff --git a/tests/Api/Parser/Crc32ValidatingParserTest.php b/tests/Api/Parser/Crc32ValidatingParserTest.php index 1aa3300198..29c817bc5e 100644 --- a/tests/Api/Parser/Crc32ValidatingParserTest.php +++ b/tests/Api/Parser/Crc32ValidatingParserTest.php @@ -9,11 +9,10 @@ use Aws\Exception\AwsException; use Aws\ResultInterface; use GuzzleHttp\Psr7\Response; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Api\Parser\Crc32ValidatingParser - */ +#[CoversClass(Crc32ValidatingParser::class)] class Crc32ValidatingParserTest extends TestCase { private function getWrapped() diff --git a/tests/Api/Parser/DecodingEventStreamIteratorTest.php b/tests/Api/Parser/DecodingEventStreamIteratorTest.php index 8afe8cdd73..7c078e802b 100644 --- a/tests/Api/Parser/DecodingEventStreamIteratorTest.php +++ b/tests/Api/Parser/DecodingEventStreamIteratorTest.php @@ -7,13 +7,13 @@ use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Stream; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Api\Parser\DecodingEventStreamIterator - */ +#[CoversClass(DecodingEventStreamIterator::class)] class DecodingEventStreamIteratorTest extends TestCase { - public function complianceTests(): \Generator + public static function complianceTests(): \Generator { $dataFilesIterator = \Aws\recursive_dir_iterator( realpath(__DIR__ . '/../test_cases/eventstream/encoded/') @@ -37,9 +37,7 @@ public function complianceTests(): \Generator } } - /** - * @dataProvider complianceTests - */ + #[DataProvider('complianceTests')] public function testPassesComplianceTest( Stream $encodedData, Stream $decodedData, diff --git a/tests/Api/Parser/EventParsingIteratorTest.php b/tests/Api/Parser/EventParsingIteratorTest.php index f8d7c4d4e7..8f1db82c98 100644 --- a/tests/Api/Parser/EventParsingIteratorTest.php +++ b/tests/Api/Parser/EventParsingIteratorTest.php @@ -15,10 +15,10 @@ use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Api\Parser\EventParsingIterator - */ +#[CoversClass(EventParsingIterator::class)] class EventParsingIteratorTest extends TestCase { const PROTOCOL_XML = 'XML'; @@ -67,11 +67,11 @@ class EventParsingIteratorTest extends TestCase * * @return \Generator */ - public function iteratorDataProvider() + public static function iteratorDataProvider(): \Generator { foreach (self::$eventCases as $eventCase) { - $shape = $this->loadEventStreamShapeFromJson($eventCase['shape']); - $restParser = $this->createRestParser($eventCase['protocol']); + $shape = self::loadEventStreamShapeFromJson($eventCase['shape']); + $restParser = self::createRestParser($eventCase['protocol']); foreach ($eventCase['eventNames'] as $eventName) { $input = base64_decode(file_get_contents( __DIR__ . '/../eventstream_fixtures/input/' . $eventName @@ -95,9 +95,8 @@ public function iteratorDataProvider() * this unique element against the expected output, otherwise we evaluate the whole array * against the expected output. The reason for this is to test parsing either single or multiple * events. - * - * @dataProvider iteratorDataProvider */ + #[DataProvider('iteratorDataProvider')] public function testParsedEventsMatchExpectedOutput($iterator, $expectedOutput) { $parsedMessage = []; @@ -115,9 +114,8 @@ public function testParsedEventsMatchExpectedOutput($iterator, $expectedOutput) /** * This method tests for whether the deserialized event members match the equivalent * shape member types. - * - * @dataProvider iteratorDataProvider */ + #[DataProvider('iteratorDataProvider')] public function testParsedEventsMatchExpectedType($iterator) { $reflectedIteratorClass = new \ReflectionClass(get_class($iterator)); @@ -197,7 +195,7 @@ public function testThrowsOnErrorEvent() __DIR__ . '/../eventstream_fixtures/input/error_event' )) ); - $shape = $this->loadEventStreamShapeFromJson(self::EVENT_STREAM_SHAPE); + $shape = self::loadEventStreamShapeFromJson(self::EVENT_STREAM_SHAPE); $iterator = new EventParsingIterator( $stream, $shape, @@ -226,7 +224,7 @@ public function testThrowsOnUnknownMessageType() { $this->expectExceptionMessage("Failed to parse unknown message type."); $this->expectException(\Aws\Api\Parser\Exception\ParserException::class); - $shape = $this->loadEventStreamShapeFromJson(self::EVENT_STREAM_SHAPE); + $shape = self::loadEventStreamShapeFromJson(self::EVENT_STREAM_SHAPE); $stream = Psr7\Utils::streamFor( base64_decode(file_get_contents( __DIR__ . '/../eventstream_fixtures/input/unknown_message_type' @@ -251,7 +249,7 @@ public function testThrowsOnUnknownEventType() { $this->expectExceptionMessage("Failed to parse without event type."); $this->expectException(\Aws\Api\Parser\Exception\ParserException::class); - $shape = $this->loadEventStreamShapeFromJson(self::EVENT_STREAM_SHAPE); + $shape = self::loadEventStreamShapeFromJson(self::EVENT_STREAM_SHAPE); $stream = Psr7\Utils::streamFor( base64_decode(file_get_contents( __DIR__ . '/../eventstream_fixtures/input/unknown_event_type' @@ -277,7 +275,7 @@ public function testThrowsOnUnknownEventType() * * @return StructureShape */ - private function loadEventStreamShapeFromJson($jsonFilePath) + private static function loadEventStreamShapeFromJson($jsonFilePath): StructureShape { $shape = json_decode( file_get_contents($jsonFilePath), @@ -293,22 +291,21 @@ private function loadEventStreamShapeFromJson($jsonFilePath) /** * This method creates an instance of a RestParser class based on the protocol provided. * + * @param $protocol + * * @return AbstractRestParser */ - private function createRestParser($protocol) + private static function createRestParser($protocol): AbstractRestParser { - switch ($protocol) { - case self::PROTOCOL_XML: - return new RestXmlParser(new Service([], function () { - return []; - })); - case self::PROTOCOL_JSON: - return new RestJsonParser(new Service([], function () { - return []; - })); - default: - throw new ParserException('Unknown parser protocol "' . $protocol . '"'); - } + return match ($protocol) { + self::PROTOCOL_XML => new RestXmlParser(new Service([], function () { + return []; + })), + self::PROTOCOL_JSON => new RestJsonParser(new Service([], function () { + return []; + })), + default => throw new ParserException('Unknown parser protocol "' . $protocol . '"'), + }; } public function testCanHandleNonSeekableStream() @@ -345,7 +342,7 @@ public function testCanHandleNonSeekableStream() $eventParsingIterator = new EventParsingIterator( $noSeekableStream, $structureShape, - $this->createRestParser(self::PROTOCOL_JSON) + self::createRestParser(self::PROTOCOL_JSON) ); $expected = [ 'person' => [ @@ -366,20 +363,12 @@ public function testHandleInitialResponse() EOF; $stream = Psr7\Utils::streamFor(base64_decode($event)); $structureShape = new StructureShape([], new ShapeMap([])); - $iterator = new EventParsingIterator($stream, $structureShape, $this->createRestParser(self::PROTOCOL_JSON)); + $iterator = new EventParsingIterator($stream, $structureShape, self::createRestParser(self::PROTOCOL_JSON)); $this->assertEquals(['initial-response' => []], $iterator->current()); } - /** - * @param array $eventStreams - * @param string $expectedExceptionMessage - * - * @return void - * - * @dataProvider handleEventWithExceptionsProvider - * - */ + #[DataProvider('handleEventWithExceptionsProvider')] public function testHandleEventWithExceptions( array $eventStreams, string $expectedExceptionMessage, @@ -404,7 +393,7 @@ public function testHandleEventWithExceptions( $iterator = new EventParsingIterator( $stream, $structureShape, - $this->createRestParser(self::PROTOCOL_JSON) + self::createRestParser(self::PROTOCOL_JSON) ); foreach ($iterator as $_) {} } @@ -412,7 +401,8 @@ public function testHandleEventWithExceptions( /** * @return array[] */ - public function handleEventWithExceptionsProvider(): array { + public static function handleEventWithExceptionsProvider(): array + { return [ 'handle_event_with_exceptions_1' => [ 'event_streams' => diff --git a/tests/Api/Parser/Exception/ParserExceptionTest.php b/tests/Api/Parser/Exception/ParserExceptionTest.php index 5c588d8042..76d63e86e6 100644 --- a/tests/Api/Parser/Exception/ParserExceptionTest.php +++ b/tests/Api/Parser/Exception/ParserExceptionTest.php @@ -3,10 +3,9 @@ use Aws\Api\Parser\Exception\ParserException; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Api\Parser\Exception\ParserException - */ +#[CoversClass(ParserException::class)] class ParserExceptionTest extends TestCase { public function testExtractsContext() diff --git a/tests/Api/Parser/JsonParserTest.php b/tests/Api/Parser/JsonParserTest.php index 8a2c82071b..b4128d3a9f 100644 --- a/tests/Api/Parser/JsonParserTest.php +++ b/tests/Api/Parser/JsonParserTest.php @@ -2,19 +2,23 @@ namespace Aws\Test\Api\Parser; use Aws\Api\Parser\Exception\ParserException; +use Aws\Api\Parser\JsonRpcParser; +use Aws\Api\Parser\JsonParser; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; /** * This class tests the custom functionality of the JsonParser; * generic testing is done in ComplianceTest.php - * @covers \Aws\Api\Parser\JsonRpcParser - * @covers \Aws\Api\Parser\JsonParser */ +#[CoversClass(JsonRpcParser::class)] +#[CoversClass(JsonParser::class)] class JsonParserTest extends TestCase { use ParserTestServiceTrait; - public function timeStampModelProvider() + public static function timeStampModelProvider(): array { return [ [932169600, "ParseIso8601", "1999-07-17T00:00:00+00:00"], @@ -59,7 +63,7 @@ public function timeStampModelProvider() ]; } - public function timeStampExceptionModelProvider() + public static function timeStampExceptionModelProvider(): array { return [ ["this text is not a date", "ParseIso8601", ParserException::class, "Invalid timestamp value passed to DateTimeResult::fromTimestamp"], @@ -92,9 +96,7 @@ public function timeStampExceptionModelProvider() ]; } - /** - * @dataProvider timeStampModelProvider - */ + #[DataProvider('timeStampModelProvider')] public function testHandlesTimeStamps( $timestamp, $commandName, @@ -113,9 +115,7 @@ public function testHandlesTimeStamps( self::assertEquals($expectedValue, $result); } - /** - * @dataProvider timeStampExceptionModelProvider - */ + #[DataProvider('timeStampExceptionModelProvider')] public function testTimeStampExceptions( $timestamp, $commandName, @@ -135,4 +135,3 @@ public function testTimeStampExceptions( $handler($command)->wait(); } } - diff --git a/tests/Api/Parser/JsonRpcParserTest.php b/tests/Api/Parser/JsonRpcParserTest.php index d966b59258..a289e4ed80 100644 --- a/tests/Api/Parser/JsonRpcParserTest.php +++ b/tests/Api/Parser/JsonRpcParserTest.php @@ -13,16 +13,19 @@ use Aws\CommandInterface; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Utils; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversNothing; use PHPUnit\Framework\TestCase; +#[CoversClass(JsonRpcParser::class)] class JsonRpcParserTest extends TestCase { - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testCanHandleNullResponses() { $operation = $this->getMockBuilder(Operation::class) ->disableOriginalConstructor() - ->setMethods(['getOutput']) + ->onlyMethods(['getOutput']) ->getMock(); $operation->expects($this->any()) ->method('getOutput') @@ -30,13 +33,13 @@ public function testCanHandleNullResponses() ->willReturn( $this->getMockBuilder(Shape::class) ->disableOriginalConstructor() - ->setMethods([]) + ->onlyMethods([]) ->getMock() ); $service = $this->getMockBuilder(Service::class) ->disableOriginalConstructor() - ->setMethods(['getOperation']) + ->onlyMethods(['getOperation']) ->getMock(); $service->expects($this->any()) ->method('getOperation') @@ -45,7 +48,7 @@ public function testCanHandleNullResponses() $parser = $this->getMockBuilder(JsonParser::class) ->disableOriginalConstructor() - ->setMethods(['parse']) + ->onlyMethods(['parse']) ->getMock(); $parser->expects($this->any()) ->method('parse') @@ -57,13 +60,14 @@ public function testCanHandleNullResponses() $this->getMockBuilder(CommandInterface::class)->getMock(), new Response(200, [], json_encode(null)) ); + $this->assertTrue(true); } public function testCanHandleEmptyResponses() { $operation = $this->getMockBuilder(Operation::class) ->disableOriginalConstructor() - ->setMethods(['offsetGet']) + ->onlyMethods(['offsetGet']) ->getMock(); $operation->expects($this->atLeastOnce()) ->method('offsetGet') @@ -72,7 +76,7 @@ public function testCanHandleEmptyResponses() $service = $this->getMockBuilder(Service::class) ->disableOriginalConstructor() - ->setMethods(['getOperation']) + ->onlyMethods(['getOperation']) ->getMock(); $service->expects($this->any()) ->method('getOperation') @@ -81,7 +85,7 @@ public function testCanHandleEmptyResponses() $parser = $this->getMockBuilder(JsonParser::class) ->disableOriginalConstructor() - ->setMethods(['parse']) + ->onlyMethods(['parse']) ->getMock(); $parser->expects($this->never()) ->method('parse'); @@ -96,13 +100,13 @@ public function testCanHandleEmptyResponses() public function testCanHandleNonStreamingResponses() { $service = $this->getMockBuilder(Service::class) - -> disableOriginalConstructor() - -> setMethods(['getOperation']) - -> getMock(); + ->disableOriginalConstructor() + ->onlyMethods(['getOperation']) + ->getMock(); $operation = $this->getMockBuilder(Operation::class) - -> disableOriginalConstructor() - -> setMethods(['getOutput']) - -> getMock(); + ->disableOriginalConstructor() + ->onlyMethods(['getOutput']) + ->getMock(); $outputShape = new StructureShape([ 'type' => 'structure', 'members' => [ @@ -121,16 +125,16 @@ public function testCanHandleNonStreamingResponses() ] ], new ShapeMap([])); $operation->method('getOutput') - -> willReturn($outputShape); + ->willReturn($outputShape); $operation['output'] = $outputShape; $service->method('getOperation') - -> withAnyParameters() - -> willReturn($operation); + ->withAnyParameters() + ->willReturn($operation); $jsonRPCParser = new JsonRpcParser($service); $command = $this->getMockBuilder(Command::class) - -> disableOriginalConstructor() - -> setMethods(['getName']) - -> getMock(); + ->disableOriginalConstructor() + ->onlyMethods(['getName']) + ->getMock(); $command->method('getName') ->willReturn('TestCommand'); $body = json_encode([ @@ -154,13 +158,13 @@ public function testCanHandleNonStreamingResponses() public function testCanHandleStreamingResponses() { $service = $this->getMockBuilder(Service::class) - -> disableOriginalConstructor() - -> setMethods(['getOperation']) - -> getMock(); + ->disableOriginalConstructor() + ->onlyMethods(['getOperation']) + ->getMock(); $operation = $this->getMockBuilder(Operation::class) - -> disableOriginalConstructor() - -> setMethods(['getOutput']) - -> getMock(); + ->disableOriginalConstructor() + ->onlyMethods(['getOutput']) + ->getMock(); $outputShape = new StructureShape([ 'type' => 'structure', 'members' => [ @@ -190,16 +194,16 @@ public function testCanHandleStreamingResponses() ] ], new ShapeMap([])); $operation->method('getOutput') - -> willReturn($outputShape); + ->willReturn($outputShape); $operation['output'] = $outputShape; $service->method('getOperation') - -> withAnyParameters() - -> willReturn($operation); + ->withAnyParameters() + ->willReturn($operation); $jsonRPCParser = new JsonRpcParser($service); $command = $this->getMockBuilder(Command::class) - -> disableOriginalConstructor() - -> setMethods(['getName']) - -> getMock(); + ->disableOriginalConstructor() + ->onlyMethods(['getName']) + ->getMock(); $command->method('getName') ->willReturn('TestCommand'); $expectedResult = [ diff --git a/tests/Api/Parser/NonSeekableStreamDecodingEventStreamIteratorTest.php b/tests/Api/Parser/NonSeekableStreamDecodingEventStreamIteratorTest.php index d4b5630253..9da889679f 100644 --- a/tests/Api/Parser/NonSeekableStreamDecodingEventStreamIteratorTest.php +++ b/tests/Api/Parser/NonSeekableStreamDecodingEventStreamIteratorTest.php @@ -6,9 +6,12 @@ use GuzzleHttp\Psr7\NoSeekStream; use GuzzleHttp\Psr7\StreamDecoratorTrait; use GuzzleHttp\Psr7\Utils; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\TestCase; use Psr\Http\Message\StreamInterface; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +#[CoversClass(NonSeekableStreamDecodingEventStreamIterator::class)] class NonSeekableStreamDecodingEventStreamIteratorTest extends TestCase { const EVENT_STREAMS_DIR = __DIR__ . '/event-streams/'; @@ -73,14 +76,7 @@ public function testValidReturnsTrueOnEOF() $this->assertFalse($iterator->valid()); } - /** - * @param string $eventName - * @param array $expected - * - * @dataProvider readAndHashBytesHandlesPartialReadsProvider - * - * @return void - */ + #[DataProvider('readAndHashBytesHandlesPartialReadsProvider')] public function testReadAndHashBytesHandlesPartialReads( string $eventName, array $expected @@ -123,10 +119,7 @@ public function testReadAndHashBytesHandlesPartialReads( ); } - /** - * @return \Generator - */ - public function readAndHashBytesHandlesPartialReadsProvider(): \Generator + public static function readAndHashBytesHandlesPartialReadsProvider(): \Generator { $cases = json_decode( file_get_contents(self::CASES_FILE), diff --git a/tests/Api/Parser/RestJsonParserTest.php b/tests/Api/Parser/RestJsonParserTest.php index 132c2cc35d..a0e64d4a89 100644 --- a/tests/Api/Parser/RestJsonParserTest.php +++ b/tests/Api/Parser/RestJsonParserTest.php @@ -7,22 +7,16 @@ use Aws\CommandInterface; use Aws\Test\Api\Parser\ParserTestServiceTrait; use GuzzleHttp\Psr7\Response; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Api\Parser\RestJsonParser - */ +#[CoversClass(RestJsonParser::class)] class RestJsonParserTest extends TestCase { use ParserTestServiceTrait; - /** - * @param string|array $value - * @param array $expected - * - * @return void - * @dataProvider parsesDocumentTypePayloadProvider - */ + #[DataProvider('parsesDocumentTypePayloadProvider')] public function testParsesDocumentTypePayload( string $value, string|array $expected @@ -40,7 +34,7 @@ public function testParsesDocumentTypePayload( self::assertEquals($expected, $result['documentValue']); } - public function parsesDocumentTypePayloadProvider(): iterable + public static function parsesDocumentTypePayloadProvider(): iterable { return [ 'string payload' => ["\"hello\"", 'hello'], diff --git a/tests/Api/Parser/RestXmlParserTest.php b/tests/Api/Parser/RestXmlParserTest.php index 3a968373ab..431d347dfc 100644 --- a/tests/Api/Parser/RestXmlParserTest.php +++ b/tests/Api/Parser/RestXmlParserTest.php @@ -6,11 +6,10 @@ use Aws\Api\Service; use Aws\CommandInterface; use GuzzleHttp\Psr7\Response; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Api\Parser\RestXmlParser - */ +#[CoversClass(RestXmlParser::class)] class RestXmlParserTest extends TestCase { public function testParsesFalsyHeaderValues(): void diff --git a/tests/Api/Parser/XmlParserTest.php b/tests/Api/Parser/XmlParserTest.php index ab41a62986..c4ddaf1983 100644 --- a/tests/Api/Parser/XmlParserTest.php +++ b/tests/Api/Parser/XmlParserTest.php @@ -2,19 +2,23 @@ namespace Aws\Test\Api\Parser; use Aws\Api\Parser\Exception\ParserException; +use Aws\Api\Parser\RestXmlParser; +use Aws\Api\Parser\XmlParser; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; /** * This class tests the custom functionality of the XmlParser; * generic testing is done in ComplianceTest.php - * @covers \Aws\Api\Parser\RestXmlParser - * @covers \Aws\Api\Parser\XmlParser */ +#[CoversClass(RestXmlParser::class)] +#[CoversClass(XmlParser::class)] class XmlParserTest extends TestCase { use ParserTestServiceTrait; - public function timeStampModelProvider() + public static function timeStampModelProvider(): array { return [ [932169600, "ParseIso8601", "1999-07-17T00:00:00+00:00"], @@ -62,7 +66,7 @@ public function timeStampModelProvider() ]; } - public function timeStampExceptionModelProvider() + public static function timeStampExceptionModelProvider(): array { return [ ["this text is not a date", "ParseIso8601", ParserException::class, "Invalid timestamp value passed to DateTimeResult::fromTimestamp"], @@ -89,9 +93,7 @@ public function timeStampExceptionModelProvider() ]; } - /** - * @dataProvider timeStampModelProvider - */ + #[DataProvider('timeStampModelProvider')] public function testTimeStamps($timestamp, $commandName, $expectedValue) { $service = $this->generateTestService('rest-xml'); @@ -107,10 +109,7 @@ public function testTimeStamps($timestamp, $commandName, $expectedValue) self::assertEquals($expectedValue, $result); } - - /** - * @dataProvider timeStampExceptionModelProvider - */ + #[DataProvider('timeStampExceptionModelProvider')] public function testExceptionTimeStamps( $timestamp, $commandName, diff --git a/tests/Api/Serializer/ComplianceTest.php b/tests/Api/Serializer/ComplianceTest.php index c0aadf4e32..7934c280de 100644 --- a/tests/Api/Serializer/ComplianceTest.php +++ b/tests/Api/Serializer/ComplianceTest.php @@ -6,18 +6,27 @@ use Aws\Signature\SignatureInterface; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; - -/** - * @covers \Aws\Api\Serializer\QuerySerializer - * @covers \Aws\Api\Serializer\JsonRpcSerializer - * @covers \Aws\Api\Serializer\RestSerializer - * @covers \Aws\Api\Serializer\RestJsonSerializer - * @covers \Aws\Api\Serializer\RestXmlSerializer - * @covers \Aws\Api\Serializer\JsonBody - * @covers \Aws\Api\Serializer\XmlBody - * @covers \Aws\Api\Serializer\Ec2ParamBuilder - * @covers \Aws\Api\Serializer\QueryParamBuilder - */ +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; +use Aws\Api\Serializer\QuerySerializer; +use Aws\Api\Serializer\JsonRpcSerializer; +use Aws\Api\Serializer\RestSerializer; +use Aws\Api\Serializer\RestJsonSerializer; +use Aws\Api\Serializer\RestXmlSerializer; +use Aws\Api\Serializer\JsonBody; +use Aws\Api\Serializer\XmlBody; +use Aws\Api\Serializer\Ec2ParamBuilder; +use Aws\Api\Serializer\QueryParamBuilder; + +#[CoversClass(QuerySerializer::class)] +#[CoversClass(JsonRpcSerializer::class)] +#[CoversClass(RestSerializer::class)] +#[CoversClass(RestJsonSerializer::class)] +#[CoversClass(RestXmlSerializer::class)] +#[CoversClass(JsonBody::class)] +#[CoversClass(XmlBody::class)] +#[CoversClass(Ec2ParamBuilder::class)] +#[CoversClass(QueryParamBuilder::class)] class ComplianceTest extends TestCase { use UsesServiceTrait; @@ -39,8 +48,7 @@ class ComplianceTest extends TestCase 'HttpPayloadWithMemberXmlName' => true ]; - /** @doesNotPerformAssertions */ - public function testCaseProvider(): \Generator + public static function caseProvider(): \Generator { $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator( @@ -81,9 +89,7 @@ function () { return []; } } } - /** - * @dataProvider testCaseProvider - */ + #[DataProvider('caseProvider')] public function testPassesComplianceTest( Service $service, $name, @@ -182,6 +188,7 @@ public function testPassesComplianceTest( $this->assertNotTrue($request->hasHeader($header)); } } + $this->assertTrue(true); } private function assertXmlEquals( diff --git a/tests/Api/Serializer/JsonBodyTest.php b/tests/Api/Serializer/JsonBodyTest.php index d7c180285b..5f070c56ec 100644 --- a/tests/Api/Serializer/JsonBodyTest.php +++ b/tests/Api/Serializer/JsonBodyTest.php @@ -7,10 +7,10 @@ use Aws\Api\ShapeMap; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Api\Serializer\JsonBody - */ +#[CoversClass(JsonBody::class)] class JsonBodyTest extends TestCase { use UsesServiceTrait; @@ -24,7 +24,7 @@ public function testUsesEmptyHashByDefault(): void ); } - public function formatProvider() + public static function formatProvider(): iterable { yield [['type' => 'string'], ['foo' => 'bar'], '{"foo":"bar"}']; yield [['type' => 'integer'], ['foo' => 1], '{"foo":1}']; @@ -144,9 +144,7 @@ public function formatProvider() ]; } - /** - * @dataProvider formatProvider - */ + #[DataProvider('formatProvider')] public function testFormatsJson(array $def, array $args, string $result): void { $j = new JsonBody(new Service([], function() { return []; })); @@ -154,7 +152,7 @@ public function testFormatsJson(array $def, array $args, string $result): void $this->assertEquals($result, $j->build($shape, $args)); } - public function formatNoReferencesProvider(): iterable + public static function formatNoReferencesProvider(): iterable { return [ // Formats nested maps and structures @@ -192,9 +190,7 @@ public function formatNoReferencesProvider(): iterable ]; } - /** - * @dataProvider formatNoReferencesProvider - */ + #[DataProvider('formatNoReferencesProvider')] public function testFormatsJsonDoesNotCreateReferences( array $def, array $args, @@ -211,13 +207,7 @@ public function testFormatsJsonDoesNotCreateReferences( $this->assertEquals($result, $builtShape); } - /** - * @param string|array $args - * @param string $expected - * - * @return void - * @dataProvider buildsDocTypesProvider - */ + #[DataProvider('buildsDocTypesProvider')] public function testBuildsDocTypes(string|array $args, string $expected): void { $j = new JsonBody(new Service([], function() { return []; })); @@ -233,7 +223,7 @@ public function testBuildsDocTypes(string|array $args, string $expected): void $this->assertEquals($expected, $builtShape); } - public function buildsDocTypesProvider(): iterable + public static function buildsDocTypesProvider(): iterable { return [ ['hello', '"hello"'], diff --git a/tests/Api/Serializer/JsonRpcSerializerTest.php b/tests/Api/Serializer/JsonRpcSerializerTest.php index ecc0bd0852..373f835a39 100644 --- a/tests/Api/Serializer/JsonRpcSerializerTest.php +++ b/tests/Api/Serializer/JsonRpcSerializerTest.php @@ -9,10 +9,9 @@ use Aws\EndpointV2\Ruleset\RulesetEndpoint; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Api\Serializer\JsonRpcSerializer - */ +#[CoversClass(JsonRpcSerializer::class)] class JsonRpcSerializerTest extends TestCase { use UsesServiceTrait; diff --git a/tests/Api/Serializer/QuerySerializerTest.php b/tests/Api/Serializer/QuerySerializerTest.php index f5619a5894..176355d5ee 100644 --- a/tests/Api/Serializer/QuerySerializerTest.php +++ b/tests/Api/Serializer/QuerySerializerTest.php @@ -9,10 +9,9 @@ use Aws\EndpointV2\Ruleset\RulesetEndpoint; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Api\Serializer\QuerySerializer - */ +#[CoversClass(QuerySerializer::class)] class QuerySerializerTest extends TestCase { use UsesServiceTrait; diff --git a/tests/Api/Serializer/RestJsonSerializerTest.php b/tests/Api/Serializer/RestJsonSerializerTest.php index 1781724acd..1906f1822d 100644 --- a/tests/Api/Serializer/RestJsonSerializerTest.php +++ b/tests/Api/Serializer/RestJsonSerializerTest.php @@ -12,10 +12,10 @@ use Aws\Test\UsesServiceTrait; use Psr\Http\Message\RequestInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Api\Serializer\RestJsonSerializer - */ +#[CoversClass(RestJsonSerializer::class)] class RestJsonSerializerTest extends TestCase { use UsesServiceTrait; @@ -260,6 +260,7 @@ public function testPreparesRequestsWithJsonValueTraitString(): void $this->assertSame('POST', $request->getMethod()); $this->assertSame('http://foo.com/', (string) $request->getUri()); $this->assertSame('', $request->getHeaderLine('Content-Type')); + $this->assertTrue(true); } public function testPreparesRequestsWithJsonValueTraitArray(): void @@ -305,10 +306,10 @@ public function testPreparesRequestsWithStructPayload(): void } /** - * @dataProvider doctypeTestProvider * @param $input * @param $expectedOutput */ + #[DataProvider('doctypeTestProvider')] public function testHandlesDoctype($input, $expectedOutput): void { $request = $this->getRequest('doctype', $input); @@ -321,8 +322,7 @@ public function testHandlesDoctype($input, $expectedOutput): void ); } - - public function doctypeTestProvider(): iterable + public static function doctypeTestProvider(): iterable { return [ [ @@ -356,12 +356,11 @@ public function doctypeTestProvider(): iterable ]; } - /** - * @dataProvider restJsonContentTypeProvider * @param string $operation * @param array $input */ + #[DataProvider('restJsonContentTypeProvider')] public function testRestJsonContentTypeNoPayload( string $operation, array $input @@ -377,8 +376,7 @@ public function testRestJsonContentTypeNoPayload( self::assertEmpty($request->getHeader("Content-length")); } - - public function restJsonContentTypeProvider(): iterable + public static function restJsonContentTypeProvider(): iterable { return [ [ @@ -391,10 +389,10 @@ public function restJsonContentTypeProvider(): iterable } /** - * @dataProvider boolProvider * @param bool $arg * @param string $expected */ + #[DataProvider('boolProvider')] public function testSerializesHeaderValueToBoolString( bool $arg, string $expected @@ -404,7 +402,7 @@ public function testSerializesHeaderValueToBoolString( $this->assertSame($expected, $request->getHeaderLine('Is-Bool')); } - public function boolProvider(): iterable + public static function boolProvider(): iterable { return [ [true, 'true'], @@ -424,10 +422,8 @@ public function testDoesNotOverrideScheme(): void /** * @param string|array $input * @param string $expectedOutput - * - * @return void - * @dataProvider handlesDocTypeAsPayloadProvider */ + #[DataProvider('handlesDocTypeAsPayloadProvider')] public function testHandlesDocTypeAsPayload( string|array $input, string $expectedOutput @@ -443,7 +439,7 @@ public function testHandlesDocTypeAsPayload( ); } - public function handlesDocTypeAsPayloadProvider(): \Generator + public static function handlesDocTypeAsPayloadProvider(): \Generator { yield 'string payload' => ['hello', '"hello"']; yield 'simple string field' => [ @@ -486,10 +482,8 @@ public function handlesDocTypeAsPayloadProvider(): \Generator /** * @param array|string $input - * - * @return void - * @dataProvider rejectsInvalidJsonAsPayloadProvider */ + #[DataProvider('rejectsInvalidJsonAsPayloadProvider')] public function testRejectsInvalidJsonAsPayload(array|string $input): void { $this->expectException(InvalidJsonException::class); @@ -497,7 +491,7 @@ public function testRejectsInvalidJsonAsPayload(array|string $input): void $this->getRequest('DocumentTypeAsPayload', ['documentValue' => $input]); } - public function rejectsInvalidJsonAsPayloadProvider(): iterable + public static function rejectsInvalidJsonAsPayloadProvider(): iterable { return [ 'malformed byte sequence' => ["\xB1\x31"], @@ -519,10 +513,8 @@ public function rejectsInvalidJsonAsPayloadProvider(): iterable * @param array $queryParams * @param string $expected * @param string $description - * - * @return void - * @dataProvider endpointResolutionProvider */ + #[DataProvider('endpointResolutionProvider')] public function testEndpointResolution( string $endpoint, string $requestUri, @@ -545,9 +537,7 @@ public function testEndpointResolution( ); } - /** - * @dataProvider endpointResolutionProvider - */ + #[DataProvider('endpointResolutionProvider')] public function testEndpointV2Resolution( string $endpoint, string $requestUri, @@ -571,9 +561,7 @@ public function testEndpointV2Resolution( ); } - /** - * @dataProvider geoServiceEndpointResolutionProvider - */ + #[DataProvider('geoServiceEndpointResolutionProvider')] public function testGeoServiceEndpointResolution( string $endpoint, string $requestUri, @@ -595,9 +583,7 @@ public function testGeoServiceEndpointResolution( ); } - /** - * @dataProvider geoServiceEndpointResolutionProvider - */ + #[DataProvider('geoServiceEndpointResolutionProvider')] public function testGeoServiceEndpointV2Resolution( string $endpoint, string $requestUri, @@ -620,7 +606,7 @@ public function testGeoServiceEndpointV2Resolution( ); } - public function endpointResolutionProvider(): \Generator + public static function endpointResolutionProvider(): \Generator { // Basic endpoints without path yield 'no_base_path_simple_request' => [ @@ -813,7 +799,7 @@ public function endpointResolutionProvider(): \Generator ]; } - public function geoServiceEndpointResolutionProvider(): \Generator + public static function geoServiceEndpointResolutionProvider(): \Generator { yield 'geo_places_v2' => [ 'endpoint' => 'https://places.geo.region.amazonaws.com/v2', @@ -856,9 +842,7 @@ public function geoServiceEndpointResolutionProvider(): \Generator ]; } - /** - * @dataProvider geoServiceE2EProvider - */ + #[DataProvider('geoServiceE2EProvider')] public function testGeoServiceEndpointResolutionE2E( string $service, string $region, @@ -891,7 +875,7 @@ public function testGeoServiceEndpointResolutionE2E( $client->{$operation}($params); } - public function geoServiceE2EProvider(): \Generator + public static function geoServiceE2EProvider(): \Generator { yield 'geo_places_simple' => [ 'service' => 'geo-places', diff --git a/tests/Api/Serializer/RestXmlSerializerTest.php b/tests/Api/Serializer/RestXmlSerializerTest.php index 940c1bcecc..6bd3dde2b6 100644 --- a/tests/Api/Serializer/RestXmlSerializerTest.php +++ b/tests/Api/Serializer/RestXmlSerializerTest.php @@ -10,10 +10,10 @@ use Aws\Result; use Aws\Test\UsesServiceTrait; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Api\Serializer\RestXmlSerializer - */ +#[CoversClass(RestXmlSerializer::class)] class RestXmlSerializerTest extends TestCase { use UsesServiceTrait; @@ -83,10 +83,10 @@ public function testPreparesRequestsWithStructurePayloadXmlContentType() } /** - * @dataProvider boolProvider * @param bool $arg * @param string $expected */ + #[DataProvider('boolProvider')] public function testSerializesHeaderValueToBoolString($arg, $expected) { $request = $this->getRequest('PutObject', [ @@ -101,7 +101,8 @@ public function testSerializesHeaderValueToBoolString($arg, $expected) ); } - public function boolProvider() { + public static function boolProvider(): array + { return [ [true, 'true'], [false, 'false'] @@ -118,9 +119,7 @@ public function testDoesNotOverrideScheme() $this->assertSame('http://foo.com/', (string) $request->getUri()); } - /** - * @dataProvider s3EndpointResolutionProvider - */ + #[DataProvider('s3EndpointResolutionProvider')] public function testS3EndpointResolution( string $endpoint, string $bucket, @@ -142,9 +141,7 @@ public function testS3EndpointResolution( ); } - /** - * @dataProvider s3EndpointResolutionProvider - */ + #[DataProvider('s3EndpointResolutionProvider')] public function testS3EndpointV2Resolution( string $endpoint, string $bucket, @@ -167,9 +164,7 @@ public function testS3EndpointV2Resolution( ); } - /** - * @dataProvider s3DotSegmentProvider - */ + #[DataProvider('s3DotSegmentProvider')] public function testS3DotSegmentPreservation( string $endpoint, string $bucket, @@ -191,9 +186,7 @@ public function testS3DotSegmentPreservation( ); } - /** - * @dataProvider s3DotSegmentProvider - */ + #[DataProvider('s3DotSegmentProvider')] public function testS3DotSegmentV2Preservation( string $endpoint, string $bucket, @@ -216,9 +209,7 @@ public function testS3DotSegmentV2Preservation( ); } - /** - * @dataProvider restXmlEndpointResolutionProvider - */ + #[DataProvider('restXmlEndpointResolutionProvider')] public function testRestXmlEndpointResolution( string $endpoint, string $requestUri, @@ -241,9 +232,7 @@ public function testRestXmlEndpointResolution( ); } - /** - * @dataProvider restXmlEndpointResolutionProvider - */ + #[DataProvider('restXmlEndpointResolutionProvider')] public function testRestXmlEndpointV2Resolution( string $endpoint, string $requestUri, @@ -267,7 +256,7 @@ public function testRestXmlEndpointV2Resolution( ); } - public function s3EndpointResolutionProvider(): \Generator + public static function s3EndpointResolutionProvider(): \Generator { // Virtual-hosted-style (default) yield 's3_virtual_hosted_standard' => [ @@ -379,7 +368,7 @@ public function s3EndpointResolutionProvider(): \Generator ]; } - public function s3DotSegmentProvider(): \Generator + public static function s3DotSegmentProvider(): \Generator { // Virtual-hosted-style (default) yield 's3_virtual_dot_segment_start' => [ @@ -440,7 +429,7 @@ public function s3DotSegmentProvider(): \Generator ]; } - public function restXmlEndpointResolutionProvider(): \Generator + public static function restXmlEndpointResolutionProvider(): \Generator { // Basic REST XML service endpoints yield 'restxml_no_path' => [ @@ -489,9 +478,7 @@ public function restXmlEndpointResolutionProvider(): \Generator ]; } - /** - * @dataProvider s3E2EProvider - */ + #[DataProvider('s3E2EProvider')] public function testS3EndpointResolutionE2E( string $region, string $bucket, @@ -525,9 +512,7 @@ public function testS3EndpointResolutionE2E( $client->getObject(['Bucket' => $bucket, 'Key' => $key]); } - /** - * @dataProvider s3E2EProvider - */ + #[DataProvider('s3E2EProvider')] public function testS3EndpointResolutionE2ELegacyProvider( string $region, string $bucket, @@ -562,7 +547,7 @@ public function testS3EndpointResolutionE2ELegacyProvider( $client->getObject(['Bucket' => $bucket, 'Key' => $key]); } - public function s3E2EProvider(): \Generator + public static function s3E2EProvider(): \Generator { // Virtual-hosted style (default) yield 's3_virtual_simple' => [ diff --git a/tests/Api/ServiceTest.php b/tests/Api/ServiceTest.php index 0a79674a0e..bf69a325e2 100644 --- a/tests/Api/ServiceTest.php +++ b/tests/Api/ServiceTest.php @@ -12,10 +12,10 @@ use Aws\Test\TestServiceTrait; use Aws\Test\UsesServiceTrait; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Api\Service - */ +#[CoversClass(Service::class)] class ServiceTest extends TestCase { use UsesServiceTrait; @@ -144,7 +144,7 @@ public function testLoadWaiterConfigs() $api->getWaiterConfig('Fizz'); } - public function errorParserProvider() + public static function errorParserProvider(): array { return [ ['json', ErrorParser\JsonRpcErrorParser::class], @@ -154,9 +154,7 @@ public function errorParserProvider() ]; } - /** - * @dataProvider errorParserProvider - */ + #[DataProvider('errorParserProvider')] public function testCreatesRelevantErrorParsers($p, $cl) { $this->assertInstanceOf($cl, Service::createErrorParser($p)); @@ -168,7 +166,7 @@ public function testThrowsOnUnexpectedProtocol() Service::createErrorParser('undefined_protocol'); } - public function serializerDataProvider() + public static function serializerDataProvider(): array { return [ ['json', Serializer\JsonRpcSerializer::class], @@ -179,9 +177,7 @@ public function serializerDataProvider() ]; } - /** - * @dataProvider serializerDataProvider - */ + #[DataProvider('serializerDataProvider')] public function testCreatesSerializer($type, $cl) { $data = ['metadata' => ['protocol' => $type]]; @@ -196,7 +192,7 @@ function () { return []; } $this->assertInstanceOf($cl, $serializer); } - public function parserDataProvider() + public static function parserDataProvider(): array { return [ ['json', Parser\JsonRpcParser::class], @@ -207,9 +203,7 @@ public function parserDataProvider() ]; } - /** - * @dataProvider parserDataProvider - */ + #[DataProvider('parserDataProvider')] public function testCreatesParsers($type, $cl) { $service = new Service( @@ -306,9 +300,7 @@ function () { return []; } ); } - /** - * @dataProvider selectsProtocolProvider - */ + #[DataProvider('selectsProtocolProvider')] public function testSelectsProtocol($protocols, $expected) { $s = new Service( @@ -352,7 +344,7 @@ function () { return []; } $this->assertEquals($expected, $protocol); } - public function selectsProtocolProvider() + public static function selectsProtocolProvider(): array { return [ [['smithy-rpc-v2-cbor', 'json'], 'json'], diff --git a/tests/Api/ShapeMapTest.php b/tests/Api/ShapeMapTest.php index bafa2a4ebf..6aa33be110 100644 --- a/tests/Api/ShapeMapTest.php +++ b/tests/Api/ShapeMapTest.php @@ -4,10 +4,9 @@ use Aws\Api\Shape; use Aws\Api\ShapeMap; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Api\ShapeMap - */ +#[CoversClass(ShapeMap::class)] class ShapeMapTest extends TestCase { private $shapeDefinitions; diff --git a/tests/Api/ShapeTest.php b/tests/Api/ShapeTest.php index a0fe589a3c..7ad17bd5a4 100644 --- a/tests/Api/ShapeTest.php +++ b/tests/Api/ShapeTest.php @@ -4,11 +4,9 @@ use Aws\Api\Shape; use Aws\Api\ShapeMap; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Api\Shape - * @covers Aws\Api\AbstractModel - */ +#[CoversClass(Shape::class)] class ShapeTest extends TestCase { public function testImplementsArray() diff --git a/tests/Api/StructureShapeTest.php b/tests/Api/StructureShapeTest.php index 3bd0c8b772..e2624cbd14 100644 --- a/tests/Api/StructureShapeTest.php +++ b/tests/Api/StructureShapeTest.php @@ -4,11 +4,10 @@ use Aws\Api\Shape; use Aws\Api\ShapeMap; use Aws\Api\StructureShape; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Api\StructureShape - */ +#[CoversClass(StructureShape::class)] class StructureShapeTest extends TestCase { public function testReturnsWhenMembersAreEmpty() diff --git a/tests/Api/SupportedProtocolsTest.php b/tests/Api/SupportedProtocolsTest.php index d96f52fa3c..6a70aba830 100644 --- a/tests/Api/SupportedProtocolsTest.php +++ b/tests/Api/SupportedProtocolsTest.php @@ -4,20 +4,19 @@ use Aws\Api\SupportedProtocols; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(SupportedProtocols::class)] class SupportedProtocolsTest extends TestCase { - /** - * @dataProvider validProtocolsProvider - */ + #[DataProvider('validProtocolsProvider')] public function testIsSupportedReturnsTrueForValidProtocols(string $protocol) { $this->assertTrue(SupportedProtocols::isSupported($protocol)); } - /** - * @dataProvider invalidProtocolsProvider - */ + #[DataProvider('invalidProtocolsProvider')] public function testIsSupportedReturnsFalseForInvalidProtocols(string $protocol) { $this->assertFalse(SupportedProtocols::isSupported($protocol)); @@ -28,7 +27,7 @@ public function testIsSupportedReturnsFalseForInvalidProtocols(string $protocol) * * @return array */ - public function validProtocolsProvider(): array + public static function validProtocolsProvider(): array { return [ ['rest-json'], @@ -44,7 +43,7 @@ public function validProtocolsProvider(): array * * @return array */ - public function invalidProtocolsProvider(): array + public static function invalidProtocolsProvider(): array { return [ ['graphql'], diff --git a/tests/Api/TimestampShapeTest.php b/tests/Api/TimestampShapeTest.php index 3a3b503af7..68dd2967ef 100644 --- a/tests/Api/TimestampShapeTest.php +++ b/tests/Api/TimestampShapeTest.php @@ -4,13 +4,13 @@ use Aws\Api\TimestampShape; use Aws\Api\ShapeMap; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Api\TimestampShape - */ +#[CoversClass(TimestampShape::class)] class TimestampShapeTest extends TestCase { - public function formatProvider() + public static function formatProvider(): array { $t = strtotime('january 5, 1999'); @@ -29,9 +29,7 @@ public function formatProvider() ]; } - /** - * @dataProvider formatProvider - */ + #[DataProvider('formatProvider')] public function testFormatsData($value, $format, $result) { $s = new TimestampShape([], new ShapeMap([])); diff --git a/tests/Api/ValidatorTest.php b/tests/Api/ValidatorTest.php index 701223a7f3..00dc23022f 100644 --- a/tests/Api/ValidatorTest.php +++ b/tests/Api/ValidatorTest.php @@ -6,13 +6,14 @@ use Aws\Api\Validator; use Yoast\PHPUnitPolyfills\TestCases\TestCase; use GuzzleHttp\Psr7; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversNothing; -/** - * @covers Aws\Api\Validator - */ +#[CoversClass(Validator::class)] class ValidatorTest extends TestCase { - public function validationProvider() + public static function validationProvider(): array { return [ [ @@ -638,9 +639,7 @@ public function validationProvider() ]; } - /** - * @dataProvider validationProvider - */ + #[DataProvider('validationProvider')] public function testValidatesInput($shape, $input, $result) { $shape = Shape::create($shape, new ShapeMap([])); @@ -681,7 +680,7 @@ public function testValidatesMinByDefault() $validator->validate('Foo', $shape, ['foo' => '']); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testDoesNotValidateMaxByDefault() { $shape = Shape::create( @@ -693,9 +692,10 @@ public function testDoesNotValidateMaxByDefault() ); $validator = new Validator(); $validator->validate('Foo', $shape, ['foo' => '1234567890']); + $this->assertTrue(true); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testDoesNotValidatePatternsByDefault() { $validator = new Validator(); @@ -712,9 +712,10 @@ public function testDoesNotValidatePatternsByDefault() new ShapeMap([]) ); $validator->validate('Foo', $shape, ['caps' => 'abc']); + $this->assertTrue(true); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testCanDisableRequiredTrait() { $validator = new Validator(['required' => false]); @@ -727,5 +728,6 @@ public function testCanDisableRequiredTrait() new ShapeMap([]) ); $validator->validate('Foo', $shape, []); + $this->assertTrue(true); } } diff --git a/tests/Arn/AccessPointArnTest.php b/tests/Arn/AccessPointArnTest.php index eb56b94580..1504344f13 100644 --- a/tests/Arn/AccessPointArnTest.php +++ b/tests/Arn/AccessPointArnTest.php @@ -4,19 +4,13 @@ use Aws\Arn\AccessPointArn; use Aws\Arn\Exception\InvalidArnException; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Arn\AccessPointArn - */ +#[CoversClass(AccessPointArn::class)] class AccessPointArnTest extends TestCase { - /** - * @dataProvider parsedArnProvider - * - * @param $string - * @param $expected - * @param $expectedString - */ + #[DataProvider('parsedArnProvider')] public function testParsesArnString($string, $expected, $expectedString) { $arn = new AccessPointArn($string); @@ -31,7 +25,7 @@ public function testParsesArnString($string, $expected, $expectedString) $this->assertEquals($expectedString, (string) $arn); } - public function parsedArnProvider() + public static function parsedArnProvider(): array { return [ // All components @@ -85,12 +79,7 @@ public function parsedArnProvider() ]; } - /** - * @dataProvider invalidArnCases - * - * @param $string - * @param $message - */ + #[DataProvider('invalidArnCases')] public function testThrowsOnInvalidArn($string, $message) { try { @@ -101,7 +90,7 @@ public function testThrowsOnInvalidArn($string, $message) } } - public function invalidArnCases() + public static function invalidArnCases(): array { return [ [ diff --git a/tests/Arn/ArnParserTest.php b/tests/Arn/ArnParserTest.php index d5cb5c6623..f0d5f594f6 100644 --- a/tests/Arn/ArnParserTest.php +++ b/tests/Arn/ArnParserTest.php @@ -9,25 +9,20 @@ use Aws\Arn\S3\OutpostsBucketArn; use Aws\Arn\S3\RegionalBucketArn; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Arn\ArnParser - */ +#[CoversClass(ArnParser::class)] class ArnParserTest extends TestCase { - /** - * @dataProvider isArnCases - * - * @param $string - * @param $expected - */ + #[DataProvider('isArnCases')] public function testDeterminesShouldAttemptToParseAsArn($string, $expected) { $this->assertEquals($expected, ArnParser::isArn($string)); } - public function isArnCases() + public static function isArnCases(): array { return [ [ @@ -57,18 +52,13 @@ public function isArnCases() ]; } - /** - * @dataProvider parsedArnCases - * - * @param $string - * @param $expected - */ + #[DataProvider('parsedArnCases')] public function testCorrectlyChoosesArnClass($string, $expected) { $this->assertTrue(ArnParser::parse($string) instanceof $expected); } - public function parsedArnCases() + public static function parsedArnCases(): array { return [ [ diff --git a/tests/Arn/ArnTest.php b/tests/Arn/ArnTest.php index 0e431b2c58..5ebd3c99cd 100644 --- a/tests/Arn/ArnTest.php +++ b/tests/Arn/ArnTest.php @@ -5,20 +5,13 @@ use Aws\Arn\Exception\InvalidArnException; use GuzzleHttp\Promise\Promise; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Arn\Arn - */ +#[CoversClass(Arn::class)] class ArnTest extends TestCase { - - /** - * @dataProvider parsedArnProvider - * - * @param $string - * @param $expected - * @param $expectedString - */ + #[DataProvider('parsedArnProvider')] public function testParsesArnString($string, $expected, $expectedString) { $arn = new Arn($string); @@ -32,7 +25,7 @@ public function testParsesArnString($string, $expected, $expectedString) $this->assertEquals($expectedString, (string) $arn); } - public function parsedArnProvider() + public static function parsedArnProvider(): array { return [ // All components @@ -116,12 +109,7 @@ public function parsedArnProvider() ]; } - /** - * @dataProvider invalidArnCases - * - * @param $string - * @param $message - */ + #[DataProvider('invalidArnCases')] public function testThrowsOnInvalidArn($string, $message) { try { @@ -132,7 +120,7 @@ public function testThrowsOnInvalidArn($string, $message) } } - public function invalidArnCases() + public static function invalidArnCases(): array { return [ [ diff --git a/tests/Arn/S3/AccessPointArnTest.php b/tests/Arn/S3/AccessPointArnTest.php index c014d51cc9..cf26035b05 100644 --- a/tests/Arn/S3/AccessPointArnTest.php +++ b/tests/Arn/S3/AccessPointArnTest.php @@ -4,18 +4,13 @@ use Aws\Arn\S3\AccessPointArn; use Aws\Arn\Exception\InvalidArnException; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Arn\S3\AccessPointArn - */ +#[CoversClass(AccessPointArn::class)] class AccessPointArnTest extends TestCase { - /** - * @dataProvider invalidArnCases - * - * @param $string - * @param $message - */ + #[DataProvider('invalidArnCases')] public function testThrowsOnInvalidArn($string, $message) { try { @@ -26,7 +21,7 @@ public function testThrowsOnInvalidArn($string, $message) } } - public function invalidArnCases() + public static function invalidArnCases(): array { return [ [ diff --git a/tests/Arn/S3/OutpostsAccessPointArnTest.php b/tests/Arn/S3/OutpostsAccessPointArnTest.php index 3c5cca2143..a9afddd08c 100644 --- a/tests/Arn/S3/OutpostsAccessPointArnTest.php +++ b/tests/Arn/S3/OutpostsAccessPointArnTest.php @@ -5,19 +5,13 @@ use Aws\Arn\Exception\InvalidArnException; use Aws\Arn\S3\OutpostsAccessPointArn; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Arn\S3\OutpostsAccessPointArn - */ +#[CoversClass(OutpostsAccessPointArn::class)] class OutpostsAccessPointArnTest extends TestCase { - /** - * @dataProvider parsedArnProvider - * - * @param $string - * @param $expected - * @param $expectedString - */ + #[DataProvider('parsedArnProvider')] public function testParsesArnString($string, $expected, $expectedString) { $arn = new OutpostsAccessPointArn($string); @@ -35,7 +29,7 @@ public function testParsesArnString($string, $expected, $expectedString) $this->assertEquals($expectedString, (string) $arn); } - public function parsedArnProvider() + public static function parsedArnProvider(): array { return [ // Colon delimiters @@ -113,12 +107,7 @@ public function parsedArnProvider() ]; } - /** - * @dataProvider badArnProvider - * - * @param $string - * @param \Exception $expected - */ + #[DataProvider('badArnProvider')] public function testThrowsForBadArn($string, \Exception $expected) { try { @@ -133,7 +122,7 @@ public function testThrowsForBadArn($string, \Exception $expected) } } - public function badArnProvider() + public static function badArnProvider(): array { return [ [ diff --git a/tests/Arn/S3/OutpostsBucketArnTest.php b/tests/Arn/S3/OutpostsBucketArnTest.php index c9d6325dbc..02c6769bff 100644 --- a/tests/Arn/S3/OutpostsBucketArnTest.php +++ b/tests/Arn/S3/OutpostsBucketArnTest.php @@ -6,19 +6,13 @@ use Aws\Arn\S3\OutpostsAccessPointArn; use Aws\Arn\S3\OutpostsBucketArn; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Arn\S3\OutpostsBucketArn - */ +#[CoversClass(OutpostsBucketArn::class)] class OutpostsBucketArnTest extends TestCase { - /** - * @dataProvider parsedArnProvider - * - * @param $string - * @param $expected - * @param $expectedString - */ + #[DataProvider('parsedArnProvider')] public function testParsesArnString($string, $expected, $expectedString) { $arn = new OutpostsBucketArn($string); @@ -36,7 +30,7 @@ public function testParsesArnString($string, $expected, $expectedString) $this->assertEquals($expectedString, (string) $arn); } - public function parsedArnProvider() + public static function parsedArnProvider(): array { return [ // Colon delimiters @@ -114,12 +108,7 @@ public function parsedArnProvider() ]; } - /** - * @dataProvider badArnProvider - * - * @param $string - * @param \Exception $expected - */ + #[DataProvider('badArnProvider')] public function testThrowsForBadArn($string, \Exception $expected) { try { @@ -134,7 +123,7 @@ public function testThrowsForBadArn($string, \Exception $expected) } } - public function badArnProvider() + public static function badArnProvider(): array { return [ [ diff --git a/tests/Auth/AuthSchemeResolverTest.php b/tests/Auth/AuthSchemeResolverTest.php index 4ea193e9f1..0ae046ca69 100644 --- a/tests/Auth/AuthSchemeResolverTest.php +++ b/tests/Auth/AuthSchemeResolverTest.php @@ -8,7 +8,10 @@ use Aws\Identity\BearerTokenIdentity; use GuzzleHttp\Promise; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(AuthSchemeResolver::class)] class AuthSchemeResolverTest extends TestCase { public function testUsesDefaultSchemeMapWhenNoneProvided() @@ -34,9 +37,7 @@ public function testAcceptsCustomSchemeMap() $this->assertEquals('v4', $resolver->selectAuthScheme(['custom.auth#example'])); } - /** - * @dataProvider schemeForIdentityProvider - */ + #[DataProvider('schemeForIdentityProvider')] public function testSelectAuthSchemeReturnsCorrectSchemeForIdentity( $authScheme, $expectedSignatureVersion, @@ -62,7 +63,7 @@ public function testSelectAuthSchemeReturnsCorrectSchemeForIdentity( $this->assertEquals($expectedSignatureVersion, $resolver->selectAuthScheme($authScheme, $args)); } - public function schemeForIdentityProvider() + public static function schemeForIdentityProvider(): array { return [ [ @@ -189,16 +190,24 @@ public function testUnmetV4aRequirementsThrows() $resolver->selectAuthScheme(['aws.auth#sigv4a']); } - /** - * @dataProvider fallsBackWhenIdentityNotAvailableProvider - */ + #[DataProvider('fallsBackWhenIdentityNotAvailableProvider')] public function testFallsBackWhenIdentityNotAvailable( - $credentialProvider, - $tokenProvider, - $authSchemes, - $expected + string $credentialIdentityClass, + string $tokenIdentityClass, + array $authSchemes, + string $expected ) { + $credentialProvider = function () use ($credentialIdentityClass) { + return Promise\Create::promiseFor( + $this->createMock($credentialIdentityClass) + ); + }; + $tokenProvider = function () use ($tokenIdentityClass) { + return Promise\Create::promiseFor( + $this->createMock($tokenIdentityClass) + ); + }; if ($expected === 'error') { $this->expectException(UnresolvedAuthSchemeException::class); } @@ -206,35 +215,42 @@ public function testFallsBackWhenIdentityNotAvailable( $this->assertEquals($expected, $resolver->selectAuthScheme($authSchemes)); } - public function fallsBackWhenIdentityNotAvailableProvider() + public static function fallsBackWhenIdentityNotAvailableProvider(): array { - $credentialProvider = function () { - return Promise\Create::promiseFor( - $this->createMock(AwsCredentialIdentity::class) - ); - }; - $tokenProvider = function () { - return Promise\Create::promiseFor( - $this->createMock(BearerTokenIdentity::class) - ); - }; - $badCredentialProvider = function () { - return Promise\Create::promiseFor( - $this->createMock(BearerTokenIdentity::class) - ); - }; - $badTokenProvider = function () { - return Promise\Create::promiseFor( - $this->createMock(AwsCredentialIdentity::class) - ); - }; + $credentialIdentity = AwsCredentialIdentity::class; + $tokenIdentity = BearerTokenIdentity::class; return [ - [$credentialProvider, $tokenProvider, ['aws.auth#sigv4', 'smithy.api#httpBearerAuth'], 'v4'], - [$badCredentialProvider, $tokenProvider, ['aws.auth#sigv4', 'smithy.api#httpBearerAuth'], 'bearer'], - [$credentialProvider, $badTokenProvider, ['aws.auth#sigv4', 'smithy.api#httpBearerAuth'], 'v4'], - [$badCredentialProvider, $badTokenProvider, ['aws.auth#sigv4', 'smithy.api#httpBearerAuth'], 'error'], - [$badCredentialProvider, $tokenProvider, ['aws.auth#sigv4'], 'error'] + 'credential_provider' => [ + 'credential_identity' => $credentialIdentity, + 'token_identity' => $tokenIdentity, + 'auth_schemes' => ['aws.auth#sigv4', 'smithy.api#httpBearerAuth'], + 'resolved_auth_scheme' => 'v4' + ], + 'bad_credential_provider' => [ + 'credential_identity' => $tokenIdentity, + 'token_identity' => $tokenIdentity, + 'auth_schemes' => ['aws.auth#sigv4', 'smithy.api#httpBearerAuth'], + 'resolved_auth_scheme' => 'bearer' + ], + 'bad_token_provider' => [ + 'credential_identity' => $credentialIdentity, + 'token_identity' => $credentialIdentity, + 'auth_schemes' => ['aws.auth#sigv4', 'smithy.api#httpBearerAuth'], + 'resolved_auth_scheme' => 'v4' + ], + 'bad_credential_provider_2' => [ + 'credential_identity' => $tokenIdentity, + 'token_identity' => $credentialIdentity, + 'auth_schemes' => ['aws.auth#sigv4', 'smithy.api#httpBearerAuth'], + 'resolved_auth_scheme' => 'error' + ], + 'bad_credential_provider_3' => [ + 'credential_identity' => $tokenIdentity, + 'token_identity' => $tokenIdentity, + 'auth_schemes' => ['aws.auth#sigv4'], + 'resolved_auth_scheme' => 'error' + ] ]; } } diff --git a/tests/Auth/AuthSelectionMiddlewareTest.php b/tests/Auth/AuthSelectionMiddlewareTest.php index 210189e6e1..a7c91579de 100644 --- a/tests/Auth/AuthSelectionMiddlewareTest.php +++ b/tests/Auth/AuthSelectionMiddlewareTest.php @@ -13,17 +13,14 @@ use Aws\MockHandler; use Aws\Result; use GuzzleHttp\Promise; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(AuthSelectionMiddleware::class)] class AuthSelectionMiddlewareTest extends TestCase { - /** - * @param $serviceAuth - * @param $operationAuth - * @param $expected - * - * @dataProvider resolvesAuthSchemeWithoutCRTProvider - */ + #[DataProvider('resolvesAuthSchemeWithoutCRTProvider')] public function testResolvesAuthSchemeWithoutCRT( $serviceAuth, $operationAuth, @@ -59,7 +56,7 @@ public function testResolvesAuthSchemeWithoutCRT( $middleware($command); } - public function ResolvesAuthSchemeWithoutCRTProvider() + public static function resolvesAuthSchemeWithoutCRTProvider(): array { return [ [ @@ -91,13 +88,7 @@ public function ResolvesAuthSchemeWithoutCRTProvider() ]; } - /** - * @param $serviceAuth - * @param $operationAuth - * @param $expected - * - * @dataProvider ResolvesAuthSchemeWithCRTprovider - */ + #[DataProvider('resolvesAuthSchemeWithCRTProvider')] public function testResolvesAuthSchemeWithCRT( $serviceAuth, $operationAuth, @@ -127,7 +118,7 @@ public function testResolvesAuthSchemeWithCRT( $middleware($command); } - public function ResolvesAuthSchemeWithCRTprovider() + public static function resolvesAuthSchemeWithCRTProvider(): array { return [ [ @@ -159,20 +150,21 @@ public function ResolvesAuthSchemeWithCRTprovider() ]; } - /** - * @param $serviceAuth - * @param $operationAuth - * @param $identity - * @param $expected - * - * @dataProvider resolvesBearerAuthSchemeProvider - */ + #[DataProvider('resolvesBearerAuthSchemeProvider')] public function testResolvesBearerAuthScheme( $serviceAuth, $operationAuth, - $tokenProvider, + $identity, $expected ){ + // Normalize token provider + $tokenProvider = $identity === null + ? null + : function () use ($identity) { + return Promise\Create::promiseFor( + $this->createMock($identity) + ); + }; $nextHandler = function (CommandInterface $command) use ($expected) { $this->assertEquals($expected, $command['@context']['signature_version']); }; @@ -198,37 +190,25 @@ public function testResolvesBearerAuthScheme( $middleware($command); } - public function resolvesBearerAuthSchemeProvider() + public static function resolvesBearerAuthSchemeProvider(): array { return [ [ ['smithy.api#httpBearerAuth', 'aws.auth#sigv4'], [], - function () { - return Promise\Create::promiseFor( - $this->createMock(BearerTokenIdentity::class) - ); - }, + BearerTokenIdentity::class, 'bearer' ], [ ['smithy.api#httpBearerAuth', 'aws.auth#sigv4'], [], - function () { - return Promise\Create::promiseFor( - null - ); - }, + null, 'v4' ], [ ['aws.auth#sigv4', 'aws.auth#sigv4a'], ['smithy.api#httpBearerAuth'], - function () { - return Promise\Create::promiseFor( - $this->createMock(BearerTokenIdentity::class) - ); - }, + BearerTokenIdentity::class, 'bearer' ] ]; @@ -316,17 +296,8 @@ function () { return []; } /** * Test auth select is done based on user's provided auth schemes. - * - * @dataProvider authSelectionBasedOnUserPreferenceProvider - * - * @param array $supportedAuthSchemes - * @param array|null $serviceAuthSchemes - * @param array|null $operationAuthSchemes - * @param array|null $userPreferredAuthSchemes - * @param string $expected - * - * @return void */ + #[DataProvider('authSelectionBasedOnUserPreferenceProvider')] public function testAuthSelectionBasedOnUserPreference( array $supportedAuthSchemes, ?array $serviceAuthSchemes, @@ -377,10 +348,7 @@ public function testAuthSelectionBasedOnUserPreference( $middleware($command); } - /** - * @return \Generator - */ - public function authSelectionBasedOnUserPreferenceProvider(): \Generator + public static function authSelectionBasedOnUserPreferenceProvider(): \Generator { $cases = [ 'user_auth_scheme_preferred_none' => [ diff --git a/tests/AwsClientTest.php b/tests/AwsClientTest.php index 6523a5cf7f..d1b77b2d0b 100644 --- a/tests/AwsClientTest.php +++ b/tests/AwsClientTest.php @@ -27,10 +27,11 @@ use GuzzleHttp\Psr7\Response; use Psr\Http\Message\RequestInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversNothing; +use PHPUnit\Framework\Attributes\DataProvider; -/** - * @covers Aws\AwsClient - */ +#[CoversClass(AwsClient::class)] class AwsClientTest extends TestCase { use UsesServiceTrait; @@ -280,22 +281,24 @@ public function testSignsRequestsUsingSigner() $this->assertStringContainsString('AWS4-HMAC-SHA256', $str); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testAllowsFactoryMethodForBc() { Ec2Client::factory([ 'region' => 'us-west-2', 'version' => 'latest' ]); + $this->assertTrue(true); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testCanInstantiateAliasedClients() { new SesClient([ 'region' => 'us-west-2', 'version' => 'latest' ]); + $this->assertTrue(true); } public function testCanGetSignatureProvider() @@ -353,23 +356,41 @@ public function testDoesNotSignOperationsWithAnAuthTypeOfNone() $client->bar(); } - /** - * @param $service - * @param $clientConfig - * - * @dataProvider signOperationsWithAnAuthTypeProvider - */ - public function testSignOperationsWithAnAuthType($service, $clientConfig) - { - $client = $this->createHttpsEndpointClient($service, $clientConfig); + #[DataProvider('signOperationsWithAnAuthTypeProvider')] + public function testSignOperationsWithAnAuthType( + array $serviceDefinition, + array $clientArguments, + array $expectedHeaders, + array $expectedHeaderValues + ) + { + $clientArguments += [ + 'handler' => function(CommandInterface $command, + RequestInterface $request) + use ($expectedHeaders, $expectedHeaderValues) { + foreach ($expectedHeaders as $header) { + $this->assertTrue($request->hasHeader($header)); + } + + foreach ($expectedHeaderValues as $headerValue) { + $this->assertEquals( + $headerValue['value'], + $request->getHeaderLine($headerValue['header']) + ); + } + + return new Result(); + } + ]; + $client = $this->createHttpsEndpointClient($serviceDefinition, $clientArguments); $client->bar(); } - public function signOperationsWithAnAuthTypeProvider() + public static function signOperationsWithAnAuthTypeProvider(): array { return [ - [ - [ + 'unsigned_payload' => [ + 'service_definition' => [ 'metadata' => [ 'signatureVersion' => 'v4', ], @@ -380,21 +401,14 @@ public function signOperationsWithAnAuthTypeProvider() ], ], ], - [ - 'handler' => function ( - CommandInterface $command, - RequestInterface $request - ) { - foreach (['Authorization','X-Amz-Content-Sha256', 'X-Amz-Date'] as $signatureHeader) { - $this->assertTrue($request->hasHeader($signatureHeader)); - } - $this->assertSame('UNSIGNED-PAYLOAD', $request->getHeader('X-Amz-Content-Sha256')[0]); - return new Result; - } + 'client_arguments' => [], + 'expected_headers' => ['Authorization','X-Amz-Content-Sha256', 'X-Amz-Date'], + 'expected_header_values' => [ + ['header' => 'X-Amz-Content-Sha256', 'value' => 'UNSIGNED-PAYLOAD'] ] ], - [ - [ + 'bearer_token' => [ + 'service_definition' => [ 'metadata' => [ 'signatureVersion' => 'v4', ], @@ -405,17 +419,12 @@ public function signOperationsWithAnAuthTypeProvider() ], ], ], - [ - 'handler' => function ( - CommandInterface $command, - RequestInterface $request - ) { - - $this->assertTrue($request->hasHeader('Authorization')); - $this->assertSame('Bearer foo', $request->getHeader('Authorization')[0]); - return new Result; - }, + 'client_arguments' => [ 'token' => new Token('foo', time() + 1000) + ], + 'expected_headers' => ['Authorization'], + 'expected_header_values' => [ + ['header' => 'Authorization', 'value' => 'Bearer foo'] ] ] ]; @@ -603,7 +612,7 @@ public function testIsUseGlobalEndpoint() { ); } - /** @dataProvider configuredEndpointUrlProvider */ + #[DataProvider('configuredEndpointUrlProvider')] public function testAppliesConfiguredEndpointUrl($ini, $env, $expected) { $dir = sys_get_temp_dir() . '/.aws'; @@ -634,7 +643,7 @@ public function testAppliesConfiguredEndpointUrl($ini, $env, $expected) } } - /** @dataProvider configuredEndpointUrlProvider */ + #[DataProvider('configuredEndpointUrlProvider')] public function testDoesNotApplyConfiguredEndpointWhenConfiguredUrlsIgnored($ini, $env) { putenv('AWS_IGNORE_CONFIGURED_ENDPOINT_URLS=true'); @@ -669,7 +678,7 @@ public function testDoesNotApplyConfiguredEndpointWhenConfiguredUrlsIgnored($ini putenv('AWS_IGNORE_CONFIGURED_ENDPOINT_URLS='); } - public function configuredEndpointUrlProvider() + public static function configuredEndpointUrlProvider(): array { return [ [ @@ -774,21 +783,7 @@ public function testAppliesConfiguredSignatureVersionViaClientConfig() { $client->foo(); } - - public function testCallingEmitDeprecationWarningEmitsDeprecationWarning() - { - $this->expectDeprecation(); - $this->expectDeprecationMessage( - "This method is deprecated. It will be removed in an upcoming release." - ); - $client = $this->createClient(); - $client::emitDeprecationWarning(); - } - - /** - * @dataProvider signingRegionSetProvider - * @runInSeparateProcess - */ + #[DataProvider('signingRegionSetProvider')] public function testSigningRegionSetResolution( $command, $env, @@ -853,7 +848,7 @@ public function testSigningRegionSetResolution( putenv('AWS_SIGV4A_SIGNING_REGION_SET='); } - public function signingRegionSetProvider() + public static function signingRegionSetProvider(): array { return [ [null, null, null, null, 'us-west-2'], diff --git a/tests/Build/Changelog/ChangelogBuilderTest.php b/tests/Build/Changelog/ChangelogBuilderTest.php index 1ca3b5de42..3661a27291 100644 --- a/tests/Build/Changelog/ChangelogBuilderTest.php +++ b/tests/Build/Changelog/ChangelogBuilderTest.php @@ -2,11 +2,10 @@ namespace Aws\Test\Build\Changelog; use Aws\Build\Changelog\ChangelogBuilder; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Build\Changelog\ChangelogBuilder - */ +#[CoversClass(ChangelogBuilder::class)] class ChangelogBuilderTest extends TestCase { private static $resourceDir = 'tests/Build/Changelog/resources/'; @@ -48,13 +47,8 @@ public function testBuildChangelogInvalidChangelog() public function testBuildChangelogInvalidPathChangelog() { - if (PHP_VERSION_ID >= 80300) { - $this->expectException(\PHPUnit\Framework\Error\Deprecated::class); - } else { - $this->expectException(\InvalidArgumentException::class); - $this->expectExceptionMessage('Invalid tag value'); - } - + $this->expectException(\InvalidArgumentException::class); + $this->expectExceptionMessage('Invalid tag value'); $params = []; $params['base_dir'] = self::$invalidResourceDir; $params['release_notes_output_dir'] = sys_get_temp_dir() . "/"; diff --git a/tests/Build/Changelog/CurrentChangesTest.php b/tests/Build/Changelog/CurrentChangesTest.php index 4fda017f65..edc7c907b6 100644 --- a/tests/Build/Changelog/CurrentChangesTest.php +++ b/tests/Build/Changelog/CurrentChangesTest.php @@ -2,6 +2,7 @@ namespace Aws\Test\Build\Changelog; +use PHPUnit\Framework\Attributes\CoversNothing; use PHPUnit\Framework\TestCase; class CurrentChangesTest extends TestCase @@ -12,7 +13,7 @@ private function getNameFromFilePath($filePath) return end($portions); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testVerifyDotChangesFolder() { $files = glob(__DIR__ . '/../../../.changes/*'); @@ -29,12 +30,14 @@ public function testVerifyDotChangesFolder() $this->fail('Files in `.changes` must be valid JSON.'); } } + $this->assertTrue(true); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testVerifyNextreleaseContents() { if (!is_dir(__DIR__ . '/../../../.changes/nextrelease/')) { + $this->assertTrue(true); return; } @@ -70,5 +73,7 @@ public function testVerifyNextreleaseContents() . $name . '` changelog document.'); } } + + $this->assertTrue(true); } } diff --git a/tests/Build/Docs/CodeSnippetGeneratorTest.php b/tests/Build/Docs/CodeSnippetGeneratorTest.php index 987ca77bed..11551afa38 100644 --- a/tests/Build/Docs/CodeSnippetGeneratorTest.php +++ b/tests/Build/Docs/CodeSnippetGeneratorTest.php @@ -1,23 +1,17 @@ assertSame($expected, $builder($operation, $input, [], $isInput)); } - public function exampleProvider() + public static function exampleProvider(): array { $provider = ApiProvider::defaultProvider(); return [ diff --git a/tests/ClientResolverTest.php b/tests/ClientResolverTest.php index 123cf11098..7930faea96 100644 --- a/tests/ClientResolverTest.php +++ b/tests/ClientResolverTest.php @@ -22,10 +22,10 @@ use GuzzleHttp\Psr7\Response; use Psr\Http\Message\RequestInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\ClientResolver - */ +#[CoversClass(ClientResolver::class)] class ClientResolverTest extends TestCase { use UsesServiceTrait; @@ -38,7 +38,7 @@ public function testEnsuresRequiredArgumentsAreProvided() $r->resolve([], new HandlerList()); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testAddsValidationSubscriber() { $c = new DynamoDbClient([ @@ -52,9 +52,10 @@ public function testAddsValidationSubscriber() $this->fail('Did not validate'); } catch (\InvalidArgumentException $e) { } + $this->assertTrue(true); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testCanDisableValidation() { $c = new DynamoDbClient([ @@ -66,9 +67,10 @@ public function testCanDisableValidation() $handler = \Aws\constantly(new Result([])); $command->getHandlerList()->setHandler($handler); $c->execute($command); + $this->assertTrue(true); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testCanDisableSpecificValidationConstraints() { $c = new DynamoDbClient([ @@ -84,6 +86,7 @@ public function testCanDisableSpecificValidationConstraints() $handler = \Aws\constantly(new Result([])); $command->getHandlerList()->setHandler($handler); $c->execute($command); + $this->assertTrue(true); } public function testAppliesLegacyDefaults() @@ -166,7 +169,7 @@ public function testAppliesClientContextParams() . "\n\n" . 'Accelerate: (boolean)' . "\n\n" . ' Enables this client to use S3 Transfer Acceleration endpoints.' ); - $conf = $r->resolve([ + $r->resolve([ 'service' => 's3', 'version' => 'latest', 'region' => 'x', @@ -314,7 +317,7 @@ public function testCreatesFromArray() $this->assertSame($exp, $creds->getExpiration()); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testCanDisableRetries() { $r = new ClientResolver(ClientResolver::getDefaultArguments()); @@ -324,9 +327,10 @@ public function testCanDisableRetries() 'version' => 'latest', 'retries' => 0, ], new HandlerList()); + $this->assertTrue(true); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testCanEnableRetries() { $r = new ClientResolver(ClientResolver::getDefaultArguments()); @@ -336,9 +340,10 @@ public function testCanEnableRetries() 'version' => 'latest', 'retries' => 2, ], new HandlerList()); + $this->assertTrue(true); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testCanEnableRetriesStandardMode() { $r = new ClientResolver(ClientResolver::getDefaultArguments()); @@ -351,9 +356,10 @@ public function testCanEnableRetriesStandardMode() 'max_attempts' => 10, ] ], new HandlerList()); + $this->assertTrue(true); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testCanEnableRetriesAdaptivedMode() { $r = new ClientResolver(ClientResolver::getDefaultArguments()); @@ -366,6 +372,7 @@ public function testCanEnableRetriesAdaptivedMode() 'max_attempts' => 10, ] ], new HandlerList()); + $this->assertTrue(true); } public function testCanCreateNullCredentials() @@ -579,14 +586,15 @@ public function testCanPassStsRegionalEndpointsToEndpointProvider() } /** - * @dataProvider dualStackEndpointCases * * @param $service * @param $useDualstackEndpoint * @param $useFipsEndpoint * @param $region * @param $expectedEndpoint - */ + + */ + #[DataProvider('dualStackEndpointCases')] public function testDualstackEndpoints( $service, $useDualstackEndpoint, @@ -610,7 +618,7 @@ public function testDualstackEndpoints( ); } - public function dualStackEndpointCases() + public static function dualStackEndpointCases() { return [ ["ec2", false, false, "us-west-2", "ec2.us-west-2.amazonaws.com",], @@ -665,11 +673,12 @@ public function testDualstackEndpointFailureOnDualstackNotSupported() } /** - * @dataProvider s3EndpointCases * * @param $config * @param $endpoint - */ + + */ + #[DataProvider('s3EndpointCases')] public function testCanPassS3RegionalEndpointToEndpointProvider($config, $endpoint) { $data = json_decode( @@ -688,7 +697,7 @@ public function testCanPassS3RegionalEndpointToEndpointProvider($config, $endpoi $this->assertEquals($endpoint, $conf['endpoint']); } - public function s3EndpointCases() + public static function s3EndpointCases() { return [ ['regional', 'https://s3.us-east-1.amazonaws.com'], @@ -696,7 +705,7 @@ public function s3EndpointCases() ]; } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testAddsLoggerWithDebugSettings() { $r = new ClientResolver(ClientResolver::getDefaultArguments()); @@ -707,9 +716,10 @@ public function testAddsLoggerWithDebugSettings() 'endpoint' => 'http://us-east-1.foo.amazonaws.com', 'version' => 'latest' ], new HandlerList()); + $this->assertTrue(true); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testAddsDebugListener() { $em = new HandlerList(); @@ -721,6 +731,7 @@ public function testAddsDebugListener() 'endpoint' => 'http://us-east-1.foo.amazonaws.com', 'version' => 'latest' ], $em); + $this->assertTrue(true); } public function canSetDebugToFalse() @@ -758,7 +769,7 @@ public function testCanAddConfigOptions() $this->assertTrue($c->getConfig('bucket_endpoint')); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testSkipsNonRequiredKeys() { $r = new ClientResolver([ @@ -768,6 +779,7 @@ public function testSkipsNonRequiredKeys() ] ]); $r->resolve([], new HandlerList()); + $this->assertTrue(true); } public function testAppliesLatestAsDefaultVersionWithoutSuppliedVersion() @@ -848,10 +860,11 @@ public function testAppliesUserAgent() } /** - * @dataProvider statValueProvider * @param bool|array $userValue * @param array $resolvedValue - */ + + */ + #[DataProvider('statValueProvider')] public function testAcceptsBooleansAndArraysForSelectiveStatCollection($userValue, array $resolvedValue) { $list = new HandlerList; @@ -863,7 +876,7 @@ public function testAcceptsBooleansAndArraysForSelectiveStatCollection($userValu } } - public function statValueProvider() + public static function statValueProvider() { return [ [ @@ -890,13 +903,14 @@ public function statValueProvider() } /** - * @dataProvider endpointProviderReturnProvider * * @param array $args * @param string $argName * @param string $expected * @param string $override - */ + + */ + #[DataProvider('endpointProviderReturnProvider')] public function testResolvesValuesReturnedByEndpointProvider( array $args, $argName, @@ -917,7 +931,7 @@ public function testResolvesValuesReturnedByEndpointProvider( $this->assertSame($override, $resolved[$argName]); } - public function endpointProviderReturnProvider() + public static function endpointProviderReturnProvider() { $partition = new Partition([ 'partition' => 'aws-test', @@ -955,12 +969,13 @@ public function endpointProviderReturnProvider() /** - * @dataProvider partitionReturnProvider * * @param array $args * @param string $argName * @param string $expected - */ + + */ + #[DataProvider('partitionReturnProvider')] public function testSigningValuesAreFetchedFromPartition( array $args, $argName, @@ -977,7 +992,7 @@ public function testSigningValuesAreFetchedFromPartition( $this->assertSame($expected, $resolved[$argName]); } - public function partitionReturnProvider() + public static function partitionReturnProvider() { $invocationArgs = ['endpoint' => 'https://foo.bar.amazonaws.com']; @@ -1004,11 +1019,12 @@ public function partitionReturnProvider() } /** - * @dataProvider idempotencyAutoFillProvider * * @param mixed $value * @param bool $shouldAddIdempotencyMiddleware - */ + + */ + #[DataProvider('idempotencyAutoFillProvider')] public function testIdempotencyTokenMiddlewareAddedAsAppropriate( $value, $shouldAddIdempotencyMiddleware @@ -1026,7 +1042,7 @@ public function testIdempotencyTokenMiddlewareAddedAsAppropriate( $this->assertCount($shouldAddIdempotencyMiddleware ? 1 : 0, $list); } - public function idempotencyAutoFillProvider() + public static function idempotencyAutoFillProvider() { return [ [true, true], @@ -1040,11 +1056,12 @@ public function idempotencyAutoFillProvider() } /** - * @dataProvider validateRegionProvider * * @param $region * @param $expected - */ + + */ + #[DataProvider('validateRegionProvider')] public function testValidatesRegion($region, $expected) { $resolver = new ClientResolver(ClientResolver::getDefaultArguments()); @@ -1068,7 +1085,7 @@ public function testValidatesRegion($region, $expected) } } - public function validateRegionProvider() + public static function validateRegionProvider() { return [ [ @@ -1086,7 +1103,7 @@ public function validateRegionProvider() ]; } - public function invalidDisableRequestCompressionValues() + public static function invalidDisableRequestCompressionValues() { return [ ['foo'], @@ -1096,8 +1113,9 @@ public function invalidDisableRequestCompressionValues() } /** - * @dataProvider invalidDisableRequestCompressionValues - */ + + */ + #[DataProvider('invalidDisableRequestCompressionValues')] public function testInvalidDisableRequestCompressionTypeThrowsException($invalidType) { $this->expectException(\InvalidArgumentException::class); @@ -1129,7 +1147,7 @@ public function testDisableRequestCompressionDefault() $this->assertFalse($conf['disable_request_compression']); } - public function invalidMinCompressionSizeValues() + public static function invalidMinCompressionSizeValues() { return [ [ true ], @@ -1141,8 +1159,9 @@ public function invalidMinCompressionSizeValues() } /** - * @dataProvider invalidMinCompressionSizeValues - */ + + */ + #[DataProvider('invalidMinCompressionSizeValues')] public function testInvalidMinCompressionSizeValues($invalidType) { $this->expectException(\InvalidArgumentException::class); @@ -1173,14 +1192,15 @@ public function testMinCompressionSizeDefault() } /** - * @dataProvider configResolutionProvider * * @param $ini * @param $env * @param $expected * @param $configKey * @param $configType - */ + + */ + #[DataProvider('configResolutionProvider')] public function testConfigResolutionOrder($ini, $env, $expected, $configKey, $configType) { $dir = sys_get_temp_dir() . '/.aws'; @@ -1217,7 +1237,7 @@ public function testConfigResolutionOrder($ini, $env, $expected, $configKey, $co } } - public function configResolutionProvider() + public static function configResolutionProvider() { return [ [ @@ -1433,25 +1453,6 @@ public function testAppliesAuthSchemeResolver() ); } - public function testEmitsDeprecationWarning() - { - if (PHP_VERSION_ID >= 80100) { - $this->markTestSkipped(); - } - - putenv('AWS_SUPPRESS_PHP_DEPRECATION_WARNING=false'); - $this->expectDeprecation(); - $this->expectDeprecationMessage('This installation of the SDK is using PHP version'); - - $r = new ClientResolver(ClientResolver::getDefaultArguments()); - - try { - $r->resolve(['service' => 'sqs', 'region' => 'x'], new HandlerList()); - } finally { - putenv('AWS_SUPPRESS_PHP_DEPRECATION_WARNING=true'); - } - } - /** * Tests the flag `use_aws_shared_config_files` is applied to the method * for resolving a default value for a config. @@ -1545,8 +1546,9 @@ public function testResolveFromEnvIniUseAwsSharedFiles(): void * @param string|null $env * @return void * - * @dataProvider resolvesAuthSchemePreferenceProvider - */ + + */ + #[DataProvider('resolvesAuthSchemePreferenceProvider')] public function testResolvesAuthSchemePreference( bool $isExpected, array $expectedValue, @@ -1610,7 +1612,7 @@ public function testResolvesAuthSchemePreference( /** * @return Generator */ - public function resolvesAuthSchemePreferenceProvider(): Generator + public static function resolvesAuthSchemePreferenceProvider(): Generator { $cases = [ 'provided_at_client_construction' => [ diff --git a/tests/ClientSideMonitoring/ApiCallAttemptMonitoringMiddlewareTest.php b/tests/ClientSideMonitoring/ApiCallAttemptMonitoringMiddlewareTest.php index 291878432d..4f67736bdf 100644 --- a/tests/ClientSideMonitoring/ApiCallAttemptMonitoringMiddlewareTest.php +++ b/tests/ClientSideMonitoring/ApiCallAttemptMonitoringMiddlewareTest.php @@ -13,11 +13,9 @@ use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\ClientSideMonitoring\ApiCallAttemptMonitoringMiddleware - * @covers Aws\ClientSideMonitoring\AbstractMonitoringMiddleware - */ +#[CoversClass(ApiCallAttemptMonitoringMiddleware::class)] class ApiCallAttemptMonitoringMiddlewareTest extends TestCase { use MonitoringMiddlewareTestingTrait; @@ -59,8 +57,13 @@ protected function resetMiddlewareSocket() $prepareSocket->invokeArgs($middleware, array(true)); } - public function getMonitoringDataTests() + public static function getMonitoringDataTests(): array { + $configuration = new Configuration(true, '127.0.0.1', 31000, 'AwsPhpSdkTestApp'); + $credentialProvider = CredentialProvider::fromCredentials( + new Credentials('testkey', 'testsecret', 'testtoken') + ); + $command = new Command('RunScheduledInstances', [ 'LaunchSpecification' => [ 'ImageId' => 'test-image', @@ -70,8 +73,8 @@ public function getMonitoringDataTests() ]); $testBase = [ ApiCallAttemptMonitoringMiddleware::wrap( - $this->getCredentialProvider(), - $this->getConfiguration(), + $credentialProvider, + $configuration, 'us-east-1', 'ec2' ), diff --git a/tests/ClientSideMonitoring/ApiCallMonitoringMiddlewareTest.php b/tests/ClientSideMonitoring/ApiCallMonitoringMiddlewareTest.php index aba2473439..8e49cec96e 100644 --- a/tests/ClientSideMonitoring/ApiCallMonitoringMiddlewareTest.php +++ b/tests/ClientSideMonitoring/ApiCallMonitoringMiddlewareTest.php @@ -10,11 +10,9 @@ use Aws\Exception\AwsException; use GuzzleHttp\Psr7\Request; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\ClientSideMonitoring\ApiCallMonitoringMiddleware - * @covers Aws\ClientSideMonitoring\AbstractMonitoringMiddleware - */ +#[CoversClass(ApiCallMonitoringMiddleware::class)] class ApiCallMonitoringMiddlewareTest extends TestCase { use MonitoringMiddlewareTestingTrait; @@ -56,8 +54,12 @@ protected function resetMiddlewareSocket() $prepareSocket->invokeArgs($middleware, array(true)); } - public function getMonitoringDataTests() + public static function getMonitoringDataTests(): array { + $credentials = new Credentials('testkey', 'testsecret', 'testtoken'); + $credentialProvider = CredentialProvider::fromCredentials($credentials); + $configuration = new Configuration(true, '127.0.0.1', 31000, 'AwsPhpSdkTestApp'); + $command = new Command('RunScheduledInstances', [ 'LaunchSpecification' => [ 'ImageId' => 'test-image', @@ -68,8 +70,8 @@ public function getMonitoringDataTests() $testBase = [ ApiCallMonitoringMiddleware::wrap( - $this->getCredentialProvider(), - $this->getConfiguration(), + $credentialProvider, + $configuration, 'us-east-1', 'ec2' ), diff --git a/tests/ClientSideMonitoring/ConfigurationProviderTest.php b/tests/ClientSideMonitoring/ConfigurationProviderTest.php index 96ae1e86e2..cc19996949 100644 --- a/tests/ClientSideMonitoring/ConfigurationProviderTest.php +++ b/tests/ClientSideMonitoring/ConfigurationProviderTest.php @@ -10,14 +10,12 @@ use Aws\LruArrayCache; use GuzzleHttp\Promise; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; - -/** - * @covers Aws\ClientSideMonitoring\ConfigurationProvider - */ +#[CoversClass(ConfigurationProvider::class)] class ConfigurationProviderTest extends TestCase { - private static $originalEnv; private $iniFile = <<clearEnv(); @@ -425,7 +423,7 @@ public function testCreatesFromCache() { $expected = new Configuration(true, '123.4.5.6', 555, 'FooApp'); $cacheBuilder = $this->getMockBuilder(CacheInterface::class); - $cacheBuilder->setMethods(['get', 'set', 'remove']); + $cacheBuilder->onlyMethods(['get', 'set', 'remove']); $cache = $cacheBuilder->getMock(); $cache->expects($this->any()) ->method('get') @@ -439,7 +437,7 @@ public function testCreatesFromCache() $this->assertSame($expected->toArray(), $result->toArray()); } - public function getSuccessfulUnwrapData() + public static function getSuccessfulUnwrapData(): array { $expected = new Configuration(true, '123.4.5.6', 555, 'FooApp'); return [ @@ -469,11 +467,7 @@ function() use ($expected) { ]; } - /** - * @dataProvider getSuccessfulUnwrapData - * @param $toUnwrap - * @param ConfigurationInterface $expected - */ + #[DataProvider('getSuccessfulUnwrapData')] public function testSuccessfulUnwraps($toUnwrap, ConfigurationInterface $expected) { $this->assertSame( diff --git a/tests/ClientSideMonitoring/ConfigurationTest.php b/tests/ClientSideMonitoring/ConfigurationTest.php index 6add824ee4..d26aa789df 100644 --- a/tests/ClientSideMonitoring/ConfigurationTest.php +++ b/tests/ClientSideMonitoring/ConfigurationTest.php @@ -4,12 +4,9 @@ use Aws\ClientSideMonitoring\Configuration; use Yoast\PHPUnitPolyfills\TestCases\TestCase; -use Psr\Log\InvalidArgumentException; +use PHPUnit\Framework\Attributes\CoversClass; - -/** - * @covers \Aws\ClientSideMonitoring\Configuration - */ +#[CoversClass(Configuration::class)] class ConfigurationTest extends TestCase { public function testGetsCorrectValues() diff --git a/tests/CloudFront/CloudFrontClientTest.php b/tests/CloudFront/CloudFrontClientTest.php index 04d2cd12c7..e609d55ee7 100644 --- a/tests/CloudFront/CloudFrontClientTest.php +++ b/tests/CloudFront/CloudFrontClientTest.php @@ -4,10 +4,10 @@ use Aws\CloudFront\CloudFrontClient; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversNothing; -/** - * @covers Aws\CloudFront\CloudFrontClient - */ +#[CoversClass(CloudFrontClient::class)] class CloudFrontClientTest extends TestCase { protected $key; @@ -29,7 +29,7 @@ public function testEnsuresKeysArePassed() $c->getSignedUrl([]); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testCreatesSignedUrl() { $c = new CloudFrontClient([ @@ -43,9 +43,10 @@ public function testCreatesSignedUrl() 'url' => 'https://foo.bar.com', 'expires' => strtotime('+10 minutes'), ]); + $this->assertTrue(true); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testCreatesSignedCookie() { $c = new CloudFrontClient([ @@ -59,5 +60,6 @@ public function testCreatesSignedCookie() 'url' => 'https://foo.bar.com', 'expires' => strtotime('+10 minutes'), ]); + $this->assertTrue(true); } } diff --git a/tests/CloudFront/CookieSignerTest.php b/tests/CloudFront/CookieSignerTest.php index 54856629db..a3e9e082ac 100644 --- a/tests/CloudFront/CookieSignerTest.php +++ b/tests/CloudFront/CookieSignerTest.php @@ -2,14 +2,16 @@ namespace Aws\Test\CloudFront; use Aws\CloudFront\CookieSigner; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\TestCase; +#[CoversClass(CookieSigner::class)] class CookieSignerTest extends TestCase { protected $key; protected $kp; - public function set_up() + public function setUp(): void { openssl_pkey_export(openssl_pkey_new(),$this->key); $this->kp = 'test'; diff --git a/tests/CloudFront/SignerTest.php b/tests/CloudFront/SignerTest.php index daad495448..633ea8292b 100644 --- a/tests/CloudFront/SignerTest.php +++ b/tests/CloudFront/SignerTest.php @@ -3,7 +3,10 @@ use Aws\CloudFront\Signer; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(Signer::class)] class SignerTest extends TestCase { /** @var Signer */ @@ -75,7 +78,10 @@ public function testReturnsSignatureAndKeyPairId() $this->assertArrayHasKey('Key-Pair-Id', $signature); } - public function getExpiresCases() + /** + * @return array> + */ + public static function getExpiresCases(): array { return [ [ @@ -87,9 +93,7 @@ public function getExpiresCases() ]; } - /** - * @dataProvider getExpiresCases - */ + #[DataProvider('getExpiresCases')] public function testReturnsExpiresForCannedPolicies($expires) { $signature = $this->instance->getSignature('test.mp4', $expires); @@ -137,12 +141,7 @@ public function testPolicyContainsNoForbiddenCharacters() $this->assertDoesNotMatchRegularExpression('/[\+\=\/]/', $signature['Policy']); } - /** - * @dataProvider cannedPolicyParameterProvider - * - * @param string $resource - * @param int $ts - */ + #[DataProvider('cannedPolicyParameterProvider')] public function testCreatesCannedPolicies($resource, $ts) { $m = new \ReflectionMethod(Signer::class, 'createCannedPolicy'); @@ -155,7 +154,10 @@ public function testCreatesCannedPolicies($resource, $ts) ); } - public function cannedPolicyParameterProvider() + /** + * @return array> + */ + public static function cannedPolicyParameterProvider(): array { return [ [ diff --git a/tests/CloudFront/UrlSignerTest.php b/tests/CloudFront/UrlSignerTest.php index efea2df581..243efb564e 100644 --- a/tests/CloudFront/UrlSignerTest.php +++ b/tests/CloudFront/UrlSignerTest.php @@ -6,10 +6,10 @@ use Aws\CloudFront\UrlSigner; use GuzzleHttp\Psr7\Uri; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\CloudFront\UrlSigner - */ +#[CoversClass(UrlSigner::class)] class UrlSignerTest extends TestCase { protected $key; @@ -131,12 +131,7 @@ public function testEnsuresUriSchemeIsPresent() $s->getSignedUrl('bar.com'); } - /** - * @dataProvider urlAndResourceProvider - * - * @param string $url - * @param string $resource - */ + #[DataProvider('urlAndResourceProvider')] public function testIsolatesResourceIUrls($url, $resource) { $s = new UrlSigner('a', $this->key); @@ -152,7 +147,7 @@ public function testIsolatesResourceIUrls($url, $resource) $this->assertSame($resource, $result); } - public function urlAndResourceProvider() + public static function urlAndResourceProvider(): array { return [ ['rtmp://foo.cloudfront.net/videos/test.mp4', 'videos/test.mp4'], diff --git a/tests/CloudSearchDomain/CloudSearchDomainTest.php b/tests/CloudSearchDomain/CloudSearchDomainTest.php index 6ba8816612..37593f82e8 100644 --- a/tests/CloudSearchDomain/CloudSearchDomainTest.php +++ b/tests/CloudSearchDomain/CloudSearchDomainTest.php @@ -4,10 +4,9 @@ use Aws\CloudSearchDomain\CloudSearchDomainClient; use GuzzleHttp\Psr7\Request; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\CloudSearchDomain\CloudSearchDomainClient - */ +#[CoversClass(CloudSearchDomainClient::class)] class CloudSearchDomainTest extends TestCase { public function testRequiresEndpoint() diff --git a/tests/CloudTrail/LogFileIteratorTest.php b/tests/CloudTrail/LogFileIteratorTest.php index c040424817..de29407510 100644 --- a/tests/CloudTrail/LogFileIteratorTest.php +++ b/tests/CloudTrail/LogFileIteratorTest.php @@ -8,11 +8,10 @@ use Aws\S3\S3Client; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7\Response; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\CloudTrail\LogFileIterator - */ +#[CoversClass(LogFileIterator::class)] class LogFileIteratorTest extends TestCase { use UsesServiceTrait; diff --git a/tests/CloudTrail/LogFileReaderTest.php b/tests/CloudTrail/LogFileReaderTest.php index a44211a3df..6c6c0966d1 100644 --- a/tests/CloudTrail/LogFileReaderTest.php +++ b/tests/CloudTrail/LogFileReaderTest.php @@ -5,17 +5,15 @@ use Aws\Result; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\CloudTrail\LogFileReader - */ +#[CoversClass(LogFileReader::class)] class LogFileReaderTest extends TestCase { use UsesServiceTrait; - /** - * @dataProvider dataForLogReadingTest - */ + #[DataProvider('dataForLogReadingTest')] public function testCorrectlyReadsLogFiles($responseBody, $recordCount) { $s3Client = $this->getTestClient('s3', [ @@ -30,7 +28,7 @@ public function testCorrectlyReadsLogFiles($responseBody, $recordCount) $this->assertCount($recordCount, $records); } - public function dataForLogReadingTest() + public static function dataForLogReadingTest(): array { return [ ['{"Records":[{"foo":"1"},{"bar":"2"},{"baz":"3"}]}', 3], diff --git a/tests/CloudTrail/LogRecordIteratorTest.php b/tests/CloudTrail/LogRecordIteratorTest.php index b7fd009355..58cafd3321 100644 --- a/tests/CloudTrail/LogRecordIteratorTest.php +++ b/tests/CloudTrail/LogRecordIteratorTest.php @@ -9,10 +9,9 @@ use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\CloudTrail\LogRecordIterator - */ +#[CoversClass(LogRecordIterator::class)] class LogRecordIteratorTest extends TestCase { use UsesServiceTrait; diff --git a/tests/CloudWatchLogs/CloudWatchLogsClientTest.php b/tests/CloudWatchLogs/CloudWatchLogsClientTest.php index 69a2935f73..bd7d26cbbb 100644 --- a/tests/CloudWatchLogs/CloudWatchLogsClientTest.php +++ b/tests/CloudWatchLogs/CloudWatchLogsClientTest.php @@ -7,9 +7,11 @@ use GuzzleHttp\Psr7\NoSeekStream; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Utils; +use PHPUnit\Framework\Attributes\CoversClass; use Psr\Http\Message\RequestInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +#[CoversClass(CloudWatchLogsClient::class)] class CloudWatchLogsClientTest extends TestCase { public function testSetStreamingFlagMiddleware() diff --git a/tests/CognitoIdentity/CognitoIdentityProviderTest.php b/tests/CognitoIdentity/CognitoIdentityProviderTest.php index 6098430316..bfdfbd53b1 100644 --- a/tests/CognitoIdentity/CognitoIdentityProviderTest.php +++ b/tests/CognitoIdentity/CognitoIdentityProviderTest.php @@ -5,8 +5,10 @@ use Aws\CognitoIdentity\CognitoIdentityProvider; use Aws\MockHandler; use Aws\Result; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\TestCase; +#[CoversClass(CognitoIdentityProvider::class)] class CognitoIdentityProviderTest extends TestCase { public function testCreatesFromCognitoIdentity() @@ -48,9 +50,15 @@ public function testAccessTokensCanBeRefreshed() ); $provider->updateLogin('www.amazon.com', 'access-token-new'); + + $reflection = new \ReflectionClass($provider); + $property = $reflection->getProperty('logins'); + $property->setAccessible(true); + $logins = $property->getValue($provider); + $this->assertSame( 'access-token-new', - $this->getPropertyValue($provider, 'logins')['www.amazon.com'] + $logins['www.amazon.com'] ); } } diff --git a/tests/CognitoSync/CognitoSyncClientTest.php b/tests/CognitoSync/CognitoSyncClientTest.php index 1884163f68..6e86a59ba9 100644 --- a/tests/CognitoSync/CognitoSyncClientTest.php +++ b/tests/CognitoSync/CognitoSyncClientTest.php @@ -1,12 +1,15 @@ new Result(), 'B' => new Result()]; - $client = $this->getTestClient('s3'); - $this->addMockResults($client, $results); - $iter = [ - 'A' => $client->getCommand('HeadBucket', ['Bucket' => 'Foo']), - 'B' => $client->getCommand('HeadBucket', ['Bucket' => 'Foo']) - ]; - $pool = new CommandPool($client, $iter, [ - 'fulfilled' => function ($result, $key) use (&$called) { - $called[$key] = $result; - }, - 'preserve_iterator_keys' => true, + { + $results = ['A' => new Result(), 'B' => new Result()]; + $client = $this->getTestClient('s3'); + $this->addMockResults($client, $results); + $iter = [ + 'A' => $client->getCommand('HeadBucket', ['Bucket' => 'Foo']), + 'B' => $client->getCommand('HeadBucket', ['Bucket' => 'Foo']) + ]; + $pool = new CommandPool($client, $iter, [ + 'fulfilled' => function ($result, $key) use (&$called) { + $called[$key] = $result; + }, + 'preserve_iterator_keys' => true, ]); $pool->promise()->wait(); $this->assertSame($results, $called); diff --git a/tests/CommandTest.php b/tests/CommandTest.php index df2bcb444e..da6313ff0e 100644 --- a/tests/CommandTest.php +++ b/tests/CommandTest.php @@ -4,12 +4,10 @@ use Aws\Command; use Aws\HandlerList; use Aws\MetricsBuilder; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Command - * @covers Aws\HasDataTrait - */ +#[CoversClass(Command::class)] class CommandTest extends TestCase { public function testHasName() @@ -97,26 +95,39 @@ public function testCanAccessLikeArray() public function testGetAuthSchemesEmitsWarning() { - $this->expectWarning(); - $this->expectWarningMessage( + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage( 'Aws\Command::getAuthSchemes is deprecated. Auth schemes resolved using the service' .' `auth` trait or via endpoint resolution can now be found in the command `@context` property.' ); - - $c = new Command('foo', ['bar' => 'baz', 'qux' => 'boo']); - $c->getAuthSchemes(); + set_error_handler(function ($errno, $errstr) { + throw new \RuntimeException($errstr, $errno); + }); + try { + $c = new Command('foo', ['bar' => 'baz', 'qux' => 'boo']); + $c->getAuthSchemes(); + } finally { + restore_error_handler(); + } } public function testSetAuthSchemesEmitsWarning() { - $this->expectWarning(); - $this->expectWarningMessage( + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage( 'Aws\Command::setAuthSchemes is deprecated. Auth schemes resolved using the service' .' `auth` trait or via endpoint resolution are now set in the command `@context` property.' ); - $c = new Command('foo', ['bar' => 'baz', 'qux' => 'boo']); - $c->setAuthSchemes([]); + set_error_handler(function ($errno, $errstr) { + throw new \RuntimeException($errstr, $errno); + }); + try { + $c = new Command('foo', ['bar' => 'baz', 'qux' => 'boo']); + $c->setAuthSchemes([]); + } finally { + restore_error_handler(); + } } public function testInitializeMetricsBuilderObject() diff --git a/tests/ConfigurationResolverTest.php b/tests/ConfigurationResolverTest.php index cd6fdf2198..30b3695a63 100644 --- a/tests/ConfigurationResolverTest.php +++ b/tests/ConfigurationResolverTest.php @@ -3,7 +3,10 @@ use Aws\Configuration\ConfigurationResolver; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(ConfigurationResolver::class)] class ConfigurationResolverTest extends TestCase { private static $configurationKey = 'foo_configuration_option'; @@ -80,7 +83,7 @@ public static function tear_down_after_class() self::$originalEnv['config_file']); } - public function getEnvValues() + public static function getEnvValues(): array { return [ ['true', 'bool', true], @@ -90,9 +93,7 @@ public function getEnvValues() ]; } - /** - * @dataProvider getEnvValues - */ + #[DataProvider('getEnvValues')] public function testRetrievesAndConvertsEnvironmentVariables($envValue, $type, $expected) { $this->clearEnv(); @@ -125,18 +126,37 @@ public function testResolvesDefaultFromFallback() $this->assertFalse($result); } - public function iniFileProvider() + public static function iniFileProvider(): array { + $boolIniFile = <<boolIniFile, 'bool', true], - [$this->intIniFile, 'int', 15], - [$this->stringIniFile, 'string', 'standard'], + [$boolIniFile, 'bool', true], + [$intIniFile, 'int', 15], + [$stringIniFile, 'string', 'standard'], ]; } - /** - * @dataProvider IniFileProvider - */ + #[DataProvider('iniFileProvider')] public function testResolvesFromIniFileWithDefaultProfile($iniFile, $type, $expected) { $dir = $this->clearEnv(); @@ -147,9 +167,7 @@ public function testResolvesFromIniFileWithDefaultProfile($iniFile, $type, $expe unlink($dir . '/config'); } - /** - * @dataProvider IniFileProvider - */ + #[DataProvider('iniFileProvider')] public function testCreatesFromIniFileWithDifferentDefaultFilename($iniFile, $type, $expected) { $dir = $this->clearEnv(); @@ -164,18 +182,37 @@ public function testCreatesFromIniFileWithDifferentDefaultFilename($iniFile, $ty unlink($dir . '/alt_config'); } - public function iniFileWithAltProfileProvider() + public static function iniFileWithAltProfileProvider(): array { + $boolIniFile = <<boolIniFile, 'bool', false], - [$this->intIniFile, 'int', 25], - [$this->stringIniFile, 'string', 'experimental'], + [$boolIniFile, 'bool', false], + [$intIniFile, 'int', 25], + [$stringIniFile, 'string', 'experimental'], ]; } - /** - * @dataProvider IniFileWIthAltProfileProvider - */ + #[DataProvider('iniFileWithAltProfileProvider')] public function testCreatesFromIniFileWithSpecifiedProfile($iniFile, $type, $expected) { $dir = $this->clearEnv(); @@ -344,9 +381,7 @@ public function testResolvesServiceIni() ); } - /** - * @dataProvider duplicateIniFileProvider - */ + #[DataProvider('duplicateIniFileProvider')] public function testResolvesServiceIniWithDuplicateSections($ini) { $dir = $this->clearEnv(); @@ -378,7 +413,7 @@ public function testResolvesServiceIniWithDuplicateSections($ini) ); } - public function duplicateIniFileProvider() + public static function duplicateIniFileProvider(): array { return [ [ @@ -425,4 +460,3 @@ public function duplicateIniFileProvider() ]; } } - diff --git a/tests/Credentials/AssumeRoleCredentialProviderTest.php b/tests/Credentials/AssumeRoleCredentialProviderTest.php index 3e663d70f8..cf486edb22 100644 --- a/tests/Credentials/AssumeRoleCredentialProviderTest.php +++ b/tests/Credentials/AssumeRoleCredentialProviderTest.php @@ -12,21 +12,17 @@ use GuzzleHttp\Promise\RejectedPromise; use Aws\Test\UsesServiceTrait; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Credentials\AssumeRoleCredentialProvider - */ +#[CoversClass(AssumeRoleCredentialProvider::class)] class AssumeRoleCredentialProviderTest extends TestCase { const SAMPLE_ROLE_ARN = 'arn:aws:iam::012345678910:role/role_name'; use UsesServiceTrait; - /** - * @dataProvider insufficientArguments - * - * @param array $config - */ + #[DataProvider('insufficientArguments')] public function testEnsureSourceProfileProvidedForAssumeRole($config) { $this->expectExceptionMessage("Missing required 'AssumeRoleCredentialProvider' configuration option:"); @@ -34,10 +30,7 @@ public function testEnsureSourceProfileProvidedForAssumeRole($config) new AssumeRoleCredentialProvider($config); } - /** - * @dataProvider insufficientArguments - */ - public function insufficientArguments() + public static function insufficientArguments(): array { $client = [ 'client' => new StsClient([ diff --git a/tests/Credentials/AssumeRoleWithWebIdentityCredentialProviderTest.php b/tests/Credentials/AssumeRoleWithWebIdentityCredentialProviderTest.php index 44f2043229..26e5752505 100644 --- a/tests/Credentials/AssumeRoleWithWebIdentityCredentialProviderTest.php +++ b/tests/Credentials/AssumeRoleWithWebIdentityCredentialProviderTest.php @@ -4,7 +4,6 @@ use Aws\Arn\ArnParser; use Aws\Command; use Aws\Credentials\AssumeRoleWithWebIdentityCredentialProvider; -use Aws\Credentials\Credentials; use Aws\Exception\AwsException; use Aws\Middleware; use Aws\Result; @@ -15,10 +14,10 @@ use GuzzleHttp\Promise\RejectedPromise; use Aws\Test\UsesServiceTrait; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Credentials\AssumeRoleWithWebIdentityCredentialProvider - */ +#[CoversClass(AssumeRoleWithWebIdentityCredentialProvider::class)] class AssumeRoleWithWebIdentityCredentialProviderTest extends TestCase { const SAMPLE_ROLE_ARN = 'arn:aws:iam::123456789012:role/role_name'; @@ -400,10 +399,7 @@ public function testCanDisableInvalidIdentityTokenRetries() } } - /** - * Tests region precedence: config > env var > fallback - * @dataProvider regionPrecedenceProvider - */ + #[DataProvider('regionPrecedenceProvider')] public function testRegionPrecedence( ?string $configRegion, ?string $envRegion, @@ -433,8 +429,11 @@ public function testRegionPrecedence( } if ($expectNotice) { - $this->expectNotice(); - $this->expectNoticeMessage( + set_error_handler(function ($errno, $errstr) use ($config) { + throw new \RuntimeException($errstr, $errno); + }); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage( 'NOTICE: STS client created without explicit `region` configuration.' ); } @@ -457,10 +456,14 @@ public function testRegionPrecedence( } else { putenv("AWS_REGION"); } + + if ($expectNotice) { + restore_error_handler(); + } } } - public function regionPrecedenceProvider(): array + public static function regionPrecedenceProvider(): array { return [ 'config overrides env' => ['us-west-2', 'eu-west-1', 'us-west-2', false], @@ -470,10 +473,7 @@ public function regionPrecedenceProvider(): array ]; } - /** - * Tests that correct endpoints are called - * @dataProvider endpointProvider - */ + #[DataProvider('endpointProvider')] public function testEndpointSelection( string $region, string $expectedEndpoint @@ -537,7 +537,7 @@ function ($c, $r) { } } - public function endpointProvider(): array + public static function endpointProvider(): array { return [ 'us-east-1' => [ diff --git a/tests/Credentials/CredentialProviderTest.php b/tests/Credentials/CredentialProviderTest.php index bc76731efb..6c291ae2cb 100644 --- a/tests/Credentials/CredentialProviderTest.php +++ b/tests/Credentials/CredentialProviderTest.php @@ -21,10 +21,10 @@ use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Utils; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Credentials\CredentialProvider - */ +#[CoversClass(CredentialProvider::class)] class CredentialProviderTest extends TestCase { use UsesServiceTrait; @@ -281,8 +281,9 @@ public function testCreatesFromEnvironmentVariablesNullToken(): void } /** - * @dataProvider iniFileProvider - */ + + */ + #[DataProvider('iniFileProvider')] public function testCreatesFromIniFile( string $iniFile, Credentials $expectedCreds @@ -295,7 +296,7 @@ public function testCreatesFromIniFile( $this->assertEquals($expectedCreds->toArray(), $creds->toArray()); } - public function iniFileProvider(): array + public static function iniFileProvider(): array { $credentials = new Credentials( 'foo', @@ -768,10 +769,13 @@ public function testCreatesFromRoleArn(): void public function testCreatesFromRoleArnWithSourceProfileEmitsNoticeOnFallbackRegion(): void { - $this->expectNotice(); - $this->expectNoticeMessage( + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage( 'NOTICE: STS client created without explicit `region` configuration' ); + set_error_handler(function ($errno, $errstr) { + throw new \RuntimeException($errstr, $errno); + }); $awsDir = $this->createAwsHome(); $ini = <<wait(); + try { + file_put_contents($awsDir . '/credentials', $ini); + call_user_func(CredentialProvider::ini('assume', null))->wait(); + } finally { + restore_error_handler(); + } } public function testCreatesFromRoleArnWithCredentialSourceEmitsNoticeOnFallbackRegion(): void { - $this->expectNotice(); - $this->expectNoticeMessage( + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage( 'NOTICE: STS client created without explicit `region` configuration' ); - + set_error_handler(function ($errno, $errstr) { + throw new \RuntimeException($errstr, $errno); + }); $awsDir = $this->createAwsHome(); $ini = <<wait(); + call_user_func(CredentialProvider::ini('assume-with-credential-source', null))->wait(); + } finally { + restore_error_handler(); + } } public function testCreatesFromRoleArnCatchesCircular(): void @@ -1929,8 +1943,9 @@ public function testProcessCredentialConfigDefaultChain(): void } /** - * @dataProvider shouldUseEcsProvider - */ + + */ + #[DataProvider('shouldUseEcsProvider')] public function testShouldUseEcs( string $relative, string $serverRelative, @@ -1956,7 +1971,7 @@ public function testShouldUseEcs( $this->assertEquals($expected, $result); } - public function shouldUseEcsProvider(): array + public static function shouldUseEcsProvider(): array { return [ ['=foo', '', '', '', true], @@ -2722,8 +2737,9 @@ public function testLoginUsedFromCacheInDefaultChain(): void } /** - * @dataProvider loginInvalidCacheProvider - */ + + */ + #[DataProvider('loginInvalidCacheProvider')] public function testLoginWithInvalidCache( string $cacheContent, string $expectedMessage, @@ -2754,7 +2770,7 @@ public function testLoginWithInvalidCache( $provider()->wait(); } - public function loginInvalidCacheProvider(): array + public static function loginInvalidCacheProvider(): array { $validDpopKey = '-----BEGIN EC PRIVATE KEY----- MHcCAQEEIFDZHUzOG1Pzq+6F0mjMlOSp1syN9LRPBuHMoCFXTcXhoAoGCCqGSM49 diff --git a/tests/Credentials/CredentialsTest.php b/tests/Credentials/CredentialsTest.php index eea715e5d8..3feda7eb34 100644 --- a/tests/Credentials/CredentialsTest.php +++ b/tests/Credentials/CredentialsTest.php @@ -7,10 +7,9 @@ use Aws\Identity\AwsCredentialIdentityInterface; use Aws\Identity\IdentityInterface; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Credentials\Credentials - */ +#[CoversClass(Credentials::class)] class CredentialsTest extends TestCase { public function testHasGetters() diff --git a/tests/Credentials/CredentialsUtilsTest.php b/tests/Credentials/CredentialsUtilsTest.php index ea97e7d9b1..ba2430e66e 100644 --- a/tests/Credentials/CredentialsUtilsTest.php +++ b/tests/Credentials/CredentialsUtilsTest.php @@ -3,19 +3,13 @@ use Aws\Credentials\CredentialsUtils; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Credentials\CredentialsUtils - */ +#[CoversClass(CredentialsUtils::class)] class CredentialsUtilsTest extends TestCase { - - /** - * @param string $host - * @param bool $expectedResult - * - * @dataProvider loopBackAddressCasesProvider - */ + #[DataProvider('loopBackAddressCasesProvider')] public function testLoopBackAddressCases(string $host, bool $expectedResult) { $isLoopBack = CredentialsUtils::isLoopBackAddress($host); @@ -23,9 +17,9 @@ public function testLoopBackAddressCases(string $host, bool $expectedResult) } /** - * @return string[] + * @return array */ - public function loopBackAddressCasesProvider(): array + public static function loopBackAddressCasesProvider(): array { return [ 'IPv6_invalid_loopBack' => diff --git a/tests/Credentials/EcsCredentialProviderTest.php b/tests/Credentials/EcsCredentialProviderTest.php index 246ccac3ff..1571b1c6f3 100644 --- a/tests/Credentials/EcsCredentialProviderTest.php +++ b/tests/Credentials/EcsCredentialProviderTest.php @@ -17,10 +17,11 @@ use GuzzleHttp\Ring\Future\CompletedFutureArray; use Psr\Http\Message\RequestInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversNothing; -/** - * @covers \Aws\Credentials\EcsCredentialProvider - */ +#[CoversClass(EcsCredentialProvider::class)] class EcsCredentialProviderTest extends TestCase { private $uripath; @@ -85,7 +86,7 @@ public function testThrowsExceptionOnInvalidEcsCredential() $this->expectExceptionMessage("Unexpected container metadata credentials value"); $this->expectException(\Aws\Exception\CredentialsException::class); $this->getTestCreds( - $this->getCredentialArray(null, null, null, null, false) + self::getCredentialArray(null, null, null, null, false) )->wait(); } @@ -93,7 +94,7 @@ public function testLoadsCredentialsAndProfile() { $t = time() + 1000; $c = $this->getTestCreds( - $this->getCredentialArray('foo', 'baz', null, "@{$t}") + self::getCredentialArray('foo', 'baz', null, "@{$t}") )->wait(); $this->assertSame('foo', $c->getAccessKeyId()); $this->assertSame('baz', $c->getSecretKey()); @@ -101,10 +102,11 @@ public function testLoadsCredentialsAndProfile() $this->assertSame($t, $c->getExpiration()); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testDoesNotRequireConfig() { new EcsCredentialProvider(); + $this->assertTrue(true); } public function testRequestHeaderWithAuthorisationKey() @@ -144,9 +146,7 @@ public function testNoProxying() putenv("NO_PROXY=$no"); } - /** - * @dataProvider uriAndTokenResolutionProvider - */ + #[DataProvider('uriAndTokenResolutionProvider')] public function testUriAndTokenResolution($case) { $dir = $this->clearEnv(); @@ -180,7 +180,7 @@ public function testUriAndTokenResolution($case) } $t = time() + 1000; - $creds = $this->getCredentialArray( + $creds = self::getCredentialArray( 'foo', 'baz', 'bar', $t, true ); $c = $this->resolveCredentials($creds)->wait(); @@ -193,7 +193,7 @@ public function testUriAndTokenResolution($case) } } - public function uriAndTokenResolutionProvider(): \Generator + public static function uriAndTokenResolutionProvider(): \Generator { $cases = json_decode(file_get_contents( __DIR__ . '/fixtures/ecs/uri-token-resolution.json') @@ -205,7 +205,7 @@ public function uriAndTokenResolutionProvider(): \Generator } } - private function getCredentialArray( + private static function getCredentialArray( $key, $secret, $token = null, $time = null, $success = true ){ return [ @@ -261,8 +261,8 @@ private function resolveCredentials($result, ?Response $more = null) private function getProxyCheckGuzzleClient() { $t = (time() + 1000); - $credentials = $this->getCredentialArray('foo', 'baz', null, "@{$t}"); - return new \Aws\Handler\Guzzle\GuzzleHandler( + $credentials = self::getCredentialArray('foo', 'baz', null, "@{$t}"); + return new GuzzleHandler( new Client([ 'handler' => function ( Psr7\Request $request, @@ -364,17 +364,20 @@ public function testResolveCredentialsWithAccountIdFromArn() } /** - * @dataProvider successTestCases - * - * @param callable $client + * @param array $clientDef * @param CredentialsInterface $expected + * @throws GuzzleException */ + #[DataProvider('successDataProvider')] public function testHandlesSuccessScenarios( - callable $client, + array $clientDef, CredentialsInterface $expected ) { $provider = new EcsCredentialProvider([ - 'client' => $client, + 'client' => $this->getTestClient( + $clientDef['responses'], + $clientDef['credentials'] + ), 'retries' => 5 ]); @@ -398,7 +401,7 @@ public function testHandlesSuccessScenarios( ); } - public function successTestCases() + public static function successDataProvider(): array { $expiry = time() + 1000; $creds = ['foo_key', 'baz_secret', 'qux_token', "@{$expiry}"]; @@ -415,7 +418,7 @@ public function successTestCases() $promiseCreds = Promise\Create::promiseFor( new Response(200, [], Psr7\Utils::streamFor( json_encode(call_user_func_array( - [$this, 'getCredentialArray'], + [self::class, 'getCredentialArray'], $creds ))) ) @@ -423,42 +426,50 @@ public function successTestCases() return [ 'Happy path' => [ - $this->getTestClient([], $creds), + [ + 'responses' => [], + 'credentials' => $creds + ], $credsObject ], 'With retries for ConnectException (Guzzle 7)' => [ - $this->getTestClient( - [ + [ + 'responses' => [ $rejectionConnection, $promiseCreds ], - $creds - ), + 'credentials' => $creds + ], $credsObject ], 'With 4 retries for ConnectException (Guzzle 7)' => [ - $this->getTestClient( - [ + [ + 'responses' => [ $rejectionConnection, $rejectionConnection, $rejectionConnection, $promiseCreds ], - $creds - ), + 'credentials' => $creds + ], $credsObject ], ]; } /** - * @dataProvider failureTestCases - * * @param $client * @param \Exception $expected + * + * @throws GuzzleException */ - public function testHandlesFailureScenarios($client, \Exception $expected) + #[DataProvider('failureDataProvider')] + public function testHandlesFailureScenarios( + array $responses, + \Exception $expected + ) { + $client = $this->getTestClient($responses); $provider = new EcsCredentialProvider([ 'client' => $client, 'retries' => 1, @@ -473,7 +484,7 @@ public function testHandlesFailureScenarios($client, \Exception $expected) } } - public function failureTestCases() + public static function failureDataProvider(): array { $getRequest = new Psr7\Request('GET', '/latest'); @@ -494,22 +505,18 @@ public function failureTestCases() return [ 'Non-retryable error' => [ - $this->getTestClient( - [ - $rejectionCreds, - ] - ), + [ + $rejectionCreds, + ], new CredentialsException( 'Error retrieving credentials from container metadata after attempt 0/1 (401 Unathorized)' ) ], 'Retryable error' => [ - $this->getTestClient( - [ - $rejectionConnection, - $rejectionConnection, - ] - ), + [ + $rejectionConnection, + $rejectionConnection, + ], new CredentialsException( 'Error retrieving credentials from container metadata after attempt 1/1 (cURL error 28: Connection timed out after 1000 milliseconds)' ) diff --git a/tests/Credentials/InstanceProfileProviderTest.php b/tests/Credentials/InstanceProfileProviderTest.php index 09483703df..0d180e88d1 100644 --- a/tests/Credentials/InstanceProfileProviderTest.php +++ b/tests/Credentials/InstanceProfileProviderTest.php @@ -17,10 +17,10 @@ use GuzzleHttp\Psr7\Response; use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Credentials\InstanceProfileProvider - */ +#[CoversClass(InstanceProfileProvider::class)] class InstanceProfileProviderTest extends TestCase { private $originalEnv = []; @@ -74,7 +74,7 @@ protected function tearDown(): void $this->tempFiles = []; } - private function getCredentialArray( + private static function getCredentialArray( $key, $secret, $token = null, @@ -90,17 +90,17 @@ private function getCredentialArray( ]; } - private function getRequestClass() + private static function getRequestClass(): string { return "\GuzzleHttp\Psr7\Request"; } - private function getResponseClass() + private static function getResponseClass(): string { return "\GuzzleHttp\Psr7\Response"; } - private function getRequestException() + private static function getRequestException(): RequestException { return new RequestException('test', new Psr7\Request('GET', 'http://www.example.com')); } @@ -114,7 +114,7 @@ private function getRequestException() * @param bool $throwConnectException * @return \Closure */ - private function getSecureTestClient( + private static function getSecureTestClient( $responses = [], $profile = 'MockProfile', $creds = ['foo_key', 'baz_secret', 'qux_token', null], @@ -195,7 +195,7 @@ private function getSecureTestClient( [], Psr7\Utils::streamFor( json_encode(call_user_func_array( - [$this, 'getCredentialArray'], + [__CLASS__, 'getCredentialArray'], array_values($creds) )) ) @@ -222,14 +222,14 @@ private function getSecureTestClient( * @param bool $throwConnectException * @return \Closure */ - private function getInsecureTestClient( + private static function getInsecureTestClient( $responses = [], $profile = 'MockProfile', $creds = ['foo_key', 'baz_secret', 'qux_token', null], $throwConnectException = false ) { - $requestClass = $this->getRequestClass(); - $responseClass = $this->getResponseClass(); + $requestClass = self::getRequestClass(); + $responseClass = self::getResponseClass(); $getProfileRequests = 0; $getCredsRequests = 0; @@ -292,13 +292,12 @@ private function getInsecureTestClient( [], Psr7\Utils::streamFor( json_encode(call_user_func_array( - [$this, 'getCredentialArray'], + [__CLASS__, 'getCredentialArray'], $creds )) ) ) ); - break; } } @@ -311,16 +310,33 @@ private function getInsecureTestClient( } /** - * @dataProvider successTestCases * - * @param $client - * @param $expected - */ + * @param array $clientDefinition + * @param CredentialsInterface $expected + * @param int|null $expectedAttempts + + */ + #[DataProvider('successDataProvider')] public function testHandlesSuccessScenarios( - callable $client, + array $clientDefinition, CredentialsInterface $expected, - $expectedAttempts = null + ?int $expectedAttempts ) { + $clientParameters = [ + $clientDefinition['responses'], + 'MockProfile', + $clientDefinition['credentials'] + ?? ['foo_key', 'baz_secret', 'qux_token', null], + $clientDefinition['throw_on_connect_exception'] ?? false, + + ]; + + if ($clientDefinition['secure']) { + $client = self::getSecureTestClient(...$clientParameters); + } else { + $client = self::getInsecureTestClient(...$clientParameters); + } + $provider = new InstanceProfileProvider([ 'client' => $client, 'retries' => 5 @@ -349,14 +365,14 @@ public function testHandlesSuccessScenarios( } } - public function successTestCases() + public static function successDataProvider(): \Generator { $expiry = time() + 1000; $creds = ['foo_key', 'baz_secret', 'qux_token', "@{$expiry}"]; $credsObject = new Credentials($creds[0], $creds[1], $creds[2], $expiry); - $requestClass = $this->getRequestClass(); - $responseClass = $this->getResponseClass(); + $requestClass = self::getRequestClass(); + $responseClass = self::getResponseClass(); $getRequest = new $requestClass('GET', '/latest/meta-data/foo'); $putRequest = new $requestClass('PUT', '/latest/meta-data/foo'); $throttledResponse = new $responseClass(503); @@ -378,7 +394,7 @@ public function successTestCases() $promiseCreds = Promise\Create::promiseFor( new Response(200, [], Psr7\Utils::streamFor( json_encode(call_user_func_array( - [$this, 'getCredentialArray'], + [__CLASS__, 'getCredentialArray'], $creds ))) ) @@ -394,23 +410,28 @@ public function successTestCases() 'exception' => $getThrottleException ]); - return [ - // Secure data flow, happy path - [ - $this->getSecureTestClient([], 'MockProfile', $creds), - $credsObject + $cases = [ + 'secure_data_flow_happy_path' => [ + 'client_definition' => [ + 'responses' => [], + 'credentials' => $creds, + 'secure' => true, + ], + 'expected_credentials' => $credsObject, + 'expected_retries' => null ], - - // Insecure data flow, happy path - [ - $this->getInsecureTestClient([], 'MockProfile', $creds), - $credsObject + 'insecure_data_flow_happy_path' => [ + 'client_definition' => [ + 'responses' => [], + 'credentials' => $creds, + 'secure' => false, + ], + 'expected_credentials' => $credsObject, + 'expected_retries' => null ], - - // Secure data flow, with retries for request exception - [ - $this->getSecureTestClient( - [ + 'secure_data_flow_with_retries_for_request_exception' => [ + 'client_definition' => [ + 'responses' => [ 'put' => [ Promise\Create::rejectionFor([ 'exception' => $putThrottleException @@ -428,17 +449,15 @@ public function successTestCases() $promiseCreds ], ], - 'MockProfile', - $creds - ), - $credsObject, - 6 + 'secure' => true, + 'credentials' => $creds + ], + 'expected_credentials' => $credsObject, + 'expected_retries' => 6 ], - - // Insecure data flow, with retries for request exception - [ - $this->getInsecureTestClient( - [ + 'insecure_data_flow_with_retries_for_request_exception' => [ + 'client_definition' => [ + 'responses' => [ 'get_profile' => [ $rejectionThrottleProfile, $promiseProfile @@ -448,49 +467,43 @@ public function successTestCases() $promiseCreds ], ], - 'MockProfile', - $creds - ), - $credsObject, - 5 + 'secure' => false, + 'credentials' => $creds + ], + 'expected_credentials' => $credsObject, + 'expected_retries' => 5 ], - - // Secure data flow, with retries for json exception - [ - $this->getSecureTestClient( - [ + 'secure_data_flow_with_retries_for_json_exception' => [ + 'client_definition' => [ + 'responses' => [ 'get_creds' => [ $promiseBadJsonCreds, $promiseCreds ], ], - 'MockProfile', - $creds - ), - $credsObject, - 4 + 'secure' => true, + 'credentials' => $creds + ], + 'expected_credentials' => $credsObject, + 'expected_retries' => 4 ], - - // Insecure data flow, with retries for json exception - [ - $this->getInsecureTestClient( - [ + 'insecure_data_flow_with_retries_for_json_exception' => [ + 'client_definition' => [ + 'responses' => [ 'get_creds' => [ $promiseBadJsonCreds, $promiseCreds ], ], - 'MockProfile', - $creds - ), - $credsObject, - 4 + 'secure' => false, + 'credentials' => $creds + ], + 'expected_credentials' => $credsObject, + 'expected_retries' => 4 ], - - // Secure data flow, with retries for ConnectException (Guzzle 7) - [ - $this->getSecureTestClient( - [ + 'secure_data_flow_with_retries_for_connect_exception' => [ + 'client_definition' => [ + 'responses' => [ 'put' => [ Promise\Create::rejectionFor([ 'exception' => $putThrottleException @@ -508,18 +521,16 @@ public function successTestCases() $promiseCreds ], ], - 'MockProfile', - $creds, - true - ), - $credsObject, - 6 + 'secure' => true, + 'credentials' => $creds, + 'throw_on_connect_exception' => true + ], + 'expected_credentials' => $credsObject, + 'expected_retries' => 6 ], - - // Insecure data flow, with retries for ConnectException (Guzzle 7) - [ - $this->getInsecureTestClient( - [ + 'insecure_data_flow_with_retries_for_connect_exception' => [ + 'client_definition' => [ + 'responses' => [ 'get_profile' => [ $rejectionThrottleProfile, $promiseProfile @@ -529,24 +540,47 @@ public function successTestCases() $promiseCreds ], ], - 'MockProfile', - $creds, - true - ), - $credsObject, - 5 - ], + 'secure' => false, + 'credentials' => $creds, + 'throw_on_connect_exception' => true + ], + 'expected_credentials' => $credsObject, + 'expected_retries' => 5 + ] ]; + + foreach ($cases as $key => $case) { + yield $key => $case; + } } /** - * @dataProvider failureTestCases * - * @param $client + * @param array $clientDefinition * @param \Exception $expected - */ - public function testHandlesFailureScenarios($client, \Exception $expected) + + */ + #[DataProvider('failureDataProvider')] + public function testHandlesFailureScenarios( + array $clientDefinition, + \Exception $expected + ) { + $clientParameters = [ + $clientDefinition['responses'], + 'MockProfile', + $clientDefinition['credentials'] + ?? ['foo_key', 'baz_secret', 'qux_token', null], + $clientDefinition['throw_on_connect_exception'] ?? false, + + ]; + + if ($clientDefinition['secure']) { + $client = self::getSecureTestClient(...$clientParameters); + } else { + $client = self::getInsecureTestClient(...$clientParameters); + } + $provider = new InstanceProfileProvider([ 'client' => $client, 'retries' => 1, @@ -561,10 +595,10 @@ public function testHandlesFailureScenarios($client, \Exception $expected) } } - public function failureTestCases() + public static function failureDataProvider(): \Generator { - $requestClass = $this->getRequestClass(); - $responseClass = $this->getResponseClass(); + $requestClass = self::getRequestClass(); + $responseClass = self::getResponseClass(); $getRequest = new $requestClass('GET', '/latest/meta-data/foo'); $putRequest = new $requestClass('PUT', '/latest/meta-data/foo'); @@ -607,230 +641,206 @@ public function failureTestCases() ) ]); - return [ - - // Secure data flow, profile call, non-retryable error - [ - $this->getSecureTestClient( - [ + $cases = [ + 'secure_data_flow_profile_call_non_retryable_error' => [ + 'client_definition' => [ + 'responses' => [ 'get_profile' => [$rejectionProfile] ], - 'MockProfile' - ), - new CredentialsException( + 'secure' => true, + ], + 'expected' => new CredentialsException( 'Error retrieving credentials from the instance profile ' . 'metadata service. (401 Unathorized)' - ) + ), ], - - // Insecure data flow, profile call, non-retryable error - [ - $this->getInsecureTestClient( - [ + 'insecure_data_flow_profile_call_non_retryable_error' => [ + 'client_definition' => [ + 'responses' => [ 'get_profile' => [$rejectionProfile] ], - 'MockProfile' - ), - new CredentialsException( + 'secure' => false, + ], + 'expected' => new CredentialsException( 'Error retrieving credentials from the instance profile ' . 'metadata service. (401 Unathorized)' - ) + ), ], - - // Secure data flow, profile call, non-retryable error, ConnectException (Guzzle 7) - [ - $this->getSecureTestClient( - [ + 'secure_data_flow_profile_call_non_retryable_error_connect_exception' => [ + 'client_definition' => [ + 'responses' => [ 'get_profile' => [$rejectionProfile] ], - 'MockProfile', - ['foo_key', 'baz_secret', 'qux_token', null], - true - ), - new CredentialsException( + 'throw_on_connect_exception' => true, + 'secure' => true, + ], + 'expected' => new CredentialsException( 'Error retrieving credentials from the instance profile ' . 'metadata service. (401 Unathorized)' - ) + ), ], - - // Insecure data flow, profile call, non-retryable error, ConnectException (Guzzle 7) - [ - $this->getInsecureTestClient( - [ + 'insecure_data_flow_profile_call_non_retryable_error_connect_exception' => [ + 'client_definition' => [ + 'responses' => [ 'get_profile' => [$rejectionProfile] ], - 'MockProfile', - ['foo_key', 'baz_secret', 'qux_token', null], - true - ), - new CredentialsException( + 'throw_on_connect_exception' => true, + 'secure' => false, + ], + 'expected' => new CredentialsException( 'Error retrieving credentials from the instance profile ' . 'metadata service. (401 Unathorized)' - ) + ), ], - - // Secure data flow, credentials call, non-retryable error - [ - $this->getSecureTestClient( - [ + 'secure_data_flow_credentials_call_non_retryable_error' => [ + 'client_definition' => [ + 'responses' => [ 'get_creds' => [$rejectionCreds] ], - 'MockProfile' - ), - new CredentialsException( + 'secure' => true, + ], + 'expected' => new CredentialsException( 'Error retrieving credentials from the instance profile ' . 'metadata service. (401 Unathorized)' - ) + ), ], - - // Insecure data flow, credentials call, non-retryable error - [ - $this->getInsecureTestClient( - [ + 'insecure_data_flow_credentials_call_non_retryable_error' => [ + 'client_definition' => [ + 'responses' => [ 'get_creds' => [$rejectionCreds] ], - 'MockProfile' - ), - new CredentialsException( + 'secure' => false, + ], + 'expected' => new CredentialsException( 'Error retrieving credentials from the instance profile ' . 'metadata service. (401 Unathorized)' - ) + ), ], - - // Secure data flow, token call, retryable error - [ - $this->getSecureTestClient( - [ + 'secure_data_flow_token_call_retryable_error' => [ + 'client_definition' => [ + 'responses' => [ 'put' => [ $rejectionThrottleToken, $rejectionThrottleToken, $rejectionThrottleToken, ] ], - 'MockProfile' - ), - new CredentialsException( + 'secure' => true, + ], + 'expected' => new CredentialsException( 'Error retrieving credentials from the instance profile ' . 'metadata service. (Error retrieving metadata token)' - ) + ), ], - - // Secure data flow, profile call, retryable error - [ - $this->getSecureTestClient( - [ + 'secure_data_flow_profile_call_retryable_error' => [ + 'client_definition' => [ + 'responses' => [ 'get_profile' => [ $rejectionThrottleProfile, $rejectionThrottleProfile, $rejectionThrottleProfile, ] ], - 'MockProfile' - ), - new CredentialsException( + 'secure' => true, + ], + 'expected' => new CredentialsException( 'Error retrieving credentials from the instance profile ' . 'metadata service. (503 ThrottlingException)' - ) + ), ], - - // Insecure data flow, profile call, retryable error - [ - $this->getInsecureTestClient( - [ + 'insecure_data_flow_profile_call_retryable_error' => [ + 'client_definition' => [ + 'responses' => [ 'get_profile' => [ $rejectionThrottleProfile, $rejectionThrottleProfile, $rejectionThrottleProfile, - ], + ] ], - 'MockProfile' - ), - new CredentialsException( + 'secure' => false, + ], + 'expected' => new CredentialsException( 'Error retrieving credentials from the instance profile ' . 'metadata service. (503 ThrottlingException)' - ) + ), ], - - // Secure data flow, credentials call, retryable error - [ - $this->getSecureTestClient( - [ - 'get_creds' => [ + 'secure_data_flow_credentials_call_retryable_error' => [ + 'client_definition' => [ + 'responses' => [ + 'get_profile' => [ $rejectionThrottleCreds, $rejectionThrottleCreds, $rejectionThrottleCreds, - ], + ] ], - 'MockProfile' - ), - new CredentialsException( + 'secure' => true, + ], + 'expected' => new CredentialsException( 'Error retrieving credentials from the instance profile ' . 'metadata service. (503 ThrottlingException)' - ) + ), ], - - // Insecure data flow, credentials call, retryable error - [ - $this->getInsecureTestClient( - [ - 'get_creds' => [ + 'insecure_data_flow_credentials_call_retryable_error' => [ + 'client_definition' => [ + 'responses' => [ + 'get_profile' => [ $rejectionThrottleCreds, $rejectionThrottleCreds, $rejectionThrottleCreds, - ], + ] ], - 'MockProfile' - ), - new CredentialsException( + 'secure' => false, + ], + 'expected' => new CredentialsException( 'Error retrieving credentials from the instance profile ' . 'metadata service. (503 ThrottlingException)' - ) + ), ], - - // Secure data flow, credentials call, retryable invalid json error - [ - $this->getSecureTestClient( - [ + 'secure_data_flow_credentials_call_retryable_invalid_json_error' => [ + 'client_definition' => [ + 'responses' => [ 'get_creds' => [ $promiseBadJsonCreds, $promiseBadJsonCreds, - $promiseBadJsonCreds + $promiseBadJsonCreds, ] ], - 'MockProfile' - ), - new CredentialsException( + 'secure' => true, + ], + 'expected' => new CredentialsException( 'Error retrieving credentials from the instance profile ' . 'metadata service. (Invalid JSON response, retries exhausted)' - ) + ), ], - - // Insecure data flow, credentials call, retryable invalid json error - [ - $this->getInsecureTestClient( - [ + 'insecure_data_flow_credentials_call_retryable_invalid_json_error' => [ + 'client_definition' => [ + 'responses' => [ 'get_creds' => [ $promiseBadJsonCreds, $promiseBadJsonCreds, - $promiseBadJsonCreds + $promiseBadJsonCreds, ] ], - 'MockProfile' - ), - new CredentialsException( + 'secure' => false, + ], + 'expected' => new CredentialsException( 'Error retrieving credentials from the instance profile ' . 'metadata service. (Invalid JSON response, retries exhausted)' - ) - ], + ), + ] ]; + + foreach ($cases as $key => $case) { + yield $key => $case; + } } public function testSwitchesBackToSecureModeOn401() { $this->expectExceptionMessage("Error retrieving credentials from the instance profile metadata service. (999 Expected Exception)"); $this->expectException(\Aws\Exception\CredentialsException::class); - $requestClass = $this->getRequestClass(); - $responseClass = $this->getResponseClass(); + $requestClass = self::getRequestClass(); + $responseClass = self::getResponseClass(); $getRequest = new $requestClass('GET', '/latest/meta-data/foo'); $putRequest = new $requestClass('PUT', '/latest/meta-data/foo'); $reqNumber = 0; @@ -891,7 +901,7 @@ private function getTestCreds( array $args = [] ) { $args['profile'] = $profile; - $args['client'] = $this->getSecureTestClient([], $profile, $result); + $args['client'] = self::getSecureTestClient([], $profile, $result); $provider = new InstanceProfileProvider($args); return $provider(); @@ -930,18 +940,19 @@ public function testThrowsExceptionOnInvalidMetadata() $this->expectExceptionMessage("Unexpected instance profile response"); $this->expectException(\Aws\Exception\CredentialsException::class); $this->getTestCreds( - $this->getCredentialArray(null, null, null, null, false), + self::getCredentialArray(null, null, null, null, false), 'foo' )->wait(); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testDoesNotRequireConfig() { new InstanceProfileProvider(); + $this->assertTrue(true); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testEnvDisableFlag() { $flag = getenv(InstanceProfileProvider::ENV_DISABLE); @@ -950,7 +961,7 @@ public function testEnvDisableFlag() putenv(InstanceProfileProvider::ENV_DISABLE . '=true'); $t = time() + 1000; $this->getTestCreds( - json_encode($this->getCredentialArray('foo', 'baz', null, "@{$t}")) + json_encode(self::getCredentialArray('foo', 'baz', null, "@{$t}")) )->wait(); $this->fail('Did not throw expected CredentialException.'); } catch (CredentialsException $e) { @@ -961,6 +972,7 @@ public function testEnvDisableFlag() } finally { putenv(InstanceProfileProvider::ENV_DISABLE . '=' . $flag); } + $this->assertTrue(true); } public function testRetriesEnvVarIsUsed() @@ -969,7 +981,7 @@ public function testRetriesEnvVarIsUsed() $retries = (int) getenv(InstanceProfileProvider::ENV_RETRIES); $t = time() + 1000; - $result = json_encode($this->getCredentialArray('foo', 'baz', null, "@{$t}")); + $result = json_encode(self::getCredentialArray('foo', 'baz', null, "@{$t}")); $responses = [new Response(200, [], Psr7\Utils::streamFor($result))]; $client = function () use (&$retries, $responses) { @@ -995,48 +1007,56 @@ public function testRetriesEnvVarIsUsed() } /** - * @dataProvider returnsExpiredCredsProvider * * @param $client - */ + + */ + #[DataProvider('returnsExpiredCredsProvider')] public function testExtendsExpirationAndSendsRequestIfImdsYieldsExpiredCreds($client) { //expect warning emitted from extension - $this->expectWarning(); - $this->expectWarningMessageMatches( + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessageMatches( '/Attempting credential expiration extension/' ); + set_error_handler(function ($errno, $errstr) { + throw new \RuntimeException($errstr, $errno); + }, E_USER_WARNING); - $provider = new InstanceProfileProvider([ - 'client' => $client - ]); - $creds = $provider()->wait(); + try { + $provider = new InstanceProfileProvider([ + 'client' => $client + ]); + $creds = $provider()->wait(); - $this->assertSame('foo', $creds->getAccessKeyId()); - $this->assertSame('baz', $creds->getSecretKey()); - $this->assertFalse($creds->isExpired()); + $this->assertSame('foo', $creds->getAccessKeyId()); + $this->assertSame('baz', $creds->getSecretKey()); + $this->assertFalse($creds->isExpired()); - $requestHandler = new MockHandler([ - new Result(['message' => 'Request sent']), - new Result(['message' => 'Request sent']), - new Result(['message' => 'Request sent']) - ]); + $requestHandler = new MockHandler([ + new Result(['message' => 'Request sent']), + new Result(['message' => 'Request sent']), + new Result(['message' => 'Request sent']) + ]); - $s3Client = new S3Client([ - 'region' => 'us-west-2', - 'version' => 'latest', - 'credentials' => $creds, - 'handler' => $requestHandler - ]); - $s3Client->listBuckets(); - $s3Client->listBuckets(); - $result = $s3Client->listBuckets(); + $s3Client = new S3Client([ + 'region' => 'us-west-2', + 'version' => 'latest', + 'credentials' => $creds, + 'handler' => $requestHandler + ]); + $s3Client->listBuckets(); + $s3Client->listBuckets(); + $result = $s3Client->listBuckets(); - $this->assertEquals('Request sent', $result['message']); - $this->assertLessThanOrEqual(3,$this->getPropertyValue($provider,'attempts')); + $this->assertEquals('Request sent', $result['message']); + $this->assertLessThanOrEqual(3,$this->getPropertyValue($provider,'attempts')); + } finally { + restore_error_handler(); + } } - public function returnsExpiredCredsProvider() + public static function returnsExpiredCredsProvider(): array { $expiredTime = time() - 1000; $expiredCreds = ['foo', 'baz', null, "@{$expiredTime}"]; @@ -1044,7 +1064,7 @@ public function returnsExpiredCredsProvider() $promiseCreds = Promise\Create::promiseFor( new Response(200, [], Psr7\Utils::streamFor( json_encode(call_user_func_array( - [$this, 'getCredentialArray'], + [__CLASS__, 'getCredentialArray'], $expiredCreds ))) ) @@ -1052,7 +1072,7 @@ public function returnsExpiredCredsProvider() return [ [ - $client = $this->getSecureTestClient( + $client = self::getSecureTestClient( [ 'get_creds' => [ $promiseCreds @@ -1063,7 +1083,7 @@ public function returnsExpiredCredsProvider() ) ], [ - $client = $this->getInsecureTestClient( + $client = self::getInsecureTestClient( [ 'get_creds' => [ $promiseCreds @@ -1077,54 +1097,61 @@ public function returnsExpiredCredsProvider() } /** - * @dataProvider imdsUnavailableProvider * * @param $client - */ + + */ + #[DataProvider('imdsUnavailableProvider')] public function testExtendsExpirationAndSendsRequestIfImdsUnavailable($client) { //expect warning emitted from extension - $this->expectWarning(); - $this->expectWarningMessageMatches( + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessageMatches( '/Attempting credential expiration extension/' ); - + set_error_handler(function ($errno, $errstr) { + throw new \RuntimeException($errstr, $errno); + }); $expiredTime = time() - 1000; $expiredCreds = new Credentials('foo', 'baz', null, $expiredTime); - $this->assertTrue($expiredCreds->isExpired()); + try { + $this->assertTrue($expiredCreds->isExpired()); - $provider = new InstanceProfileProvider([ - 'client' => $client - ]); - $creds = $provider($expiredCreds)->wait(); - $this->assertSame('foo', $creds->getAccessKeyId()); - $this->assertSame('baz', $creds->getSecretKey()); - $this->assertFalse($expiredCreds->isExpired()); - - $requestHandler = new MockHandler([ - new Result(['message' => 'Request sent']), - new Result(['message' => 'Request sent']), - new Result(['message' => 'Request sent']) - ]); + $provider = new InstanceProfileProvider([ + 'client' => $client + ]); + $creds = $provider($expiredCreds)->wait(); + $this->assertSame('foo', $creds->getAccessKeyId()); + $this->assertSame('baz', $creds->getSecretKey()); + $this->assertFalse($expiredCreds->isExpired()); + + $requestHandler = new MockHandler([ + new Result(['message' => 'Request sent']), + new Result(['message' => 'Request sent']), + new Result(['message' => 'Request sent']) + ]); - $s3Client = new S3Client([ - 'region' => 'us-west-2', - 'version' => 'latest', - 'credentials' => $creds, - 'handler' => $requestHandler - ]); - $s3Client -> listBuckets(); - $s3Client -> listBuckets(); - $result = $s3Client->listBuckets(); + $s3Client = new S3Client([ + 'region' => 'us-west-2', + 'version' => 'latest', + 'credentials' => $creds, + 'handler' => $requestHandler + ]); + $s3Client -> listBuckets(); + $s3Client -> listBuckets(); + $result = $s3Client->listBuckets(); - $this->assertEquals('Request sent', $result['message']); - $this->assertLessThanOrEqual(3,$this->getPropertyValue($provider,'attempts')); + $this->assertEquals('Request sent', $result['message']); + $this->assertLessThanOrEqual(3,$this->getPropertyValue($provider,'attempts')); + } finally { + restore_error_handler(); + } } - public function imdsUnavailableProvider() + public static function imdsUnavailableProvider() { - $requestClass = $this->getRequestClass(); - $responseClass = $this->getResponseClass(); + $requestClass = self::getRequestClass(); + $responseClass = self::getResponseClass(); $getRequest = new $requestClass('GET', '/latest/meta-data/foo'); $putRequest = new $requestClass('PUT', '/latest/meta-data/foo'); @@ -1151,7 +1178,7 @@ public function imdsUnavailableProvider() return [ [ - $client = $this->getSecureTestClient( + $client = self::getSecureTestClient( [ 'put' => [ $profileRejection500 @@ -1161,7 +1188,7 @@ public function imdsUnavailableProvider() ) ], [ - $client = $this->getSecureTestClient( + $client = self::getSecureTestClient( [ 'get_creds' => [ $credsRejection500 @@ -1171,7 +1198,7 @@ public function imdsUnavailableProvider() ) ], [ - $client = $this->getSecureTestClient( + $client = self::getSecureTestClient( [ 'get_creds' => [ $credsRejectionReadTimeout @@ -1181,7 +1208,7 @@ public function imdsUnavailableProvider() ) ], [ - $client = $this->getInsecureTestClient( + $client = self::getInsecureTestClient( [ 'get_creds' => [ $credsRejection500 @@ -1191,7 +1218,7 @@ public function imdsUnavailableProvider() ) ], [ - $client = $this->getInsecureTestClient( + $client = self::getInsecureTestClient( [ 'get_creds' => [ $credsRejectionReadTimeout @@ -1208,7 +1235,7 @@ public function testResetsAttempts() $now = time() + 10000; $creds = ['foo', 'baz', null, "@{$now}"]; - $client = $this->getSecureTestClient( + $client = self::getSecureTestClient( [], 'MockProfile', $creds @@ -1348,7 +1375,7 @@ private function fetchMockedCredentialsAndAlwaysExpectAToken($config=[]) { 200, [], Psr7\Utils::streamFor( - json_encode($this->getCredentialArray('foo', 'baz', null, "@$expiration")) + json_encode(self::getCredentialArray('foo', 'baz', null, "@$expiration")) ) ) ); @@ -1382,8 +1409,9 @@ private function fetchMockedCredentialsAndAlwaysExpectAToken($config=[]) { * @param string $expectedEndpointMode this parameter is the endpoint mode that is expected to be resolved by * the credential provider. * - * @dataProvider endpointModeCasesProvider - */ + + */ + #[DataProvider('endpointModeCasesProvider')] public function testEndpointModeResolution( ?string $endpointModeClientConfig, ?string $endpointModeEnv, @@ -1445,7 +1473,7 @@ public function testEndpointModeResolution( * * @return array[] */ - public function endpointModeCasesProvider() : array + public static function endpointModeCasesProvider() : array { return [ 'endpoint_mode_not_specified' => [ @@ -1507,8 +1535,9 @@ public function endpointModeCasesProvider() : array * @param string $expectedEndpoint this parameter is the endpoint that is expected to be resolved * by the credential provider. * - * @dataProvider endpointCasesProvider - */ + + */ + #[DataProvider('endpointCasesProvider')] public function testEndpointResolution( string $endpointMode, ?string $endpointEnv, @@ -1550,7 +1579,7 @@ public function testEndpointResolution( * * @return array[] */ - public function endpointCasesProvider() : array + public static function endpointCasesProvider() : array { return [ 'with_endpoint_mode_ipv4' => [ @@ -1667,7 +1696,7 @@ private function createMockHandlerWithUriCapture(): callable 200, [], Psr7\Utils::streamFor( - json_encode($this->getCredentialArray('foo', 'baz', null, "@$expiration")) + json_encode(self::getCredentialArray('foo', 'baz', null, "@$expiration")) ) ) ); diff --git a/tests/Credentials/LoginCredentialProviderTest.php b/tests/Credentials/LoginCredentialProviderTest.php index 19d6304cc8..a2943a3d51 100644 --- a/tests/Credentials/LoginCredentialProviderTest.php +++ b/tests/Credentials/LoginCredentialProviderTest.php @@ -11,10 +11,10 @@ use Aws\Signin\Exception\SigninException; use Aws\Test\UsesServiceTrait; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Credentials\LoginCredentialProvider - */ +#[CoversClass(LoginCredentialProvider::class)] class LoginCredentialProviderTest extends TestCase { use UsesServiceTrait; @@ -301,9 +301,7 @@ public function testLoadTokenFailsWithInvalidJson(): void $provider()->wait(); } - /** - * @dataProvider missingCacheKeysProvider - */ + #[DataProvider('missingCacheKeysProvider')] public function testLoadTokenFailsWithMissingOrEmptyCacheKeys( array $tokenData, string $expectedMessage @@ -327,7 +325,7 @@ public function testLoadTokenFailsWithMissingOrEmptyCacheKeys( $provider()->wait(); } - public function missingCacheKeysProvider(): array + public static function missingCacheKeysProvider(): array { $validDpopKey = "-----BEGIN EC PRIVATE KEY-----\n" . "MHcCAQEEID9l+ckeHBxlF47cg0h5qJnAErPvCm1brUY8i7b6qSJToAoGCCqGSM49\n" . @@ -1249,9 +1247,7 @@ public function testLoadCredentialsWithSpecifiedCurveKey(): void $this->assertEquals('123456789012', $credentials->getAccountId()); } - /** - * @dataProvider loginTestCasesProvider - */ + #[DataProvider('loginTestCasesProvider')] public function testLoginCredentialProviderFromTestCases( string $documentation, string $configContents, @@ -1381,7 +1377,7 @@ public function testLoginCredentialProviderFromTestCases( * @return \Generator * @throws \JsonException */ - public function loginTestCasesProvider(): \Generator + public static function loginTestCasesProvider(): \Generator { $testCasesFile = __DIR__ . '/fixtures/login/test-cases.json'; @@ -1407,9 +1403,7 @@ public function loginTestCasesProvider(): \Generator } } - /** - * @dataProvider externalRefreshProvider - */ + #[DataProvider('externalRefreshProvider')] public function testExternalRefreshBehavior( string $scenario, int $currentExpiryMinutes, @@ -1532,7 +1526,7 @@ public function testExternalRefreshBehavior( } } - public function externalRefreshProvider(): array + public static function externalRefreshProvider(): array { return [ 'external refresh detected - all conditions met' => [ diff --git a/tests/Crypto/AesDecryptingStreamTest.php b/tests/Crypto/AesDecryptingStreamTest.php index da2d03cf22..7092d25a27 100644 --- a/tests/Crypto/AesDecryptingStreamTest.php +++ b/tests/Crypto/AesDecryptingStreamTest.php @@ -6,8 +6,11 @@ use Aws\Crypto\Cipher\CipherMethod; use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +#[CoversClass(AesDecryptingStream::class)] class AesDecryptingStreamTest extends TestCase { const KB = 1024; @@ -15,12 +18,7 @@ class AesDecryptingStreamTest extends TestCase use AesEncryptionStreamTestTrait; - /** - * @dataProvider cartesianJoinInputCipherMethodProvider - * - * @param StreamInterface $plainText - * @param CipherMethod $iv - */ + #[DataProvider('cartesianJoinInputCipherMethodProvider')] public function testStreamOutputSameAsOpenSSL( StreamInterface $plainText, CipherMethod $iv @@ -57,12 +55,7 @@ public function testStreamOutputSameAsOpenSSL( ); } - /** - * @dataProvider cartesianJoinInputCipherMethodProvider - * - * @param StreamInterface $plainText - * @param CipherMethod $iv - */ + #[DataProvider('cartesianJoinInputCipherMethodProvider')] public function testReportsSizeOfPlaintextWherePossible( StreamInterface $plainText, CipherMethod $iv @@ -88,12 +81,7 @@ public function testReportsSizeOfPlaintextWherePossible( } } - /** - * @dataProvider cartesianJoinInputCipherMethodProvider - * - * @param StreamInterface $plainText - * @param CipherMethod $iv - */ + #[DataProvider('cartesianJoinInputCipherMethodProvider')] public function testSupportsRewinding( StreamInterface $plainText, CipherMethod $iv @@ -112,11 +100,7 @@ public function testSupportsRewinding( $this->assertSame($firstBytes, $deciphered->read(256 * 2 + 3)); } - /** - * @dataProvider cipherMethodProvider - * - * @param CipherMethod $iv - */ + #[DataProvider('cipherMethodProvider')] public function testMemoryUsageRemainsConstant(CipherMethod $iv) { $memory = memory_get_usage(); @@ -154,11 +138,7 @@ public function testDoesNotSupportArbitrarySeeking() $stream->seek(1); } - /** - * @dataProvider cipherMethodProvider - * - * @param CipherMethod $cipherMethod - */ + #[DataProvider('cipherMethodProvider')] public function testReturnsEmptyStringWhenSourceStreamEmpty( CipherMethod $cipherMethod ) { diff --git a/tests/Crypto/AesEncryptingStreamTest.php b/tests/Crypto/AesEncryptingStreamTest.php index 086e52c146..d9b8c3754d 100644 --- a/tests/Crypto/AesEncryptingStreamTest.php +++ b/tests/Crypto/AesEncryptingStreamTest.php @@ -8,7 +8,10 @@ use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(AesEncryptingStream::class)] class AesEncryptingStreamTest extends TestCase { const KB = 1024; @@ -16,12 +19,7 @@ class AesEncryptingStreamTest extends TestCase use AesEncryptionStreamTestTrait; - /** - * @dataProvider cartesianJoinInputCipherMethodProvider - * - * @param StreamInterface $plainText - * @param CipherMethod $iv - */ + #[DataProvider('cartesianJoinInputCipherMethodProvider')] public function testStreamOutputSameAsOpenSSL( StreamInterface $plainText, CipherMethod $iv @@ -42,12 +40,7 @@ public function testStreamOutputSameAsOpenSSL( ); } - /** - * @dataProvider cartesianJoinInputCipherMethodProvider - * - * @param StreamInterface $plainText - * @param CipherMethod $iv - */ + #[DataProvider('cartesianJoinInputCipherMethodProvider')] public function testGetOpenSslName( StreamInterface $plainText, CipherMethod $iv @@ -62,12 +55,7 @@ public function testGetOpenSslName( ); } - /** - * @dataProvider cartesianJoinInputCipherMethodProvider - * - * @param StreamInterface $plainText - * @param CipherMethod $iv - */ + #[DataProvider('cartesianJoinInputCipherMethodProvider')] public function testGetCurrentIv( StreamInterface $plainText, CipherMethod $iv @@ -82,12 +70,7 @@ public function testGetCurrentIv( ); } - /** - * @dataProvider cartesianJoinInputCipherMethodProvider - * - * @param StreamInterface $plainText - * @param CipherMethod $iv - */ + #[DataProvider('cartesianJoinInputCipherMethodProvider')] public function testSupportsRewinding( StreamInterface $plainText, CipherMethod $iv @@ -99,12 +82,7 @@ public function testSupportsRewinding( $this->assertSame($firstBytes, $cipherText->read(256 * 2 + 3)); } - /** - * @dataProvider cartesianJoinInputCipherMethodProvider - * - * @param StreamInterface $plainText - * @param CipherMethod $iv - */ + #[DataProvider('cartesianJoinInputCipherMethodProvider')] public function testAccuratelyReportsSizeOfCipherText( StreamInterface $plainText, CipherMethod $iv @@ -114,11 +92,7 @@ public function testAccuratelyReportsSizeOfCipherText( $this->assertSame($cipherText->getSize(), strlen((string) $cipherText)); } - /** - * @dataProvider cipherMethodProvider - * - * @param CipherMethod $cipherMethod - */ + #[DataProvider('cipherMethodProvider')] public function testMemoryUsageRemainsConstant(CipherMethod $cipherMethod) { $memory = memory_get_usage(); @@ -148,11 +122,7 @@ public function testIsNotWritable() $this->assertFalse($stream->isWritable()); } - /** - * @dataProvider cipherMethodProvider - * - * @param CipherMethod $cipherMethod - */ + #[DataProvider('cipherMethodProvider')] public function testReturnsPaddedOrEmptyStringWhenSourceStreamEmpty( CipherMethod $cipherMethod ) { @@ -168,11 +138,7 @@ public function testReturnsPaddedOrEmptyStringWhenSourceStreamEmpty( $this->assertSame($stream->read(self::MB), ''); } - /** - * @dataProvider cipherMethodProvider - * - * @param CipherMethod $cipherMethod - */ + #[DataProvider('cipherMethodProvider')] public function testDoesNotSupportSeekingFromEnd(CipherMethod $cipherMethod) { $this->expectException(\LogicException::class); @@ -181,14 +147,15 @@ public function testDoesNotSupportSeekingFromEnd(CipherMethod $cipherMethod) $stream->seek(1, SEEK_END); } - /** - * @dataProvider seekableCipherMethodProvider - * - * @param CipherMethod $cipherMethod - */ + #[DataProvider('seekableCipherMethodProvider')] public function testSupportsSeekingFromCurrentPosition( - CipherMethod $cipherMethod + ?CipherMethod $cipherMethod, + bool $skipTest ) { + if ($skipTest) { + $this->markTestSkipped(); + } + $stream = new AesEncryptingStream( Psr7\Utils::streamFor(openssl_random_pseudo_bytes(2 * self::MB)), 'foo', diff --git a/tests/Crypto/AesEncryptionStreamTestTrait.php b/tests/Crypto/AesEncryptionStreamTestTrait.php index 36626ba4c7..09ff684fbf 100644 --- a/tests/Crypto/AesEncryptionStreamTestTrait.php +++ b/tests/Crypto/AesEncryptionStreamTestTrait.php @@ -7,11 +7,11 @@ trait AesEncryptionStreamTestTrait { - public function cartesianJoinInputCipherMethodProvider() + public function cartesianJoinInputCipherMethodProvider(): array { $toReturn = []; - $plainTexts = $this->unwrapProvider([$this, 'plainTextProvider']); - $ivs = $this->unwrapProvider([$this, 'cipherMethodProvider']); + $plainTexts = self::unwrapProvider([__CLASS__, 'plainTextProvider']); + $ivs = self::unwrapProvider([__CLASS__, 'cipherMethodProvider']); for ($i = 0; $i < count($plainTexts); $i++) { for ($j = 0; $j < count($ivs); $j++) { @@ -22,11 +22,11 @@ public function cartesianJoinInputCipherMethodProvider() return $toReturn; } - public function cartesianJoinInputKeySizeProvider() + public static function cartesianJoinInputKeySizeProvider(): array { $toReturn = []; - $plainTexts = $this->unwrapProvider([$this, 'plainTextProvider']); - $keySizes = $this->unwrapProvider([$this, 'keySizeProvider']); + $plainTexts = self::unwrapProvider([__CLASS__, 'plainTextProvider']); + $keySizes = self::unwrapProvider([__CLASS__, 'keySizeProvider']); for ($i = 0; $i < count($plainTexts); $i++) { for ($j = 0; $j < count($keySizes); $j++) { @@ -40,10 +40,10 @@ public function cartesianJoinInputKeySizeProvider() return $toReturn; } - public function cipherMethodProvider() + public static function cipherMethodProvider(): array { $toReturn = []; - foreach ($this->unwrapProvider([$this, 'keySizeProvider']) as $keySize) { + foreach (self::unwrapProvider([__CLASS__, 'keySizeProvider']) as $keySize) { $toReturn []= [new Cbc( openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc')), $keySize @@ -53,14 +53,24 @@ public function cipherMethodProvider() return $toReturn; } - public function seekableCipherMethodProvider() + public static function seekableCipherMethodProvider(): array { - return array_filter($this->cipherMethodProvider(), function (array $args) { + $data = array_filter(self::cipherMethodProvider(), function (array $args) { return !($args[0] instanceof Cbc); }); + + if (empty($data)) { + return [ + 'empty_data' => [null, true] + ]; + } + + return array_map(function ($entry) { + return [$entry[0], false]; + }, $data); } - public function keySizeProvider() + public static function keySizeProvider(): array { return [ [128], @@ -69,7 +79,7 @@ public function keySizeProvider() ]; } - public function plainTextProvider() + public static function plainTextProvider(): array { return [ [Psr7\Utils::streamFor('The rain in Spain falls mainly on the plain.')], @@ -79,7 +89,7 @@ public function plainTextProvider() ]; } - private function unwrapProvider(callable $provider) + private static function unwrapProvider(callable $provider): array { return array_map(function (array $wrapped) { return $wrapped[0]; diff --git a/tests/Crypto/AesGcmDecryptingStreamTest.php b/tests/Crypto/AesGcmDecryptingStreamTest.php index 6e9ffc57c0..200c7f36df 100644 --- a/tests/Crypto/AesGcmDecryptingStreamTest.php +++ b/tests/Crypto/AesGcmDecryptingStreamTest.php @@ -5,17 +5,15 @@ use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(AesGcmDecryptingStream::class)] class AesGcmDecryptingStreamTest extends TestCase { use AesEncryptionStreamTestTrait; - /** - * @dataProvider cartesianJoinInputKeySizeProvider - * - * @param StreamInterface $plainText - * @param int $keySize - */ + #[DataProvider('cartesianJoinInputKeySizeProvider')] public function testStreamOutputSameAsOpenSSL( StreamInterface $plainText, $keySize @@ -54,12 +52,7 @@ public function testStreamOutputSameAsOpenSSL( $this->assertSame((string) $decryptingStream, $plainText); } - /** - * @dataProvider cartesianJoinInputKeySizeProvider - * - * @param StreamInterface $plainText - * @param int $keySize - */ + #[DataProvider('cartesianJoinInputKeySizeProvider')] public function testThrowsForInvalidTag( StreamInterface $plainText, $keySize diff --git a/tests/Crypto/AesGcmEncryptingStreamTest.php b/tests/Crypto/AesGcmEncryptingStreamTest.php index 7cc4293422..dc12106a65 100644 --- a/tests/Crypto/AesGcmEncryptingStreamTest.php +++ b/tests/Crypto/AesGcmEncryptingStreamTest.php @@ -5,17 +5,15 @@ use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(AesGcmEncryptingStream::class)] class AesGcmEncryptingStreamTest extends TestCase { use AesEncryptionStreamTestTrait; - /** - * @dataProvider cartesianJoinInputKeySizeProvider - * - * @param StreamInterface $plainText - * @param int $keySize - */ + #[DataProvider('cartesianJoinInputKeySizeProvider')] public function testStreamOutputSameAsOpenSSL( StreamInterface $plainText, $keySize @@ -51,9 +49,7 @@ public function testStreamOutputSameAsOpenSSL( $this->assertSame($tag, $encryptingStream->getTag()); } - /** - * @dataProvider encryptDataProvider - */ + #[DataProvider('encryptDataProvider')] public function testCorrectlyEncryptsData( $plaintext, $key, @@ -82,7 +78,7 @@ public function testCorrectlyEncryptsData( ); } - public function encryptDataProvider() + public static function encryptDataProvider(): array { // [[ $plaintext, $key, $iv, $aad, $keySize, $expectedCipher, $expectedTag ]] return [ diff --git a/tests/Crypto/AlgorithmSuiteTest.php b/tests/Crypto/AlgorithmSuiteTest.php index 11a5e490d4..033bef3021 100644 --- a/tests/Crypto/AlgorithmSuiteTest.php +++ b/tests/Crypto/AlgorithmSuiteTest.php @@ -5,11 +5,11 @@ use Aws\Crypto\AlgorithmConstants; use Aws\Crypto\MaterialsProviderV3; use Aws\S3\Crypto\S3EncryptionClientV3; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Crypto\AlgorithmSuite - */ +#[CoversClass(AlgorithmSuite::class)] class AlgorithmSuiteTest extends TestCase { /** @@ -95,8 +95,8 @@ public static function cipherNameProvider(): array /** * Test getCipherName() method - * @dataProvider cipherNameProvider */ + #[DataProvider('cipherNameProvider')] public function testGetCipherName(AlgorithmSuite $suite, string $expectedCipher): void { $this->assertSame($expectedCipher, $suite->getCipherName()); @@ -148,8 +148,8 @@ public static function ivLengthProvider(): array /** * Test getIvLengthBits() and getIvLengthBytes() methods - * @dataProvider ivLengthProvider */ + #[DataProvider('ivLengthProvider')] public function testGetIvLength(AlgorithmSuite $suite, int $expectedBits, int $expectedBytes): void { $this->assertSame($expectedBits, $suite->getIvLengthBits()); @@ -182,8 +182,8 @@ public static function cipherTagLengthProvider(): array /** * Test getCipherTagLengthBits() and getCipherTagLengthInBytes() methods - * @dataProvider cipherTagLengthProvider */ + #[DataProvider('cipherTagLengthProvider')] public function testGetCipherTagLength(AlgorithmSuite $suite, int $expectedBits, int $expectedBytes): void { $this->assertSame($expectedBits, $suite->getCipherTagLengthBits()); @@ -232,8 +232,8 @@ public static function keyDerivationProvider(): array /** * Test key derivation length methods - * @dataProvider keyDerivationProvider */ + #[DataProvider('keyDerivationProvider')] public function testGetDerivationKeyLengths( AlgorithmSuite $suite, int $expectedInputBits, @@ -279,8 +279,8 @@ public static function commitmentKeyLengthProvider(): array /** * Test commitment key length methods - * @dataProvider commitmentKeyLengthProvider */ + #[DataProvider('commitmentKeyLengthProvider')] public function testGetCommitmentKeyLengths( AlgorithmSuite $suite, int $expectedInputBits, diff --git a/tests/Crypto/Cipher/CbcTest.php b/tests/Crypto/Cipher/CbcTest.php index ee4b6cca0d..7d97e05385 100644 --- a/tests/Crypto/Cipher/CbcTest.php +++ b/tests/Crypto/Cipher/CbcTest.php @@ -2,8 +2,10 @@ namespace Aws\Test\Crypto\Cipher; use Aws\Crypto\Cipher\Cbc; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\TestCase; +#[CoversClass(Cbc::class)] class CbcTest extends TestCase { public function testShouldReportCipherMethodOfCBC() diff --git a/tests/Crypto/EncryptionDecryptionTraitV3Test.php b/tests/Crypto/EncryptionDecryptionTraitV3Test.php index 23d4581cab..edcf66bea8 100644 --- a/tests/Crypto/EncryptionDecryptionTraitV3Test.php +++ b/tests/Crypto/EncryptionDecryptionTraitV3Test.php @@ -16,11 +16,11 @@ use GuzzleHttp\Psr7\AppendStream; use PHPUnit\Framework\MockObject\MockObject; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Crypto\EncryptionTraitV3 - * @covers \Aws\Crypto\DecryptionTraitV3 - */ +#[CoversClass(EncryptionTraitV3::class)] +#[CoversClass(DecryptionTraitV3::class)] class EncryptionDecryptionTraitV3Test extends TestCase { use UsesCryptoParamsTraitV3; @@ -231,8 +231,7 @@ public function testValidV2ObjectHasV2EnvelopeFields(): void } /** - * Tests that a V2 envelope with V3 fields appropriately errors - * @return void + * Tests that a V2 envelope with V3 fields appropriately errors */ public function testV2EnvelopeWithV3FieldsThrows(): void { @@ -286,8 +285,7 @@ public function testV2EnvelopeWithV3FieldsThrows(): void } /** - * Tests that a V3 envelope with V2 fields appropriately errors - * @return void + * Tests that a V3 envelope with V2 fields appropriately errors */ public function testV3EnvelopeWithV2FieldsThrows(): void { @@ -381,11 +379,7 @@ public function testV3EnvelopeECValidSetCorrectly(): void $this->assertEquals($envelope[MetadataEnvelope::ENCRYPTED_DATA_KEY_ALGORITHM_V3], 12); } - /** - * Summary of testDiffAlgorithmSuitesProduceDiffObjectVersions - * @dataProvider getAlgorithmSuites - * @return void - */ + #[DataProvider('getAlgorithmSuites')] public function testDiffAlgorithmSuitesProduceDiffObjectVersions(AlgorithmSuite $algorithmSuite): void { $plaintext = new Stream(fopen('data://text/plain,Hello World', 'r')); @@ -433,7 +427,6 @@ public function testDiffAlgorithmSuitesProduceDiffObjectVersions(AlgorithmSuite /** * Summary of testDiffAlgorithmSuitesProduceDiffObjectVersions - * @return void */ public function testCbcAlgSuiteProducesV2Envelope(): void { @@ -483,8 +476,8 @@ public function testCbcAlgSuiteProducesV2Envelope(): void /** * Given a CommitmentPolicy assert error gets appropriately thrown if the key commitment policy * does not support decryption of the object. - * @dataProvider getCommitmentPolicies */ + #[DataProvider('getCommitmentPolicies')] public function testThrowsOnInvalidKCPolicyAndNoKeyCommitmentAlgSuite($commitmentPolicy): void { $plaintext = new Stream(fopen('data://text/plain,Hello World', 'r')); @@ -562,8 +555,8 @@ public function testThrowsOnInvalidKCPolicyAndNoKeyCommitmentAlgSuite($commitmen /** * Given a CommitmentPolicy assert error gets appropriately thrown if the key commitment policy * does not support decryption of the object. - * @dataProvider getCommitmentPolicies */ + #[DataProvider('getCommitmentPolicies')] public function testThrowsOnInvalidKCPolicyAndKeyCommitmentAlgSuite($commitmentPolicy): void { $plaintext = new Stream(fopen('data://text/plain,Hello World', 'r')); diff --git a/tests/Crypto/HkdfKatTest.php b/tests/Crypto/HkdfKatTest.php index 79910a1ad4..6a3b089553 100644 --- a/tests/Crypto/HkdfKatTest.php +++ b/tests/Crypto/HkdfKatTest.php @@ -15,7 +15,9 @@ use GuzzleHttp\Psr7\LimitStream; use PHPUnit\Framework\Constraint\IsEmpty; use Psr\Http\Message\StreamInterface; +use PHPUnit\Framework\Attributes\CoversNothing; +#[CoversNothing] class HkdfKatTest extends TestCase { public static function getKats(): array @@ -48,7 +50,7 @@ public static function getKats(): array ]; } - public function testHkdf(): void + public function testHkdf(): void { $kats = HkdfKatTest::getKats(); foreach ($kats as $kat) { diff --git a/tests/Crypto/KmsMaterialsProviderTest.php b/tests/Crypto/KmsMaterialsProviderTest.php index 8e961eb1d9..3d7b4b297a 100644 --- a/tests/Crypto/KmsMaterialsProviderTest.php +++ b/tests/Crypto/KmsMaterialsProviderTest.php @@ -6,10 +6,9 @@ use Aws\Result; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Crypto\KmsMaterialsProvider - */ +#[CoversClass(KmsMaterialsProvider::class)] class KmsMaterialsProviderTest extends TestCase { use UsesServiceTrait; diff --git a/tests/Crypto/KmsMaterialsProviderV2Test.php b/tests/Crypto/KmsMaterialsProviderV2Test.php index 007278f83b..ee07f78c0c 100644 --- a/tests/Crypto/KmsMaterialsProviderV2Test.php +++ b/tests/Crypto/KmsMaterialsProviderV2Test.php @@ -7,10 +7,9 @@ use Aws\Result; use Aws\Test\UsesServiceTrait; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Crypto\KmsMaterialsProviderV2 - */ +#[CoversClass(KmsMaterialsProviderV2::class)] class KmsMaterialsProviderV2Test extends TestCase { use UsesServiceTrait; diff --git a/tests/Crypto/KmsMaterialsProviderV3Test.php b/tests/Crypto/KmsMaterialsProviderV3Test.php index d0064cbae7..4199d53e7b 100644 --- a/tests/Crypto/KmsMaterialsProviderV3Test.php +++ b/tests/Crypto/KmsMaterialsProviderV3Test.php @@ -7,10 +7,9 @@ use Aws\Result; use Aws\Test\UsesServiceTrait; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Crypto\KmsMaterialsProviderV3 - */ +#[CoversClass(KmsMaterialsProviderV3::class)] class KmsMaterialsProviderV3Test extends TestCase { use UsesServiceTrait; diff --git a/tests/Crypto/MetadataEnvelopeTest.php b/tests/Crypto/MetadataEnvelopeTest.php index 8bd271ae13..b13547b405 100644 --- a/tests/Crypto/MetadataEnvelopeTest.php +++ b/tests/Crypto/MetadataEnvelopeTest.php @@ -3,17 +3,15 @@ use Aws\Crypto\MetadataEnvelope; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Crypto\MetadataEnvelope - */ +#[CoversClass(MetadataEnvelope::class)] class MetadataEnvelopeTest extends TestCase { use UsesMetadataEnvelopeTrait; - /** - * @dataProvider getIndividualMetadataFields - */ + #[DataProvider('getIndividualMetadataFields')] public function testSetsValidFields($field, $value) { $envelope = new MetadataEnvelope(); @@ -22,9 +20,7 @@ public function testSetsValidFields($field, $value) $this->assertEquals($value, $envelope[$field]); } - /** - * @dataProvider getMetadataFields - */ + #[DataProvider('getMetadataFields')] public function testSetsAllFields($allValidFields) { $envelope = new MetadataEnvelope(); @@ -38,9 +34,7 @@ public function testSetsAllFields($allValidFields) ); } - /** - * @dataProvider getIndividualInvalidMetadataFields - */ + #[DataProvider('getIndividualInvalidMetadataFields')] public function testThrowsOnInvalidMetadataField($field, $value) { //= ../specification/s3-encryption/data-format/content-metadata.md#determining-s3ec-object-status @@ -66,7 +60,7 @@ public function testNoReservedPrefixInEnvelope(): void $this->assertStringStartsNotWith('x-amz-meta', $envelopeKey); } } - + /** * Tests that all the metadata mapkeys are prefixed with * `x-amz-` @@ -83,5 +77,4 @@ public function testReservedPrefixInEnvelope(): void $this->assertStringStartsWith('x-amz-', $envelopeKey); } } - } diff --git a/tests/Crypto/UsesCryptoParamsTrait.php b/tests/Crypto/UsesCryptoParamsTrait.php index 47c8b2c2af..75e5345932 100644 --- a/tests/Crypto/UsesCryptoParamsTrait.php +++ b/tests/Crypto/UsesCryptoParamsTrait.php @@ -146,4 +146,4 @@ public function getKeySizes() ] ]; } -} \ No newline at end of file +} diff --git a/tests/Crypto/UsesMetadataEnvelopeTrait.php b/tests/Crypto/UsesMetadataEnvelopeTrait.php index df64400f1a..1ec784767f 100644 --- a/tests/Crypto/UsesMetadataEnvelopeTrait.php +++ b/tests/Crypto/UsesMetadataEnvelopeTrait.php @@ -5,7 +5,7 @@ trait UsesMetadataEnvelopeTrait { - public function getIndividualMetadataFields(): array + public static function getIndividualMetadataFields(): array { return [ [ @@ -39,12 +39,12 @@ public function getIndividualMetadataFields(): array ]; } - public function getIndividualV3MetadataFields(): array + public static function getIndividualV3MetadataFields(): array { return [ [ MetadataEnvelope::ENCRYPTED_DATA_KEY_V3, - 1 + 1 ], [ MetadataEnvelope::MAT_DESC_V3, @@ -71,15 +71,14 @@ public function getIndividualV3MetadataFields(): array 7 ] ]; - } - public function getIndividualV3MetadataOnlyFields(): array + public static function getIndividualV3MetadataOnlyFields(): array { return [ [ MetadataEnvelope::CONTENT_CIPHER_V3, - 1 + 1 ], [ MetadataEnvelope::KEY_COMMITMENT_V3, @@ -90,15 +89,14 @@ public function getIndividualV3MetadataOnlyFields(): array 3 ] ]; - } - public function getIndividualV3InstructionFileOnlyFields(): array + public static function getIndividualV3InstructionFileOnlyFields(): array { return [ [ MetadataEnvelope::ENCRYPTED_DATA_KEY_V3, - 4 + 4 ], [ MetadataEnvelope::MAT_DESC_V3, @@ -113,15 +111,14 @@ public function getIndividualV3InstructionFileOnlyFields(): array 7 ], ]; - } - public function getIndividualV3DuplicateKeysInstructionFileOnlyFields(): array + public static function getIndividualV3DuplicateKeysInstructionFileOnlyFields(): array { return [ [ MetadataEnvelope::ENCRYPTED_DATA_KEY_V3, - 4 + 4 ], [ MetadataEnvelope::MAT_DESC_V3, @@ -142,9 +139,9 @@ public function getIndividualV3DuplicateKeysInstructionFileOnlyFields(): array ]; } - public function getCondensedFields(): array + public static function getCondensedFields(): array { - $individualMetadataFields = $this->getIndividualMetadataFields(); + $individualMetadataFields = self::getIndividualMetadataFields(); $fields = []; foreach ($individualMetadataFields as $fieldInfo) { $fields[$fieldInfo[0]] = $fieldInfo[1]; @@ -153,9 +150,9 @@ public function getCondensedFields(): array return $fields; } - public function getCondensedV3Fields(): array + public static function getCondensedV3Fields(): array { - $individualMetadataFields = $this->getIndividualV3MetadataFields(); + $individualMetadataFields = self::getIndividualV3MetadataFields(); $fields = []; foreach ($individualMetadataFields as $fieldInfo) { $fields[$fieldInfo[0]] = $fieldInfo[1]; @@ -164,22 +161,20 @@ public function getCondensedV3Fields(): array return $fields; } - public function getMetadataOnlyCondensedV3Fields(): array + public static function getMetadataOnlyCondensedV3Fields(): array { - $individualMetadataFields = $this->getIndividualV3MetadataOnlyFields(); + $individualMetadataFields = self::getIndividualV3MetadataOnlyFields(); $fields = []; foreach ($individualMetadataFields as $fieldInfo) { $fields[$fieldInfo[0]] = $fieldInfo[1]; } return $fields; - } - public function getInstructionFileOnlyCondensedV3Fields(): array + public static function getInstructionFileOnlyCondensedV3Fields(): array { - - $individualMetadataFields = $this->getIndividualV3InstructionFileOnlyFields(); + $individualMetadataFields = self::getIndividualV3InstructionFileOnlyFields(); $fields = []; foreach ($individualMetadataFields as $fieldInfo) { $fields[$fieldInfo[0]] = $fieldInfo[1]; @@ -188,9 +183,9 @@ public function getInstructionFileOnlyCondensedV3Fields(): array return $fields; } - public function getV3DuplicateKeysForInstructionFile(): array + public static function getV3DuplicateKeysForInstructionFile(): array { - $individualMetadataFields = $this->getIndividualV3DuplicateKeysInstructionFileOnlyFields(); + $individualMetadataFields = self::getIndividualV3DuplicateKeysInstructionFileOnlyFields(); $fields = []; foreach ($individualMetadataFields as $fieldInfo) { $fields[$fieldInfo[0]] = $fieldInfo[1]; @@ -209,9 +204,9 @@ public function getFieldsAsMetaHeaders($fields): array return $metadataFields; } - public function getMetadataFields(): array + public static function getMetadataFields(): array { - $fields = $this->getCondensedFields(); + $fields = self::getCondensedFields(); return [ [ @@ -220,17 +215,17 @@ public function getMetadataFields(): array ]; } - public function getV3MetadataFields(): array + public static function getV3MetadataFields(): array { - $fields = $this->getCondensedV3Fields(); + $fields = self::getCondensedV3Fields(); return [ [$fields] ]; } - public function getMetadataResult(): array + public static function getMetadataResult(): array { - $fields = $this->getCondensedFields(); + $fields = self::getCondensedFields(); return [ [ @@ -244,9 +239,9 @@ public function getMetadataResult(): array ]; } - public function getV3MetadataResult(): array + public static function getV3MetadataResult(): array { - $fields = $this->getCondensedV3Fields(); + $fields = self::getCondensedV3Fields(); return [ [ @@ -260,10 +255,10 @@ public function getV3MetadataResult(): array ]; } - public function getV3FieldsForInstructionFile(): array + public static function getV3FieldsForInstructionFile(): array { - $metadataOnlyFields = $this->getMetadataOnlyCondensedV3Fields(); - $instructionFileOnlyFields = $this->getInstructionFileOnlyCondensedV3Fields(); + $metadataOnlyFields = self::getMetadataOnlyCondensedV3Fields(); + $instructionFileOnlyFields = self::getInstructionFileOnlyCondensedV3Fields(); return [ [ @@ -274,7 +269,7 @@ public function getV3FieldsForInstructionFile(): array ], $instructionFileOnlyFields ] - ]; + ]; } public function getMetadataEnvelope($fields): MetadataEnvelope @@ -289,14 +284,14 @@ public function getMetadataEnvelope($fields): MetadataEnvelope public function getV3InstructionFileFields($fields): MetadataEnvelope { - $envelope = $this->getMetadataEnvelope($fields); + $envelope = $this->getMetadataEnvelope($fields); unset($envelope[MetadataEnvelope::CONTENT_CIPHER_V3]); unset($envelope[MetadataEnvelope::KEY_COMMITMENT_V3]); unset($envelope[MetadataEnvelope::MESSAGE_ID_V3]); return $envelope; } - public function getIndividualInvalidMetadataFields(): array + public static function getIndividualInvalidMetadataFields(): array { return [ [ diff --git a/tests/DSQL/AuthTokenGeneratorTest.php b/tests/DSQL/AuthTokenGeneratorTest.php index 6e297c6358..cba6479504 100644 --- a/tests/DSQL/AuthTokenGeneratorTest.php +++ b/tests/DSQL/AuthTokenGeneratorTest.php @@ -7,20 +7,13 @@ use GuzzleHttp\Promise; use TypeError; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\DSQL\AuthTokenGenerator - */ +#[CoversClass(AuthTokenGenerator::class)] class AuthTokenGeneratorTest extends TestCase { - /** - * @param $endpoint - * @param $credentials - * @param $action - * @return void - * - * @dataProvider generateAuthTokenProvider - */ + #[DataProvider('generateAuthTokenProvider')] public function testGeneratesAuthToken($credentials, $action) { $tokenGenerator = new AuthTokenGenerator($credentials); @@ -38,8 +31,9 @@ public function testGeneratesAuthToken($credentials, $action) $this->assertStringNotContainsString('https://', $token); } - public function generateAuthTokenProvider() - { $accessKeyId = 'AKID'; + public static function generateAuthTokenProvider(): array + { + $accessKeyId = 'AKID'; $secretKeyId = 'SECRET'; $credentials = new Credentials($accessKeyId, $secretKeyId); $credentialProvider = static function () use ($accessKeyId, $secretKeyId) { @@ -56,14 +50,7 @@ public function generateAuthTokenProvider() ]; } - /** - * @param $action - * @param $endpoint - * @param $region - * @return void - * - * @dataProvider missingInputProvider - */ + #[DataProvider('missingInputProvider')] public function testThrowsOnMissingInput($action, $endpoint, $region) { $this->expectException(TypeError::class); @@ -75,7 +62,7 @@ public function testThrowsOnMissingInput($action, $endpoint, $region) ); } - public function missingInputProvider() + public static function missingInputProvider(): array { return [ ['generateDbConnectAuthToken', 'foo.bar.baz', null], @@ -85,15 +72,7 @@ public function missingInputProvider() ]; } - /** - * @param $action - * @param $endpoint - * @param $region - * - * @return void - * - * @dataProvider emptyInputProvider - */ + #[DataProvider('emptyInputProvider')] public function testThrowsOnEmptyInput($action, $endpoint, $region) { $this->expectException(\InvalidArgumentException::class); @@ -106,7 +85,7 @@ public function testThrowsOnEmptyInput($action, $endpoint, $region) ); } - public function emptyInputProvider() + public static function emptyInputProvider(): array { return [ ['generateDbConnectAuthToken', 'foo.bar.baz', ''], @@ -116,7 +95,7 @@ public function emptyInputProvider() ]; } - public function lifetimeFailureProvider() + public static function lifetimeFailureProvider(): array { return [ [0, 'generateDbConnectAuthToken'], @@ -126,11 +105,7 @@ public function lifetimeFailureProvider() ]; } - /** - * @dataProvider lifetimeFailureProvider - * - * @param $lifetime - */ + #[DataProvider('lifetimeFailureProvider')] public function testThrowsExceptionWithInvalidLifetime($expiration, $action) { $this->expectExceptionMessage("Lifetime must be a positive number, was"); diff --git a/tests/DefaultsMode/ConfigurationProviderTest.php b/tests/DefaultsMode/ConfigurationProviderTest.php index f7a71e2948..0b4fbbe1d6 100644 --- a/tests/DefaultsMode/ConfigurationProviderTest.php +++ b/tests/DefaultsMode/ConfigurationProviderTest.php @@ -9,10 +9,10 @@ use Aws\DefaultsMode\Exception\ConfigurationException; use GuzzleHttp\Promise; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\DefaultsMode\ConfigurationProvider - */ +#[CoversClass(ConfigurationProvider::class)] class ConfigurationProviderTest extends TestCase { private static $originalEnv; @@ -335,7 +335,7 @@ public function testCreatesFromCache() { $expected = new Configuration('standard'); $cacheBuilder = $this->getMockBuilder(CacheInterface::class); - $cacheBuilder->setMethods(['get', 'set', 'remove']); + $cacheBuilder->onlyMethods(['get', 'set', 'remove']); $cache = $cacheBuilder->getMock(); $cache->expects($this->any()) ->method('get') @@ -349,7 +349,7 @@ public function testCreatesFromCache() $this->assertSame($expected->toArray(), $result->toArray()); } - public function getSuccessfulUnwrapData() + public static function getSuccessfulUnwrapData(): array { $expected = new Configuration('standard'); return [ @@ -375,11 +375,7 @@ function () use ($expected) { ]; } - /** - * @dataProvider getSuccessfulUnwrapData - * @param $toUnwrap - * @param ConfigurationInterface $expected - */ + #[DataProvider('getSuccessfulUnwrapData')] public function testSuccessfulUnwraps($toUnwrap, ConfigurationInterface $expected) { $this->assertSame( @@ -388,7 +384,6 @@ public function testSuccessfulUnwraps($toUnwrap, ConfigurationInterface $expecte ); } - public function testCreatesLegacy() { $config = new Configuration(); diff --git a/tests/DefaultsMode/ConfigurationTest.php b/tests/DefaultsMode/ConfigurationTest.php index 3460ee8fe9..3c2448f170 100644 --- a/tests/DefaultsMode/ConfigurationTest.php +++ b/tests/DefaultsMode/ConfigurationTest.php @@ -4,10 +4,9 @@ use Aws\DefaultsMode\Configuration; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\DefaultsMode\Configuration - */ +#[CoversClass(Configuration::class)] class ConfigurationTest extends TestCase { public function testGetsCorrectValues() diff --git a/tests/DocDb/DocDbClientTest.php b/tests/DocDb/DocDbClientTest.php index d65c13241b..68c17c58ed 100644 --- a/tests/DocDb/DocDbClientTest.php +++ b/tests/DocDb/DocDbClientTest.php @@ -7,11 +7,11 @@ use Aws\Result; use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; require_once __DIR__ . '/../Signature/sig_hack.php'; -/** - * @covers Aws\DocDB\DocDBClient - */ +#[CoversClass(DocDBClient::class)] class DocDbClientTest extends TestCase { public static function set_up_before_class() @@ -26,7 +26,7 @@ public static function tear_down_after_class() $_SERVER['formatAwsTime'] = null; } - public function DocDbPresignMethodProvider() + public static function DocDbPresignMethodProvider(): array { return [ ['CopyDBClusterSnapshot', ['SourceDBClusterSnapshotIdentifier' => 'arn:aws:rds:us-east-1:123456789012:cluster-snapshot:source-db-cluster-snapshot', 'TargetDBClusterSnapshotIdentifier' => 'target-db-cluster-snapshot'], null, null, null, null], @@ -35,15 +35,7 @@ public function DocDbPresignMethodProvider() ]; } - /** - * @dataProvider DocDbPresignMethodProvider - * - * @param string $functionName - * @param string $presignedUrl - * @param string $sourceRegion - * @param string $expectedUrl - * @param string $expectedSignature - */ + #[DataProvider('DocDbPresignMethodProvider')] public function testCorrectPresignDocDbUrls( $functionName, $functionArgs, @@ -85,4 +77,3 @@ public function testCorrectPresignDocDbUrls( call_user_func([$docDb, $functionName], $functionArgs); } } - diff --git a/tests/DoctrineCacheAdapterTest.php b/tests/DoctrineCacheAdapterTest.php index 7ce21f324c..2217c27608 100644 --- a/tests/DoctrineCacheAdapterTest.php +++ b/tests/DoctrineCacheAdapterTest.php @@ -4,8 +4,10 @@ use Aws\CacheInterface; use Aws\DoctrineCacheAdapter; use Doctrine\Common\Cache\Cache; +use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; +#[CoversClass(DoctrineCacheAdapter::class)] class DoctrineCacheAdapterTest extends TestCase { public function testProxiesCallsToDoctrine() diff --git a/tests/DynamoDb/DynamoDbClientTest.php b/tests/DynamoDb/DynamoDbClientTest.php index b2b8488f85..288260449f 100644 --- a/tests/DynamoDb/DynamoDbClientTest.php +++ b/tests/DynamoDb/DynamoDbClientTest.php @@ -13,10 +13,10 @@ use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Stream; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\DynamoDb\DynamoDbClient - */ +#[CoversClass(DynamoDbClient::class)] class DynamoDbClientTest extends TestCase { use UsesServiceTrait; @@ -31,7 +31,7 @@ public function testRegisterSessionHandlerReturnsHandler() ); } - public function dataForFormatValueTest() + public static function dataForFormatValueTest(): array { $handle = fopen('php://memory', 'w+'); fwrite($handle, 'foo'); @@ -84,9 +84,7 @@ public function dataForFormatValueTest() ]; } - /** - * @dataProvider dataProviderRetrySettings - */ + #[DataProvider('dataProviderRetrySettings')] public function testRetriesOnDynamoSpecificRetryableException($settings) { $params = [ @@ -137,7 +135,7 @@ public function testRetriesOnDynamoSpecificRetryableException($settings) $this->assertSame(3, $attemptCount); } - public function dataProviderRetrySettings() + public static function dataProviderRetrySettings(): array { return [ [ @@ -188,11 +186,7 @@ public function testValidatesAndRetriesCrc32() $this->assertEmpty($queue); } - /** - * @dataProvider dataProviderRetrySettings - * - * @param $settings - */ + #[DataProvider('dataProviderRetrySettings')] public function testAppliesRetryStatsConfig($settings) { $client = new DynamoDbClient([ diff --git a/tests/DynamoDb/LockingSessionConnectionTest.php b/tests/DynamoDb/LockingSessionConnectionTest.php index 1c9993226b..461a2a1932 100644 --- a/tests/DynamoDb/LockingSessionConnectionTest.php +++ b/tests/DynamoDb/LockingSessionConnectionTest.php @@ -6,10 +6,9 @@ use Aws\Result; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\DynamoDb\LockingSessionConnection - */ +#[CoversClass(LockingSessionConnection::class)] class LockingSessionConnectionTest extends TestCase { use UsesServiceTrait; diff --git a/tests/DynamoDb/MarshalerTest.php b/tests/DynamoDb/MarshalerTest.php index bcc9f3ec83..23f670563a 100644 --- a/tests/DynamoDb/MarshalerTest.php +++ b/tests/DynamoDb/MarshalerTest.php @@ -7,17 +7,15 @@ use Aws\DynamoDb\SetValue; use GuzzleHttp\Psr7; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\DynamoDb\Marshaler - */ +#[CoversClass(Marshaler::class)] class MarshalerTest extends TestCase { const ERROR = 'ERROR'; - /** - * @dataProvider getMarshalValueUseCases - */ + #[DataProvider('getMarshalValueUseCases')] public function testMarshalValueUseCases($value, $expectedResult, $options = []) { $m = new Marshaler($options); @@ -29,7 +27,7 @@ public function testMarshalValueUseCases($value, $expectedResult, $options = []) $this->assertSame($expectedResult, $actualResult); } - public function getMarshalValueUseCases() + public static function getMarshalValueUseCases(): array { $m = new Marshaler; @@ -239,7 +237,6 @@ public function testErrorIfMarshalingBadJsonDoc() (new Marshaler)->marshalJson('foo'); } - public function testUnmarshalingHandlesAllDynamoDbTypes() { $item = [ @@ -344,9 +341,6 @@ public function testCanWrapLargeNumbersWithOption() $this->assertSame('99999999999999999999.99999999999999999999', (string) $result['bar']); } - /** - * @covers Aws\DynamoDb\NumberValue - */ public function testNumberValueCanBeFormattedAndSerialized() { $number = new NumberValue('99999999999999999999'); @@ -354,9 +348,6 @@ public function testNumberValueCanBeFormattedAndSerialized() $this->assertSame('"99999999999999999999"', json_encode($number)); } - /** - * @covers Aws\DynamoDb\BinaryValue - */ public function testBinaryValueCanBeFormattedAndSerialized() { $resource = fopen('php://temp', 'w+'); @@ -368,9 +359,6 @@ public function testBinaryValueCanBeFormattedAndSerialized() $this->assertSame('"foo"', json_encode($binary)); } - /** - * @covers Aws\DynamoDb\SetValue - */ public function testSetValueCanBeFormattedAndSerialized() { $set = new SetValue(['foo', 'bar', 'baz']); diff --git a/tests/DynamoDb/SessionConnectionConfigTraitTest.php b/tests/DynamoDb/SessionConnectionConfigTraitTest.php index a3e91ab5e5..2e06925e69 100644 --- a/tests/DynamoDb/SessionConnectionConfigTraitTest.php +++ b/tests/DynamoDb/SessionConnectionConfigTraitTest.php @@ -4,10 +4,9 @@ use Aws\DynamoDb\SessionConnectionConfigTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\DynamoDb\SessionConnectionConfigTrait - */ +#[CoversClass(SessionConnectionConfigTrait::class)] class SessionConnectionConfigTraitTest extends TestCase { use UsesServiceTrait; diff --git a/tests/DynamoDb/SessionHandlerTest.php b/tests/DynamoDb/SessionHandlerTest.php index f038eccd9e..26de646be7 100644 --- a/tests/DynamoDb/SessionHandlerTest.php +++ b/tests/DynamoDb/SessionHandlerTest.php @@ -7,10 +7,9 @@ use Aws\DynamoDb\StandardSessionConnection; use Aws\Test\UsesServiceTrait; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\DynamoDb\SessionHandler - */ +#[CoversClass(SessionHandler::class)] class SessionHandlerTest extends TestCase { use UsesServiceTrait; diff --git a/tests/DynamoDb/StandardSessionConnectionTest.php b/tests/DynamoDb/StandardSessionConnectionTest.php index 54fc3fa6b2..fdcb86fcbe 100644 --- a/tests/DynamoDb/StandardSessionConnectionTest.php +++ b/tests/DynamoDb/StandardSessionConnectionTest.php @@ -8,10 +8,9 @@ use Aws\Result; use Aws\Test\UsesServiceTrait; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\DynamoDb\StandardSessionConnection - */ +#[CoversClass(StandardSessionConnection::class)] class StandardSessionConnectionTest extends TestCase { use UsesServiceTrait; @@ -157,19 +156,26 @@ public function testWriteReturnsFalseOnFailure() public function testWriteTriggersWarningOnFailure() { - $this->expectWarning(); - $client = $this->getTestSdk()->createDynamoDb(); - $this->addMockResults($client, [ - $this->createMockAwsException('ERROR', DynamoDbException::class) - ]); - $client->getHandlerList()->appendBuild(Middleware::tap(function ($command) { - $this->assertEquals( - ['Action' => 'DELETE'], - $command['AttributeUpdates']['data'] - ); - })); - $connection = new StandardSessionConnection($client); - $connection->write('s1', '', true); + $this->expectException(\RuntimeException::class); + set_error_handler(function ($errno, $errstr) { + throw new \RuntimeException($errstr, $errno); + }); + try { + $client = $this->getTestSdk()->createDynamoDb(); + $this->addMockResults($client, [ + $this->createMockAwsException('ERROR', DynamoDbException::class) + ]); + $client->getHandlerList()->appendBuild(Middleware::tap(function ($command) { + $this->assertEquals( + ['Action' => 'DELETE'], + $command['AttributeUpdates']['data'] + ); + })); + $connection = new StandardSessionConnection($client); + $connection->write('s1', '', true); + } finally { + restore_error_handler(); + } } public function testDeleteReturnsBoolBasedOnSuccess() @@ -191,19 +197,26 @@ public function testDeleteReturnsBoolBasedOnSuccess() public function testDeleteTriggersWarningOnFailure() { - $this->expectWarning(); - $client = $this->getTestSdk()->createDynamoDb(); - $this->addMockResults($client, [ - new Result([]), - $this->createMockAwsException('ERROR', DynamoDbException::class) - ]); - - $connection = new StandardSessionConnection($client); - - $return = $connection->delete('s1'); - $this->assertTrue($return); - - $connection->delete('s1'); + $this->expectException(\RuntimeException::class); + set_error_handler(function ($errno, $errstr) { + throw new \RuntimeException($errstr, $errno); + }); + try { + $client = $this->getTestSdk()->createDynamoDb(); + $this->addMockResults($client, [ + new Result([]), + $this->createMockAwsException('ERROR', DynamoDbException::class) + ]); + + $connection = new StandardSessionConnection($client); + + $return = $connection->delete('s1'); + $this->assertTrue($return); + + $connection->delete('s1'); + } finally { + restore_error_handler(); + } } public function testDeleteExpiredReturnsBoolBasedOnSuccess() diff --git a/tests/DynamoDb/WriteRequestBatchTest.php b/tests/DynamoDb/WriteRequestBatchTest.php index 2be84a22e3..f0b473b891 100644 --- a/tests/DynamoDb/WriteRequestBatchTest.php +++ b/tests/DynamoDb/WriteRequestBatchTest.php @@ -8,10 +8,10 @@ use Aws\DynamoDb\WriteRequestBatch; use Aws\Test\UsesServiceTrait; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\DynamoDb\WriteRequestBatch - */ +#[CoversClass(WriteRequestBatch::class)] class WriteRequestBatchTest extends TestCase { use UsesServiceTrait; @@ -23,16 +23,14 @@ public function testInstantiateWriteRequestBatch() $this->assertSame(50, $this->getPropertyValue($batch, 'config')['threshold']); } - /** - * @dataProvider getInvalidArgUseCases - */ + #[DataProvider('getInvalidArgUseCases')] public function testInstantiationFailsOnInvalidArgs($config) { $this->expectException(\InvalidArgumentException::class); new WriteRequestBatch($this->getTestClient('DynamoDb'), $config); } - public function getInvalidArgUseCases() + public static function getInvalidArgUseCases(): array { return [ [['batch_size' => 1]], diff --git a/tests/Ec2/Ec2ClientTest.php b/tests/Ec2/Ec2ClientTest.php index c2a9a80e9d..e3c6e28759 100644 --- a/tests/Ec2/Ec2ClientTest.php +++ b/tests/Ec2/Ec2ClientTest.php @@ -9,10 +9,9 @@ use GuzzleHttp\Psr7\Response; use PHPUnit\Framework\TestCase; use Psr\Http\Message\RequestInterface; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Ec2\Ec2Client - */ +#[CoversClass(Ec2Client::class)] class Ec2ClientTest extends TestCase { use UsesServiceTrait; @@ -95,7 +94,6 @@ function ($command, $request) { public function testSkipEmptyListSerialization() { - $ec2Client = new Ec2Client([ 'region' => 'us-east-1', 'http_handler' => function (RequestInterface $request) { diff --git a/tests/ElasticLoadBalancingV2/ElasticLoadBalancingV2ClientTest.php b/tests/ElasticLoadBalancingV2/ElasticLoadBalancingV2ClientTest.php index 86a696a17a..e504b1d352 100644 --- a/tests/ElasticLoadBalancingV2/ElasticLoadBalancingV2ClientTest.php +++ b/tests/ElasticLoadBalancingV2/ElasticLoadBalancingV2ClientTest.php @@ -1,12 +1,12 @@ assertEquals($output, $p($input)); } - public function endpointProvider() + public static function endpointProvider(): array { return [ [ @@ -154,12 +152,11 @@ public function endpointProvider() } /** - * @dataProvider partitionRegionProvider - * * @param string $region * @param string $service * @param string $partition */ + #[DataProvider('partitionRegionProvider')] public function testResolvesPartitionsByRegion($region, $service, $partition) { // Use the default endpoints file @@ -167,7 +164,7 @@ public function testResolvesPartitionsByRegion($region, $service, $partition) $this->assertSame($partition, $p->getPartition($region, $service)->getName()); } - public function partitionRegionProvider() + public static function partitionRegionProvider(): array { return [ ['us-east-1', 's3', 'aws'], @@ -216,13 +213,12 @@ public function testPassesOptionsToProvider() } /** - * @dataProvider knownEndpointProvider - * * @param PartitionEndpointProvider $provider * @param $region * @param $service * @param $endpoint */ + #[DataProvider('knownEndpointProvider')] public function testCanGenerateKnownEndpointsKnownToPatternProvider( PartitionEndpointProvider $provider, $region, @@ -293,7 +289,7 @@ public function testCanMergePrefixData() } } - public function knownEndpointProvider() + public static function knownEndpointProvider(): array { $partitions = PartitionEndpointProvider::defaultProvider(); diff --git a/tests/Endpoint/PartitionTest.php b/tests/Endpoint/PartitionTest.php index 9642602781..c7a3e7d4b1 100644 --- a/tests/Endpoint/PartitionTest.php +++ b/tests/Endpoint/PartitionTest.php @@ -6,17 +6,13 @@ use Aws\Endpoint\UseDualstackEndpoint; use Aws\Endpoint\UseFipsEndpoint; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Endpoint\Partition - */ +#[CoversClass(Partition::class)] class PartitionTest extends TestCase { - /** - * @dataProvider partitionDefinitionProvider - * - * @param array $definition - */ + #[DataProvider('partitionDefinitionProvider')] public function testAcceptsValidDefinitions(array $definition) { $this->assertInstanceOf( @@ -25,11 +21,7 @@ public function testAcceptsValidDefinitions(array $definition) ); } - /** - * @dataProvider invalidPartitionDefinitionProvider - * - * @param array $invalidDefinition - */ + #[DataProvider('invalidPartitionDefinitionProvider')] public function testRejectsInvalidDefinitions(array $invalidDefinition) { $this->expectExceptionMessageMatches("/missing required \w+ field/"); @@ -37,11 +29,7 @@ public function testRejectsInvalidDefinitions(array $invalidDefinition) new Partition($invalidDefinition); } - /** - * @dataProvider partitionDefinitionProvider - * - * @param array $definition - */ + #[DataProvider('partitionDefinitionProvider')] public function testReportsData(array $definition) { $this->assertSame( @@ -53,11 +41,8 @@ public function testReportsData(array $definition) (new Partition($definition))->getDnsSuffix() ); } - /** - * @dataProvider partitionDefinitionProvider - * - * @param array $definition - */ + + #[DataProvider('partitionDefinitionProvider')] public function testFipsEndpoint(array $definition) { $partition = new Partition($definition); @@ -65,7 +50,7 @@ public function testFipsEndpoint(array $definition) self::assertStringContainsString('service-fips.amazonaws.com', $resolved['endpoint']); } - public function partitionDefinitionProvider() + public static function partitionDefinitionProvider(): array { return [ [[ @@ -89,9 +74,9 @@ public function partitionDefinitionProvider() ]; } - public function invalidPartitionDefinitionProvider() + public static function invalidPartitionDefinitionProvider(): array { - $validDefinition = $this->partitionDefinitionProvider()[0][0]; + $validDefinition = self::partitionDefinitionProvider()[0][0]; $return = []; foreach ($validDefinition as $requiredKey => $v) { @@ -104,11 +89,7 @@ public function invalidPartitionDefinitionProvider() return $return; } - /** - * @dataProvider partitionDefinitionProvider - * - * @param array $definition - */ + #[DataProvider('partitionDefinitionProvider')] public function testReportsRegionMatches(array $definition) { $partition = new Partition($definition); @@ -117,11 +98,7 @@ public function testReportsRegionMatches(array $definition) $this->assertFalse($partition->isRegionMatch('foo', 'bar')); } - /** - * @dataProvider partitionDefinitionProvider - * - * @param array $definition - */ + #[DataProvider('partitionDefinitionProvider')] public function testReportsRegionMatchesByPattern(array $definition) { $definition['regionRegex'] = '^fo[\w]{1}'; @@ -132,14 +109,7 @@ public function testReportsRegionMatchesByPattern(array $definition) $this->assertFalse($partition->isRegionMatch('bar', 's3')); } - /** - * @dataProvider serviceRegionsProvider - * - * @param Partition $partition - * @param string $service - * @param array $regions - * @param bool $allowNonRegionalEndpoints - */ + #[DataProvider('serviceRegionsProvider')] public function testEnumeratesRegionsForGivenService( Partition $partition, $service, @@ -152,7 +122,7 @@ public function testEnumeratesRegionsForGivenService( )); } - public function serviceRegionsProvider() + public static function serviceRegionsProvider(): array { $partition = new Partition([ 'partition' => 'foo', @@ -190,14 +160,7 @@ public function serviceRegionsProvider() ]; } - /** - * @dataProvider signingRegionProvider - * - * @param Partition $partition - * @param $region - * @param $service - * @param $signingRegion - */ + #[DataProvider('signingRegionProvider')] public function testDeterminesSigningRegion( Partition $partition, $region, @@ -214,7 +177,7 @@ public function testDeterminesSigningRegion( $this->assertSame($signingRegion, $resolved['signingRegion']); } - public function signingRegionProvider() + public static function signingRegionProvider(): array { $partition = new Partition([ 'partition' => 'foo', @@ -245,14 +208,7 @@ public function signingRegionProvider() ]; } - /** - * @dataProvider endpointProvider - * - * @param Partition $partition - * @param $region - * @param $service - * @param $endpoint - */ + #[DataProvider('endpointProvider')] public function testDeterminesEndpoint( Partition $partition, $region, @@ -269,7 +225,7 @@ public function testDeterminesEndpoint( $this->assertSame($endpoint, $resolved['endpoint']); } - public function endpointProvider() + public static function endpointProvider(): array { $partition = new Partition([ 'partition' => 'foo', @@ -330,14 +286,7 @@ public function testIgnoresIsRegionalizedFlagIfPartitionEndpointAbsent() $this->assertSame('https://baz.us-east-1.bar', $resolved['endpoint']); } - /** - * @dataProvider signatureVersionProvider - * - * @param Partition $partition - * @param $region - * @param $service - * @param $signatureVersion - */ + #[DataProvider('signatureVersionProvider')] public function testDeterminesSignatureVersion( Partition $partition, $region, @@ -354,7 +303,7 @@ public function testDeterminesSignatureVersion( $this->assertSame($signatureVersion, $resolved['signatureVersion']); } - public function signatureVersionProvider() + public static function signatureVersionProvider(): array { $partition = new Partition([ 'partition' => 'foo', @@ -410,14 +359,7 @@ public function signatureVersionProvider() ]; } - /** - * @dataProvider signingNameProvider - * - * @param Partition $partition - * @param string $region - * @param string $service - * @param string $signingName - */ + #[DataProvider('signingNameProvider')] public function testDeterminesSigningName( Partition $partition, $region, @@ -434,7 +376,7 @@ public function testDeterminesSigningName( $this->assertSame($signingName, $resolved['signingName']); } - public function signingNameProvider() + public static function signingNameProvider(): array { $partition = new Partition([ 'partition' => 'foo', @@ -482,13 +424,7 @@ public function signingNameProvider() ]; } - /** - * @dataProvider stsEndpointTestCases - * - * @param $region - * @param $configOption - * @param $expectedEndpoint - */ + #[DataProvider('stsEndpointTestCases')] public function testResolvesStsRegionalEndpoints( $region, $configOption, @@ -515,7 +451,7 @@ public function testResolvesStsRegionalEndpoints( } - public function stsEndpointTestCases() + public static function stsEndpointTestCases(): array { return [ [ @@ -581,13 +517,7 @@ public function stsEndpointTestCases() ]; } - /** - * @dataProvider s3EndpointTestCases - * - * @param $region - * @param $configOption - * @param $expectedEndpoint - */ + #[DataProvider('s3EndpointTestCases')] public function testResolvesS3RegionalEndpoint( $region, $configOption, @@ -614,7 +544,7 @@ public function testResolvesS3RegionalEndpoint( } - public function s3EndpointTestCases() + public static function s3EndpointTestCases(): array { return [ [ @@ -665,19 +595,33 @@ public function s3EndpointTestCases() ]; } - /** - * @dataProvider variantTagProvider - * - * @param array $definition - * @param @fipsConfig - * @param @dualstackConfig - */ + #[DataProvider('variantTagProvider')] public function testGetVariantIgnoresVariantTagOrder( array $definition, - $fipsConfig, - $dualstackConfig + bool $useFipsConfig, + bool $useDualstackConfig ) { + $fipsConfig = null; + if ($useFipsConfig) { + $fipsConfig = $this->getMockBuilder(UseFipsEndpoint\Configuration::class) + ->disableOriginalConstructor() + ->getMock(); + $fipsConfig->expects($this->any()) + ->method('isUseFipsEndpoint') + ->willReturn(true); + } + + $dualstackConfig = null; + if ($useDualstackConfig) { + $dualstackConfig = $this->getMockBuilder(UseDualstackEndpoint\Configuration::class) + ->disableOriginalConstructor() + ->getMock(); + $dualstackConfig->expects($this->any()) + ->method('isUseDualstackEndpoint') + ->willReturn(true); + } + $partition = new Partition($definition); $resolved = $partition([ 'region' => 'us-east-1', @@ -691,22 +635,8 @@ public function testGetVariantIgnoresVariantTagOrder( $this->assertStringContainsString('testsuffix.com', $resolved['endpoint']); } - public function variantTagProvider() + public static function variantTagProvider(): array { - $useFipsEndpointConfig = $this->getMockBuilder(UseFipsEndpoint\Configuration::class) - ->disableOriginalConstructor() - ->getMock(); - $useFipsEndpointConfig->expects($this->any()) - ->method('isUseFipsEndpoint') - ->willReturn(true); - - $useDualstackEndpointConfig = $this->getMockBuilder(UseDualstackEndpoint\Configuration::class) - ->disableOriginalConstructor() - ->getMock(); - $useDualstackEndpointConfig->expects($this->any()) - ->method('isUseDualstackEndpoint') - ->willReturn(true); - return [ [ [ @@ -731,8 +661,8 @@ public function variantTagProvider() ], ], ], - $useFipsEndpointConfig, - $useDualstackEndpointConfig + true, + true ], [ [ @@ -757,8 +687,8 @@ public function variantTagProvider() ], ], ], - $useFipsEndpointConfig, - $useDualstackEndpointConfig + true, + true ], [ [ @@ -783,8 +713,8 @@ public function variantTagProvider() ], ], ], - $useFipsEndpointConfig, - null + true, + false ], [ [ @@ -809,25 +739,39 @@ public function variantTagProvider() ], ], ], - null, - $useDualstackEndpointConfig + false, + true ] ]; } - /** - * @dataProvider variantTagEmptyProvider - * - * @param array $definition - * @param @fipsConfig - * @param @dualstackConfig - */ + #[DataProvider('variantTagEmptyProvider')] public function testGetVariantNoVariantSelectedIfTagsAreEmpty( array $definition, - $fipsConfig, - $dualstackConfig + bool $useFipsConfig, + bool $useDualstackConfig ) { + $fipsConfig = null; + if ($useFipsConfig) { + $fipsConfig = $this->getMockBuilder(UseFipsEndpoint\Configuration::class) + ->disableOriginalConstructor() + ->getMock(); + $fipsConfig->expects($this->any()) + ->method('isUseFipsEndpoint') + ->willReturn(true); + } + + $dualstackConfig = null; + if ($useDualstackConfig) { + $dualstackConfig = $this->getMockBuilder(UseDualstackEndpoint\Configuration::class) + ->disableOriginalConstructor() + ->getMock(); + $dualstackConfig->expects($this->any()) + ->method('isUseDualstackEndpoint') + ->willReturn(true); + } + $partition = new Partition($definition); $resolved = $partition([ 'region' => 'us-east-1', @@ -841,22 +785,8 @@ public function testGetVariantNoVariantSelectedIfTagsAreEmpty( $this->assertStringNotContainsString('testsuffix.com', $resolved['endpoint']); } - public function variantTagEmptyProvider() + public static function variantTagEmptyProvider(): array { - $useFipsEndpointConfig = $this->getMockBuilder(UseFipsEndpoint\Configuration::class) - ->disableOriginalConstructor() - ->getMock(); - $useFipsEndpointConfig->expects($this->any()) - ->method('isUseFipsEndpoint') - ->willReturn(true); - - $useDualstackEndpointConfig = $this->getMockBuilder(UseDualstackEndpoint\Configuration::class) - ->disableOriginalConstructor() - ->getMock(); - $useDualstackEndpointConfig->expects($this->any()) - ->method('isUseDualstackEndpoint') - ->willReturn(true); - return [ [ [ @@ -881,8 +811,8 @@ public function variantTagEmptyProvider() ], ], ], - $useFipsEndpointConfig, - $useDualstackEndpointConfig + true, + true ], [ [ @@ -907,8 +837,8 @@ public function variantTagEmptyProvider() ], ], ], - $useFipsEndpointConfig, - null + true, + false ], [ [ @@ -933,8 +863,8 @@ public function variantTagEmptyProvider() ], ], ], - null, - $useDualstackEndpointConfig + false, + true ], [ [ @@ -959,19 +889,13 @@ public function variantTagEmptyProvider() ], ], ], - null, - null + false, + false ] ]; } - /** - * @dataProvider booleanConfigProvider - * - * @param array $tags - * @param @fipsConfig - * @param @dualstackConfig - */ + #[DataProvider('booleanConfigProvider')] public function testGetVariantWithBooleanConfigValues( array $tags, $fipsConfig, @@ -1013,7 +937,7 @@ public function testGetVariantWithBooleanConfigValues( $this->assertStringContainsString('testsuffix.com', $resolved['endpoint']); } - public function booleanConfigProvider() + public static function booleanConfigProvider(): array { return [ [ diff --git a/tests/Endpoint/PatternEndpointProviderTest.php b/tests/Endpoint/PatternEndpointProviderTest.php index d9d7af07cc..32883eefd0 100644 --- a/tests/Endpoint/PatternEndpointProviderTest.php +++ b/tests/Endpoint/PatternEndpointProviderTest.php @@ -4,10 +4,10 @@ use Aws\Endpoint\EndpointProvider; use Aws\Endpoint\PatternEndpointProvider; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Endpoint\PatternEndpointProvider - */ +#[CoversClass(PatternEndpointProvider::class)] class PatternEndpointProviderTest extends TestCase { public function testReturnsNullWhenUnresolved() @@ -16,7 +16,7 @@ public function testReturnsNullWhenUnresolved() $this->assertNull($e(['service' => 'foo', 'region' => 'bar'])); } - public function endpointProvider() + public static function endpointProvider(): array { return [ [ @@ -72,9 +72,7 @@ public function endpointProvider() ]; } - /** - * @dataProvider endpointProvider - */ + #[DataProvider('endpointProvider')] public function testResolvesEndpoints($input, $output) { $p = EndpointProvider::patterns([ diff --git a/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php b/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php index f6d823928c..2610e9c51b 100644 --- a/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php +++ b/tests/Endpoint/UseDualstackEndpoint/ConfigurationProviderTest.php @@ -1,7 +1,6 @@ getMockBuilder(CacheInterface::class); - $cacheBuilder->setMethods(['get', 'set', 'remove']); + $cacheBuilder->onlyMethods(['get', 'set', 'remove']); $cache = $cacheBuilder->getMock(); $cache->expects($this->any()) ->method('get') @@ -354,4 +352,3 @@ public function testCreatesFromCache() $this->assertSame($expected->toArray(), $result->toArray()); } } - diff --git a/tests/Endpoint/UseDualstackEndpoint/ConfigurationTest.php b/tests/Endpoint/UseDualstackEndpoint/ConfigurationTest.php index 621146e6d6..5de15f2afd 100644 --- a/tests/Endpoint/UseDualstackEndpoint/ConfigurationTest.php +++ b/tests/Endpoint/UseDualstackEndpoint/ConfigurationTest.php @@ -3,25 +3,20 @@ use Aws\Endpoint\UseDualstackEndpoint\Configuration; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Endpoint\UseDualstackEndpoint\Configuration - */ +#[CoversClass(Configuration::class)] class ConfigurationTest extends TestCase { - /** - * @dataProvider correctValueCases - * - * @param $param - * @param $expected - */ + #[DataProvider('correctValueCases')] public function testGetsCorrectValues($param, $expected) { $config = new Configuration($param, 'us-east-1'); $this->assertEquals($expected, $config->isuseDualstackEndpoint()); } - public function correctValueCases() + public static function correctValueCases(): array { return [ [true, true], diff --git a/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php b/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php index b5bda1eb97..6d95b093cf 100644 --- a/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php +++ b/tests/Endpoint/UseFipsEndpoint/ConfigurationProviderTest.php @@ -9,10 +9,9 @@ use Aws\Endpoint\UseFipsEndpoint\Exception\ConfigurationException; use GuzzleHttp\Promise; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Endpoint\UseFipsEndpoint\ConfigurationProvider - */ +#[CoversClass(ConfigurationProvider::class)] class ConfigurationProviderTest extends TestCase { private static $originalEnv; @@ -347,7 +346,7 @@ public function testCreatesFromCache() { $expected = new Configuration(true); $cacheBuilder = $this->getMockBuilder(CacheInterface::class); - $cacheBuilder->setMethods(['get', 'set', 'remove']); + $cacheBuilder->onlyMethods(['get', 'set', 'remove']); $cache = $cacheBuilder->getMock(); $cache->expects($this->any()) ->method('get') @@ -361,4 +360,3 @@ public function testCreatesFromCache() $this->assertSame($expected->toArray(), $result->toArray()); } } - diff --git a/tests/Endpoint/UseFipsEndpoint/ConfigurationTest.php b/tests/Endpoint/UseFipsEndpoint/ConfigurationTest.php index b77a7a030c..9fe56615ab 100644 --- a/tests/Endpoint/UseFipsEndpoint/ConfigurationTest.php +++ b/tests/Endpoint/UseFipsEndpoint/ConfigurationTest.php @@ -3,25 +3,20 @@ use Aws\Endpoint\UseFipsEndpoint\Configuration; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Endpoint\UseFipsEndpoint\Configuration - */ +#[CoversClass(Configuration::class)] class ConfigurationTest extends TestCase { - /** - * @dataProvider correctValueCases - * - * @param $param - * @param $expected - */ + #[DataProvider('correctValueCases')] public function testGetsCorrectValues($param, $expected) { $config = new Configuration($param); $this->assertEquals($expected, $config->isuseFipsEndpoint()); } - public function correctValueCases() + public static function correctValueCases(): array { return [ [true, true], diff --git a/tests/EndpointDiscovery/ConfigurationProviderTest.php b/tests/EndpointDiscovery/ConfigurationProviderTest.php index 2c5127d864..3e523e1d9e 100644 --- a/tests/EndpointDiscovery/ConfigurationProviderTest.php +++ b/tests/EndpointDiscovery/ConfigurationProviderTest.php @@ -11,10 +11,10 @@ use Aws\LruArrayCache; use GuzzleHttp\Promise; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\EndpointDiscovery\ConfigurationProvider - */ +#[CoversClass(ConfigurationProvider::class)] class ConfigurationProviderTest extends TestCase { private static $originalEnv; @@ -75,10 +75,7 @@ public static function tear_down_after_class() putenv('HOME=' . self::$originalEnv['home']); } - /** - * @dataProvider getEnvVariableNames - * @param $envName - */ + #[DataProvider('getEnvVariableNames')] public function testCreatesFromEnvironmentVariables($envName) { $this->clearEnv(); @@ -88,7 +85,7 @@ public function testCreatesFromEnvironmentVariables($envName) $this->assertSame($expected->toArray(), $result->toArray()); } - public function getEnvVariableNames() + public static function getEnvVariableNames(): array { return [ [ConfigurationProvider::ENV_ENABLED], @@ -389,7 +386,7 @@ public function testCreatesFromCache() { $expected = new Configuration(true, 3500); $cacheBuilder = $this->getMockBuilder(CacheInterface::class); - $cacheBuilder->setMethods(['get', 'set', 'remove']); + $cacheBuilder->onlyMethods(['get', 'set', 'remove']); $cache = $cacheBuilder->getMock(); $cache->expects($this->any()) ->method('get') @@ -403,7 +400,6 @@ public function testCreatesFromCache() $this->assertSame($expected->toArray(), $result->toArray()); } - public function testUsesIniWithUseAwsConfigFileTrue() { $dir = $this->clearEnv(); @@ -432,7 +428,7 @@ public function testIgnoresIniWithUseAwsConfigFileFalse() unlink($dir . '/config'); } - public function getSuccessfulUnwrapData() + public static function getSuccessfulUnwrapData(): array { $expected = new Configuration(true, 4000); return [ @@ -469,11 +465,7 @@ function () use ($expected) { ]; } - /** - * @dataProvider getSuccessfulUnwrapData - * @param $toUnwrap - * @param ConfigurationInterface $expected - */ + #[DataProvider('getSuccessfulUnwrapData')] public function testSuccessfulUnwraps($toUnwrap, ConfigurationInterface $expected) { $this->assertSame( diff --git a/tests/EndpointDiscovery/ConfigurationTest.php b/tests/EndpointDiscovery/ConfigurationTest.php index 1d2588eaf9..13fc8e7f51 100644 --- a/tests/EndpointDiscovery/ConfigurationTest.php +++ b/tests/EndpointDiscovery/ConfigurationTest.php @@ -4,11 +4,9 @@ use Aws\EndpointDiscovery\Configuration; use Yoast\PHPUnitPolyfills\TestCases\TestCase; -use Psr\Log\InvalidArgumentException; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\EndpointDiscovery\Configuration - */ +#[CoversClass(Configuration::class)] class ConfigurationTest extends TestCase { public function testGetsCorrectValues() diff --git a/tests/EndpointDiscovery/EndpointDiscoveryMiddlewareTest.php b/tests/EndpointDiscovery/EndpointDiscoveryMiddlewareTest.php index 662cf69f70..4d610305b9 100644 --- a/tests/EndpointDiscovery/EndpointDiscoveryMiddlewareTest.php +++ b/tests/EndpointDiscovery/EndpointDiscoveryMiddlewareTest.php @@ -21,10 +21,10 @@ use GuzzleHttp\Psr7\Uri; use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\EndpointDiscovery\EndpointDiscoveryMiddleware - */ +#[CoversClass(EndpointDiscoveryMiddleware::class)] class EndpointDiscoveryMiddlewareTest extends TestCase { use UsesServiceTrait; @@ -70,13 +70,7 @@ public function tear_down() $cacheReflection->setValue(null, self::$originalCache); } - /** - * @dataProvider getRequestTestCases - * @param array $commandArgs - * @param array $clientArgs - * @param ResultInterface $describeResult - * @param RequestInterface $expected - */ + #[DataProvider('getRequestTestCases')] public function testCorrectlyModifiesRequest( array $commandArgs, array $clientArgs, @@ -113,7 +107,7 @@ public function testCorrectlyModifiesRequest( $client->execute($command); } - public function getRequestTestCases() + public static function getRequestTestCases(): array { $baseUri = new Uri('https://awsendpointdiscoverytestservice.us-east-1.amazonaws.com/'); $baseUserAgent = 'aws-sdk-php/' . Sdk::VERSION; @@ -296,12 +290,7 @@ public function getRequestTestCases() ]; } - /** - * @dataProvider getDiscoveryRequestTestCases - * @param CommandInterface $mainCmd - * @param CommandInterface $expectedCmd - * @param RequestInterface $expectedReq - */ + #[DataProvider('getDiscoveryRequestTestCases')] public function testCorrectlyConstructsDiscoveryRequest( CommandInterface $mainCmd, CommandInterface $expectedCmd, @@ -328,7 +317,7 @@ public function testCorrectlyConstructsDiscoveryRequest( $handler($mainCmd, new Request('POST', new Uri('https://foo.com'))); } - public function getDiscoveryRequestTestCases() + public static function getDiscoveryRequestTestCases(): array { $baseUri = new Uri('https://awsendpointdiscoverytestservice.us-east-1.amazonaws.com'); $baseRequest = new Request( @@ -550,10 +539,7 @@ public function testThrowsExceptionOnDescribeFailure() } } - /** - * @dataProvider getInvalidEndpointExceptions - * @param $exception - */ + #[DataProvider('invalidEndpointExceptionsDataProvider')] public function testUsesCachedEndpointForInvalidEndpointException($exception) { $callOrder = []; @@ -585,10 +571,7 @@ public function testUsesCachedEndpointForInvalidEndpointException($exception) $this->assertEquals(['describe', 'failure', 'success'], $callOrder); } - /** - * @dataProvider getInvalidEndpointExceptions - * @param $exception - */ + #[DataProvider('invalidEndpointExceptionsDataProvider')] public function testUseRegionalEndpointForInvalidEndpointException($exception) { $callOrder = []; @@ -628,10 +611,7 @@ public function testUseRegionalEndpointForInvalidEndpointException($exception) ); } - /** - * @dataProvider getInvalidEndpointExceptions - * @param $exception - */ + #[DataProvider('invalidEndpointExceptionsDataProvider')] public function testThrowsExceptionOnInvalidEndpointException($exception) { $callOrder = []; @@ -669,10 +649,7 @@ public function testThrowsExceptionOnInvalidEndpointException($exception) $this->assertEquals(['describe', 'failure'], $callOrder); } - /** - * @dataProvider getInvalidEndpointExceptions - * @param $exception - */ + #[DataProvider('invalidEndpointExceptionsDataProvider')] public function testCallsDiscoveryApiOnInvalidEndpointException($exception) { // Use Reflection to set private static discoveryCooldown variable to 0 @@ -731,14 +708,12 @@ public function testCallsDiscoveryApiOnInvalidEndpointException($exception) /** * Data provider for exceptions treated as invalid endpoint exceptions - * - * @return array */ - public function getInvalidEndpointExceptions() + public static function invalidEndpointExceptionsDataProvider(): array { return [ - [$this->generateInvalidEndpointException()], - [$this->generate421Exception()], + [self::generateInvalidEndpointException()], + [self::generate421Exception()], ]; } @@ -862,7 +837,7 @@ private function generateGenericResult() return Promise\Create::promiseFor(new Result([])); } - private function generateInvalidEndpointException() + private static function generateInvalidEndpointException(): Promise\PromiseInterface { $message = 'Test invalid endpoint exception'; return Promise\Create::rejectionFor(new AwsException( @@ -875,7 +850,7 @@ private function generateInvalidEndpointException() )); } - private function generate421Exception() + private static function generate421Exception(): Promise\PromiseInterface { $message = 'Test invalid endpoint exception'; return Promise\Create::rejectionFor(new AwsException( diff --git a/tests/EndpointDiscovery/EndpointListTest.php b/tests/EndpointDiscovery/EndpointListTest.php index 1cb608f875..6c0dc89f63 100644 --- a/tests/EndpointDiscovery/EndpointListTest.php +++ b/tests/EndpointDiscovery/EndpointListTest.php @@ -4,10 +4,9 @@ use Aws\EndpointDiscovery\EndpointList; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\EndpointDiscovery\EndpointList - */ +#[CoversClass(EndpointList::class)] class EndpointListTest extends TestCase { public function testStoresRetrievesAndCyclesActiveEndpoints() diff --git a/tests/EndpointParameterMiddlewareTest.php b/tests/EndpointParameterMiddlewareTest.php index 44089b2feb..72292e6639 100644 --- a/tests/EndpointParameterMiddlewareTest.php +++ b/tests/EndpointParameterMiddlewareTest.php @@ -7,10 +7,10 @@ use Aws\Api\Service; use GuzzleHttp\Psr7\Request; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\EndpointParameterMiddleware - */ +#[CoversClass(EndpointParameterMiddleware::class)] class EndpointParameterMiddlewareTest extends TestCase { public function testThrowsExceptionForMissingParameter() @@ -66,17 +66,15 @@ public function testThrowsExceptionForInvalidParameter() } } - /** - * @dataProvider getTestCases - */ + #[DataProvider('correctlyOutputsHostDataProvider')] public function testCorrectlyOutputsHost( - Service $service, $clientArgs, $cmdName, $params, $endpoint, $expectedHost ) { + $service = $this->generateTestService(); if ($cmdName === 'NoEndpointOp') { $this->addToAssertionCount(1); // To be replaced with $this->expectNotToPerformAssertions(); } @@ -95,14 +93,11 @@ public function testCorrectlyOutputsHost( $handler($command, new Request('POST', $endpoint)); } - public function getTestCases() + public static function correctlyOutputsHostDataProvider(): array { - $service = $this->generateTestService(); - return [ // Operation without any prefix injection [ - $service, [], 'NoEndpointOp', [ @@ -113,7 +108,6 @@ public function getTestCases() ], // Operation with static prefix injection [ - $service, [], 'StaticOp', [ @@ -124,7 +118,6 @@ public function getTestCases() ], // Operation with host parameter injection [ - $service, [], 'MemberRefOp', [ @@ -135,7 +128,6 @@ public function getTestCases() ], // Operation with multiple host parameter injections [ - $service, [], 'MultiRefOp', [ @@ -147,7 +139,6 @@ public function getTestCases() ], // Operation with host parameter injection, disabled via client argument [ - $service, [ 'disable_host_prefix_injection' => true ], diff --git a/tests/EndpointV2/EndpointDefinitionProviderTest.php b/tests/EndpointV2/EndpointDefinitionProviderTest.php index 953099bc36..6873a6b909 100644 --- a/tests/EndpointV2/EndpointDefinitionProviderTest.php +++ b/tests/EndpointV2/EndpointDefinitionProviderTest.php @@ -3,8 +3,11 @@ namespace Aws\Test\EndpointV2; use Aws\EndpointV2\EndpointDefinitionProvider; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +#[CoversClass(EndpointDefinitionProvider::class)] class EndpointDefinitionProviderTest extends TestCase { public function testProvidesRuleset() @@ -46,7 +49,7 @@ public function testThrowsExceptionOnInvalidApiVersion() EndpointDefinitionProvider::getEndpointRuleset('s3', '10-22-2022'); } - public function getEndpointFileProvider() + public static function getEndpointFileProvider(): array { return [ ['Ruleset'], @@ -54,11 +57,7 @@ public function getEndpointFileProvider() ]; } - /** - * @dataProvider getEndpointFileProvider - * - * @param $type - */ + #[DataProvider('getEndpointFileProvider')] public function testThrowsExceptionOnMissingFiles($type) { $method = 'getEndpoint' . $type; @@ -74,4 +73,4 @@ public function testThrowsExceptionOnMissingFiles($type) rmdir($tmpdir . 'data/' . 's3/'); rmdir($tmpdir . 'data'); } -} \ No newline at end of file +} diff --git a/tests/EndpointV2/EndpointProviderV2Test.php b/tests/EndpointV2/EndpointProviderV2Test.php index b916304972..131decd5e7 100644 --- a/tests/EndpointV2/EndpointProviderV2Test.php +++ b/tests/EndpointV2/EndpointProviderV2Test.php @@ -14,10 +14,10 @@ use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7\Uri; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\EndpointV2\EndpointProviderV2 - */ +#[CoversClass(EndpointProviderV2::class)] class EndpointProviderV2Test extends TestCase { use UsesServiceTrait; @@ -26,7 +26,7 @@ class EndpointProviderV2Test extends TestCase * Iterates through test cases located in ../test-cases and * ../valid-rules, parses into parameters used for endpoint and error tests */ - public function basicTestCaseProvider(): \Generator + public static function basicTestCaseProvider(): \Generator { $testfileNames = [ "aws-region", @@ -67,9 +67,7 @@ public function basicTestCaseProvider(): \Generator } } - /** - * @dataProvider basicTestCaseProvider - */ + #[DataProvider('basicTestCaseProvider')] public function testBasicEndpointAndErrorCases( $ruleset, $isSuccessCase, @@ -103,7 +101,7 @@ public function testBasicEndpointAndErrorCases( * Iterates through test cases located in each service's endpoint test file. * Parses into parameters used for endpoint and error tests */ - public function serviceTestCaseProvider(): \Generator + public static function serviceTestCaseProvider(): \Generator { $services = \Aws\Manifest(); @@ -129,9 +127,7 @@ public function serviceTestCaseProvider(): \Generator } } - /** - * @dataProvider serviceTestCaseProvider - */ + #[DataProvider('serviceTestCaseProvider')] public function testServiceEndpointAndErrorCases( $service, $isSuccessCase, @@ -161,7 +157,7 @@ public function testServiceEndpointAndErrorCases( } } - public function rulesetProtocolEndpointAndErrorCaseProvider(): \Generator + public static function rulesetProtocolEndpointAndErrorCaseProvider(): \Generator { $serviceList = \Aws\manifest(); @@ -224,9 +220,8 @@ public function rulesetProtocolEndpointAndErrorCaseProvider(): \Generator * End-to-end tests which ensure the correct values are resolved * before being passed into the endpoint provider and after other * middleware has acted upon the request. - * - * @dataProvider rulesetProtocolEndpointAndErrorCaseProvider */ + #[DataProvider('rulesetProtocolEndpointAndErrorCaseProvider')] public function testRulesetProtocolEndpointAndErrorCases($service, $clientArgs, $operationInput, $expected, $errorCase) { if ($errorCase) { @@ -352,7 +347,7 @@ public function testCachesEndpointObject() $endpointMock = $this->getMockBuilder(RulesetEndpoint::class) ->disableOriginalConstructor() - ->setMethods([]) + ->onlyMethods([]) ->getMock(); $rulesetMock = $this->getMockBuilder(Ruleset::class) @@ -377,10 +372,7 @@ public function testCachesEndpointObject() $endpointProvider->resolveEndpoint(['Region' => 'us-west-2']); } - /** - * @dataProvider stringArrayOperationInputsProvider - * @return void - */ + #[DataProvider('stringArrayOperationInputsProvider')] public function testStringArrayOperationInputs( $params, $expected, @@ -434,7 +426,7 @@ public function testStringArrayOperationInputs( } } - public function stringArrayOperationInputsProvider(): \Generator + public static function stringArrayOperationInputsProvider(): \Generator { $cases = json_decode( file_get_contents(__DIR__ . '/test-cases/string-array.json'), diff --git a/tests/EndpointV2/EndpointV2MiddlewareTest.php b/tests/EndpointV2/EndpointV2MiddlewareTest.php index 3db9e9a6b3..2eca25ec8b 100644 --- a/tests/EndpointV2/EndpointV2MiddlewareTest.php +++ b/tests/EndpointV2/EndpointV2MiddlewareTest.php @@ -9,20 +9,15 @@ use Aws\Test\UsesServiceTrait; use ReflectionClass; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(EndpointV2Middleware::class)] class EndpointV2MiddlewareTest extends TestCase { use UsesServiceTrait; - /** - * @dataProvider providedSuccessCases - * - * @param $service - * @param $clientArgs - * @param $commandName - * @param $commandArgs - * @param $expectedUri - */ + #[DataProvider('providedSuccessCases')] public function testSuccessfullyResolvesEndpointAndAuthScheme( $service, $clientArgs, @@ -47,7 +42,7 @@ public function testSuccessfullyResolvesEndpointAndAuthScheme( $mw($command); } - public function providedSuccessCases() + public static function providedSuccessCases(): array { return [ [ @@ -120,12 +115,7 @@ function ($command, $endpoint) {}, $method->invoke($middleware, [['name' => 'invalidAuthScheme']]); } - /** - * @param $authSchemes - * @param $expected - * - * @dataProvider v4aAuthProvider - */ + #[DataProvider('v4aAuthProvider')] public function testV4aAuthSchemeSelection($authSchemes, $expected) { if ($expected === 'v4a' && (!extension_loaded('awscrt'))) { @@ -153,7 +143,7 @@ function ($command, $endpoint) {}, $this->assertSame($expected, $result['version']); } - public function v4aAuthProvider() + public static function v4aAuthProvider(): array { return [ [ @@ -193,66 +183,67 @@ function ($command, $endpoint) {}, $reflection = new ReflectionClass(EndpointV2Middleware::class); $method = $reflection->getMethod('resolveAuthScheme'); - $method->invoke($middleware, [['name' => 'sigv4a']]); + $method->invoke($middleware, [['name' => 'sigv4a']]); } - /** - * @dataProvider invalidInitializationProvider - */ + #[DataProvider('invalidInitializationProvider')] public function testInitializationWithInvalidParameters( $nextHandler, - $endpointProvider, - $api, + bool $validEndpointProvider, + bool $validApi, $args ) { + $endpointProvider = 'invalid'; + if ($validEndpointProvider) { + $endpointProvider = $this->getMockBuilder(EndpointProviderV2::class) + ->disableOriginalConstructor() + ->getMock(); + } + + $api = 'invalid'; + if ($validApi) { + $api = $this->getMockBuilder(Service::class) + ->disableOriginalConstructor() + ->getMock(); + } + $this->expectException(\TypeError::class); new EndpointV2Middleware($nextHandler, $endpointProvider, $api, $args); } - public function invalidInitializationProvider() + public static function invalidInitializationProvider(): array { return [ 'Invalid nextHandler' => [ 'not_a_callable', - $this->getMockBuilder(EndpointProviderV2::class) - ->disableOriginalConstructor() - ->getMock(), - $this->getMockBuilder(Service::class) - ->disableOriginalConstructor() - ->getMock(), + true, + true, [] ], 'Invalid endpointProvider' => [ function ($command, $endpoint) {}, - 'not_an_endpoint_provider', - $this->getMockBuilder(Service::class) - ->disableOriginalConstructor() - ->getMock(), + false, + true, [] ], 'Invalid api' => [ function ($command, $endpoint) {}, - $this->getMockBuilder(EndpointProviderV2::class) - ->disableOriginalConstructor() - ->getMock(), - 'not_a_service', + true, + false, [] ], 'Invalid array' => [ function ($command, $endpoint) {}, - $this->getMockBuilder(EndpointProviderV2::class) - ->disableOriginalConstructor() - ->getMock(), - $this->getMockBuilder(Service::class) - ->disableOriginalConstructor() - ->getMock(), + true, + true, 'not_an_array' ], ]; } - public function testBadParametersOnInvocation() { + public function testBadParametersOnInvocation() + { $this->expectException(\TypeError::class); $nextHandler = function ($command, $endpoint) {}; diff --git a/tests/EndpointV2/EndpointV2SerializerTraitTest.php b/tests/EndpointV2/EndpointV2SerializerTraitTest.php index c03ba0e684..6108495e3d 100644 --- a/tests/EndpointV2/EndpointV2SerializerTraitTest.php +++ b/tests/EndpointV2/EndpointV2SerializerTraitTest.php @@ -7,10 +7,9 @@ use Aws\Middleware; use Aws\Test\UsesServiceTrait; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\EndpointV2\EndpointV2SerializerTrait - */ +#[CoversClass(EndpointV2SerializerTrait::class)] class EndpointV2SerializerTraitTest extends TestCase { use UsesServiceTrait; @@ -81,4 +80,4 @@ public function testThrowsExceptionForInvalidAuthScheme() $handler = $list->resolve(); $handler($command)->wait(); } -} \ No newline at end of file +} diff --git a/tests/EndpointV2/RuleCreatorTest.php b/tests/EndpointV2/RuleCreatorTest.php index 825bcba12f..d97c5a5445 100644 --- a/tests/EndpointV2/RuleCreatorTest.php +++ b/tests/EndpointV2/RuleCreatorTest.php @@ -2,15 +2,16 @@ namespace Aws\Test\EndpointV2; use Aws\EndpointV2\Rule; +use Aws\EndpointV2\Rule\RuleCreator; use Aws\Exception\UnresolvedEndpointException; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\EndpointV2\Rule\RuleCreator - */ +#[CoversClass(RuleCreator::class)] class RuleCreatorTest extends TestCase { - public function ruleCreationProvider() + public static function ruleCreationProvider(): array { return [ [ @@ -44,15 +45,13 @@ public function ruleCreationProvider() ]; } - /** - * @dataProvider RuleCreationProvider - */ + #[DataProvider('ruleCreationProvider')] public function testRuleCreation($spec, $expected) { $result = Rule\RuleCreator::create($spec['type'], $spec); $this->assertInstanceOf($expected, $result); } - public function invalidRuleTypeProvider() + public static function invalidRuleTypeProvider(): array { return [ ['foo'], @@ -61,9 +60,7 @@ public function invalidRuleTypeProvider() ]; } - /** - * @dataProvider invalidRuleTypeProvider - */ + #[DataProvider('invalidRuleTypeProvider')] public function testThrowsExceptionForInvalidRuleType($input) { $this->expectException(UnresolvedEndpointException::class); diff --git a/tests/EndpointV2/RulesetEndpointTest.php b/tests/EndpointV2/RulesetEndpointTest.php index d8b15262ce..e7a8d0eb85 100644 --- a/tests/EndpointV2/RulesetEndpointTest.php +++ b/tests/EndpointV2/RulesetEndpointTest.php @@ -1,11 +1,10 @@ expectException(UnresolvedEndpointException::class); @@ -40,19 +36,27 @@ public function testWrongParameterTypeThrowsException($inputParameter) public function testDeprecatedParameterLogsError() { - $this->expectWarning(); + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage( 'Region has been deprecated since then. There is a new parameter.' ); - $parameter = new RulesetParameter('Region', [ - "type" => "string", - "builtIn" => "AWS::Region", - "deprecated" => [ - "since" => 'then', - "message" => 'There is a new parameter.' - ] - ]); - $parameter->validateInputParam('us-east-1'); + + set_error_handler(function ($errno, $errstr) { + throw new \RuntimeException($errstr, $errno); + }); + try { + $parameter = new RulesetParameter('Region', [ + "type" => "string", + "builtIn" => "AWS::Region", + "deprecated" => [ + "since" => 'then', + "message" => 'There is a new parameter.' + ] + ]); + $parameter->validateInputParam('us-east-1'); + } finally { + restore_error_handler(); + } } public function testUnknownTypeThrowsException() @@ -79,16 +83,14 @@ public function testGetDefault() $this->assertSame($spec['default'], $ruleset->getDefault()); } - /** - * @dataProvider validTypesProvider - * @doesNotPerformAssertions - */ + #[DataProvider('validTypesProvider')] public function testRulesetCreationWithValidTypes($spec) { new RulesetParameter('FooParam', $spec); + $this->assertTrue(true); } - public function validTypesProvider() + public static function validTypesProvider(): array { return [ [ diff --git a/tests/EndpointV2/RulesetStandardLibraryTest.php b/tests/EndpointV2/RulesetStandardLibraryTest.php index da3275c169..22c93d476a 100644 --- a/tests/EndpointV2/RulesetStandardLibraryTest.php +++ b/tests/EndpointV2/RulesetStandardLibraryTest.php @@ -5,10 +5,10 @@ use Aws\EndpointV2\Ruleset\RulesetStandardLibrary; use Aws\Exception\UnresolvedEndpointException; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\EndpointV2\Ruleset\RulesetStandardLibrary - */ +#[CoversClass(RulesetStandardLibrary::class)] class RulesetStandardLibraryTest extends TestCase { private $standardLibrary; @@ -20,7 +20,10 @@ protected function set_up() $this->standardLibrary = new RulesetStandardLibrary($partitions); } - public function isSetProvider() + /** + * @return array> + */ + public static function isSetProvider(): array { return [ [null, false], @@ -33,18 +36,16 @@ public function isSetProvider() ]; } - /** - * @dataProvider isSetProvider - * - * @param $input - * @param $expected - */ + #[DataProvider('isSetProvider')] public function testIsSet($input, $expected) { $this->assertSame($expected, $this->standardLibrary->is_set($input)); } - public function notProvider() + /** + * @return array> + */ + public static function notProvider(): array { return [ [true, false], @@ -55,18 +56,16 @@ public function notProvider() ]; } - /** - * @dataProvider notProvider - * - * @param $input - * @param $expected - */ + #[DataProvider('notProvider')] public function testNot($input, $expected) { $this->assertSame($expected, $this->standardLibrary->not($input)); } - public function getAttrProvider() + /** + * @return array> + */ + public static function getAttrProvider(): array { return [ ['{"Thing1": "foo", "Thing2": ["index0", "index1"], "Thing3": {"SubThing": 42}}', "Thing1", "foo"], @@ -76,12 +75,7 @@ public function getAttrProvider() ]; } - /** - * @dataProvider getAttrProvider - * - * @param $path - * @param $expected - */ + #[DataProvider('getAttrProvider')] public function testGetAttr($from, $path, $expected) { $from = json_decode($from, true); @@ -94,7 +88,10 @@ public function testGetAttrFromArray() $this->assertSame("foo", $this->standardLibrary->getAttr($from, 0)); } - public function stringEqualsProvider() + /** + * @return array> + */ + public static function stringEqualsProvider(): array { return [ ["abc", "abc", true], @@ -103,19 +100,16 @@ public function stringEqualsProvider() ]; } - /** - * @dataProvider stringEqualsProvider - * - * @param $string1 - * @param $string2 - * @param $expected - */ + #[DataProvider('stringEqualsProvider')] public function testStringEquals($string1, $string2, $expected) { $this->assertSame($expected, $this->standardLibrary->stringEquals($string1, $string2)); } - public function booleanEqualsProvider() + /** + * @return array> + */ + public static function booleanEqualsProvider(): array { return [ [true, true, true], @@ -133,13 +127,7 @@ public function booleanEqualsProvider() ]; } - /** - * @dataProvider booleanEqualsProvider - * - * @param $boolean1 - * @param $boolean2 - * @param $expected - */ + #[DataProvider('booleanEqualsProvider')] public function testBooleanEquals($boolean1, $boolean2, $expected) { $this->assertSame($expected, $this->standardLibrary->booleanEquals($boolean1, $boolean2)); @@ -151,7 +139,10 @@ public function testParseUrlReturnsNullWithQuery() $this->assertEquals(null, $result); } - public function isValidHostLabelProvider() + /** + * @return array> + */ + public static function isValidHostLabelProvider(): array { return [ "valid" => ["exampleHostLabel", false, true], @@ -162,19 +153,16 @@ public function isValidHostLabelProvider() ]; } - /** - * @dataProvider isValidHostLabelProvider - * - * @param $hostLabel - * @param $allowSubDomains - * @param $expected - */ + #[DataProvider('isValidHostLabelProvider')] public function testIsValidHostLabel($hostLabel, $allowSubDomains, $expected) { $this->assertSame($expected, $this->standardLibrary->isValidHostLabel($hostLabel, $allowSubDomains)); } - public function resolveTemplateStringProvider() + /** + * @return array> + */ + public static function resolveTemplateStringProvider(): array { $params = [ 'ShorthandSyntax' => [ @@ -220,20 +208,17 @@ public function resolveTemplateStringProvider() ]; } - /** - * @dataProvider resolveTemplateStringProvider - * - * @param $string - * @param $inputParams - * @param $expected - */ + #[DataProvider('resolveTemplateStringProvider')] public function testResolveTemplateString($string, $inputParams, $expected) { $result = $this->standardLibrary->resolveTemplateString($string, $inputParams); $this->assertEquals($expected, $result); } - public function NullParamProvider() + /** + * @return array> + */ + public static function NullParamProvider(): array { $params = [ 'Region' => 'us-east-1', @@ -254,12 +239,7 @@ public function NullParamProvider() ]; } - /** - * @dataProvider NullParamProvider - * - * @param $string - * @param $inputParams - */ + #[DataProvider('NullParamProvider')] public function testResolveTemplateStringThrowsExceptionIfNullParam($string, $inputParams) { $this->expectException(UnresolvedEndpointException::class); @@ -326,4 +306,3 @@ public function testCallFunctionThrowsErrorIfAlreadyAssigned() { $this->standardLibrary->callFunction($condition, $inputParameters); } } - diff --git a/tests/EventBridge/EventBridgeClientTest.php b/tests/EventBridge/EventBridgeClientTest.php index c09f3ad122..c6fe52c511 100644 --- a/tests/EventBridge/EventBridgeClientTest.php +++ b/tests/EventBridge/EventBridgeClientTest.php @@ -2,20 +2,21 @@ namespace Aws\Test\EventBridge; use Aws\CommandInterface; -use Aws\Exception\UnresolvedEndpointException; -use Aws\Result; use Aws\EventBridge\EventBridgeClient; +use Aws\Result; use Aws\Test\UsesServiceTrait; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; use Psr\Http\Message\RequestInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +#[CoversClass(EventBridgeClient::class)] class EventBridgeClientTest extends TestCase { use UsesServiceTrait; - public function putEventsEndpointSuccessProvider() + public static function putEventsEndpointSuccessProvider(): array { - return [ [ "us-east-1", @@ -54,7 +55,8 @@ public function putEventsEndpointSuccessProvider() ], [ "us-iso-east-1", - [], 'abc123.456def', + [], + 'abc123.456def', 'https://abc123.456def.endpoint.events.c2s.ic.gov/', ['x-amz-region-set' => '*'], ], @@ -75,15 +77,7 @@ public function putEventsEndpointSuccessProvider() ]; } - /** - * @dataProvider putEventsEndpointSuccessProvider - * - * @param $clientRegion - * @param $additionalConfig - * @param $endpointId - * @param $expectedEndpoint - * @param $additionalHeaders - */ + #[DataProvider('putEventsEndpointSuccessProvider')] public function testPutEventsEndpointSuccessCases( $clientRegion, $additionalConfig, @@ -138,9 +132,8 @@ public function testPutEventsEndpointSuccessCases( $client->execute($command); } - public function putEventsEndpointFailureProvider() + public static function putEventsEndpointFailureProvider(): array { - return [ ["us-east-1", [], 'badactor.com?foo=bar', 'EndpointId must be a valid host label.'], ["us-east-1", ['use_fips_endpoint' => true], 'abc123.456def', 'Invalid Configuration: FIPS is not supported with EventBridge multi-region endpoints.'], @@ -148,14 +141,7 @@ public function putEventsEndpointFailureProvider() ]; } - /** - * @dataProvider putEventsEndpointFailureProvider - * - * @param $clientRegion - * @param $additionalConfig - * @param $endpointId - * @param $expectedException - */ + #[DataProvider('putEventsEndpointFailureProvider')] public function testPutEventsEndpointFailureCases( $clientRegion, $additionalConfig, @@ -198,4 +184,4 @@ public function testPutEventsEndpointFailureCases( self::assertStringContainsString($expectedException, $exception->getMessage()); } } -} \ No newline at end of file +} diff --git a/tests/Exception/AwsExceptionTest.php b/tests/Exception/AwsExceptionTest.php index 4f36415cdf..9897ce6cf2 100644 --- a/tests/Exception/AwsExceptionTest.php +++ b/tests/Exception/AwsExceptionTest.php @@ -12,10 +12,10 @@ use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Response; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Exception\AwsException - */ +#[CoversClass(AwsException::class)] class AwsExceptionTest extends TestCase { use UsesServiceTrait; @@ -223,9 +223,7 @@ public function testAcceptsNullAsPrevious(): void $this->assertNull($e->getPrevious()); } - /** - * @dataProvider previousThrowableProvider - */ + #[DataProvider('previousThrowableProvider')] public function testAcceptsVariousThrowableTypes(\Throwable $previous): void { $command = new Command('foo'); @@ -235,7 +233,7 @@ public function testAcceptsVariousThrowableTypes(\Throwable $previous): void $this->assertInstanceOf(\Throwable::class, $e->getPrevious()); } - public function previousThrowableProvider(): array + public static function previousThrowableProvider(): array { return [ 'standard exception' => [new \Exception('Standard exception')], diff --git a/tests/Exception/CouldNotCreateChecksumExceptionTest.php b/tests/Exception/CouldNotCreateChecksumExceptionTest.php index 8d23bc27c2..52079346fb 100644 --- a/tests/Exception/CouldNotCreateChecksumExceptionTest.php +++ b/tests/Exception/CouldNotCreateChecksumExceptionTest.php @@ -3,10 +3,9 @@ use Aws\Exception\CouldNotCreateChecksumException; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Exception\CouldNotCreateChecksumException - */ +#[CoversClass(CouldNotCreateChecksumException::class)] class CouldNotCreateChecksumExceptionTest extends TestCase { public function testUsesCorrectWords() diff --git a/tests/Exception/EventStreamDataExceptionTest.php b/tests/Exception/EventStreamDataExceptionTest.php index 6911d3735e..012d5b3c60 100644 --- a/tests/Exception/EventStreamDataExceptionTest.php +++ b/tests/Exception/EventStreamDataExceptionTest.php @@ -4,10 +4,9 @@ use Aws\Exception\EventStreamDataException; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Exception\EventStreamDataException - */ +#[CoversClass(EventStreamDataException::class)] class EventStreamDataExceptionTest extends TestCase { public function testAccessors() diff --git a/tests/Exception/MultipartUploadExceptionTest.php b/tests/Exception/MultipartUploadExceptionTest.php index 336e637951..49f1b7fe74 100644 --- a/tests/Exception/MultipartUploadExceptionTest.php +++ b/tests/Exception/MultipartUploadExceptionTest.php @@ -6,15 +6,13 @@ use Aws\Exception\MultipartUploadException; use Aws\Multipart\UploadState; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Exception\MultipartUploadException - */ +#[CoversClass(MultipartUploadException::class)] class MultipartUploadExceptionTest extends TestCase { - /** - * @dataProvider getTestCases - */ + #[DataProvider('getTestCases')] public function testCanCreateMultipartException($commandName, $status) { $msg = 'Error encountered while reticulating splines.'; @@ -30,7 +28,7 @@ public function testCanCreateMultipartException($commandName, $status) $this->assertSame($prev, $exception->getPrevious()); } - public function getTestCases() + public static function getTestCases(): array { return [ ['CreateMultipartUpload', 'initiating'], diff --git a/tests/FunctionsTest.php b/tests/FunctionsTest.php index bd42037585..a84523e10f 100644 --- a/tests/FunctionsTest.php +++ b/tests/FunctionsTest.php @@ -5,13 +5,30 @@ use Aws\MockHandler; use Aws\Result; use Aws\S3\S3Client; +use PHPUnit\Framework\Attributes\CoversFunction; use Yoast\PHPUnitPolyfills\TestCases\TestCase; - +use PHPUnit\Framework\Attributes\DataProvider; + +#[CoversFunction('Aws\recursive_dir_iterator')] +#[CoversFunction('Aws\or_chain')] +#[CoversFunction('Aws\load_compiled_json')] +#[CoversFunction('Aws\constantly')] +#[CoversFunction('Aws\filter')] +#[CoversFunction('Aws\map')] +#[CoversFunction('Aws\flatmap')] +#[CoversFunction('Aws\partition')] +#[CoversFunction('Aws\describe_type')] +#[CoversFunction('Aws\dir_iterator')] +#[CoversFunction('Aws\default_http_handler')] +#[CoversFunction('Aws\serialize')] +#[CoversFunction('Aws\manifest')] +#[CoversFunction('Aws\is_valid_hostname')] +#[CoversFunction('Aws\is_valid_hostlabel')] +#[CoversFunction('Aws\parse_ini_file')] +#[CoversFunction('Aws\parse_ini_section_with_subsections')] +#[CoversFunction('Aws\is_associative')] class FunctionsTest extends TestCase { - /** - * @covers Aws\recursive_dir_iterator() - */ public function testCreatesRecursiveDirIterator() { $iter = Aws\recursive_dir_iterator(__DIR__); @@ -20,9 +37,6 @@ public function testCreatesRecursiveDirIterator() $this->assertContains(realpath(__FILE__), $files); } - /** - * @covers Aws\dir_iterator() - */ public function testCreatesNonRecursiveDirIterator() { $iter = Aws\dir_iterator(__DIR__); @@ -31,21 +45,17 @@ public function testCreatesNonRecursiveDirIterator() $this->assertContains('FunctionsTest.php', $files); } - /** - * @covers Aws\or_chain() - */ public function testComposesOrFunctions() { - $a = function ($a, $b) { return null; }; + $a = function ($a, $b) { return null; + + $this->assertTrue(true);}; $b = function ($a, $b) { return $a . $b; }; $c = function ($a, $b) { return 'C'; }; $comp = Aws\or_chain($a, $b, $c); $this->assertSame('+-', $comp('+', '-')); } - /** - * @covers Aws\or_chain() - */ public function testReturnsNullWhenNonResolve() { $called = []; @@ -57,27 +67,18 @@ public function testReturnsNullWhenNonResolve() $this->assertEquals(['a', 'b', 'c'], $called); } - /** - * @covers Aws\constantly() - */ public function testCreatesConstantlyFunctions() { $fn = Aws\constantly('foo'); $this->assertSame('foo', $fn()); } - /** - * @covers Aws\load_compiled_json() - */ public function testUsesJsonCompiler() { $this->expectException(\InvalidArgumentException::class); Aws\load_compiled_json('/path/to/not/here.json'); } - /** - * @covers Aws\load_compiled_json() - */ public function testUsesPhpCompilationOfJsonIfPossible() { $soughtData = ['foo' => 'bar']; @@ -98,9 +99,6 @@ public function testUsesPhpCompilationOfJsonIfPossible() $this->assertSame($soughtData, Aws\load_compiled_json($jsonPath)); } - /** - * @covers Aws\load_compiled_json() - */ public function testOnlyLoadsCompiledJsonOnce() { $soughtData = ['foo' => 'bar']; @@ -130,9 +128,6 @@ public function testOnlyLoadsCompiledJsonOnce() $this->assertEquals($compiledAtime, fileatime($compiledPath)); } - /** - * @covers Aws\filter() - */ public function testFilter() { $data = [0, 1, 2, 3, 4]; @@ -141,9 +136,6 @@ public function testFilter() $this->assertEquals([1, 3], iterator_to_array($result)); } - /** - * @covers Aws\map() - */ public function testMap() { $data = [0, 1, 2, 3, 4]; @@ -151,9 +143,6 @@ public function testMap() $this->assertEquals([1, 2, 3, 4, 5], iterator_to_array($result)); } - /** - * @covers Aws\flatmap() - */ public function testFlatMap() { $data = ['Hello', 'World']; @@ -165,9 +154,6 @@ public function testFlatMap() ); } - /** - * @covers Aws\partition() - */ public function testPartition() { $data = [1, 2, 3, 4, 5]; @@ -175,27 +161,18 @@ public function testPartition() $this->assertEquals([[1, 2], [3, 4], [5]], iterator_to_array($result)); } - /** - * @covers Aws\describe_type() - */ public function testDescribeObject() { $obj = new \stdClass(); $this->assertSame('object(stdClass)', Aws\describe_type($obj)); } - /** - * @covers Aws\describe_type() - */ public function testDescribeArray() { $arr = [0, 1, 2]; $this->assertSame('array(3)', Aws\describe_type($arr)); } - /** - * @covers Aws\describe_type() - */ public function testDescribeDoubleToFloat() { if (PHP_VERSION_ID >= 80500) { @@ -208,18 +185,12 @@ public function testDescribeDoubleToFloat() $this->assertSame('float(1.3)', Aws\describe_type($double)); } - /** - * @covers Aws\describe_type() - */ public function testDescribeType() { $this->assertSame('int(1)', Aws\describe_type(1)); $this->assertSame('string(4) "test"', Aws\describe_type("test")); } - /** - * @covers Aws\default_http_handler() - */ public function testGuzzleHttpHandler() { if (!class_exists('GuzzleHttp\Handler\StreamHandler')) { @@ -231,9 +202,6 @@ public function testGuzzleHttpHandler() ); } - /** - * @covers Aws\serialize() - */ public function testSerializesHttpRequests() { $mock = new MockHandler([new Result([])]); @@ -264,17 +232,11 @@ public function testSerializesHttpRequests() $this->assertSame('123', (string) $request->getBody()); } - /** - * @covers Aws\manifest() - */ public function testLoadsManifest() { $this->assertNotNull(Aws\manifest()); } - /** - * @covers Aws\manifest() - */ public function testServiceManifest() { $manifest = Aws\manifest('s3'); @@ -290,9 +252,6 @@ public function testServiceManifest() $this->assertEquals($data, $manifest); } - /** - * @covers Aws\manifest() - */ public function testAliasManifest() { $manifest = Aws\manifest('iotdataplane'); @@ -308,25 +267,19 @@ public function testAliasManifest() $this->assertEquals($data, $manifest); } - /** - * @covers Aws\manifest() - */ public function testInvalidManifest() { $this->expectException(\InvalidArgumentException::class); Aws\manifest('notarealservicename'); } - /** - * @covers Aws\is_valid_hostname() - * @dataProvider getHostnameTestCases - */ + #[DataProvider('getHostnameTestCases')] public function testValidatesHostnames($hostname, $expected) { $this->assertEquals($expected, Aws\is_valid_hostname($hostname)); } - public function getHostnameTestCases() + public static function getHostnameTestCases(): array { return [ ['a', true], @@ -368,17 +321,16 @@ public function getHostnameTestCases() } /** - * @covers Aws\is_valid_hostlabel() - * @dataProvider getHostlabelTestCases * @param string $label * @param bool $expected */ + #[DataProvider('getHostlabelTestCases')] public function testValidatesHostlabels($label, $expected) { $this->assertEquals($expected, Aws\is_valid_hostlabel($label)); } - public function getHostlabelTestCases() + public static function getHostlabelTestCases(): array { return [ ['us-west-2', true], @@ -404,10 +356,7 @@ public function getHostlabelTestCases() ]; } - /** - * @covers Aws\parse_ini_file() - * @dataProvider getIniFileTestCases - */ + #[DataProvider('getIniFileTestCases')] public function testParsesIniFile($ini, $expected) { $tmpFile = sys_get_temp_dir() . '/test.ini'; @@ -419,7 +368,7 @@ public function testParsesIniFile($ini, $expected) unlink($tmpFile); } - public function getIniFileTestCases() + public static function getIniFileTestCases(): array { return [ [ @@ -464,10 +413,7 @@ public function getIniFileTestCases() ]; } - /** - * @covers Aws\parse_ini_section_with_subsections() - * @dataProvider getIniFileServiceTestCases - */ + #[DataProvider('getIniFileServiceTestCases')] public function testParsesIniSectionsWithSubsections($ini, $expected) { $tmpFile = sys_get_temp_dir() . '/test.ini'; @@ -479,7 +425,7 @@ public function testParsesIniSectionsWithSubsections($ini, $expected) unlink($tmpFile); } - public function getIniFileServiceTestCases() + public static function getIniFileServiceTestCases(): array { return [ [ @@ -512,16 +458,15 @@ public function getIniFileServiceTestCases() /** * @param $array * @param $expected - * - * @dataProvider isAssociativeProvider */ + #[DataProvider('isAssociativeProvider')] public function testIsAssociative($array, $expected) { $result = Aws\is_associative($array); $this->assertEquals($expected, $result); } - public function isAssociativeProvider() + public static function isAssociativeProvider(): array { return [ [[], false], diff --git a/tests/Glacier/GlacierClientTest.php b/tests/Glacier/GlacierClientTest.php index 1e4688e121..8328a9420b 100644 --- a/tests/Glacier/GlacierClientTest.php +++ b/tests/Glacier/GlacierClientTest.php @@ -9,10 +9,9 @@ use GuzzleHttp\Psr7\NoSeekStream; use GuzzleHttp\Psr7; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Glacier\GlacierClient - */ +#[CoversClass(GlacierClient::class)] class GlacierClientTest extends TestCase { use UsesServiceTrait; diff --git a/tests/Glacier/MultipartUploaderTest.php b/tests/Glacier/MultipartUploaderTest.php index 023dd21d19..f528b6c2a4 100644 --- a/tests/Glacier/MultipartUploaderTest.php +++ b/tests/Glacier/MultipartUploaderTest.php @@ -7,10 +7,10 @@ use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Glacier\MultipartUploader - */ +#[CoversClass(MultipartUploader::class)] class MultipartUploaderTest extends TestCase { use UsesServiceTrait; @@ -23,9 +23,7 @@ public static function _tearDownAfterClass() @unlink(sys_get_temp_dir() . '/' . self::FILENAME); } - /** - * @dataProvider getTestCases - */ + #[DataProvider('getTestCases')] public function testGlacierMultipartUploadWorkflow( array $uploadOptions = [], ?StreamInterface $source = null, @@ -55,7 +53,7 @@ public function testGlacierMultipartUploadWorkflow( $this->assertSame('buzz', $result['fizz']); } - public function getTestCases() + public static function getTestCases(): array { $defaults = [ 'account_id' => 'foo', diff --git a/tests/Glacier/TreeHashTest.php b/tests/Glacier/TreeHashTest.php index 907faac89e..6acb842891 100644 --- a/tests/Glacier/TreeHashTest.php +++ b/tests/Glacier/TreeHashTest.php @@ -3,15 +3,11 @@ use Aws\Glacier\TreeHash; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +#[CoversClass(TreeHash::class)] class TreeHashTest extends TestCase { - /** - * @covers Aws\Glacier\TreeHash::__construct - * @covers Aws\Glacier\TreeHash::update - * @covers Aws\Glacier\TreeHash::addChecksum - * @covers Aws\Glacier\TreeHash::complete - */ public function testHashingIsHappeningCorrectly() { $chunks = [ @@ -37,9 +33,6 @@ public function testHashingIsHappeningCorrectly() $this->assertSame($expectedTreeHash, $hash->complete()); } - /** - * @covers Aws\Glacier\TreeHash::update - */ public function testCannotUpdateAfterHashCalculation() { $this->expectException(\LogicException::class); @@ -50,9 +43,6 @@ public function testCannotUpdateAfterHashCalculation() $hash->update('bar'); } - /** - * @covers Aws\Glacier\TreeHash::addChecksum - */ public function testCannotAddChecksumsAfterHashCalculation() { $this->expectException(\LogicException::class); @@ -63,9 +53,6 @@ public function testCannotAddChecksumsAfterHashCalculation() $hash->addChecksum('bar'); } - /** - * @covers Aws\Glacier\TreeHash::reset - */ public function testCanResetHash() { $hash = new TreeHash('sha256'); @@ -76,9 +63,6 @@ public function testCanResetHash() $this->assertSame(hash('sha256', 'foo', true), $hash->complete()); } - /** - * @covers Aws\Glacier\TreeHash::complete - */ public function testCanCalculateEmptyHash() { $hash = new TreeHash('sha256'); @@ -86,9 +70,6 @@ public function testCanCalculateEmptyHash() $this->assertSame(TreeHash::EMPTY_HASH, bin2hex($hash->complete())); } - /** - * @covers Aws\Glacier\TreeHash::complete - */ public function testCanCalculateHashForSingleZero() { $data = "0"; diff --git a/tests/Handler/Guzzle/HandlerTest.php b/tests/Handler/Guzzle/HandlerTest.php index fd047c868d..e8477af940 100644 --- a/tests/Handler/Guzzle/HandlerTest.php +++ b/tests/Handler/Guzzle/HandlerTest.php @@ -11,10 +11,9 @@ use GuzzleHttp\Psr7\Response; use GuzzleHttp\TransferStats; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Handler\Guzzle\GuzzleHandler - */ +#[CoversClass(GuzzleHandler::class)] class HandlerTest extends TestCase { public function testHandlerWorksWithSuccessfulRequest() diff --git a/tests/Handler/GuzzleV6/HandlerTest.php b/tests/Handler/GuzzleV6/HandlerTest.php index 1a2f0b64f7..b1251a8add 100644 --- a/tests/Handler/GuzzleV6/HandlerTest.php +++ b/tests/Handler/GuzzleV6/HandlerTest.php @@ -1,16 +1,23 @@ expectDeprecation(); - $this->expectDeprecationMessage( + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage( 'Using the "Aws\Handler\GuzzleV6\GuzzleHandler" class is deprecated, use "Aws\Handler\Guzzle\GuzzleHandler" instead.' ); $this->assertTrue(class_exists(\Aws\Handler\GuzzleV6\GuzzleHandler::class)); + restore_error_handler(); } } diff --git a/tests/HandlerListTest.php b/tests/HandlerListTest.php index f167309df3..f365cc2a73 100644 --- a/tests/HandlerListTest.php +++ b/tests/HandlerListTest.php @@ -6,11 +6,11 @@ use Aws\HandlerList; use Aws\Middleware; use GuzzleHttp\Psr7\Request; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversNothing; +use PHPUnit\Framework\TestCase; -/** - * @covers Aws\HandlerList - */ +#[CoversClass(HandlerList::class)] class HandlerListTest extends TestCase { public function testEnsuresHandlerIsSet() @@ -23,7 +23,9 @@ public function testEnsuresHandlerIsSet() public function testHandlerCanBeSetInCtor() { - $handler = function () {}; + $handler = function () { + $this->assertTrue(true); + }; $list = new HandlerList($handler); $this->assertTrue($list->hasHandler()); $this->assertSame($handler, $list->resolve()); @@ -31,7 +33,9 @@ public function testHandlerCanBeSetInCtor() public function testHandlerCanBeSetInSetter() { - $handler = function () {}; + $handler = function () { + $this->assertTrue(true); + }; $list = new HandlerList(); $list->setHandler($handler); $this->assertTrue($list->hasHandler()); @@ -47,7 +51,9 @@ public function testCanPrependWithName() public function testCanRemoveByInstance() { - $handler = function () {}; + $handler = function () { + $this->assertTrue(true); + }; $list = new HandlerList($handler); $middleware = function () { return function () {}; }; $list->appendInit($middleware); @@ -58,16 +64,19 @@ public function testCanRemoveByInstance() $this->assertSame($handler, $list->resolve()); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testIgnoreWhenNameNotFound() { $list = new HandlerList(); $list->remove('foo'); + $this->assertTrue(true); } public function testCanRemoveByName() { - $handler = function () {}; + $handler = function () { + $this->assertTrue(true); + }; $list = new HandlerList($handler); $middleware = function () { return function () {}; }; $list->appendInit($middleware, 'foo'); @@ -177,7 +186,9 @@ public function testMustExistByNameToPrependOrAppend() public function testCanInterposeMiddleware() { - $list = new HandlerList(function () {}); + $list = new HandlerList(function () { + $this->assertTrue(true); + }); $list->appendInit(Middleware::tap(function () {}), 'a'); $list->appendValidate(Middleware::tap(function () {}), 'b'); $list->appendBuild(Middleware::tap(function () {}), 'c'); diff --git a/tests/HasMonitoringEventsTraitTest.php b/tests/HasMonitoringEventsTraitTest.php index b32cf97248..82655e5ae3 100644 --- a/tests/HasMonitoringEventsTraitTest.php +++ b/tests/HasMonitoringEventsTraitTest.php @@ -3,14 +3,11 @@ use Aws\HasMonitoringEventsTrait; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; - -/** - * @covers \Aws\HasMonitoringEventsTrait - */ +#[CoversClass(HasMonitoringEventsTrait::class)] class HasMonitoringEventsTraitTest extends TestCase { - public function testAddsAndRetrievesMonitoringEvents() { $events = [ @@ -27,7 +24,7 @@ public function testAddsAndRetrievesMonitoringEvents() ]; $mock = $this->getMockForTrait(HasMonitoringEventsTrait::class); - foreach($events as $event) { + foreach ($events as $event) { $mock->appendMonitoringEvent($event); } @@ -35,5 +32,4 @@ public function testAddsAndRetrievesMonitoringEvents() $events, $mock->getMonitoringEvents() ); } - } diff --git a/tests/HashingStreamTest.php b/tests/HashingStreamTest.php index ddb4a86844..f092cc746d 100644 --- a/tests/HashingStreamTest.php +++ b/tests/HashingStreamTest.php @@ -5,10 +5,9 @@ use Aws\PhpHash; use Aws\HashingStream; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\HashingStream - */ +#[CoversClass(HashingStream::class)] class HashingStreamTest extends TestCase { public function testCanCreateRollingMd5() diff --git a/tests/HistoryTest.php b/tests/HistoryTest.php index 71e103dfc8..85a7103cc8 100644 --- a/tests/HistoryTest.php +++ b/tests/HistoryTest.php @@ -6,11 +6,10 @@ use Aws\History; use Aws\Exception\AwsException; use GuzzleHttp\Psr7\Request; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\History - */ +#[CoversClass(History::class)] class HistoryTest extends TestCase { public function testIsCountable() diff --git a/tests/IdempotencyTokenMiddlewareTest.php b/tests/IdempotencyTokenMiddlewareTest.php index c26c66dde6..30d2a08cad 100644 --- a/tests/IdempotencyTokenMiddlewareTest.php +++ b/tests/IdempotencyTokenMiddlewareTest.php @@ -10,10 +10,9 @@ use Aws\Command; use GuzzleHttp\Psr7\Request; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\IdempotencyTokenMiddleware - */ +#[CoversClass(IdempotencyTokenMiddleware::class)] class IdempotencyTokenMiddlewareTest extends TestCase { public function testAutoFillsMemberWithIdempotencyTrait() diff --git a/tests/Identity/S3Express/S3ExpressIdentityProviderTest.php b/tests/Identity/S3Express/S3ExpressIdentityProviderTest.php index a05a5e3b18..51e74d5518 100644 --- a/tests/Identity/S3Express/S3ExpressIdentityProviderTest.php +++ b/tests/Identity/S3Express/S3ExpressIdentityProviderTest.php @@ -6,10 +6,9 @@ use Aws\Result; use Aws\Test\UsesServiceTrait; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Identity\S3\S3ExpressIdentityProvider - */ +#[CoversClass(S3ExpressIdentityProvider::class)] class S3ExpressIdentityProviderTest extends TestCase { use UsesServiceTrait; @@ -28,13 +27,13 @@ private function getCredentialResultFromTimestamp($timestamp) ] ]); } - + public function testProvidesIdentity() { $expiration = time() + 5000; $client = $this->getTestClient('S3', []); $this->addMockResults($client, [ - $this->getCredentialResultFromTimestamp($expiration) + $this->getCredentialResultFromTimestamp($expiration) ]); $cmd = $client->getCommand('getObject', ['Bucket' => 'foo', 'Key' => 'bar']); $provider = new S3ExpressIdentityProvider( @@ -77,7 +76,6 @@ public function testRefreshesCache() $this->addMockResults($client, [ $this->getCredentialResultFromTimestamp($before), $this->getCredentialResultFromTimestamp($after), - ]); $cmd = $client->getCommand('getObject', ['Bucket' => 'foo', 'Key' => 'bar']); $provider = new S3ExpressIdentityProvider( diff --git a/tests/InputValidationMiddlewareTest.php b/tests/InputValidationMiddlewareTest.php index 3dd52a3b55..d52bcbb2b1 100644 --- a/tests/InputValidationMiddlewareTest.php +++ b/tests/InputValidationMiddlewareTest.php @@ -3,17 +3,15 @@ use Aws\Api\DateTimeResult; use Aws\AwsClient; -use Aws\EndpointParameterMiddleware; use Aws\HandlerList; use Aws\Api\Service; use Aws\InputValidationMiddleware; -use Cassandra\Time; use GuzzleHttp\Psr7\Request; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\InputValidationMiddleware - */ +#[CoversClass(InputValidationMiddleware::class)] class InputValidationMiddlewareTest extends TestCase { /** @@ -21,7 +19,7 @@ class InputValidationMiddlewareTest extends TestCase * * @return array */ - public function getInvalidEndpointExceptions() + public static function getInvalidEndpointExceptions(): array { return [ [''], @@ -36,7 +34,7 @@ public function getInvalidEndpointExceptions() * * @return array */ - public function getValidInputs() + public static function getValidInputs(): array { return [ ['existing data'], @@ -48,11 +46,7 @@ public function getValidInputs() ]; } - /** - * @dataProvider getInvalidEndpointExceptions - * - * @param $input - */ + #[DataProvider('getInvalidEndpointExceptions')] public function testThrowsExceptions($input) { $service = $this->generateTestService(); @@ -80,11 +74,7 @@ public function testThrowsExceptions($input) } } - /** - * @dataProvider getInvalidEndpointExceptions - * - * @param $input - */ + #[DataProvider('getInvalidEndpointExceptions')] public function testNoValidationWithoutInputList($input) { $service = $this->generateTestService(); @@ -103,11 +93,7 @@ public function testNoValidationWithoutInputList($input) self::assertSame($result, "success"); } - /** - * @dataProvider getValidInputs - * - * @param $input - */ + #[DataProvider('getValidInputs')] public function testPassingValidations($input) { $service = $this->generateTestService(); diff --git a/tests/Integ/GuzzleStreamHandlerTest.php b/tests/Integ/GuzzleStreamHandlerTest.php index 19f9be799c..e34f3b75ce 100644 --- a/tests/Integ/GuzzleStreamHandlerTest.php +++ b/tests/Integ/GuzzleStreamHandlerTest.php @@ -2,8 +2,10 @@ namespace Aws\Test\Integ; use GuzzleHttp\Handler\StreamHandler; +use PHPUnit\Framework\Attributes\CoversNothing; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +#[CoversNothing] class GuzzleStreamHandlerTest extends TestCase { use IntegUtils; diff --git a/tests/JsonCompilerTest.php b/tests/JsonCompilerTest.php index bca34d2c4f..3d8d706dc9 100644 --- a/tests/JsonCompilerTest.php +++ b/tests/JsonCompilerTest.php @@ -3,10 +3,9 @@ use Aws\JsonCompiler; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\JsonCompiler - */ +#[CoversClass(JsonCompiler::class)] class JsonCompilerTest extends TestCase { private $models; diff --git a/tests/Lambda/LambdaClientTest.php b/tests/Lambda/LambdaClientTest.php index f484a14da1..d0ec733a77 100644 --- a/tests/Lambda/LambdaClientTest.php +++ b/tests/Lambda/LambdaClientTest.php @@ -5,13 +5,15 @@ use Aws\Result; use DMS\PHPUnitExtensions\ArraySubset\ArraySubsetAsserts; use GuzzleHttp\Promise; +use PHPUnit\Framework\Attributes\CoversClass; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +#[CoversClass(LambdaClient::class)] class LambdaClientTest extends TestCase { use ArraySubsetAsserts; - function testsAddsDefaultCurlOptions() + public function testsAddsDefaultCurlOptions() { if (!extension_loaded('curl')) { $this->markTestSkipped('Test skipped on no cURL extension'); @@ -37,4 +39,4 @@ function testsAddsDefaultCurlOptions() $client->listFunctions(); } -} \ No newline at end of file +} diff --git a/tests/LexModelsV2/LexModelsV2ClientTest.php b/tests/LexModelsV2/LexModelsV2ClientTest.php index 0eeb5177db..c60ca0a949 100644 --- a/tests/LexModelsV2/LexModelsV2ClientTest.php +++ b/tests/LexModelsV2/LexModelsV2ClientTest.php @@ -8,10 +8,9 @@ use GuzzleHttp\Psr7\NoSeekStream; use GuzzleHttp\Psr7; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\LexModelsV2\LexModelsV2Client - */ +#[CoversClass(LexModelsV2Client::class)] class LexModelsV2ClientTest extends TestCase { use UsesServiceTrait; diff --git a/tests/LruArrayCacheTest.php b/tests/LruArrayCacheTest.php index bf50d8d9c9..443a222c30 100644 --- a/tests/LruArrayCacheTest.php +++ b/tests/LruArrayCacheTest.php @@ -3,10 +3,9 @@ use Aws\LruArrayCache; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\LruArrayCache - */ +#[CoversClass(LruArrayCache::class)] class LruArrayCacheTest extends TestCase { public function testSetRemoveAndRetrieve() diff --git a/tests/MachineLearning/MachineLearningClientTest.php b/tests/MachineLearning/MachineLearningClientTest.php index fe6f767af1..7a36dba003 100644 --- a/tests/MachineLearning/MachineLearningClientTest.php +++ b/tests/MachineLearning/MachineLearningClientTest.php @@ -6,10 +6,9 @@ use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7\Uri; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\MachineLearning\MachineLearningClient - */ +#[CoversClass(MachineLearningClient::class)] class MachineLearningClientTest extends TestCase { use UsesServiceTrait; diff --git a/tests/MetricsBuilderTest.php b/tests/MetricsBuilderTest.php index 8e4fc703c9..cbda4c0e08 100644 --- a/tests/MetricsBuilderTest.php +++ b/tests/MetricsBuilderTest.php @@ -7,7 +7,10 @@ use Aws\Middleware; use Psr\Http\Message\RequestInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(MetricsBuilder::class)] class MetricsBuilderTest extends TestCase { public function testAppendMetrics() @@ -42,13 +45,8 @@ public function testEncodeMetrics() public function testConstraintsAppendToMetricsSize() { + set_error_handler(static function ( $errno, $errstr ) {}); try { - set_error_handler( - static function ( $errno, $errstr ) { - // Mute warning - }, - E_ALL - ); $metricsBuilder = new MetricsBuilder(); $firstMetric = str_repeat("*", 1024); $metricsBuilder->append($firstMetric); @@ -70,7 +68,9 @@ public function testGetMetricsBuilderFromCommand() public function testAppendMetricsCaptureMiddleware() { - $handlerList = new HandlerList(function (){}); + $handlerList = new HandlerList(function (){ + $this->assertTrue(true); + }); $metric = "Foo"; // It should be appended into the build step MetricsBuilder::appendMetricsCaptureMiddleware( @@ -103,10 +103,9 @@ function ( * @param array $args * @param string $expectedMetrics * - * @dataProvider resolveAndAppendFromArgsProvider - * * @return void */ + #[DataProvider('resolveAndAppendFromArgsProvider')] public function testResolveAndAppendFromArgs( array $args, string $expectedMetrics, @@ -122,7 +121,7 @@ public function testResolveAndAppendFromArgs( * * @return array[] */ - public function resolveAndAppendFromArgsProvider(): array + public static function resolveAndAppendFromArgsProvider(): array { return [ 'endpoint_override' => [ @@ -175,8 +174,11 @@ public function resolveAndAppendFromArgsProvider(): array * * @return void */ - public function testAppendMetricsCaptureMiddlewareJustOnce(): void { - $handlerList = new HandlerList(function (){}); + public function testAppendMetricsCaptureMiddlewareJustOnce(): void + { + $handlerList = new HandlerList(function (){ + $this->assertTrue(true); + }); MetricsBuilder::appendMetricsCaptureMiddleware( $handlerList, 'test' diff --git a/tests/MiddlewareTest.php b/tests/MiddlewareTest.php index 1cfd67ac71..7b3a3da995 100644 --- a/tests/MiddlewareTest.php +++ b/tests/MiddlewareTest.php @@ -21,10 +21,10 @@ use GuzzleHttp\Promise; use Psr\Http\Message\RequestInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Middleware - */ +#[CoversClass(Middleware::class)] class MiddlewareTest extends TestCase { public function set_up() @@ -394,17 +394,39 @@ function (AwsException $e) { $promise->wait(); } - /** - * @dataProvider recursionDetectionProvider - * - * @param $mockHandler - * @param $name - * @param $trace - */ - public function testRecursionDetection($mockHandler, $name, $trace) + #[DataProvider('recursionDetectionProvider')] + public function testRecursionDetection( + ?string $functionName, + ?string $traceId, + bool $traceHeaderExpected, + string $traceHeaderExpectedValue, + ) { - $name !== null && putenv("AWS_LAMBDA_FUNCTION_NAME={$name}"); - $trace !== null && putenv("_X_AMZN_TRACE_ID={$trace}"); + $mockHandler = function (CommandInterface $command, RequestInterface $request) + use ($traceHeaderExpected, $traceHeaderExpectedValue) { + static $traceHeaderName = 'X-Amzn-Trace-Id'; + if ($traceHeaderExpected) { + $this->assertTrue($request->hasHeader($traceHeaderName)); + $this->assertEquals( + $traceHeaderExpectedValue, + $request->getHeaderLine($traceHeaderName) + ); + } else { + $this->assertNotTrue($request->hasHeader($traceHeaderName)); + } + + return Promise\Create::promiseFor( + new Result(['@metadata' => ['statusCode' => 200]]) + ); + }; + + if ($functionName !== null) { + putenv("AWS_LAMBDA_FUNCTION_NAME={$functionName}"); + } + if ($traceId !== null) { + putenv("_X_AMZN_TRACE_ID={$traceId}"); + } + $list = new HandlerList(); $list->setHandler($mockHandler); $list->appendBuild(Middleware::recursionDetection()); @@ -414,63 +436,102 @@ public function testRecursionDetection($mockHandler, $name, $trace) putenv('_X_AMZN_TRACE_ID'); } - public function recursionDetectionProvider() + public static function recursionDetectionProvider(): \Generator { - $addHeaderMock = function ($command, $request) { - $this->assertTrue($request->hasHeader('X-Amzn-Trace-Id')); - $headerValue = $request->getHeaders()['X-Amzn-Trace-Id'][0]; - $this->assertEquals('bar', $headerValue); - return Promise\Create::promiseFor( - new Result(['@metadata' => ['statusCode' => 200]]) - ); - }; + $cases = [ + 'add_header' => [ + 'function_name' => 'foo', + 'trace_id' => 'bar', + 'trace_header_expected' => true, + 'trace_header_expected_value' => 'bar', + ], + 'add_header_with_encoding' => [ + 'function_name' => 'foo', + 'trace_id' => 'bar\ebaz', + 'trace_header_expected' => true, + 'trace_header_expected_value' => 'bar%1Bbaz', + ], + 'add_header_with_no_encoding' => [ + 'function_name' => 'foo', + 'trace_id' => 'bar=;:+&[]{}"\',baz', + 'trace_header_expected' => true, + 'trace_header_expected_value' => 'bar=;:+&[]{}"\',baz', + ], + 'dont_add_header' => [ + 'function_name' => '', + 'trace_id' => 'bar', + 'trace_header_expected' => false, + 'trace_header_expected_value' => '', + ], + 'dont_add_header_2' => [ + 'function_name' => 'foo', + 'trace_id' => '', + 'trace_header_expected' => false, + 'trace_header_expected_value' => '', + ], + 'dont_add_header_3' => [ + 'function_name' => '', + 'trace_id' => '', + 'trace_header_expected' => false, + 'trace_header_expected_value' => '', + ], + 'dont_add_header_4' => [ + 'function_name' => null, + 'trace_id' => 'bar', + 'trace_header_expected' => false, + 'trace_header_expected_value' => '', + ], + 'dont_add_header_5' => [ + 'function_name' => 'foo', + 'trace_id' => null, + 'trace_header_expected' => false, + 'trace_header_expected_value' => '', + ], + 'dont_add_header_6' => [ + 'function_name' => null, + 'trace_id' => null, + 'trace_header_expected' => false, + 'trace_header_expected_value' => '', + ], + ]; - $addHeaderWithEncodingMock = function ($command, $request) { - $this->assertTrue($request->hasHeader('X-Amzn-Trace-Id')); - $headerValue = $request->getHeaders()['X-Amzn-Trace-Id'][0]; - $this->assertEquals('bar%1Bbaz', $headerValue); - return Promise\Create::promiseFor( - new Result(['@metadata' => ['statusCode' => 200]]) - ); - }; + foreach ($cases as $key => $case) { + yield $key => $case; + } + } - $addHeaderWithNoEncodingMock = function ($command, $request) { - $this->assertTrue($request->hasHeader('X-Amzn-Trace-Id')); - $headerValue = $request->getHeaders()['X-Amzn-Trace-Id'][0]; - $this->assertEquals('bar=;:+&[]{}"\',baz', $headerValue); - return Promise\Create::promiseFor( - new Result(['@metadata' => ['statusCode' => 200]]) + public function testRecursionDetectionNotOverrideTraceHeaderIfExists() + { + $mockHandler = function (CommandInterface $command, RequestInterface $request) { + static $traceHeaderName = 'X-Amzn-Trace-Id'; + $this->assertTrue($request->hasHeader($traceHeaderName)); + $this->assertEquals( + 'already_exists', + $request->getHeaderLine($traceHeaderName) ); - }; - $dontAddHeaderMock = function ($command, $request) { - $this->assertFalse($request->hasHeader('X-Amzn-Trace-Id')); return Promise\Create::promiseFor( new Result(['@metadata' => ['statusCode' => 200]]) ); }; - $headerAlreadyExistsMock = function ($command, $request) { - $request = $request->withHeader('X-Amzn-Trace-Id', 'baz'); - $headerValue = $request->getHeaders()['X-Amzn-Trace-Id'][0]; - $this->assertNotEquals('bar', $headerValue); - return Promise\Create::promiseFor( - new Result(['@metadata' => ['statusCode' => 200]]) - ); - }; + putenv("AWS_LAMBDA_FUNCTION_NAME=foo"); + putenv("_X_AMZN_TRACE_ID=bazz"); - return [ - [$addHeaderMock, 'foo', 'bar'], - [$addHeaderWithEncodingMock, 'foo', 'bar\ebaz'], - [$addHeaderWithNoEncodingMock, 'foo', 'bar=;:+&[]{}"\',baz'], - [$dontAddHeaderMock, '', 'bar'], - [$dontAddHeaderMock, 'foo', ''], - [$dontAddHeaderMock, '', ''], - [$dontAddHeaderMock, null, 'bar'], - [$dontAddHeaderMock, 'foo', null], - [$dontAddHeaderMock, null, null], - [$headerAlreadyExistsMock, 'foo', 'bar'] - ]; + $list = new HandlerList(); + $list->setHandler($mockHandler); + $list->appendBuild(function (callable $handler) { + return function (CommandInterface $command, RequestInterface $request) + use ($handler) { + $request = $request->withHeader('X-Amzn-Trace-Id', 'already_exists'); + return $handler($command, $request); + }; + }); + $list->appendBuild(Middleware::recursionDetection()); + $handler = $list->resolve(); + $handler(new Command('foo'), new Request('GET', 'http://exmaple.com')); + putenv('AWS_LAMBDA_FUNCTION_NAME'); + putenv('_X_AMZN_TRACE_ID'); } /** diff --git a/tests/MockHandlerTest.php b/tests/MockHandlerTest.php index dd6f04e2de..be16dcff82 100644 --- a/tests/MockHandlerTest.php +++ b/tests/MockHandlerTest.php @@ -10,10 +10,9 @@ use GuzzleHttp\Psr7\Request; use GuzzleHttp\Promise; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\MockHandler - */ +#[CoversClass(MockHandler::class)] class MockHandlerTest extends TestCase { public function testValidatesEachResult() diff --git a/tests/MultiRegionClientTest.php b/tests/MultiRegionClientTest.php index 419ca63f90..19a7b14453 100644 --- a/tests/MultiRegionClientTest.php +++ b/tests/MultiRegionClientTest.php @@ -14,7 +14,10 @@ use GuzzleHttp\Psr7\Response; use Psr\Http\Message\RequestInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(MultiRegionClient::class)] class MultiRegionClientTest extends TestCase { /** @var MultiRegionClient */ @@ -109,12 +112,7 @@ public function testProxiesArbitraryCallsToRegionalizedClient() $this->instance->baz(['foo' => 'bar']); } - /** - * @dataProvider clientInterfaceMethodProvider - * - * @param string $method - * @param array $args - */ + #[DataProvider('clientInterfaceMethodProvider')] public function testProxiesCallsToRegionalizedClient($method, array $args) { $expectation = $this->mockRegionalClient->expects($this->once()) @@ -124,7 +122,7 @@ public function testProxiesCallsToRegionalizedClient($method, array $args) call_user_func_array([$this->instance, $method], $args); } - public function clientInterfaceMethodProvider() + public static function clientInterfaceMethodProvider(): array { return [ ['getConfig', ['someOption']], @@ -169,12 +167,8 @@ public function testUseCustomHandler() $response = $s3->listBuckets(); $this->assertEquals('bar', $response['foo']); - if (method_exists($this, 'expectException')) { - $this->expectException(AwsException::class); - $this->expectExceptionMessage('Mock exception'); - } else { - $this->setExpectedException(AwsException::class); - } + $this->expectException(AwsException::class); + $this->expectExceptionMessage('Mock exception'); $s3->listBuckets(); } } diff --git a/tests/Multipart/AbstractUploaderTest.php b/tests/Multipart/AbstractUploaderTest.php index f92331c294..e53404c2e7 100644 --- a/tests/Multipart/AbstractUploaderTest.php +++ b/tests/Multipart/AbstractUploaderTest.php @@ -4,16 +4,17 @@ use Aws\Command; use Aws\Exception\AwsException; use Aws\Exception\MultipartUploadException; +use Aws\Multipart\AbstractUploader; use Aws\Multipart\UploadState; use Aws\Result; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Multipart\AbstractUploader - */ +#[CoversClass(AbstractUploader::class)] class AbstractUploaderTest extends TestCase { use UsesServiceTrait; @@ -187,13 +188,7 @@ public function testCanSetSourceFromFilenameIfExists() $this->assertInstanceOf('InvalidArgumentException', $exception); } - /** - * @param bool $seekable - * @param UploadState $state - * @param array $expectedBodies - * - * @dataProvider getPartGeneratorTestCases - */ + #[DataProvider('getPartGeneratorTestCases')] public function testCommandGeneratorYieldsExpectedUploadCommands( $seekable, UploadState $state, @@ -222,7 +217,7 @@ public function testCommandGeneratorYieldsExpectedUploadCommands( $this->assertEquals($expectedBodies, $actualBodies); } - public function getPartGeneratorTestCases() + public static function getPartGeneratorTestCases(): array { $expected = [ 1 => 'AA', diff --git a/tests/Multipart/UploadStateTest.php b/tests/Multipart/UploadStateTest.php index 0d810b0d20..58609dd50f 100644 --- a/tests/Multipart/UploadStateTest.php +++ b/tests/Multipart/UploadStateTest.php @@ -3,10 +3,10 @@ use Aws\Multipart\UploadState; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Multipart\UploadState - */ +#[CoversClass(UploadState::class)] class UploadStateTest extends TestCase { public function testCanManageStatusAndUploadId() @@ -78,9 +78,7 @@ public function testEmptyUploadStateOutputWithConfigFalse() $this->expectOutputString(''); } - /** - * @dataProvider getDisplayProgressCases - */ + #[DataProvider('getDisplayProgressCases')] public function testGetDisplayProgressPrintsProgress( $totalSize, $totalUploaded, @@ -93,7 +91,7 @@ public function testGetDisplayProgressPrintsProgress( $this->expectOutputString($progressBar); } - public function getDisplayProgressCases() + public static function getDisplayProgressCases(): array { $progressBar = ["Transfer initiated...\n| | 0.0%\n", "|== | 12.5%\n", @@ -173,9 +171,7 @@ public function getDisplayProgressCases() ]; } - /** - * @dataProvider getThresholdCases - */ + #[DataProvider('getThresholdCases')] public function testUploadThresholds($totalSize) { $state = new UploadState([]); @@ -185,7 +181,7 @@ public function testUploadThresholds($totalSize) $this->assertCount(9, $threshold); } - public function getThresholdCases() + public static function getThresholdCases(): array { return [ [0], @@ -194,9 +190,7 @@ public function getThresholdCases() ]; } - /** - * @dataProvider getInvalidIntCases - */ + #[DataProvider('getInvalidIntCases')] public function testSetProgressThresholdsThrowsException($totalSize) { $state = new UploadState([]); @@ -206,9 +200,7 @@ public function testSetProgressThresholdsThrowsException($totalSize) $state->setProgressThresholds($totalSize); } - /** - * @dataProvider getInvalidIntCases - */ + #[DataProvider('getInvalidIntCases')] public function testDisplayProgressThrowsException($totalUploaded) { $state = new UploadState([]); @@ -217,7 +209,7 @@ public function testDisplayProgressThrowsException($totalUploaded) $state->getDisplayProgress($totalUploaded); } - public function getInvalidIntCases() + public static function getInvalidIntCases(): array { return [ [''], diff --git a/tests/Neptune/NeptuneClientTest.php b/tests/Neptune/NeptuneClientTest.php index 9d7daac579..0362ea7b7a 100644 --- a/tests/Neptune/NeptuneClientTest.php +++ b/tests/Neptune/NeptuneClientTest.php @@ -7,11 +7,11 @@ use Aws\Result; use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; require_once __DIR__ . '/../Signature/sig_hack.php'; -/** - * @covers Aws\Neptune\NeptuneClient - */ +#[CoversClass(NeptuneClient::class)] class NeptuneClientTest extends TestCase { public static function set_up_before_class() @@ -26,7 +26,7 @@ public static function tear_down_after_class() $_SERVER['formatAwsTime'] = null; } - public function neptunePresignMethodProvider() + public static function neptunePresignMethodProvider(): array { return [ ['CopyDBClusterSnapshot', ['SourceDBClusterSnapshotIdentifier' => 'arn:aws:rds:us-east-1:123456789012:cluster-snapshot:source-db-cluster-snapshot', 'TargetDBClusterSnapshotIdentifier' => 'target-db-cluster-snapshot'], null, null, null, null], @@ -38,15 +38,7 @@ public function neptunePresignMethodProvider() ]; } - /** - * @dataProvider neptunePresignMethodProvider - * - * @param string $functionName - * @param string $presignedUrl - * @param string $sourceRegion - * @param string $expectedUrl - * @param string $expectedSignature - */ + #[DataProvider('neptunePresignMethodProvider')] public function testCorrectPresignNeptuneUrls( $functionName, $functionArgs, @@ -89,4 +81,3 @@ function ( call_user_func([$neptune, $functionName], $functionArgs); } } - diff --git a/tests/PhpHashTest.php b/tests/PhpHashTest.php index 461a455bd2..0acee2efe1 100644 --- a/tests/PhpHashTest.php +++ b/tests/PhpHashTest.php @@ -3,10 +3,9 @@ use Aws\PhpHash; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\PhpHash - */ +#[CoversClass(PhpHash::class)] class PhpHashTest extends TestCase { public function testHashesData() diff --git a/tests/Polly/PollyClientTest.php b/tests/Polly/PollyClientTest.php index 24ee4883f4..f4dceb8b57 100644 --- a/tests/Polly/PollyClientTest.php +++ b/tests/Polly/PollyClientTest.php @@ -4,10 +4,9 @@ use Aws\Credentials\Credentials; use Aws\Polly\PollyClient; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Polly\PollyClient - */ +#[CoversClass(PollyClient::class)] class PollyClientTest extends TestCase { public function testCanGeneratePreSignedUrlForSynthesizeSpeech() diff --git a/tests/PresignUrlMiddlewareTest.php b/tests/PresignUrlMiddlewareTest.php index f1de50fee3..a713bd8f1d 100644 --- a/tests/PresignUrlMiddlewareTest.php +++ b/tests/PresignUrlMiddlewareTest.php @@ -8,10 +8,10 @@ use Aws\Result; use Psr\Http\Message\RequestInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\PresignUrlMiddleware - */ +#[CoversClass(PresignUrlMiddleware::class)] class PresignUrlMiddlewareTest extends TestCase { use UsesServiceTrait; @@ -102,15 +102,7 @@ public function testNoPreSignedUrlWhenDifferentSourceRegionRequired() ]); } - /** - * @param string $parameter - * @param string $value - * @param string $expected - * - * @dataProvider extraQueryParamsProvider - * - * @return void - */ + #[DataProvider('extraQueryParamsProvider')] public function testExtraQueryParametersAreURLEncoded( string $parameter, string $value, @@ -132,7 +124,7 @@ public function testExtraQueryParametersAreURLEncoded( return new Result; }, ]); - + $ec2->getHandlerList()->prependInit( PresignUrlMiddleware::wrap($ec2, $ec2->getEndpointProvider(), [ 'operations' => ['CopySnapshot'], @@ -140,7 +132,7 @@ public function testExtraQueryParametersAreURLEncoded( 'extra_query_params' => ['CopySnapshot' => [$parameter]] ]) ); - + $ec2->copySnapshot([ 'SourceRegion' => 'eu-west-1', 'SourceSnapshotId' => 'foo', @@ -148,10 +140,7 @@ public function testExtraQueryParametersAreURLEncoded( ]); } - /** - * @return array[] - */ - public function extraQueryParamsProvider(): array + public static function extraQueryParamsProvider(): array { return [ 'simple_parameter' => [ @@ -187,4 +176,3 @@ public function extraQueryParamsProvider(): array ]; } } - diff --git a/tests/Psr16CacheAdapterTest.php b/tests/Psr16CacheAdapterTest.php index 337d5db31e..67f52ed769 100644 --- a/tests/Psr16CacheAdapterTest.php +++ b/tests/Psr16CacheAdapterTest.php @@ -2,9 +2,12 @@ namespace Aws\Test; use Aws\Psr16CacheAdapter; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; use Psr\SimpleCache\CacheInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +#[CoversClass(Psr16CacheAdapter::class)] class Psr16CacheAdapterTest extends TestCase { /** @var CacheInterface|\PHPUnit_Framework_MockObject_MockObject $wrappedCache */ @@ -18,12 +21,7 @@ public function set_up() $this->instance = new Psr16CacheAdapter($this->wrapped); } - /** - * @dataProvider cacheDataProvider - * - * @param string $key - * @param mixed $value - */ + #[DataProvider('cacheDataProvider')] public function testProxiesGetCallsToPsrCache($key, $value) { $this->wrapped->expects($this->once()) @@ -34,13 +32,7 @@ public function testProxiesGetCallsToPsrCache($key, $value) $this->assertSame($value, $this->instance->get($key)); } - /** - * @dataProvider cacheDataProvider - * - * @param string $key - * @param mixed $value - * @param int|\DateInterval $ttl - */ + #[DataProvider('cacheDataProvider')] public function testProxiesSetCallsToPsrCache($key, $value, $ttl) { $this->wrapped->expects($this->once()) @@ -51,11 +43,7 @@ public function testProxiesSetCallsToPsrCache($key, $value, $ttl) $this->instance->set($key, $value, $ttl); } - /** - * @dataProvider cacheDataProvider - * - * @param string $key - */ + #[DataProvider('cacheDataProvider')] public function testProxiesRemoveCallsToPsrCache($key) { $this->wrapped->expects($this->once()) @@ -66,7 +54,7 @@ public function testProxiesRemoveCallsToPsrCache($key) $this->instance->remove($key); } - public function cacheDataProvider() + public static function cacheDataProvider(): array { return [ ['foo', 'bar', 300], diff --git a/tests/PsrCacheAdapterTest.php b/tests/PsrCacheAdapterTest.php index 9b1911c097..dc464fde6b 100644 --- a/tests/PsrCacheAdapterTest.php +++ b/tests/PsrCacheAdapterTest.php @@ -2,10 +2,13 @@ namespace Aws\Test; use Aws\PsrCacheAdapter; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; use Psr\Cache\CacheItemInterface; use Psr\Cache\CacheItemPoolInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +#[CoversClass(PsrCacheAdapter::class)] class PsrCacheAdapterTest extends TestCase { @@ -21,11 +24,10 @@ public function set_up() } /** - * @dataProvider cacheDataProvider - * * @param string $key * @param mixed $value */ + #[DataProvider('cacheDataProvider')] public function testProxiesGetCallsToPsrCache($key, $value) { $item = $this->getMockBuilder(CacheItemInterface::class)->getMock(); @@ -45,12 +47,11 @@ public function testProxiesGetCallsToPsrCache($key, $value) } /** - * @dataProvider cacheDataProvider - * * @param string $key * @param mixed $value * @param int|\DateInterval $ttl */ + #[DataProvider('cacheDataProvider')] public function testProxiesSetCallsToPsrCache($key, $value, $ttl) { $item = $this->getMockBuilder(CacheItemInterface::class)->getMock(); @@ -76,10 +77,9 @@ public function testProxiesSetCallsToPsrCache($key, $value, $ttl) } /** - * @dataProvider cacheDataProvider - * * @param string $key */ + #[DataProvider('cacheDataProvider')] public function testProxiesRemoveCallsToPsrCache($key) { $this->wrapped->expects($this->once()) @@ -90,7 +90,10 @@ public function testProxiesRemoveCallsToPsrCache($key) $this->instance->remove($key); } - public function cacheDataProvider() + /** + * @return array> + */ + public static function cacheDataProvider(): array { return [ ['foo', 'bar', 300], diff --git a/tests/QueryCompatibleInputMiddlewareTest.php b/tests/QueryCompatibleInputMiddlewareTest.php index 6ac662b65b..967c129d9d 100644 --- a/tests/QueryCompatibleInputMiddlewareTest.php +++ b/tests/QueryCompatibleInputMiddlewareTest.php @@ -8,44 +8,38 @@ use Aws\MockHandler; use Aws\Result; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\QueryCompatibleInputMiddleware - */ +#[CoversClass(\Aws\QueryCompatibleInputMiddleware::class)] class QueryCompatibleInputMiddlewareTest extends TestCase { - /** - * @dataProvider getInputs() - * - * @param $inputParam - * @param $inputValue - * @param $expected - * @param $type - */ + #[DataProvider('getInputsDataProvider')] public function testEmitsWarning($inputParam, $inputValue, $expected, $type) { - $this->expectWarning(); - $this->expectWarningMessage( + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage( "The provided type for `{$inputParam}` value was `" . (gettype($inputValue) === 'double' ? 'float' : gettype($inputValue)) . "`. The modeled type is `{$type}`." ); - $service = $this->generateTestService(); - $client = $this->generateTestClient($service); - $command = $client->getCommand( - 'FooOperation', - [$inputParam => $inputValue] - ); - $client->execute($command); + set_error_handler(function ($errno, $errstr) { + throw new \RuntimeException($errstr, $errno); + }); + try { + $service = $this->generateTestService(); + $client = $this->generateTestClient($service); + $command = $client->getCommand( + 'FooOperation', + [$inputParam => $inputValue] + ); + $client->execute($command); + } finally { + restore_error_handler(); + } } - /** - * @dataProvider getInputs() - * - * @param $inputParam - * @param $inputValue - * @param $expected - */ + #[DataProvider('getInputsDataProvider')] public function testAppliesMiddlewareAndCastsValues($inputParam, $inputValue, $expected) { $service = $this->generateTestService(); @@ -68,7 +62,7 @@ function (Command $command) use ($inputParam, $expected) { * * @return array */ - public function getInputs() + public static function getInputsDataProvider(): array { return [ ['IntParam', '10', 10, 'integer'], diff --git a/tests/Rds/AuthTokenGeneratorTest.php b/tests/Rds/AuthTokenGeneratorTest.php index c3bfdef93c..4ffdb1dca9 100644 --- a/tests/Rds/AuthTokenGeneratorTest.php +++ b/tests/Rds/AuthTokenGeneratorTest.php @@ -5,10 +5,10 @@ use Aws\Rds\AuthTokenGenerator; use GuzzleHttp\Promise; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Rds\AuthTokenGenerator - */ +#[CoversClass(AuthTokenGenerator::class)] class AuthTokenGeneratorTest extends TestCase { public function testCanCreateAuthTokenWthCredentialInstance() @@ -56,7 +56,7 @@ public function testCanCreateAuthTokenWthCredentialProvider() $this->assertStringContainsString('Action=connect', $token); } - public function lifetimeProvider() + public static function lifetimeProvider(): array { return [ [1], @@ -66,11 +66,7 @@ public function lifetimeProvider() ]; } - /** - * @dataProvider lifetimeProvider - * - * @param $lifetime - */ + #[DataProvider('lifetimeProvider')] public function testCanCreateAuthTokenWthNonDefaultLifetime($lifetime) { $creds = new Credentials('foo', 'bar', 'baz'); @@ -91,7 +87,7 @@ public function testCanCreateAuthTokenWthNonDefaultLifetime($lifetime) $this->assertStringContainsString('Action=connect', $token); } - public function lifetimeFailureProvider() + public static function lifetimeFailureProvider(): array { return [ [0], @@ -104,11 +100,7 @@ public function lifetimeFailureProvider() ]; } - /** - * @dataProvider lifetimeFailureProvider - * - * @param $lifetime - */ + #[DataProvider('lifetimeFailureProvider')] public function testThrowsExceptionWithInvalidLifetime($lifetime) { $this->expectExceptionMessage("Lifetime must be a positive number less than or equal to 15, was"); diff --git a/tests/Rds/RdsClientTest.php b/tests/Rds/RdsClientTest.php index ca862cc726..847265a98e 100644 --- a/tests/Rds/RdsClientTest.php +++ b/tests/Rds/RdsClientTest.php @@ -8,11 +8,11 @@ use Aws\Result; use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; require_once __DIR__ . '/../Signature/sig_hack.php'; -/** - * @covers Aws\Rds\RdsClient - */ +#[CoversClass(RdsClient::class)] class RdsClientTest extends TestCase { public static function set_up_before_class() @@ -26,7 +26,7 @@ public static function tear_down_after_class() $_SERVER['aws_time'] = null; $_SERVER['formatAwsTime'] = null; } - + public function testAddsCopySnapshotMiddleware() { $rds = new RdsClient([ @@ -53,7 +53,7 @@ function ($command, $request) { ]); } - public function rdsPresignMethodProvider() + public static function rdsPresignMethodProvider(): array { return [ ['copyDBSnapshot', ['SourceDBSnapshotIdentifier' => 'arn:aws:rds:us-east-1:123456789012:snapshot:source-db-snapshot', 'TargetDBSnapshotIdentifier' => 'target-db-snapshot'], null, null, null, null], @@ -71,15 +71,7 @@ public function rdsPresignMethodProvider() ]; } - /** - * @dataProvider rdsPresignMethodProvider - * - * @param string $functionName - * @param string $presignedUrl - * @param string $sourceRegion - * @param string $expectedUrl - * @param string $expectedSignature - */ + #[DataProvider('rdsPresignMethodProvider')] public function testCorrectPresignRdsUrls( $functionName, $functionArgs, @@ -119,4 +111,3 @@ public function testCorrectPresignRdsUrls( call_user_func([$rds, $functionName], $functionArgs); } } - diff --git a/tests/RequestCompression/RequestCompressionMiddlewareTest.php b/tests/RequestCompression/RequestCompressionMiddlewareTest.php index 93f8e4237c..4420585251 100644 --- a/tests/RequestCompression/RequestCompressionMiddlewareTest.php +++ b/tests/RequestCompression/RequestCompressionMiddlewareTest.php @@ -8,7 +8,10 @@ use GuzzleHttp\Promise\FulfilledPromise; use GuzzleHttp\Psr7\Response; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(RequestCompressionMiddleware::class)] class RequestCompressionMiddlewareTest extends TestCase { public function testCompressesRequestByDefault() @@ -46,17 +49,24 @@ public function testDoesNotCompressRequestWhenConfigured() $list->appendSign(Middleware::tap(function($cmd, $req) { $body = $req->getBody()->getContents(); $this->assertEmpty($req->getHeader('content-encoding')); - $this->expectWarning(); + $this->expectException(\RuntimeException::class); + set_error_handler(function ($errno, $errstr) { + throw new \RuntimeException($errstr, $errno); + }); gzdecode($body); })); - $client->putMetricData([ - 'MetricData' => $metricData, - 'Namespace' => 'foo' - ]); + try { + $client->putMetricData([ + 'MetricData' => $metricData, + 'Namespace' => 'foo' + ]); + } finally { + restore_error_handler(); + } } - public function specificSizeProvider() + public static function specificSizeProvider(): array { return [ [60, 0, 65], @@ -66,13 +76,7 @@ public function specificSizeProvider() ]; } - /** - * @dataProvider specificSizeProvider - * - * @param $minSize - * @param $numMetricData - * @param $expectedBodySize - */ + #[DataProvider('specificSizeProvider')] public function testCompressesRequestAtSpecificSize($minSize, $numMetricData, $expectedBodySize) { $service = $this->generateTestService(); @@ -140,15 +144,22 @@ public function testCommandLevelDisableRequestCompressionOverrides() $list->appendSign(Middleware::tap(function($cmd, $req) { $body = $req->getBody()->getContents(); $this->assertEmpty($req->getHeader('content-encoding')); - $this->expectWarning(); + $this->expectException(\RuntimeException::class); + set_error_handler(function ($errno, $errstr) { + throw new \RuntimeException($errstr, $errno); + }); gzdecode($body); })); - $client->putMetricData([ - 'MetricData' => $metricData, - 'Namespace' => 'foo', - '@disable_request_compression' => true - ]); + try { + $client->putMetricData([ + 'MetricData' => $metricData, + 'Namespace' => 'foo', + '@disable_request_compression' => true + ]); + } finally { + restore_error_handler(); + } } public function testCommandLevelMinRequestSizeOverrides() @@ -161,18 +172,25 @@ public function testCommandLevelMinRequestSizeOverrides() $list->appendSign(Middleware::tap(function($cmd, $req) { $body = $req->getBody()->getContents(); $this->assertEmpty($req->getHeader('content-encoding')); - $this->expectWarning(); + $this->expectException(\RuntimeException::class); + set_error_handler(function ($errno, $errstr) { + throw new \RuntimeException($errstr, $errno); + }); gzdecode($body); })); - $client->putMetricData([ - 'MetricData' => $metricData, - 'Namespace' => 'foo', - '@request_min_compression_size_bytes' => 10485760 - ]); + try { + $client->putMetricData([ + 'MetricData' => $metricData, + 'Namespace' => 'foo', + '@request_min_compression_size_bytes' => 10485760 + ]); + } finally { + restore_error_handler(); + } } - public function invalidDisableCompressionType() + public static function invalidDisableCompressionType(): array { return [ ['foo'], @@ -180,11 +198,7 @@ public function invalidDisableCompressionType() ]; } - /** - * @dataProvider invalidDisableCompressionType - * - * @param $invalidType - */ + #[DataProvider('invalidDisableCompressionType')] public function testThrowsExceptionWhenDisableMinCompressionNotBool($invalidType) { $this->expectException(\InvalidArgumentException::class); @@ -193,7 +207,7 @@ public function testThrowsExceptionWhenDisableMinCompressionNotBool($invalidType $client = $this->generateTestClient($service, ['disable_request_compression' => $invalidType]); } - public function invalidMinRequestSizeProvider() + public static function invalidMinRequestSizeProvider(): array { return [ [-1], @@ -202,11 +216,7 @@ public function invalidMinRequestSizeProvider() ]; } - /** - * @dataProvider invalidMinRequestSizeProvider - * - * @param $minRequestSize - */ + #[DataProvider('invalidMinRequestSizeProvider')] public function testThrowsExceptionWhenInvalidMinCompressionSizeOnClient($minRequestSize) { if (is_int($minRequestSize)) { @@ -226,11 +236,7 @@ public function testThrowsExceptionWhenInvalidMinCompressionSizeOnClient($minReq ); } - /** - * @dataProvider invalidMinRequestSizeProvider - * - * @param $minRequestSize - */ + #[DataProvider('invalidMinRequestSizeProvider')] public function testThrowsExceptionWhenInvalidMinCompressionSize($minRequestSize) { $this->expectException(\InvalidArgumentException::class); @@ -299,24 +305,22 @@ private static function getMockMetricData($numElements) { //40 brings the request body size above the default minimum // compression threshold of 10240. 10919 to be exact. - return array_fill( - 0, - $numElements, - [ - 'MetricName' => 'MyMetric', - 'Timestamp' => time(), - 'Dimensions' => [ - [ - 'Name' => 'MyDimension1', - 'Value' => 'MyValue1' - - ], + return array_fill( + 0, + $numElements, + [ + 'MetricName' => 'MyMetric', + 'Timestamp' => time(), + 'Dimensions' => [ + [ + 'Name' => 'MyDimension1', + 'Value' => 'MyValue1' + ], - 'Unit' => 'Count', - 'Value' => 1 - ] - ); - } + ], + 'Unit' => 'Count', + 'Value' => 1 + ] + ); + } } - - diff --git a/tests/ResultPaginatorTest.php b/tests/ResultPaginatorTest.php index 9cf1e77470..a378982584 100644 --- a/tests/ResultPaginatorTest.php +++ b/tests/ResultPaginatorTest.php @@ -7,15 +7,16 @@ use Aws\DynamoDb\DynamoDbClient; use Aws\MetricsBuilder; use Aws\Result; +use Aws\ResultPaginator; use Aws\S3\S3Client; use GuzzleHttp\Promise; use GuzzleHttp\Psr7\Response; use Psr\Http\Message\RequestInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\ResultPaginator - */ +#[CoversClass(ResultPaginator::class)] class ResultPaginatorTest extends TestCase { use UsesServiceTrait; @@ -41,9 +42,7 @@ private function getCustomClientProvider(array $config) ]); } - /** - * @dataProvider getPaginatorIterationData - */ + #[DataProvider('getPaginatorIterationData')] public function testStandardIterationWorkflow( array $config, array $results, @@ -77,9 +76,7 @@ function () use (&$requestCount) { $this->assertEquals($expectedTableNames, $tableNames); } - /** - * @dataProvider getPaginatorIterationData - */ + #[DataProvider('getPaginatorIterationData')] public function testAsyncWorkflow( array $config, array $results, @@ -103,8 +100,9 @@ public function testAsyncWorkflow( public function testNonIterator() { // Get test data - $config = $this->getPaginatorIterationData()[0][0]; - $results = $this->getPaginatorIterationData()[0][1]; + $data = self::getPaginatorIterationData(); + $config = $data[0][0]; + $results = $data[0][1]; // Create the client and paginator $client = $this->getCustomClientProvider($config); $this->addMockResults($client, $results); @@ -122,7 +120,7 @@ public function testNonIterator() /** * @return array Test data */ - public function getPaginatorIterationData() + public static function getPaginatorIterationData(): array { return [ // Single field token case diff --git a/tests/ResultTest.php b/tests/ResultTest.php index 633009e40d..44640aaf4d 100644 --- a/tests/ResultTest.php +++ b/tests/ResultTest.php @@ -3,10 +3,9 @@ use Aws\Result; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Result - */ +#[CoversClass(Result::class)] class ResultTest extends TestCase { public function testHasData() diff --git a/tests/Retry/ConfigurationProviderTest.php b/tests/Retry/ConfigurationProviderTest.php index cb84898b25..4d6e30eb99 100644 --- a/tests/Retry/ConfigurationProviderTest.php +++ b/tests/Retry/ConfigurationProviderTest.php @@ -9,10 +9,10 @@ use Aws\Retry\Exception\ConfigurationException; use GuzzleHttp\Promise; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Retry\ConfigurationProvider - */ +#[CoversClass(ConfigurationProvider::class)] class ConfigurationProviderTest extends TestCase { private static $originalEnv; @@ -348,7 +348,7 @@ public function testCreatesFromCache() { $expected = new Configuration('adaptive', 54); $cacheBuilder = $this->getMockBuilder(CacheInterface::class); - $cacheBuilder->setMethods(['get', 'set', 'remove']); + $cacheBuilder->onlyMethods(['get', 'set', 'remove']); $cache = $cacheBuilder->getMock(); $cache->expects($this->any()) ->method('get') @@ -362,7 +362,7 @@ public function testCreatesFromCache() $this->assertSame($expected->toArray(), $result->toArray()); } - public function getSuccessfulUnwrapData() + public static function getSuccessfulUnwrapData(): array { $expected = new Configuration('standard', 30); return [ @@ -400,11 +400,7 @@ function () use ($expected) { ]; } - /** - * @dataProvider getSuccessfulUnwrapData - * @param $toUnwrap - * @param ConfigurationInterface $expected - */ + #[DataProvider('getSuccessfulUnwrapData')] public function testSuccessfulUnwraps($toUnwrap, ConfigurationInterface $expected) { $this->assertSame( diff --git a/tests/Retry/ConfigurationTest.php b/tests/Retry/ConfigurationTest.php index 312b1d47de..6a2142ffc9 100644 --- a/tests/Retry/ConfigurationTest.php +++ b/tests/Retry/ConfigurationTest.php @@ -4,10 +4,9 @@ use Aws\Retry\Configuration; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Retry\Configuration - */ +#[CoversClass(Configuration::class)] class ConfigurationTest extends TestCase { public function testGetsCorrectValues() diff --git a/tests/Retry/QuotaManagerTest.php b/tests/Retry/QuotaManagerTest.php index 97b691fc94..9684e4b718 100644 --- a/tests/Retry/QuotaManagerTest.php +++ b/tests/Retry/QuotaManagerTest.php @@ -7,10 +7,9 @@ use Aws\Result; use Aws\Retry\QuotaManager; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Retry\QuotaManager - */ +#[CoversClass(QuotaManager::class)] class QuotaManagerTest extends TestCase { public function testReturnsFalseWithNoCapacity() diff --git a/tests/Retry/RateLimiterTest.php b/tests/Retry/RateLimiterTest.php index d2784a4ab2..b7fdf7226a 100644 --- a/tests/Retry/RateLimiterTest.php +++ b/tests/Retry/RateLimiterTest.php @@ -4,10 +4,10 @@ use Aws\Retry\RateLimiter; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Retry\RateLimiter - */ +#[CoversClass(\Aws\Retry\RateLimiter::class)] class RateLimiterTest extends TestCase { /** @@ -50,7 +50,7 @@ public function testCorrectlyCalculatesSendingRate() $this->assertSame(2.048, $rateLimiter->updateSendingRate(false)); } - public function cubicSuccessProvider() + public static function cubicSuccessProvider(): array { return [ [5, 7], @@ -63,13 +63,7 @@ public function cubicSuccessProvider() ]; } - /** - * @dataProvider cubicSuccessProvider - * - * @param $timestamp - * @param $expectedRate - * @throws \ReflectionException - */ + #[DataProvider('cubicSuccessProvider')] public function testCalculatesCubicSuccessValues($timestamp, $expectedRate) { $rateLimiter = new RateLimiter(); @@ -236,5 +230,4 @@ public function testUpdatesClientSendingRatesCorrectly() ); } } - } diff --git a/tests/RetryMiddlewareTest.php b/tests/RetryMiddlewareTest.php index f38a061543..288947e2b7 100644 --- a/tests/RetryMiddlewareTest.php +++ b/tests/RetryMiddlewareTest.php @@ -15,10 +15,10 @@ use GuzzleHttp\Psr7\Response; use Psr\Http\Message\RequestInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\RetryMiddleware - */ +#[CoversClass(RetryMiddleware::class)] class RetryMiddlewareTest extends TestCase { public function testAddRetryHeader() @@ -149,7 +149,7 @@ public function testDeciderRetriesForCustomCurlErrors() $this->assertFalse($decider(0, $command, $request, null, $err)); } - public function awsErrorCodeProvider() + public static function awsErrorCodeProvider(): array { $command = new Command('foo'); return [ @@ -165,11 +165,8 @@ public function awsErrorCodeProvider() [new AwsException('e', $command, ['code' => 'EC2ThrottledException'])], ]; } - /** - * @param $err - * - * @dataProvider awsErrorCodeProvider - */ + + #[DataProvider('awsErrorCodeProvider')] public function testDeciderRetriesWhenAwsErrorCodeMatches($err) { $decider = RetryMiddleware::createDefaultDecider(); diff --git a/tests/RetryMiddlewareV2Test.php b/tests/RetryMiddlewareV2Test.php index 325af59f49..add10ab550 100644 --- a/tests/RetryMiddlewareV2Test.php +++ b/tests/RetryMiddlewareV2Test.php @@ -19,17 +19,15 @@ use GuzzleHttp\Psr7\Response; use Psr\Http\Message\RequestInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\RetryMiddlewareV2 - */ +#[CoversClass(\Aws\RetryMiddlewareV2::class)] class RetryMiddlewareV2Test extends TestCase { use UsesServiceTrait; /** - * @dataProvider standardModeTestCases - * * @param CommandInterface $command * @param QuotaManager $quotaManager * @param array $queue @@ -37,6 +35,7 @@ class RetryMiddlewareV2Test extends TestCase * @param $expected * @throws \Exception */ + #[DataProvider('standardModeTestCases')] public function testRetriesForStandardMode( CommandInterface $command, QuotaManager $quotaManager, @@ -130,7 +129,7 @@ function() use ($expected, &$attempt, $quotaManager, &$errors, $command) { $this->assertCount($attempt, $queue); } - function standardModeTestCases() + public static function standardModeTestCases(): array { $command = new Command('foo'); $result200 = new Result([ @@ -583,7 +582,7 @@ public function testDeciderRetriesForCustomCurlErrors() $this->assertFalse($decider(0, $command, $err)); } - public function awsErrorCodeProvider() + public static function awsErrorCodeProvider(): array { $command = new Command('foo'); return [ @@ -600,10 +599,9 @@ public function awsErrorCodeProvider() } /** - * @param $err - * - * @dataProvider awsErrorCodeProvider - */ + * @param $err + */ + #[DataProvider('awsErrorCodeProvider')] public function testDeciderRetriesWhenAwsErrorCodeMatches($err) { $decider = RetryMiddlewareV2::createDefaultDecider(new QuotaManager()); diff --git a/tests/Route53/RouteClient53Test.php b/tests/Route53/RouteClient53Test.php index 88dde9306c..822b466438 100644 --- a/tests/Route53/RouteClient53Test.php +++ b/tests/Route53/RouteClient53Test.php @@ -3,10 +3,9 @@ use Aws\Route53\Route53Client; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Route53\Route53Client - */ +#[CoversClass(Route53Client::class)] class RouteClient53Test extends TestCase { public function testCleansIds() diff --git a/tests/S3/AmbiguousSuccessParserTest.php b/tests/S3/AmbiguousSuccessParserTest.php index 75d8f5ee1a..a4658362e3 100644 --- a/tests/S3/AmbiguousSuccessParserTest.php +++ b/tests/S3/AmbiguousSuccessParserTest.php @@ -8,9 +8,13 @@ use Aws\S3\AmbiguousSuccessParser; use Aws\S3\Exception\S3Exception; use GuzzleHttp\Psr7\Response; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversNothing; +use PHPUnit\Framework\Attributes\DataProvider; use Psr\Http\Message\ResponseInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +#[CoversClass(AmbiguousSuccessParser::class)] class AmbiguousSuccessParserTest extends TestCase { private $instance; @@ -29,11 +33,7 @@ public function set_up() ); } - /** - * @dataProvider opsWithAmbiguousSuccessesProvider - * - * @param string $operation - */ + #[DataProvider('opsWithAmbiguousSuccessesProvider')] public function testConvertsAmbiguousSuccessesToExceptions($operation) { $this->expectExceptionMessage("Sorry!"); @@ -51,12 +51,9 @@ public function testConvertsAmbiguousSuccessesToExceptions($operation) $instance($command, $response); } - /** - * @dataProvider opsWithoutAmbiguousSuccessesProvider - * @param string $operation - * @doesNotPerformAssertions - */ - public function testIgnoresAmbiguousSuccessesOnUnaffectedOperations($operation) + #[DataProvider('opsWithoutAmbiguousSuccessesProvider')] + #[CoversNothing] + public function testIgnoresAmbiguousSuccessesOnUnaffectedOperations(string $operation) { $command = $this->getMockBuilder(CommandInterface::class)->getMock(); $command->expects($this->any()) @@ -69,11 +66,10 @@ public function testIgnoresAmbiguousSuccessesOnUnaffectedOperations($operation) $instance = $this->instance; $instance($command, $response); + $this->assertTrue(true); } - /** - * @dataProvider opsWithAmbiguousSuccessesProvider - */ + #[DataProvider('opsWithAmbiguousSuccessesProvider')] public function testThrowsConnectionErrorForEmptyBody($operation) { $this->expectExceptionMessage("An error connecting to the service occurred while performing the"); @@ -91,7 +87,7 @@ public function testThrowsConnectionErrorForEmptyBody($operation) $instance($command, $response); } - public function opsWithAmbiguousSuccessesProvider() + public static function opsWithAmbiguousSuccessesProvider(): array { return [ ['CopyObject'], @@ -101,7 +97,7 @@ public function opsWithAmbiguousSuccessesProvider() ]; } - public function opsWithoutAmbiguousSuccessesProvider() + public static function opsWithoutAmbiguousSuccessesProvider(): array { $provider = ApiProvider::defaultProvider(); return array_map( @@ -110,7 +106,7 @@ function ($op) { return [$op]; }, array_keys($provider('api', 's3', 'latest')['operations']), array_map( function (array $args) { return $args[0]; }, - $this->opsWithAmbiguousSuccessesProvider() + self::opsWithAmbiguousSuccessesProvider() ) ) ); diff --git a/tests/S3/ApplyChecksumMiddlewareTest.php b/tests/S3/ApplyChecksumMiddlewareTest.php index 5abae7fb63..84d79fbd2d 100644 --- a/tests/S3/ApplyChecksumMiddlewareTest.php +++ b/tests/S3/ApplyChecksumMiddlewareTest.php @@ -5,17 +5,15 @@ use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7\Request; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\S3\ApplyChecksumMiddleware - */ +#[CoversClass(ApplyChecksumMiddleware::class)] class ApplyChecksumMiddlewareTest extends TestCase { use UsesServiceTrait; - /** - * @dataProvider getFlexibleChecksumUseCases - */ + #[DataProvider('getFlexibleChecksumUseCases')] public function testFlexibleChecksums( $operation, $config, @@ -54,7 +52,7 @@ public function testFlexibleChecksums( $mw($command, $request); } - public function getFlexibleChecksumUseCases() + public static function getFlexibleChecksumUseCases(): array { return [ 'http_checksum_not_modeled' => [ @@ -197,9 +195,7 @@ public function getFlexibleChecksumUseCases() ]; } - /** - * @dataProvider getContentSha256UseCases - */ + #[DataProvider('getContentSha256UseCases')] public function testAddsContentSHA256($operation, $args, $hashAdded, $hashValue) { $client = $this->getTestClient('s3'); @@ -215,7 +211,7 @@ public function testAddsContentSHA256($operation, $args, $hashAdded, $hashValue) $mw($command, $request); } - public function getContentSha256UseCases() + public static function getContentSha256UseCases(): array { $hash = 'SHA256HASH'; @@ -246,18 +242,25 @@ public function getContentSha256UseCases() public function testAddContentMd5EmitsDeprecationWarning() { - $this->expectDeprecation(); - $this->expectDeprecationMessage('S3 no longer supports MD5 checksums.'); - $client = $this->getTestClient('s3'); - $nextHandler = function ($cmd, $request) { - $this->assertTrue($request->hasHeader('x-amz-checksum-crc32')); - }; - $service = $client->getApi(); - $mw = new ApplyChecksumMiddleware($nextHandler, $service); - $command = $client->getCommand('putObject', ['AddContentMD5' => true]); - $request = new Request('PUT', 'foo'); + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('S3 no longer supports MD5 checksums.'); + try { + $client = $this->getTestClient('s3'); + $nextHandler = function ($cmd, $request) { + $this->assertTrue($request->hasHeader('x-amz-checksum-crc32')); + }; + $service = $client->getApi(); + $mw = new ApplyChecksumMiddleware($nextHandler, $service); + $command = $client->getCommand('putObject', ['AddContentMD5' => true]); + $request = new Request('PUT', 'foo'); - $mw($command, $request); + $mw($command, $request); + } finally { + restore_error_handler(); + } } public function testInvalidChecksumThrows() diff --git a/tests/S3/BatchDeleteTest.php b/tests/S3/BatchDeleteTest.php index f6d6bbd561..dd06aff199 100644 --- a/tests/S3/BatchDeleteTest.php +++ b/tests/S3/BatchDeleteTest.php @@ -7,11 +7,10 @@ use Aws\S3\BatchDelete; use Aws\S3\Exception\DeleteMultipleObjectsException; use Aws\Test\UsesServiceTrait; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\S3\BatchDelete - */ +#[CoversClass(BatchDelete::class)] class BatchDeleteTest extends TestCase { use UsesServiceTrait; @@ -186,7 +185,7 @@ public function testDeletesYieldedCommandsWhenEachCallbackReturns() $keys = \JmesPath\search('[].Delete.Objects[].Key', $cmds); $this->assertEquals(range(0, 9), $keys); } - + public function testWithNoMatchingObjects() { $client = $this->getTestClient('s3'); diff --git a/tests/S3/BucketEndpointArnMiddlewareTest.php b/tests/S3/BucketEndpointArnMiddlewareTest.php index 81cac0cd5f..35489b9e5e 100644 --- a/tests/S3/BucketEndpointArnMiddlewareTest.php +++ b/tests/S3/BucketEndpointArnMiddlewareTest.php @@ -7,31 +7,22 @@ use Aws\Exception\UnresolvedEndpointException; use Aws\Middleware; use Aws\Result; +use Aws\S3\BucketEndpointMiddleware; use Aws\S3\Exception\S3Exception; use Aws\S3\S3Client; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Promise; use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\S3\BucketEndpointMiddleware - */ +#[CoversClass(BucketEndpointMiddleware::class)] class BucketEndpointArnMiddlewareTest extends TestCase { use UsesServiceTrait; - /** - * @dataProvider accessPointArnCases - * - * @param $arn - * @param $options - * @param $endpoint - * @param $key - * @param $signingRegion - * @param $signingService - * @throws \Exception - */ + #[DataProvider('accessPointArnCases')] public function testCorrectlyModifiesUri( $arn, $options, @@ -84,7 +75,7 @@ public function testCorrectlyModifiesUri( $s3->execute($command); } - public function accessPointArnCases() + public static function accessPointArnCases(): array { return [ // Standard case @@ -329,13 +320,7 @@ public function accessPointArnCases() ]; } - /** - * @dataProvider incorrectUsageProvider - * - * @param CommandInterface $command - * @param array $config - * @param \Exception $expected - */ + #[DataProvider('incorrectUsageProvider')] public function testThrowsForIncorrectArnUsage($command, $config, \Exception $expected) { try { @@ -356,7 +341,7 @@ public function testThrowsForIncorrectArnUsage($command, $config, \Exception $ex } } - public function incorrectUsageProvider() + public static function incorrectUsageProvider(): array { return [ [ diff --git a/tests/S3/BucketEndpointMiddlewareTest.php b/tests/S3/BucketEndpointMiddlewareTest.php index 9d9a9f8110..dfd2d50e17 100644 --- a/tests/S3/BucketEndpointMiddlewareTest.php +++ b/tests/S3/BucketEndpointMiddlewareTest.php @@ -2,12 +2,13 @@ namespace Aws\Test\S3; use Aws\Middleware; +use Aws\S3\BucketEndpointMiddleware; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\S3\BucketEndpointMiddleware - */ +#[CoversClass(BucketEndpointMiddleware::class)] class BucketEndpointMiddlewareTest extends TestCase { use UsesServiceTrait; @@ -137,7 +138,7 @@ public function testHandlesDuplicatePath(): void $s3->execute($command); } - public function keyContainsBucketNameProvider(): iterable + public static function keyContainsBucketNameProvider(): iterable { return [ ['bucketname'], @@ -150,11 +151,7 @@ public function keyContainsBucketNameProvider(): iterable ]; } - /** - * @dataProvider keyContainsBucketNameProvider - * - * @param $key - */ + #[DataProvider('keyContainsBucketNameProvider')] public function testsHandlesDuplicatePathWithKeyContainsBucketName($key): void { $s3 = $this->getTestClient('s3', [ diff --git a/tests/S3/Crypto/HeadersMetadataStrategyTest.php b/tests/S3/Crypto/HeadersMetadataStrategyTest.php index 1115675b07..e301ad83d3 100644 --- a/tests/S3/Crypto/HeadersMetadataStrategyTest.php +++ b/tests/S3/Crypto/HeadersMetadataStrategyTest.php @@ -4,17 +4,15 @@ use Aws\S3\Crypto\HeadersMetadataStrategy; use Aws\Test\Crypto\UsesMetadataEnvelopeTrait; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\S3\Crypto\HeadersMetadataStrategy - */ +#[CoversClass(HeadersMetadataStrategy::class)] class HeadersMetadataStrategyTest extends TestCase { use UsesMetadataEnvelopeTrait; - /** - * @dataProvider getMetadataFields - */ + #[DataProvider('getMetadataFields')] public function testSave($fields) { $strategy = new HeadersMetadataStrategy(); @@ -29,9 +27,7 @@ public function testSave($fields) } } - /** - * @dataProvider getMetadataResult - */ + #[DataProvider('getMetadataResult')] public function testLoad($args, $metadata) { $strategy = new HeadersMetadataStrategy(); diff --git a/tests/S3/Crypto/InstructionFileMetadataStrategyTest.php b/tests/S3/Crypto/InstructionFileMetadataStrategyTest.php index d063fc0eb6..a35bccdd3c 100644 --- a/tests/S3/Crypto/InstructionFileMetadataStrategyTest.php +++ b/tests/S3/Crypto/InstructionFileMetadataStrategyTest.php @@ -8,17 +8,15 @@ use Aws\Test\Crypto\UsesMetadataEnvelopeTrait; use Aws\Test\UsesServiceTrait; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\S3\Crypto\InstructionFileMetadataStrategy - */ +#[CoversClass(InstructionFileMetadataStrategy::class)] class InstructionFileMetadataStrategyTest extends TestCase { use UsesMetadataEnvelopeTrait, UsesServiceTrait; - /** - * @dataProvider getMetadataFields - */ + #[DataProvider('getMetadataFields')] public function testSave($fields) { /** @var S3Client $client */ @@ -46,8 +44,8 @@ public function testSave($fields) /** * Tests that only required data gets saved to the instruction file * and other data is left to the object metadata headers - * @dataProvider getV3MetadataFields */ + #[DataProvider('getV3MetadataFields')] public function testSaveV3MetadataEnvelope($fields): void { /** @var S3Client $client */ @@ -109,9 +107,7 @@ public function testSaveV3MetadataEnvelope($fields): void } - /** - * @dataProvider getMetadataResult - */ + #[DataProvider('getMetadataResult')] public function testLoad($args, $metadata) { /** @var S3Client $client */ @@ -135,9 +131,7 @@ public function testLoad($args, $metadata) } } - /** - * @dataProvider getV3FieldsForInstructionFile - */ + #[DataProvider('getV3FieldsForInstructionFile')] public function testLoadV3FromInstructionFileAndMetadata($args, $instructionFile): void { /** @var S3Client $client */ @@ -165,9 +159,7 @@ public function testLoadV3FromInstructionFileAndMetadata($args, $instructionFile } } - /** - * @dataProvider getV3MetadataResult - */ + #[DataProvider('getV3MetadataResult')] public function testLoadV3FromInstructionFileAndMetadataCorruptInstructionFile($args, $instructionFile) { /** @var S3Client $client */ @@ -182,10 +174,8 @@ public function testLoadV3FromInstructionFileAndMetadataCorruptInstructionFile($ $this->expectExceptionMessage("One or more reserved keys found in Instruction file when they should not be present."); $envelope = $strategy->load($args); } - - /** - * @dataProvider getMetadataResult - */ + + #[DataProvider('getMetadataResult')] public function testLoadV2FromInstructionFileAndMetadataCorruptInstructionFile($args, $instructionFile) { /** @var S3Client $client */ @@ -202,10 +192,8 @@ public function testLoadV2FromInstructionFileAndMetadataCorruptInstructionFile($ $this->expectExceptionMessage("Malformed metadata envelope."); $envelope = $strategy->load($args); } - - /** - * @dataProvider getMetadataResult - */ + + #[DataProvider('getMetadataResult')] public function testLoadV2FromInstructionFileAndMetadataInvalidJson($args, $instructionFile) { /** @var S3Client $client */ diff --git a/tests/S3/Crypto/S3EncryptionClientTest.php b/tests/S3/Crypto/S3EncryptionClientTest.php index c79fe3c29a..821be21cf4 100644 --- a/tests/S3/Crypto/S3EncryptionClientTest.php +++ b/tests/S3/Crypto/S3EncryptionClientTest.php @@ -20,9 +20,12 @@ use GuzzleHttp\Promise\FulfilledPromise; use GuzzleHttp\Psr7\Response; use Aws\Test\MetricsBuilderTestTrait; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; use Psr\Http\Message\RequestInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +#[CoversClass(S3EncryptionClient::class)] class S3EncryptionClientTest extends TestCase { use S3EncryptionClientTestingTrait; @@ -61,9 +64,7 @@ private function setupProvidedExpectedException($exception) } } - /** - * @dataProvider getValidMaterialsProviders - */ + #[DataProvider('getValidMaterialsProviders')] public function testPutObjectTakesValidMaterialsProviders( $provider, $exception @@ -95,9 +96,7 @@ public function testPutObjectTakesValidMaterialsProviders( $this->assertTrue($this->mockQueueEmpty()); } - /** - * @dataProvider getInvalidMaterialsProviders - */ + #[DataProvider('getInvalidMaterialsProviders')] public function testPutObjectRejectsInvalidMaterialsProviders( $provider, $exception @@ -120,9 +119,7 @@ public function testPutObjectRejectsInvalidMaterialsProviders( ]); } - /** - * @dataProvider getValidMetadataStrategies - */ + #[DataProvider('getValidMetadataStrategies')] public function testPutObjectTakesValidMetadataStrategy( $strategy, $exception, @@ -161,9 +158,7 @@ public function testPutObjectTakesValidMetadataStrategy( $this->assertTrue($this->mockQueueEmpty()); } - /** - * @dataProvider getInvalidMetadataStrategies - */ + #[DataProvider('getInvalidMetadataStrategies')] public function testPutObjectRejectsInvalidMetadataStrategy($strategy, $exception) { if ($exception) { @@ -249,9 +244,7 @@ public function testPutObjectWithOperationInstructionFileSuffix() $this->assertTrue($this->mockQueueEmpty()); } - /** - * @dataProvider getCiphers - */ + #[DataProvider('getCiphers')] public function testPutObjectValidatesCipher( $cipher, $exception = null, @@ -286,9 +279,7 @@ public function testPutObjectValidatesCipher( ]); } - /** - * @dataProvider getKeySizes - */ + #[DataProvider('getKeySizes')] public function testPutObjectValidatesKeySize( $keySize, $exception @@ -710,8 +701,11 @@ public function testGetObjectSavesFile() */ public function testTriggersWarningForGcmEncryptionWithAad() { + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage("'Aad' has been supplied for content encryption with AES/GCM/NoPadding"); - $this->expectWarning(); + set_error_handler(function ($errno, $errstr) { + throw new \RuntimeException($errstr, $errno); + }, E_USER_WARNING); $s3 = new S3Client([ 'region' => 'us-west-2', 'version' => 'latest', @@ -724,28 +718,32 @@ public function testTriggersWarningForGcmEncryptionWithAad() }, ]); - $kms = $this->getKmsClient(); - $keyId = '11111111-2222-3333-4444-555555555555'; - $provider = new KmsMaterialsProvider($kms, $keyId); - $this->addMockResults($kms, [ - new Result([ - 'CiphertextBlob' => 'encrypted', - 'Plaintext' => random_bytes(32), - ]) - ]); - - $client = @new S3EncryptionClient($s3); - $client->putObject([ - 'Bucket' => 'foo', - 'Key' => 'bar', - 'Body' => 'test', - '@MaterialsProvider' => $provider, - '@CipherOptions' => [ - 'Cipher' => 'gcm', - 'Aad' => 'test' - ], - ]); - $this->assertTrue($this->mockQueueEmpty()); + try { + $kms = $this->getKmsClient(); + $keyId = '11111111-2222-3333-4444-555555555555'; + $provider = new KmsMaterialsProvider($kms, $keyId); + $this->addMockResults($kms, [ + new Result([ + 'CiphertextBlob' => 'encrypted', + 'Plaintext' => random_bytes(32), + ]) + ]); + + $client = @new S3EncryptionClient($s3); + $client->putObject([ + 'Bucket' => 'foo', + 'Key' => 'bar', + 'Body' => 'test', + '@MaterialsProvider' => $provider, + '@CipherOptions' => [ + 'Cipher' => 'gcm', + 'Aad' => 'test' + ], + ]); + $this->assertTrue($this->mockQueueEmpty()); + } finally { + restore_error_handler(); + } } public function testAppendsMetricsCaptureMiddleware() diff --git a/tests/S3/Crypto/S3EncryptionClientV2Test.php b/tests/S3/Crypto/S3EncryptionClientV2Test.php index 76492b2f81..dc3de901cc 100644 --- a/tests/S3/Crypto/S3EncryptionClientV2Test.php +++ b/tests/S3/Crypto/S3EncryptionClientV2Test.php @@ -21,7 +21,10 @@ use GuzzleHttp\Psr7\Response; use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(S3EncryptionClientV2::class)] class S3EncryptionClientV2Test extends TestCase { use S3EncryptionClientTestingTrait; @@ -60,9 +63,7 @@ private function setupProvidedExpectedException($exception) } } - /** - * @dataProvider getValidMaterialsProviders - */ + #[DataProvider('getValidMaterialsProviders')] public function testPutObjectTakesValidMaterialsProviders( $provider, $exception @@ -98,9 +99,7 @@ public function testPutObjectTakesValidMaterialsProviders( $this->assertTrue($this->mockQueueEmpty()); } - /** - * @dataProvider getInvalidMaterialsProviders - */ + #[DataProvider('getInvalidMaterialsProviders')] public function testPutObjectRejectsInvalidMaterialsProviders( $provider, $exception @@ -124,9 +123,7 @@ public function testPutObjectRejectsInvalidMaterialsProviders( ]); } - /** - * @dataProvider getValidMetadataStrategies - */ + #[DataProvider('getValidMetadataStrategies')] public function testPutObjectTakesValidMetadataStrategy( $strategy, $exception, @@ -169,9 +166,7 @@ public function testPutObjectTakesValidMetadataStrategy( $this->assertTrue($this->mockQueueEmpty()); } - /** - * @dataProvider getInvalidMetadataStrategies - */ + #[DataProvider('getInvalidMetadataStrategies')] public function testPutObjectRejectsInvalidMetadataStrategy($strategy, $exception) { if ($exception) { @@ -266,9 +261,7 @@ public function testPutObjectWithOperationInstructionFileSuffix() $this->assertTrue($this->mockQueueEmpty()); } - /** - * @dataProvider getCiphers - */ + #[DataProvider('getCiphers')] public function testPutObjectValidatesCipher( $cipher, $exception = null @@ -307,9 +300,7 @@ public function testPutObjectValidatesCipher( ]); } - /** - * @dataProvider getKeySizes - */ + #[DataProvider('getKeySizes')] public function testPutObjectValidatesKeySize( $keySize, $exception @@ -418,8 +409,11 @@ public function testPutObjectWrapsBodyInAesGcmEncryptingStream() */ public function testTriggersWarningForGcmEncryptionWithAad() { + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage("'Aad' has been supplied for content encryption with AES/GCM/NoPadding"); - $this->expectWarning(); + set_error_handler(function ($errno, $errstr) { + throw new \RuntimeException($errstr, $errno); + }, E_USER_WARNING); $s3 = new S3Client([ 'region' => 'us-west-2', 'version' => 'latest', @@ -432,29 +426,33 @@ public function testTriggersWarningForGcmEncryptionWithAad() }, ]); - $kms = $this->getKmsClient(); - $keyId = '11111111-2222-3333-4444-555555555555'; - $provider = new KmsMaterialsProviderV2($kms, $keyId); - $this->addMockResults($kms, [ - new Result([ - 'CiphertextBlob' => 'encrypted', - 'Plaintext' => random_bytes(32), - ]) - ]); - - $client = @new S3EncryptionClientV2($s3); - $client->putObject([ - 'Bucket' => 'foo', - 'Key' => 'bar', - 'Body' => 'test', - '@MaterialsProvider' => $provider, - '@CipherOptions' => [ - 'Cipher' => 'gcm', - 'Aad' => 'test' - ], - '@KmsEncryptionContext' => [], - ]); - $this->assertTrue($this->mockQueueEmpty()); + try { + $kms = $this->getKmsClient(); + $keyId = '11111111-2222-3333-4444-555555555555'; + $provider = new KmsMaterialsProviderV2($kms, $keyId); + $this->addMockResults($kms, [ + new Result([ + 'CiphertextBlob' => 'encrypted', + 'Plaintext' => random_bytes(32), + ]) + ]); + + $client = @new S3EncryptionClientV2($s3); + $client->putObject([ + 'Bucket' => 'foo', + 'Key' => 'bar', + 'Body' => 'test', + '@MaterialsProvider' => $provider, + '@CipherOptions' => [ + 'Cipher' => 'gcm', + 'Aad' => 'test' + ], + '@KmsEncryptionContext' => [], + ]); + $this->assertTrue($this->mockQueueEmpty()); + } finally { + restore_error_handler(); + } } public function testAddsEncryptionContextForKms() @@ -917,8 +915,11 @@ public function testGetObjectSavesFile() public function testEmitsWarningForLegacySecurityProfile() { + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage("This S3 Encryption Client operation is configured to read encrypted data with legacy encryption modes"); - $this->expectWarning(); + set_error_handler(function ($errno, $errstr) { + throw new \RuntimeException($errstr, $errno); + }, E_USER_WARNING); $kms = $this->getKmsClient(); $list = $kms->getHandlerList(); $list->setHandler(function($cmd, $req) { @@ -934,31 +935,35 @@ public function testEmitsWarningForLegacySecurityProfile() new Result(['Plaintext' => random_bytes(32)]) ); }); - $providerV1 = new KmsMaterialsProvider($kms); - $providerV2 = new KmsMaterialsProviderV2($kms); - - $s3 = new S3Client([ - 'region' => 'us-west-2', - 'version' => 'latest', - 'http_handler' => function () use ($providerV1) { - return new FulfilledPromise(new Response( - 200, - $this->getFieldsAsMetaHeaders( - $this->getValidV1CbcMetadataFields($providerV1) - ), - 'test' - )); - }, - ]); - - $client = @new S3EncryptionClientV2($s3); - $client->getObject([ - 'Bucket' => 'foo', - 'Key' => 'bar', - '@MaterialsProvider' => $providerV2, - '@CommitmentPolicy' => 'FORBID_ENCRYPT_ALLOW_DECRYPT', - '@SecurityProfile' => 'V2_AND_LEGACY', - ]); + try { + $providerV1 = new KmsMaterialsProvider($kms); + $providerV2 = new KmsMaterialsProviderV2($kms); + + $s3 = new S3Client([ + 'region' => 'us-west-2', + 'version' => 'latest', + 'http_handler' => function () use ($providerV1) { + return new FulfilledPromise(new Response( + 200, + $this->getFieldsAsMetaHeaders( + $this->getValidV1CbcMetadataFields($providerV1) + ), + 'test' + )); + }, + ]); + + $client = @new S3EncryptionClientV2($s3); + $client->getObject([ + 'Bucket' => 'foo', + 'Key' => 'bar', + '@MaterialsProvider' => $providerV2, + '@CommitmentPolicy' => 'FORBID_ENCRYPT_ALLOW_DECRYPT', + '@SecurityProfile' => 'V2_AND_LEGACY', + ]); + } finally { + restore_error_handler(); + } } public function testThrowsForV2ProfileAndLegacyObject() diff --git a/tests/S3/Crypto/S3EncryptionClientV3Test.php b/tests/S3/Crypto/S3EncryptionClientV3Test.php index 780fbfc6ce..34a7af7032 100644 --- a/tests/S3/Crypto/S3EncryptionClientV3Test.php +++ b/tests/S3/Crypto/S3EncryptionClientV3Test.php @@ -23,7 +23,10 @@ use TypeError; use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; +#[CoversClass(S3EncryptionClientV3::class)] class S3EncryptionClientV3Test extends TestCase { use S3EncryptionClientTestingTrait; @@ -54,9 +57,7 @@ protected function getKmsClient(): mixed return $client; } - /** - * @dataProvider getValidMaterialsProviders - */ + #[DataProvider('getValidMaterialsProviders')] public function testPutObjectTakesValidMaterialsProviders( $provider, $exception @@ -96,9 +97,7 @@ public function testPutObjectTakesValidMaterialsProviders( $this->assertTrue($this->mockQueueEmpty()); } - /** - * @dataProvider getInvalidMaterialsProviders - */ + #[DataProvider('getInvalidMaterialsProviders')] public function testPutObjectRejectsInvalidMaterialsProviders( $provider, $exception @@ -125,9 +124,7 @@ public function testPutObjectRejectsInvalidMaterialsProviders( ]); } - /** - * @dataProvider getValidMetadataStrategies - */ + #[DataProvider('getValidMetadataStrategies')] public function testPutObjectTakesValidMetadataStrategy( $strategy, $exception, @@ -174,9 +171,7 @@ public function testPutObjectTakesValidMetadataStrategy( $this->assertTrue($this->mockQueueEmpty()); } - /** - * @dataProvider getInvalidMetadataStrategies - */ + #[DataProvider('getInvalidMetadataStrategies')] public function testPutObjectRejectsInvalidMetadataStrategy( $strategy, $exception @@ -286,9 +281,7 @@ public function testPutObjectWithOperationInstructionFileSuffix(): void /** * Test that by default, S3EC stores content metadata in S3 Object Metadata (headers) * This verifies the specification requirement that metadata is stored in object headers by default. - * - * @covers \Aws\S3\Crypto\S3EncryptionClientV3::putObject - */ + * */ public function testV2MetadataStorageInObjectHeaders(): void { $s3 = new S3Client([ @@ -343,7 +336,6 @@ public function testV2MetadataStorageInObjectHeaders(): void * Test that by default, S3EC stores content metadata in S3 Object Metadata (headers) * This verifies the specification requirement that metadata is stored in object headers by default. * - * @covers \Aws\S3\Crypto\S3EncryptionClientV3::putObject */ public function testV3MetadataStorageInObjectHeaders(): void { @@ -401,7 +393,6 @@ public function testV3MetadataStorageInObjectHeaders(): void * Test that the default metadata strategy does not write instruction files * This verifies the specification requirement that instruction files are not enabled by default. * - * @covers \Aws\S3\Crypto\S3EncryptionClientV3::putObject */ public function testDefaultMetadataStrategyDoesNotWriteInstructionFile(): void { @@ -533,9 +524,7 @@ public function testDefaultVsInstructionFileMetadataStorage(): void $this->assertTrue($this->mockQueueEmpty()); } - /** - * @dataProvider getCiphers - */ + #[DataProvider('getCiphers')] public function testPutObjectValidatesCipher( $cipher, $exception = null @@ -577,9 +566,7 @@ public function testPutObjectValidatesCipher( ]); } - /** - * @dataProvider getKeySizes - */ + #[DataProvider('getKeySizes')] public function testPutObjectValidatesKeySize( $keySize, $exception @@ -693,46 +680,53 @@ public function testPutObjectWrapsBodyInAesGcmEncryptingStream(): void */ public function testTriggersWarningForGcmEncryptionWithAad(): void { + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('\'Aad\' has been supplied for content encryption' . ' with AES/GCM/NoPadding'); - $this->expectWarning(); - $s3 = new S3Client([ - 'region' => 'us-west-2', - 'version' => 'latest', - 'http_handler' => function (RequestInterface $request) { - return new FulfilledPromise(new Response( - 200, - [], - $this->getSuccessfulPutObjectResponse() - )); - }, - ]); - - $kms = $this->getKmsClient(); - $keyId = '11111111-2222-3333-4444-555555555555'; - $provider = new KmsMaterialsProviderV3($kms, $keyId); - $this->addMockResults($kms, [ - new Result([ - 'CiphertextBlob' => 'encrypted', - 'Plaintext' => random_bytes(32), - ]) - ]); - - $client = new S3EncryptionClientV3($s3); - $client->putObject([ - 'Bucket' => 'foo', - 'Key' => 'bar', - 'Body' => 'test', - '@MaterialsProvider' => $provider, - '@CommitmentPolicy' => 'FORBID_ENCRYPT_ALLOW_DECRYPT', - '@CipherOptions' => [ - 'Cipher' => 'gcm', - 'Aad' => 'test' - ], - '@KmsEncryptionContext' => [], - ]); + set_error_handler(function ($errno, $errstr) { + throw new \RuntimeException($errstr, $errno); + }, E_USER_WARNING); + try { + $s3 = new S3Client([ + 'region' => 'us-west-2', + 'version' => 'latest', + 'http_handler' => function (RequestInterface $request) { + return new FulfilledPromise(new Response( + 200, + [], + $this->getSuccessfulPutObjectResponse() + )); + }, + ]); + + $kms = $this->getKmsClient(); + $keyId = '11111111-2222-3333-4444-555555555555'; + $provider = new KmsMaterialsProviderV3($kms, $keyId); + $this->addMockResults($kms, [ + new Result([ + 'CiphertextBlob' => 'encrypted', + 'Plaintext' => random_bytes(32), + ]) + ]); + + $client = new S3EncryptionClientV3($s3); + $client->putObject([ + 'Bucket' => 'foo', + 'Key' => 'bar', + 'Body' => 'test', + '@MaterialsProvider' => $provider, + '@CommitmentPolicy' => 'FORBID_ENCRYPT_ALLOW_DECRYPT', + '@CipherOptions' => [ + 'Cipher' => 'gcm', + 'Aad' => 'test' + ], + '@KmsEncryptionContext' => [], + ]); - $this->assertTrue($this->mockQueueEmpty()); + $this->assertTrue($this->mockQueueEmpty()); + } finally { + restore_error_handler(); + } } public function testAddsEncryptionContextForKms(): void @@ -1218,49 +1212,57 @@ public function testGetObjectSavesFile(): void public function testEmitsWarningForLegacySecurityProfile(): void { + set_error_handler(function ($errno, $errstr) { + throw new \RuntimeException($errstr, $errno); + }, E_USER_WARNING); $this->expectExceptionMessage('This S3 Encryption Client operation' . ' is configured to read encrypted data with legacy encryption modes'); - $this->expectWarning(); - $kms = $this->getKmsClient(); - $list = $kms->getHandlerList(); - $list->setHandler(function ($cmd, $req) { - // Verify decryption command has correct parameters - $this->assertSame('cek', $cmd['CiphertextBlob']); - $this->assertEquals( - [ - 'kms_cmk_id' => '11111111-2222-3333-4444-555555555555' - ], - $cmd['EncryptionContext'] - ); - return Promise\Create::promiseFor( - new Result(['Plaintext' => random_bytes(32)]) - ); - }); - $providerV1 = new KmsMaterialsProvider($kms); - $providerV3 = new KmsMaterialsProviderV3($kms); - - $s3 = new S3Client([ - 'region' => 'us-west-2', - 'version' => 'latest', - 'http_handler' => function () use ($providerV1) { - return new FulfilledPromise(new Response( - 200, - $this->getFieldsAsMetaHeaders( - $this->getValidV1CbcMetadataFields($providerV1) - ), - 'test' - )); - }, - ]); - - $client = new S3EncryptionClientV3($s3); - $client->getObject([ - 'Bucket' => 'foo', - 'Key' => 'bar', - '@MaterialsProvider' => $providerV3, - '@CommitmentPolicy' => "FORBID_ENCRYPT_ALLOW_DECRYPT", - '@SecurityProfile' => 'V3_AND_LEGACY', - ]); + $this->expectException(\RuntimeException::class); + + try { + $kms = $this->getKmsClient(); + $list = $kms->getHandlerList(); + $list->setHandler(function ($cmd, $req) { + // Verify decryption command has correct parameters + $this->assertSame('cek', $cmd['CiphertextBlob']); + $this->assertEquals( + [ + 'kms_cmk_id' => '11111111-2222-3333-4444-555555555555' + ], + $cmd['EncryptionContext'] + ); + return Promise\Create::promiseFor( + new Result(['Plaintext' => random_bytes(32)]) + ); + }); + $providerV1 = new KmsMaterialsProvider($kms); + $providerV3 = new KmsMaterialsProviderV3($kms); + + $s3 = new S3Client([ + 'region' => 'us-west-2', + 'version' => 'latest', + 'http_handler' => function () use ($providerV1) { + return new FulfilledPromise(new Response( + 200, + $this->getFieldsAsMetaHeaders( + $this->getValidV1CbcMetadataFields($providerV1) + ), + 'test' + )); + }, + ]); + + $client = new S3EncryptionClientV3($s3); + $client->getObject([ + 'Bucket' => 'foo', + 'Key' => 'bar', + '@MaterialsProvider' => $providerV3, + '@CommitmentPolicy' => "FORBID_ENCRYPT_ALLOW_DECRYPT", + '@SecurityProfile' => 'V3_AND_LEGACY', + ]); + } finally { + restore_error_handler(); + } } public function testThrowsForV3ProfileAndLegacyObject(): void @@ -1397,8 +1399,9 @@ public function testAppendsMetricsCaptureMiddleware(): void /** - * @dataProvider getValidMaterialsProviders - */ + + */ + #[DataProvider('getValidMaterialsProviders')] public function testPutObjectTakesValidMaterialsProvidersKC( $provider, $exception @@ -1466,8 +1469,8 @@ public function testPutObjectRequiresCommitmentPolicy(): void /** * Test that putObject rejects invalid commitment policies - * @dataProvider getInvalidCommitmentPolicies */ + #[DataProvider('getInvalidCommitmentPolicies')] public function testPutObjectRejectsInvalidCommitmentPolicy($policy, $expectedException): void { $this->expectException($expectedException[0]); @@ -1535,8 +1538,8 @@ public function testGetObjectRequiresV3SecurityProfile(): void /** * Test that V2 security profiles are rejected in V3 - * @dataProvider getV2SecurityProfiles */ + #[DataProvider('getV2SecurityProfiles')] public function testGetObjectRejectsV2SecurityProfiles($securityProfile): void { $this->expectException(\Aws\Exception\CryptoException::class); @@ -1558,47 +1561,54 @@ public function testGetObjectRejectsV2SecurityProfiles($securityProfile): void /** * Test valid V3 security profiles are accepted - * @dataProvider getValidV3SecurityProfiles */ + #[DataProvider('getValidV3SecurityProfiles')] public function testGetObjectAcceptsValidV3SecurityProfiles($securityProfile): void { + set_error_handler(function ($errno, $errstr) { + throw new \RuntimeException($errstr, $errno); + }, E_USER_WARNING); if ($securityProfile === 'V3_AND_LEGACY') { $this->expectExceptionMessage("This S3 Encryption Client operation is configured to read encrypted data with legacy encryption modes"); - $this->expectWarning(); + $this->expectException(\RuntimeException::class); } elseif ($securityProfile === 'V3') { $this->expectExceptionMessage("Invalid MessageId length found in object envelope."); $this->expectException(\Aws\Exception\CryptoException::class); } - $kms = $this->getKmsClient(); - $provider = new KmsMaterialsProviderV3($kms, 'test-key'); - $this->addMockResults($kms, [ - new Result(['Plaintext' => random_bytes(32)]) - ]); - - $s3 = new S3Client([ - 'region' => 'us-west-2', - 'version' => 'latest', - 'http_handler' => function () use ($provider) { - return new FulfilledPromise(new Response( - 200, - $this->getFieldsAsMetaHeaders( - $this->getValidV3MetadataFields($provider) - ), - 'test' - )); - }, - ]); - - $client = new S3EncryptionClientV3($s3); - $result = $client->getObject([ - 'Bucket' => 'foo', - 'Key' => 'bar', - '@MaterialsProvider' => $provider, - '@CommitmentPolicy' => 'REQUIRE_ENCRYPT_REQUIRE_DECRYPT', - '@SecurityProfile' => $securityProfile, - ]); + try { + $kms = $this->getKmsClient(); + $provider = new KmsMaterialsProviderV3($kms, 'test-key'); + $this->addMockResults($kms, [ + new Result(['Plaintext' => random_bytes(32)]) + ]); - $this->assertInstanceOf(AesGcmDecryptingStream::class, $result['Body']); + $s3 = new S3Client([ + 'region' => 'us-west-2', + 'version' => 'latest', + 'http_handler' => function () use ($provider) { + return new FulfilledPromise(new Response( + 200, + $this->getFieldsAsMetaHeaders( + $this->getValidV3MetadataFields($provider) + ), + 'test' + )); + }, + ]); + + $client = new S3EncryptionClientV3($s3); + $result = $client->getObject([ + 'Bucket' => 'foo', + 'Key' => 'bar', + '@MaterialsProvider' => $provider, + '@CommitmentPolicy' => 'REQUIRE_ENCRYPT_REQUIRE_DECRYPT', + '@SecurityProfile' => $securityProfile, + ]); + + $this->assertInstanceOf(AesGcmDecryptingStream::class, $result['Body']); + } finally { + restore_error_handler(); + } } /** @@ -1735,8 +1745,8 @@ public function testExceptionThrownForLegacyAlgorithmOnPut(): void /** * Test that we validate the commitment policy with the encryption algorithm - * @dataProvider getCiphersAndKCPolicies */ + #[DataProvider('getCiphersAndKCPolicies')] public function testCompatibleCipherAndKC( $cipherName, $keySize, @@ -1783,8 +1793,8 @@ public function testCompatibleCipherAndKC( /** * Test that we validate the commitment policy with the encryption algorithm - * @dataProvider getIncompatibleCiphersAndKCPolicies */ + #[DataProvider('getIncompatibleCiphersAndKCPolicies')] public function testIncompatibleCipherAndKC( $cipherName, $keySize, @@ -1823,8 +1833,8 @@ public function testIncompatibleCipherAndKC( /** * Test that we validate the commitment policy with the encryption algorithm - * @dataProvider getKCPolicies */ + #[DataProvider('getKCPolicies')] public function testIncompatibleCipherCBCAndKCGetObject( $commitmentPolicy ): void @@ -1903,8 +1913,8 @@ public function testIncompatibleCipherCBCAndKCGetObject( /** * Test that we validate the commitment policy with the encryption algorithm - * @dataProvider getKCPolicies */ + #[DataProvider('getKCPolicies')] public function testIncompatibleCipherGCMAndKCGetObject( $commitmentPolicy ): void diff --git a/tests/S3/Crypto/S3EncryptionMultipartUploaderTest.php b/tests/S3/Crypto/S3EncryptionMultipartUploaderTest.php index 805b39c2de..633e5200b0 100644 --- a/tests/S3/Crypto/S3EncryptionMultipartUploaderTest.php +++ b/tests/S3/Crypto/S3EncryptionMultipartUploaderTest.php @@ -11,7 +11,10 @@ use Aws\Test\Crypto\UsesMetadataEnvelopeTrait; use GuzzleHttp\Psr7; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(S3EncryptionMultipartUploader::class)] class S3EncryptionMultipartUploaderTest extends TestCase { use UsesServiceTrait, UsesMetadataEnvelopeTrait, UsesCryptoParamsTrait; @@ -49,9 +52,7 @@ private function setupProvidedExpectedException($exception) } } - /** - * @dataProvider getValidMaterialsProviders - */ + #[DataProvider('getValidMaterialsProviders')] public function testPutObjectTakesValidMaterialsProviders( $provider, $exception @@ -93,9 +94,7 @@ public function testPutObjectTakesValidMaterialsProviders( $this->assertSame(self::TEST_URL, $result['ObjectURL']); } - /** - * @dataProvider getInvalidMaterialsProviders - */ + #[DataProvider('getInvalidMaterialsProviders')] public function testPutObjectRejectsInvalidMaterialsProviders( $provider, $exception @@ -121,9 +120,7 @@ public function testPutObjectRejectsInvalidMaterialsProviders( $uploader->upload(); } - /** - * @dataProvider getValidMetadataStrategies - */ + #[DataProvider('getValidMetadataStrategies')] public function testPutObjectTakesValidMetadataStrategy( $strategy, $exception, @@ -173,9 +170,7 @@ public function testPutObjectTakesValidMetadataStrategy( $this->assertSame(self::TEST_URL, $result['ObjectURL']); } - /** - * @dataProvider getInvalidMetadataStrategies - */ + #[DataProvider('getInvalidMetadataStrategies')] public function testPutObjectRejectsInvalidMetadataStrategy( $strategy, $exception @@ -245,9 +240,7 @@ public function testPutObjectWithClientInstructionFileSuffix() $this->assertSame(self::TEST_URL, $result['ObjectURL']); } - /** - * @dataProvider getCiphers - */ + #[DataProvider('getCiphers')] public function testPutObjectValidatesCipher( $cipher, $exception = null, @@ -291,9 +284,7 @@ public function testPutObjectValidatesCipher( $this->assertSame(self::TEST_URL, $result['ObjectURL']); } - /** - * @dataProvider getKeySizes - */ + #[DataProvider('getKeySizes')] public function testPutObjectValidatesKeySize( $keySize, $exception diff --git a/tests/S3/Crypto/S3EncryptionMultipartUploaderV2Test.php b/tests/S3/Crypto/S3EncryptionMultipartUploaderV2Test.php index 62bbe73679..f6ab5d96dc 100644 --- a/tests/S3/Crypto/S3EncryptionMultipartUploaderV2Test.php +++ b/tests/S3/Crypto/S3EncryptionMultipartUploaderV2Test.php @@ -13,7 +13,10 @@ use GuzzleHttp\Psr7; use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(S3EncryptionMultipartUploaderV2::class)] class S3EncryptionMultipartUploaderV2Test extends TestCase { use UsesServiceTrait, UsesMetadataEnvelopeTrait, UsesCryptoParamsTraitV2; @@ -51,9 +54,7 @@ private function setupProvidedExpectedException($exception) } } - /** - * @dataProvider getValidMaterialsProviders - */ + #[DataProvider('getValidMaterialsProviders')] public function testPutObjectTakesValidMaterialsProviders( $provider, $exception @@ -99,9 +100,7 @@ public function testPutObjectTakesValidMaterialsProviders( $this->assertSame(self::TEST_URL, $result['ObjectURL']); } - /** - * @dataProvider getInvalidMaterialsProviders - */ + #[DataProvider('getInvalidMaterialsProviders')] public function testPutObjectRejectsInvalidMaterialsProviders( $provider, $exception @@ -128,9 +127,7 @@ public function testPutObjectRejectsInvalidMaterialsProviders( $uploader->upload(); } - /** - * @dataProvider getValidMetadataStrategies - */ + #[DataProvider('getValidMetadataStrategies')] public function testPutObjectTakesValidMetadataStrategy( $strategy, $exception, @@ -184,9 +181,7 @@ public function testPutObjectTakesValidMetadataStrategy( $this->assertSame(self::TEST_URL, $result['ObjectURL']); } - /** - * @dataProvider getInvalidMetadataStrategies - */ + #[DataProvider('getInvalidMetadataStrategies')] public function testPutObjectRejectsInvalidMetadataStrategy( $strategy, $exception @@ -261,9 +256,7 @@ public function testPutObjectWithClientInstructionFileSuffix() $this->assertSame(self::TEST_URL, $result['ObjectURL']); } - /** - * @dataProvider getCiphers - */ + #[DataProvider('getCiphers')] public function testPutObjectValidatesCipher( $cipher, $exception = null @@ -311,9 +304,7 @@ public function testPutObjectValidatesCipher( $this->assertSame(self::TEST_URL, $result['ObjectURL']); } - /** - * @dataProvider getKeySizes - */ + #[DataProvider('getKeySizes')] public function testPutObjectValidatesKeySize( $keySize, $exception diff --git a/tests/S3/Exception/DeleteMultipleObjectsExceptionTest.php b/tests/S3/Exception/DeleteMultipleObjectsExceptionTest.php index 97acc0c053..1e9f8c3e08 100644 --- a/tests/S3/Exception/DeleteMultipleObjectsExceptionTest.php +++ b/tests/S3/Exception/DeleteMultipleObjectsExceptionTest.php @@ -3,10 +3,9 @@ use Aws\S3\Exception\DeleteMultipleObjectsException; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\S3\Exception\DeleteMultipleObjectsException - */ +#[CoversClass(DeleteMultipleObjectsException::class)] class DeleteMultipleObjectsExceptionTest extends TestCase { public function testReturnsData() diff --git a/tests/S3/Exception/S3MultipartUploadExceptionTest.php b/tests/S3/Exception/S3MultipartUploadExceptionTest.php index b27f638659..cdad5a81dd 100644 --- a/tests/S3/Exception/S3MultipartUploadExceptionTest.php +++ b/tests/S3/Exception/S3MultipartUploadExceptionTest.php @@ -7,10 +7,9 @@ use Aws\Multipart\UploadState; use GuzzleHttp\Psr7; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\S3\Exception\S3MultipartUploadException - */ +#[CoversClass(S3MultipartUploadException::class)] class S3MultipartUploadExceptionTest extends TestCase { public function testCanProviderFailedTransferFilePathInfo() diff --git a/tests/S3/ExpiresParsingMiddlewareTest.php b/tests/S3/ExpiresParsingMiddlewareTest.php index 6b1aaa6e99..71a59b77c5 100644 --- a/tests/S3/ExpiresParsingMiddlewareTest.php +++ b/tests/S3/ExpiresParsingMiddlewareTest.php @@ -8,33 +8,38 @@ use GuzzleHttp\Promise; use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\S3\ExpiresParsingMiddleware - */ +#[CoversClass(ExpiresParsingMiddleware::class)] class ExpiresParsingMiddlewareTest extends TestCase { use UsesServiceTrait; public function testEmitsWarningWhenMissingExpires() { - $this->expectWarning(); - $this->expectWarningMessage( + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage( "Failed to parse the `expires` header as a timestamp due to " . " an invalid timestamp format.\nPlease refer to `ExpiresString` " . "for the unparsed string format of this header.\n" ); + set_error_handler(function ($errno, $errstr) { + throw new \RuntimeException($errstr, $errno); + }); + try { + $command = $this->getMockBuilder(CommandInterface::class)->getMock(); + $request = $this->getMockBuilder(RequestInterface::class)->getMock(); + $nextHandler = function ($cmd, $request) { + return Promise\Create::promiseFor(new Result([ + 'ExpiresString' => 'not-a-timestamp' + ])); + }; - $command = $this->getMockBuilder(CommandInterface::class)->getMock(); - $request = $this->getMockBuilder(RequestInterface::class)->getMock(); - $nextHandler = function ($cmd, $request) { - return Promise\Create::promiseFor(new Result([ - 'ExpiresString' => 'not-a-timestamp' - ])); - }; - - $mw = new ExpiresParsingMiddleware($nextHandler); - $mw($command, $request)->wait(); + $mw = new ExpiresParsingMiddleware($nextHandler); + $mw($command, $request)->wait(); + } finally { + restore_error_handler(); + } } public function testDoesNotEmitWarningWhenExpiresPresent() diff --git a/tests/S3/GetBucketLocationParserTest.php b/tests/S3/GetBucketLocationParserTest.php index bdfccf58df..d7f27e83a3 100644 --- a/tests/S3/GetBucketLocationParserTest.php +++ b/tests/S3/GetBucketLocationParserTest.php @@ -7,17 +7,15 @@ use Aws\Result; use GuzzleHttp\Psr7\Response; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\S3\GetBucketLocationParser - */ +#[CoversClass(GetBucketLocationParser::class)] class GetBucketLocationParserTest extends TestCase { use UsesServiceTrait; - /** - * @dataProvider getTestCases - */ + #[DataProvider('getTestCases')] public function testParsesLocationFromGetBucketLocationOperations( $commandName, $responseBody, $expectedValue ) { @@ -33,7 +31,7 @@ public function testParsesLocationFromGetBucketLocationOperations( $this->assertEquals($expectedValue, $result['LocationConstraint']); } - public function getTestCases() + public static function getTestCases(): array { return [ ['GetBucketLocation', 'us-west-2', 'us-west-2'], diff --git a/tests/S3/MultipartCopyTest.php b/tests/S3/MultipartCopyTest.php index be4c9dcc34..23c81ceb39 100644 --- a/tests/S3/MultipartCopyTest.php +++ b/tests/S3/MultipartCopyTest.php @@ -9,16 +9,17 @@ use GuzzleHttp\Promise; use GuzzleHttp\Psr7; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(MultipartCopy::class)] class MultipartCopyTest extends TestCase { use UsesServiceTrait; const MB = 1048576; - /** - * @dataProvider getTestCases - */ + #[DataProvider('getTestCases')] public function testS3MultipartCopyWorkflow( array $uploadOptions = [], $error = false @@ -48,7 +49,7 @@ public function testS3MultipartCopyWorkflow( $this->assertSame($url, $result['ObjectURL']); } - public function getTestCases() + public static function getTestCases(): array { $defaults = [ 'bucket' => 'foo', diff --git a/tests/S3/MultipartUploaderTest.php b/tests/S3/MultipartUploaderTest.php index 741a49644d..c0f8c0ea20 100644 --- a/tests/S3/MultipartUploaderTest.php +++ b/tests/S3/MultipartUploaderTest.php @@ -10,10 +10,10 @@ use GuzzleHttp\Psr7; use Psr\Http\Message\StreamInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\S3\MultipartUploader - */ +#[CoversClass(MultipartUploader::class)] class MultipartUploaderTest extends TestCase { use UsesServiceTrait; @@ -26,9 +26,7 @@ public static function tear_down_after_class() @unlink(sys_get_temp_dir() . '/' . self::FILENAME); } - /** - * @dataProvider getTestCases - */ + #[DataProvider('getTestCases')] public function testS3MultipartUploadWorkflow( array $clientOptions = [], array $uploadOptions = [], @@ -60,7 +58,7 @@ public function testS3MultipartUploadWorkflow( $this->assertSame($url, $result['ObjectURL']); } - public function getTestCases() + public static function getTestCases(): array { $defaults = [ 'bucket' => 'foo', @@ -134,8 +132,7 @@ public function testCanUseCaseInsensitiveConfigKeys() $this->assertSame($configProp->getValue($classicMup), $configProp->getValue($putObjectMup)); } - /** @doesNotPerformAssertions */ - public function testMultipartSuccessStreams() + public static function multipartSuccessStreams(): array { $size = 12 * self::MB; $data = str_repeat('.', $size); @@ -154,9 +151,7 @@ public function testMultipartSuccessStreams() ]; } - /** - * @dataProvider testMultipartSuccessStreams - */ + #[DataProvider('multipartSuccessStreams')] public function testS3MultipartUploadParams($stream, $size) { /** @var \Aws\S3\S3Client $client */ @@ -194,9 +189,10 @@ public function testS3MultipartUploadParams($stream, $size) $this->assertTrue($uploader->getState()->isCompleted()); $this->assertSame($url, $result['ObjectURL']); + $this->assertTrue(true); } - public function getContentTypeSettingTests() + public static function getContentTypeSettingTests(): array { $size = 12 * self::MB; $data = str_repeat('.', $size); @@ -227,9 +223,7 @@ public function getContentTypeSettingTests() ]; } - /** - * @dataProvider getContentTypeSettingTests - */ + #[DataProvider('getContentTypeSettingTests')] public function testS3MultipartContentTypeSetting( $stream, $params, @@ -304,9 +298,7 @@ public function testAppliesAmbiguousSuccessParsing() $uploader->upload(); } - /** - * @dataProvider testMultipartSuccessStreams - */ + #[DataProvider('multipartSuccessStreams')] public function testUploaderAddsFlexibleChecksums($stream, $size) { /** @var \Aws\S3\S3Client $client */ @@ -352,25 +344,32 @@ public function testUploaderAddsFlexibleChecksums($stream, $size) public function testAddContentMd5EmitsDeprecationNotice() { - $this->expectDeprecation(); - $this->expectDeprecationMessage('S3 no longer supports MD5 checksums.'); - $data = str_repeat('.', 12 * self::MB); - $filename = sys_get_temp_dir() . '/' . self::FILENAME; - file_put_contents($filename, $data); - $source = Psr7\Utils::streamFor(fopen($filename, 'r')); - $client = $this->getTestClient('s3'); - $options = ['bucket' => 'foo', 'key' => 'bar', 'add_content_md5' => true]; - $this->addMockResults($client, [ - new Result(['UploadId' => 'baz']), - new Result(['ETag' => 'A']), - new Result(['ETag' => 'B']), - new Result(['ETag' => 'C']), - ]); - - $uploader = new MultipartUploader($client, $source, $options); - $result = $uploader->upload(); + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('S3 no longer supports MD5 checksums.'); + try { + $data = str_repeat('.', 12 * self::MB); + $filename = sys_get_temp_dir() . '/' . self::FILENAME; + file_put_contents($filename, $data); + $source = Psr7\Utils::streamFor(fopen($filename, 'r')); + $client = $this->getTestClient('s3'); + $options = ['bucket' => 'foo', 'key' => 'bar', 'add_content_md5' => true]; + $this->addMockResults($client, [ + new Result(['UploadId' => 'baz']), + new Result(['ETag' => 'A']), + new Result(['ETag' => 'B']), + new Result(['ETag' => 'C']), + ]); + + $uploader = new MultipartUploader($client, $source, $options); + $uploader->upload(); + } finally { + restore_error_handler(); + } } - + public function testUploadPrintsProgress() { $progressBar = [ diff --git a/tests/S3/ObjectCopierTest.php b/tests/S3/ObjectCopierTest.php index fd2c8bcf09..5e692601d0 100644 --- a/tests/S3/ObjectCopierTest.php +++ b/tests/S3/ObjectCopierTest.php @@ -12,14 +12,15 @@ use GuzzleHttp\Promise; use PHPUnit\Framework\TestCase; use Psr\Http\Message\RequestInterface; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(ObjectCopier::class)] class ObjectCopierTest extends TestCase { use UsesServiceTrait; - /** - * @dataProvider getCopyTestCases - */ + #[DataProvider('copyDataProvider')] public function testDoesCorrectOperation( array $mockedResults, array $options @@ -38,9 +39,7 @@ public function testDoesCorrectOperation( $this->assertTrue($this->mockQueueEmpty()); } - /** - * @dataProvider getCopyTestCasesWithPathStyle - */ + #[DataProvider('copyWithPathStyleDataProvider')] public function testDoesCorrectOperationWithPathStyle( array $mockedResults, array $options @@ -61,11 +60,7 @@ public function testDoesCorrectOperationWithPathStyle( $this->assertTrue($this->mockQueueEmpty()); } - /** - * @dataProvider getCopyTestCases - * @param array $mockedResults - * @param array $options - */ + #[DataProvider('copyDataProvider')] public function testDoesCorrectOperationWithAccessPointArn( array $mockedResults, array $options @@ -139,9 +134,7 @@ function (CommandInterface $cmd, RequestInterface $req) { $this->assertTrue($this->mockQueueEmpty()); } - /** - * @dataProvider getCopyTestCases - */ + #[DataProvider('copyDataProvider')] public function testDoesCorrectOperationAsynchronously( array $mockedResults, array $options @@ -162,9 +155,7 @@ public function testDoesCorrectOperationAsynchronously( $this->assertTrue($this->mockQueueEmpty()); } - /** - * @dataProvider getCopyTestCasesWithPathStyle - */ + #[DataProvider('copyWithPathStyleDataProvider')] public function testDoesCorrectOperationAsynchronouslyWithPathStyle( array $mockedResults, array $options @@ -187,7 +178,7 @@ public function testDoesCorrectOperationAsynchronouslyWithPathStyle( $this->assertTrue($this->mockQueueEmpty()); } - private function getSmallPutObjectMockResult() + private static function getSmallPutObjectMockResult(): array { $smallHeadObject = new Result(['ContentLength' => 1024 * 1024 * 6]); $putObject = new Result(); @@ -195,7 +186,7 @@ private function getSmallPutObjectMockResult() return [$smallHeadObject, $putObject]; } - private function getMultipartMockResults($key = 'key') + private static function getMultipartMockResults($key = 'key'): array { $smallHeadObject = new Result(['ContentLength' => 1024 * 1024 * 6]); $partCount = ceil($smallHeadObject['ContentLength'] / MultipartUploader::PART_MIN_SIZE); @@ -210,21 +201,21 @@ private function getMultipartMockResults($key = 'key') ); } - public function getCopyTestCases() + public static function copyDataProvider(): array { return [ [ - $this->getSmallPutObjectMockResult(), + self::getSmallPutObjectMockResult(), [] ], [ - $this->getMultipartMockResults(), + self::getMultipartMockResults(), ['mup_threshold' => MultipartUploader::PART_MIN_SIZE] ], ]; } - private function getPathStyleMultipartMockResults() + private static function getPathStyleMultipartMockResults(): array { $smallHeadObject = new Result(['ContentLength' => 1024 * 1024 * 6]); $partCount = ceil($smallHeadObject['ContentLength'] / MultipartUploader::PART_MIN_SIZE); @@ -239,15 +230,15 @@ private function getPathStyleMultipartMockResults() ); } - public function getCopyTestCasesWithPathStyle() + public static function copyWithPathStyleDataProvider(): array { return [ [ - $this->getSmallPutObjectMockResult(), + self::getSmallPutObjectMockResult(), [] ], [ - $this->getPathStyleMultipartMockResults(), + self::getPathStyleMultipartMockResults(), ['mup_threshold' => MultipartUploader::PART_MIN_SIZE] ], ]; @@ -257,7 +248,7 @@ public function testCanCopyVersions() { $client = $this->getMockBuilder(S3Client::class) ->disableOriginalConstructor() - ->setMethods(['getCommand', 'executeAsync']) + ->onlyMethods(['getCommand', 'executeAsync']) ->getMock(); $headObjectCommand = new Command('HeadObject'); @@ -317,7 +308,7 @@ public function testS3ObjectCopierCopyObjectParams() $this->addMockResults( $client, - $this->getSmallPutObjectMockResult() + self::getSmallPutObjectMockResult() ); $uploader = new ObjectCopier( @@ -357,7 +348,7 @@ public function testS3ObjectCopierMultipartParams() $this->addMockResults( $client, - $this->getMultipartMockResults() + self::getMultipartMockResults() ); $uploader = new ObjectCopier( @@ -382,7 +373,7 @@ public function testS3ObjectCopierDoesTransformUnicodeKeyToEncodedURL() $this->addMockResults( $client, - $this->getSmallPutObjectMockResult() + self::getSmallPutObjectMockResult() ); $uploader = new ObjectCopier( @@ -398,7 +389,8 @@ public function testS3ObjectCopierDoesTransformUnicodeKeyToEncodedURL() $this->assertSame($url, $result['ObjectURL']); } - public function MultipartCopierProvider(){ + public static function MultipartCopierProvider(): array + { return [ ["中文", "文件夹/文件"], ["文件夹/文件", "中文"], @@ -406,9 +398,7 @@ public function MultipartCopierProvider(){ ]; } - /** - * @dataProvider MultipartCopierProvider - */ + #[DataProvider('MultipartCopierProvider')] public function testS3ObjectMultipartCopier($input, $expectedOutput) { /** @var \Aws\S3\S3Client $client */ diff --git a/tests/S3/ObjectUploaderTest.php b/tests/S3/ObjectUploaderTest.php index de6ae0d3cc..d032235d30 100644 --- a/tests/S3/ObjectUploaderTest.php +++ b/tests/S3/ObjectUploaderTest.php @@ -8,19 +8,20 @@ use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\FnStream; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\StreamInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +#[CoversClass(ObjectUploader::class)] class ObjectUploaderTest extends TestCase { use UsesServiceTrait; const MB = 1048576; - /** - * @dataProvider getUploadTestCases - */ + #[DataProvider('uploadDataProvider')] public function testDoesCorrectOperation( StreamInterface $body, array $mockedResults, @@ -35,9 +36,7 @@ public function testDoesCorrectOperation( $this->assertTrue($this->mockQueueEmpty()); } - /** - * @dataProvider getUploadTestCasesWithPathStyle - */ + #[DataProvider('getUploadTestCasesWithPathStyle')] public function testDoesCorrectOperationWithPathStyle( StreamInterface $body, array $mockedResults, @@ -54,9 +53,7 @@ public function testDoesCorrectOperationWithPathStyle( $this->assertTrue($this->mockQueueEmpty()); } - /** - * @dataProvider getUploadTestCases - */ + #[DataProvider('uploadDataProvider')] public function testDoesCorrectOperationWithAccessPointArn( StreamInterface $body, array $mockedResults, @@ -90,9 +87,7 @@ function(CommandInterface $cmd, RequestInterface $req) { $this->assertTrue($this->mockQueueEmpty()); } - /** - * @dataProvider getUploadTestCases - */ + #[DataProvider('uploadDataProvider')] public function testDoesCorrectOperationAsynchronously( StreamInterface $body, array $mockedResults, @@ -108,9 +103,7 @@ public function testDoesCorrectOperationAsynchronously( $this->assertSame('https://bucket.s3.amazonaws.com/key', $result['ObjectURL']); } - /** - * @dataProvider getUploadTestCasesWithPathStyle - */ + #[DataProvider('getUploadTestCasesWithPathStyle')] public function testDoesCorrectOperationAsynchronouslyWithPathStyle( StreamInterface $body, array $mockedResults, @@ -128,7 +121,7 @@ public function testDoesCorrectOperationAsynchronouslyWithPathStyle( $this->assertSame('https://s3.amazonaws.com/bucket/key', $result['ObjectURL']); } - public function getUploadTestCases() + public static function uploadDataProvider(): array { $putObject = new Result(); $initiate = new Result(['UploadId' => 'foo']); @@ -138,44 +131,44 @@ public function getUploadTestCases() return [ [ // 3 MB, known-size stream (put) - $this->generateStream(1024 * 1024 * 3), + self::generateStream(1024 * 1024 * 3), [$putObject], ['before_upload' => function () {}] ], [ // 3 MB, unknown-size stream (put) - $this->generateStream(1024 * 1024 * 3, false), + self::generateStream(1024 * 1024 * 3, false), [$putObject], [] ], [ // 6 MB, known-size stream (put) - $this->generateStream(1024 * 1024 * 6), + self::generateStream(1024 * 1024 * 6), [$putObject], [] ], [ // 6 MB, known-size stream, above threshold (mup) - $this->generateStream(1024 * 1024 * 6), + self::generateStream(1024 * 1024 * 6), [$initiate, $putPart, $putPart, $complete], ['mup_threshold' => 1024 * 1024 * 4] ], [ // 6 MB, unknown-size stream (mup) - $this->generateStream(1024 * 1024 * 6, false), + self::generateStream(1024 * 1024 * 6, false), [$initiate, $putPart, $putPart, $complete], [] ], [ // 6 MB, unknown-size, non-seekable stream (mup) - $this->generateStream(1024 * 1024 * 6, false, false), + self::generateStream(1024 * 1024 * 6, false, false), [$initiate, $putPart, $putPart, $complete], [] ] ]; } - public function getUploadTestCasesWithPathStyle() + public static function getUploadTestCasesWithPathStyle(): array { $putObject = new Result(); $initiate = new Result(['UploadId' => 'foo']); @@ -185,44 +178,48 @@ public function getUploadTestCasesWithPathStyle() return [ [ // 3 MB, known-size stream (put) - $this->generateStream(1024 * 1024 * 3), + self::generateStream(1024 * 1024 * 3), [$putObject], ['before_upload' => function () {}] ], [ // 3 MB, unknown-size stream (put) - $this->generateStream(1024 * 1024 * 3, false), + self::generateStream(1024 * 1024 * 3, false), [$putObject], [] ], [ // 6 MB, known-size stream (put) - $this->generateStream(1024 * 1024 * 6), + self::generateStream(1024 * 1024 * 6), [$putObject], [] ], [ // 6 MB, known-size stream, above threshold (mup) - $this->generateStream(1024 * 1024 * 6), + self::generateStream(1024 * 1024 * 6), [$initiate, $putPart, $putPart, $complete], ['mup_threshold' => 1024 * 1024 * 4] ], [ // 6 MB, unknown-size stream (mup) - $this->generateStream(1024 * 1024 * 6, false), + self::generateStream(1024 * 1024 * 6, false), [$initiate, $putPart, $putPart, $complete], [] ], [ // 6 MB, unknown-size, non-seekable stream (mup) - $this->generateStream(1024 * 1024 * 6, false, false), + self::generateStream(1024 * 1024 * 6, false, false), [$initiate, $putPart, $putPart, $complete], [] ] ]; } - private function generateStream($size, $sizeKnown = true, $seekable = true) + private static function generateStream( + $size, + $sizeKnown = true, + $seekable = true + ): FnStream { return FnStream::decorate(Psr7\Utils::streamFor(str_repeat('.', $size)), [ 'getSize' => function () use ($sizeKnown, $size) { @@ -322,9 +319,8 @@ public function testS3ObjectUploaderMultipartParams() /** * @param $checksumAlgorithm * @return void - * - * @dataProvider flexibleChecksumsProvider */ + #[DataProvider('flexibleChecksumsProvider')] public function testAddsFlexibleChecksums($checksumAlgorithm, $value) { if ($checksumAlgorithm === 'crc32c' @@ -347,13 +343,14 @@ function ($cmd, $req) use ($checksumAlgorithm, $value) { $client, 'bucket', 'key', - $this->generateStream(1024 * 1024 * 1), + self::generateStream(1024 * 1024 * 1), 'private', ['params' => ['ChecksumAlgorithm' => $checksumAlgorithm]] ))->upload(); } - public function flexibleChecksumsProvider() { + public static function flexibleChecksumsProvider(): array + { return [ ['sha1', 'VfWih+7phcE4uG3HQZCHKfpUwFs='], ['sha256', 'FT+vHyoAcJfTMSC77mlEpBy4vnZDwSIva8a8aewxaI8='], @@ -364,17 +361,24 @@ public function flexibleChecksumsProvider() { public function testAddContentMd5EmitsDeprecationNotice() { - $this->expectDeprecation(); + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }); + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('S3 no longer supports MD5 checksums.'); - $client = $this->getTestClient('S3'); - $this->addMockResults($client, [new Result()]); - $result = (new ObjectUploader( - $client, - 'bucket', - 'key', - $this->generateStream(1024 * 1024 * 1), - 'private', - ['add_content_md5' => true] - ))->upload(); + try { + $client = $this->getTestClient('S3'); + $this->addMockResults($client, [new Result()]); + (new ObjectUploader( + $client, + 'bucket', + 'key', + self::generateStream(1024 * 1024 * 1), + 'private', + ['add_content_md5' => true] + ))->upload(); + } finally { + restore_error_handler(); + } } } diff --git a/tests/S3/Parser/GetBucketLocationResultMutatorTest.php b/tests/S3/Parser/GetBucketLocationResultMutatorTest.php index 95ed01a234..b873869b9c 100644 --- a/tests/S3/Parser/GetBucketLocationResultMutatorTest.php +++ b/tests/S3/Parser/GetBucketLocationResultMutatorTest.php @@ -6,8 +6,11 @@ use Aws\Result; use Aws\S3\Parser\GetBucketLocationResultMutator; use GuzzleHttp\Psr7\Response; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\TestCase; +#[CoversClass(GetBucketLocationResultMutator::class)] class GetBucketLocationResultMutatorTest extends TestCase { /** @@ -15,8 +18,8 @@ class GetBucketLocationResultMutatorTest extends TestCase * and added to the result as the LocationConstraint field. * * @return void - * @dataProvider getTestCases */ + #[DataProvider('getTestCases')] public function testInjectsLocationConstraint($operationName, $responseBody, $expectedValue) { $mutator = new GetBucketLocationResultMutator(); @@ -30,7 +33,7 @@ public function testInjectsLocationConstraint($operationName, $responseBody, $ex $this->assertEquals($expectedValue, $result['LocationConstraint']); } - public function getTestCases() + public static function getTestCases(): array { return [ ['GetBucketLocation', 'us-west-2', 'us-west-2'], diff --git a/tests/S3/Parser/S3ParserTest.php b/tests/S3/Parser/S3ParserTest.php index a028d0ab50..a2bd2a68d3 100644 --- a/tests/S3/Parser/S3ParserTest.php +++ b/tests/S3/Parser/S3ParserTest.php @@ -14,10 +14,13 @@ use GuzzleHttp\Psr7\NoSeekStream; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Utils; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\StreamInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +#[CoversClass(S3Parser::class)] class S3ParserTest extends TestCase { const INTERNAL_S3200_ERROR = << EOXML; - /** - * @dataProvider s3200ErrorHandlingCasesProvider - * @param string $operation The operation to test. - * - * @return void - */ + #[DataProvider('s3200ErrorHandlingCasesProvider')] public function testHandle200Errors(string $operation) { $this->expectException(AwsException::class); @@ -58,7 +56,7 @@ public function testHandle200Errors(string $operation) * * @return \Generator */ - public function s3200ErrorHandlingCasesProvider(): \Generator + public static function s3200ErrorHandlingCasesProvider(): \Generator { $operations = [ 'AbortMultipartUpload', @@ -249,14 +247,7 @@ public function __invoke( $this->assertFalse(isset($mutators[$s3MutatorName])); } - /** - * @param StreamInterface $stream - * @param bool $expectValidation - * - * @dataProvider validate200ErrorValidationJustInSeekableStreamsProvider - * - * @return void - */ + #[DataProvider('validate200ErrorValidationJustInSeekableStreamsProvider')] public function testValidate200ErrorValidationJustInSeekableStreams( StreamInterface $stream, bool $expectValidation @@ -284,7 +275,7 @@ public function testValidate200ErrorValidationJustInSeekableStreams( /** * @return array[] */ - public function validate200ErrorValidationJustInSeekableStreamsProvider(): array + public static function validate200ErrorValidationJustInSeekableStreamsProvider(): array { return [ 'seekable_stream_1' => [ diff --git a/tests/S3/Parser/ValidateResponseChecksumResultMutatorTest.php b/tests/S3/Parser/ValidateResponseChecksumResultMutatorTest.php index 2538241c33..36fe836576 100644 --- a/tests/S3/Parser/ValidateResponseChecksumResultMutatorTest.php +++ b/tests/S3/Parser/ValidateResponseChecksumResultMutatorTest.php @@ -11,26 +11,20 @@ use Aws\S3\Parser\ValidateResponseChecksumResultMutator; use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7\Response; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\TestCase; /** * The tests defined here are similar to the tests * from ValidateResponseChecksumParserTest. */ +#[CoversClass(ValidateResponseChecksumResultMutator::class)] class ValidateResponseChecksumResultMutatorTest extends TestCase { use UsesServiceTrait; - /** - * @dataProvider checksumCasesDataProvider - * @param array $responseAlgorithms - * @param array $checksumHeadersReturned - * @param string|null $expectedChecksumAlgorithm - * @param array $config - * @param string $operation - * @param string|null $checksumMode - * @return void - */ + #[DataProvider('checksumCasesDataProvider')] public function testChecksumValidation( array $responseAlgorithms, array $checksumHeadersReturned, @@ -83,7 +77,7 @@ public function testChecksumValidation( * * @return array[] */ - public function checksumCasesDataProvider(): array + public static function checksumCasesDataProvider(): array { return [ //Default, when_supported, no checksum headers, skips validation @@ -241,7 +235,6 @@ public function testValidatesChecksumSucceeds() $result = $mutator($result, $command, $response); $this->assertEquals($expectedAlgorithm, $result['ChecksumValidated']); - } public function testValidatesChecksumSkipsValidation() diff --git a/tests/S3/PermanentRedirectMiddlewareTest.php b/tests/S3/PermanentRedirectMiddlewareTest.php index eda7f92424..8344aa4824 100644 --- a/tests/S3/PermanentRedirectMiddlewareTest.php +++ b/tests/S3/PermanentRedirectMiddlewareTest.php @@ -3,10 +3,11 @@ use Aws\Test\UsesServiceTrait; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversNothing; +use Aws\S3\PermanentRedirectMiddleware; -/** - * @covers \Aws\S3\PermanentRedirectMiddleware - */ +#[CoversClass(PermanentRedirectMiddleware::class)] class PermanentRedirectMiddlewareTest extends TestCase { use UsesServiceTrait; @@ -20,11 +21,12 @@ public function testThrowsSpecificException() $s3->getObject(['Bucket' => 'test', 'Key' => 'key']); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testPassesThroughUntouched() { $s3 = $this->getTestClient('s3'); $this->addMockResults($s3, [['@metadata' => ['statusCode' => 200]]]); $s3->getObject(['Bucket' => 'test', 'Key' => 'key']); + $this->assertTrue(true); } } diff --git a/tests/S3/PostObjectTest.php b/tests/S3/PostObjectTest.php index dd9eeec599..606f0355f6 100644 --- a/tests/S3/PostObjectTest.php +++ b/tests/S3/PostObjectTest.php @@ -6,10 +6,10 @@ use Aws\S3\S3Client; use Aws\Test\UsesServiceTrait; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\S3\PostObject - */ +#[CoversClass(PostObject::class)] class PostObjectTest extends TestCase { use UsesServiceTrait; @@ -73,13 +73,7 @@ public function testCanHandleDomainsWithDots() ); } - /** - * @dataProvider pathStyleProvider - * - * @param string $endpoint - * @param string $bucket - * @param string $expected - */ + #[DataProvider('pathStyleProvider')] public function testCanHandleForcedPathStyleEndpoint($endpoint, $bucket, $expected) { $s3 = new S3Client([ @@ -103,7 +97,7 @@ public function testCanHandleForcedPathStyleEndpoint($endpoint, $bucket, $expect $this->assertSame($expected, $formAttrs['action']); } - public function pathStyleProvider() + public static function pathStyleProvider(): array { return [ ['http://s3.amazonaws.com', 'foo', 'http://s3.amazonaws.com/foo'], diff --git a/tests/S3/PostObjectV4Test.php b/tests/S3/PostObjectV4Test.php index b891b96847..a0774cf372 100644 --- a/tests/S3/PostObjectV4Test.php +++ b/tests/S3/PostObjectV4Test.php @@ -6,12 +6,12 @@ use Aws\S3\S3Client; use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Aws\Test\UsesServiceTrait; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; require_once __DIR__ . '/sig_hack.php'; -/** - * @covers Aws\S3\PostObjectV4 - */ +#[CoversClass(PostObjectV4::class)] class PostObjectV4Test extends TestCase { use UsesServiceTrait; @@ -244,13 +244,7 @@ public function testCanHandleDomainsWithDots() ); } - /** - * @dataProvider virtualStyleProvider - * - * @param string $endpoint - * @param string $bucket - * @param string $expected - */ + #[DataProvider('virtualStyleProvider')] public function testCanHandleVirtualStyleEndpoint($endpoint, $bucket, $expected) { $s3 = new S3Client([ @@ -268,7 +262,7 @@ public function testCanHandleVirtualStyleEndpoint($endpoint, $bucket, $expected) $this->assertSame($expected, $formAttrs['action']); } - public function virtualStyleProvider() + public static function virtualStyleProvider(): array { return [ ['http://foo.s3.amazonaws.com', 'foo', 'http://foo.s3.amazonaws.com'], @@ -279,13 +273,7 @@ public function virtualStyleProvider() ]; } - /** - * @dataProvider pathStyleProvider - * - * @param string $endpoint - * @param string $bucket - * @param string $expected - */ + #[DataProvider('pathStyleProvider')] public function testCanHandleForcedPathStyleEndpoint($endpoint, $bucket, $expected) { $s3 = new S3Client([ @@ -303,7 +291,7 @@ public function testCanHandleForcedPathStyleEndpoint($endpoint, $bucket, $expect $this->assertSame($expected, $formAttrs['action']); } - public function pathStyleProvider() + public static function pathStyleProvider(): array { return [ ['http://s3.amazonaws.com', 'foo', 'http://s3.amazonaws.com/foo'], diff --git a/tests/S3/PutObjectUrlMiddlewareTest.php b/tests/S3/PutObjectUrlMiddlewareTest.php index 5ad4d65a3e..f14410a67d 100644 --- a/tests/S3/PutObjectUrlMiddlewareTest.php +++ b/tests/S3/PutObjectUrlMiddlewareTest.php @@ -1,12 +1,12 @@ getMockBuilder(CacheInterface::class); - $cacheBuilder->setMethods(['get', 'set', 'remove']); + $cacheBuilder->onlyMethods(['get', 'set', 'remove']); $cache = $cacheBuilder->getMock(); $cache->expects($this->any()) ->method('get') @@ -262,7 +262,7 @@ public function testCreatesFromCache() $this->assertSame($expected->toArray(), $result->toArray()); } - public function getSuccessfulUnwrapData() + public static function getSuccessfulUnwrapData(): array { $expected = new Configuration('regional'); return [ @@ -293,11 +293,7 @@ function () use ($expected) { ]; } - /** - * @dataProvider getSuccessfulUnwrapData - * @param $toUnwrap - * @param ConfigurationInterface $expected - */ + #[DataProvider('getSuccessfulUnwrapData')] public function testSuccessfulUnwraps($toUnwrap, ConfigurationInterface $expected) { $this->assertSame( diff --git a/tests/S3/RegionalEndpoint/ConfigurationTest.php b/tests/S3/RegionalEndpoint/ConfigurationTest.php index a7fc2f16f7..b774ef1a95 100644 --- a/tests/S3/RegionalEndpoint/ConfigurationTest.php +++ b/tests/S3/RegionalEndpoint/ConfigurationTest.php @@ -2,12 +2,11 @@ namespace Aws\Test\S3\RegionalEndpoint; -use Aws\Sts\RegionalEndpoints\Configuration; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use Aws\S3\RegionalEndpoint\Configuration; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\TestCase; -/** - * @covers \Aws\S3\RegionalEndpoint\Configuration - */ +#[CoversClass(Configuration::class)] class ConfigurationTest extends TestCase { public function testGetsCorrectValues() diff --git a/tests/S3/RetryableMalformedResponseParserTest.php b/tests/S3/RetryableMalformedResponseParserTest.php index adc071b15f..529d194d8d 100644 --- a/tests/S3/RetryableMalformedResponseParserTest.php +++ b/tests/S3/RetryableMalformedResponseParserTest.php @@ -1,14 +1,15 @@ assertEquals($valid, S3Client::isBucketDnsCompatible($bucket)); @@ -261,42 +261,42 @@ public function testRegistersStreamWrapper() stream_wrapper_unregister('s3'); } - public function doesExistProvider() + public static function doesExistProvider(): array { $redirectException = new PermanentRedirectException( '', new Command('mockCommand'), ['response' => new Response(301)] ); - $deleteMarkerMock = $this->getS3ErrorMock('Foo', 404, true); + $deleteMarkerMock = self::getS3ErrorMock('Foo', 404, true); return [ ['foo', null, true, []], ['foo', 'bar', true, []], - ['foo', null, true, $this->getS3ErrorMock('AccessDenied', 403)], - ['foo', 'bar', true, $this->getS3ErrorMock('AccessDenied', 403)], - ['foo', null, false, $this->getS3ErrorMock('Foo', 401)], - ['foo', 'bar', false, $this->getS3ErrorMock('Foo', 401)], - ['foo', null, -1, $this->getS3ErrorMock('Foo', 500)], - ['foo', 'bar', -1, $this->getS3ErrorMock('Foo', 500)], + ['foo', null, true, self::getS3ErrorMock('AccessDenied', 403)], + ['foo', 'bar', true, self::getS3ErrorMock('AccessDenied', 403)], + ['foo', null, false, self::getS3ErrorMock('Foo', 401)], + ['foo', 'bar', false, self::getS3ErrorMock('Foo', 401)], + ['foo', null, -1, self::getS3ErrorMock('Foo', 500)], + ['foo', 'bar', -1, self::getS3ErrorMock('Foo', 500)], ['foo', null, true, [], true], ['foo', 'bar', true, [] , true], - ['foo', null, false, $this->getS3ErrorMock('Foo', 404), true], - ['foo', 'bar', false, $this->getS3ErrorMock('Foo', 404), true], - ['foo', null, -1, $this->getS3ErrorMock('Forbidden', 403), true], - ['foo', 'bar', -1, $this->getS3ErrorMock('Forbidden', 403), true], - ['foo', null, true, $this->getS3ErrorMock('Forbidden', 403), true, true], + ['foo', null, false, self::getS3ErrorMock('Foo', 404), true], + ['foo', 'bar', false, self::getS3ErrorMock('Foo', 404), true], + ['foo', null, -1, self::getS3ErrorMock('Forbidden', 403), true], + ['foo', 'bar', -1, self::getS3ErrorMock('Forbidden', 403), true], + ['foo', null, true, self::getS3ErrorMock('Forbidden', 403), true, true], ['foo', 'bar', true, $deleteMarkerMock, true, false, true], ['foo', 'bar', false, $deleteMarkerMock, true, false, false], ['foo', null, true, $redirectException, true], ]; } - private function getS3ErrorMock( + private static function getS3ErrorMock( $errCode, $statusCode, $deleteMarker = false - ) + ): S3Exception { $response = new Response($statusCode); $deleteMarker && $response = $response->withHeader( @@ -308,12 +308,14 @@ private function getS3ErrorMock( 'code' => $errCode, 'response' => $response, ]; + return new S3Exception('', new Command('mockCommand'), $context); } /** - * @dataProvider doesExistProvider - */ + + */ + #[DataProvider('doesExistProvider')] public function testsIfExists( $bucket, $key, @@ -508,8 +510,9 @@ public function testProxiesToObjectCopy() } /** - * @dataProvider getTestCasesForLocationConstraints - */ + + */ + #[DataProvider('getTestCasesForLocationConstraints')] public function testAddsLocationConstraintAutomatically($region, $target, $command, $contains) { $client = $this->getTestClient('S3', ['region' => $region]); @@ -541,7 +544,7 @@ public function testAddsLocationConstraintAutomatically($region, $target, $comma } } - public function getTestCasesForLocationConstraints() + public static function getTestCasesForLocationConstraints() { return [ ['us-west-2', 'us-west-2', 'CreateBucket', true], @@ -555,8 +558,9 @@ public function getTestCasesForLocationConstraints() /** * @param string $bucket * - * @dataProvider directoryBucketLocationConstraintProvider - */ + + */ + #[DataProvider('directoryBucketLocationConstraintProvider')] public function testDoesNotAddLocationConstraintForDirectoryBuckets( string $bucket ): void @@ -568,7 +572,7 @@ public function testDoesNotAddLocationConstraintForDirectoryBuckets( $this->assertStringNotContainsString('LocationConstraint', $body); } - public function directoryBucketLocationConstraintProvider(): array + public static function directoryBucketLocationConstraintProvider(): array { return [ ['bucket-base-name--usw2-az1--x-s3'], @@ -620,10 +624,11 @@ public function testRequestSucceedsWithColon() } /** - * @dataProvider clientRetrySettingsProvider * * @param array $retrySettings - */ + + */ + #[DataProvider('clientRetrySettingsProvider')] public function testRetriesConnectionErrors($retrySettings) { $retries = $retrySettings['max_attempts'] - 1; @@ -653,7 +658,7 @@ public function testRetriesConnectionErrors($retrySettings) $this->assertSame(0, $retries); } - public function clientRetrySettingsProvider() + public static function clientRetrySettingsProvider(): array { return [ [ @@ -678,12 +683,13 @@ public function clientRetrySettingsProvider() } /** - * @dataProvider s3OperationsProvider * * @param string $operation * @param array $payload * @param array $retryOptions - */ + + */ + #[DataProvider('s3OperationsProvider')] public function testRetries200Errors( string $operation, array $payload, @@ -718,9 +724,12 @@ public function testRetries200Errors( * * @return \Generator */ - public function s3OperationsProvider(): \Generator + public static function s3OperationsProvider(): \Generator { - $operations = $this->loadOperations(); + $jsonContent = file_get_contents( + self::OPERATIONS_WITH_PARAMS_LOCATION + ); + $operations = json_decode($jsonContent, true); $retryModes = [ 'legacy', 'standard', @@ -741,18 +750,6 @@ public function s3OperationsProvider(): \Generator } } - /** - * Load a list of s3 operations along with the required params populated. - * - * @return array - */ - private function loadOperations(): array - { - $jsonContent = file_get_contents(self::OPERATIONS_WITH_PARAMS_LOCATION); - - return json_decode($jsonContent, true); - } - private function getErrorXml() { return <<expectExceptionMessageMatches("/Your socket connection to the server/"); @@ -835,16 +833,19 @@ private function getSocketTimeoutResponse() } /** - * @dataProvider clientRetrySettingsProvider * * @param array $retrySettings - */ - public function testNetworkingErrorsAreRetriedOnIdempotentCommands($retrySettings) + */ + #[DataProvider('clientRetrySettingsProvider')] + public function testNetworkingErrorsAreRetriedOnIdempotentCommands( + array $retrySettings + ) { $networkingError = $this->getMockBuilder(RequestException::class) ->disableOriginalConstructor() - ->setMethods([]) + ->onlyMethods(['getHandlerContext']) ->getMock(); + $networkingError->method('getHandlerContext')->willReturn([]); $retries = $retrySettings['max_attempts'] - 1; $client = new S3Client([ @@ -873,18 +874,20 @@ public function testNetworkingErrorsAreRetriedOnIdempotentCommands($retrySetting } /** - * @dataProvider clientRetrySettingsProvider * * @param array $retrySettings - */ + + */ + #[DataProvider('clientRetrySettingsProvider')] public function testNetworkingErrorsAreNotRetriedOnNonIdempotentCommands($retrySettings) { $this->expectExceptionMessageMatches("/CompleteMultipartUpload/"); $this->expectException(\Aws\S3\Exception\S3Exception::class); $networkingError = $this->getMockBuilder(RequestException::class) ->disableOriginalConstructor() - ->setMethods([]) + ->onlyMethods(['getHandlerContext']) ->getMock(); + $networkingError->method('getHandlerContext')->willReturn([]); $retries = $retrySettings['max_attempts']; $client = new S3Client([ @@ -914,16 +917,18 @@ public function testNetworkingErrorsAreNotRetriedOnNonIdempotentCommands($retryS } /** - * @dataProvider clientRetrySettingsProvider * * @param array $retrySettings - */ + + */ + #[DataProvider('clientRetrySettingsProvider')] public function testErrorsWithUnparseableBodiesCanBeRetried($retrySettings) { $networkingError = $this->getMockBuilder(RequestException::class) ->disableOriginalConstructor() - ->setMethods([]) + ->onlyMethods(['getHandlerContext']) ->getMock(); + $networkingError->method('getHandlerContext')->willReturn([]); $retries = $retrySettings['max_attempts']; $client = new S3Client([ @@ -952,9 +957,10 @@ public function testErrorsWithUnparseableBodiesCanBeRetried($retrySettings) } /** - * @dataProvider clientRetrySettingsProvider * @param $retrySettings - */ + + */ + #[DataProvider('clientRetrySettingsProvider')] public function testRetriesFailOn400Errors($retrySettings) { $retryCount = 0; $client = new S3Client([ @@ -1558,10 +1564,11 @@ public function testAddsS3RegionalEndpointsCacheArgument() /** * Tests that S3 client configuration options lead to correct endpoints * - * @dataProvider optionsToEndpointsCases * @param $options * @param $host - */ + + */ + #[DataProvider('optionsToEndpointsCases')] public function testResolvesOptionsToProperEndpoints($options, $host) { $client = new S3Client($options); @@ -1573,7 +1580,7 @@ public function testResolvesOptionsToProperEndpoints($options, $host) $client->listBuckets(); } - public function optionsToEndpointsCases() + public static function optionsToEndpointsCases() { $handler = function ($cmd, $req) { return Promise\Create::promiseFor(new Result([])); @@ -1691,7 +1698,7 @@ public function testRetriesAmbiguousSuccesses() $this->assertSame(3, $counter); } - public function multiRegionSuccessProvider() + public static function multiRegionSuccessProvider() { return [ @@ -1705,8 +1712,9 @@ public function multiRegionSuccessProvider() } /** - * @dataProvider multiRegionSuccessProvider - */ + + */ + #[DataProvider('multiRegionSuccessProvider')] public function testMrapParsing( $bucketFieldInput, $clientRegion, @@ -1753,7 +1761,7 @@ public function testMrapParsing( $client->execute($command); } - public function mrapExceptionTestProvider() { + public static function mrapExceptionTestProvider() { return [ [ "arn:aws:s3::123456789012:accesspoint:mfzwi23gnjvgw.mrap", "us-west-2", null, null, true, @@ -1779,8 +1787,9 @@ public function mrapExceptionTestProvider() { } /** - * @dataProvider mrapExceptionTestProvider - */ + + */ + #[DataProvider('mrapExceptionTestProvider')] public function testMrapExceptions( $bucketFieldInput, $clientRegion, @@ -1817,14 +1826,15 @@ public function testMrapExceptions( } /** - * @dataProvider AccessPointFailureProvider * @param $bucketFieldInput * @param $clientRegion * @param $additionalFlags * @param $useArnRegion * @param $disableMraps * @param $expectedException - */ + + */ + #[DataProvider('AccessPointFailureProvider')] public function testAccessPointFailures ( $bucketFieldInput, $clientRegion, @@ -1859,7 +1869,7 @@ public function testAccessPointFailures ( self::assertStringContainsString($expectedException, $e->getMessage()); } } - public function AccessPointFailureProvider() + public static function AccessPointFailureProvider() { return [ [ @@ -1948,7 +1958,7 @@ public function testPresignedMrapFailure () } } - public function jsonCaseProvider() + public static function jsonCaseProvider() { return json_decode( file_get_contents(__DIR__ . '/test_cases/uri_addressing.json'), @@ -1957,10 +1967,11 @@ public function jsonCaseProvider() } /** - * @dataProvider jsonCaseProvider * * @param array $testCase - */ + + */ + #[DataProvider('jsonCaseProvider')] public function testPassesCompliance( $bucket, $configuredAddressingStyle, @@ -1993,7 +2004,6 @@ public function testPassesCompliance( } /** - * @dataProvider objectLambdasSuccessProvider * * @param $bucketFieldInput * @param $clientRegion @@ -2001,7 +2011,9 @@ public function testPassesCompliance( * @param $useArnRegion * @param $endpointUrl * @param $expectedEndpoint - */ + + */ + #[DataProvider('objectLambdasSuccessProvider')] public function testObjectLambdaArnSuccess( $bucketFieldInput, $clientRegion, @@ -2045,7 +2057,7 @@ public function testObjectLambdaArnSuccess( $client->execute($command); } - public function objectLambdasSuccessProvider() + public static function objectLambdasSuccessProvider() { return [ ["arn:aws:s3-object-lambda:us-east-1:123456789012:accesspoint/mybanner", "us-east-1", "none", false, null, "mybanner-123456789012.s3-object-lambda.us-east-1.amazonaws.com"], @@ -2067,7 +2079,6 @@ public function objectLambdasSuccessProvider() } /** - * @dataProvider objectLambdasFailureProvider * * @param $bucketFieldInput * @param $clientRegion @@ -2075,7 +2086,9 @@ public function objectLambdasSuccessProvider() * @param $useArnRegion * @param $endpointUrl * @param $expectedException - */ + + */ + #[DataProvider('objectLambdasFailureProvider')] public function testObjectLambdaArnFailures( $bucketFieldInput, $clientRegion, @@ -2124,7 +2137,7 @@ public function testObjectLambdaArnFailures( } } - public function objectLambdasFailureProvider() + public static function objectLambdasFailureProvider() { return [ [ @@ -2196,13 +2209,14 @@ public function objectLambdasFailureProvider() /** - * @dataProvider writeGetObjectResponseProvider * * @param $clientRegion * @param $route * @param $endpointUrl * @param $expectedEndpoint - */ + + */ + #[DataProvider('writeGetObjectResponseProvider')] public function testWriteGetObjectResponse( $clientRegion, $route, @@ -2236,7 +2250,7 @@ public function testWriteGetObjectResponse( $client->execute($command); } - public function writeGetObjectResponseProvider() + public static function writeGetObjectResponseProvider() { return [ ["us-west-2", "route", null, 'route.s3-object-lambda.us-west-2.amazonaws.com'], @@ -2286,7 +2300,7 @@ public function testAddsForwardSlashIfEmptyPathAndQuery() $s3->execute($command); } - public function addMD5Provider() { + public static function addMD5Provider() { return [ [ ['Bucket' => 'foo', 'Key' => 'foo', 'Body' => 'test'], @@ -2306,22 +2320,31 @@ public function addMD5Provider() { } /** - * @dataProvider addMD5Provider - */ + + */ + #[DataProvider('addMD5Provider')] public function testAddContentMd5EmitsDeprecationNotice($options, $operation) { - $this->expectDeprecation(); + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }); + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('S3 no longer supports MD5 checksums.'); - $s3 = $this->getTestClient('s3'); - $this->addMockResults($s3, [[]]); - $options['AddContentMD5'] = true; - $command = $s3->getCommand($operation, $options); - $s3->execute($command); + try { + $s3 = $this->getTestClient('s3'); + $this->addMockResults($s3, [[]]); + $options['AddContentMD5'] = true; + $command = $s3->getCommand($operation, $options); + $s3->execute($command); + } finally { + restore_error_handler(); + } } /** - * @dataProvider dotSegmentProvider - */ + + */ + #[DataProvider('dotSegmentProvider')] public function testHandlesDotSegmentsInKey($key, $expectedUri) { $s3 = $this->getTestClient('s3'); @@ -2335,7 +2358,7 @@ public function testHandlesDotSegmentsInKey($key, $expectedUri) $s3->execute($command); } - public function dotSegmentProvider() + public static function dotSegmentProvider() { return [ ['../foo' , 'https://foo.s3.amazonaws.com/../foo'], @@ -2347,8 +2370,9 @@ public function dotSegmentProvider() } /** - * @dataProvider dotSegmentPathStyleProvider - */ + + */ + #[DataProvider('dotSegmentPathStyleProvider')] public function testHandlesDotSegmentsInKeyWithPathStyle($key, $expectedUri) { $s3 = $this->getTestClient('s3', ['use_path_style_endpoint' => true]); @@ -2362,7 +2386,7 @@ public function testHandlesDotSegmentsInKeyWithPathStyle($key, $expectedUri) $s3->execute($command); } - public function dotSegmentPathStyleProvider() + public static function dotSegmentPathStyleProvider() { return [ ['../foo' , 'https://s3.amazonaws.com/bucket/../foo'], @@ -2374,8 +2398,9 @@ public function dotSegmentPathStyleProvider() } /** - * @dataProvider builtinRegionProvider - */ + + */ + #[DataProvider('builtinRegionProvider')] public function testCorrectlyResolvesGlobalEndpointWithoutRegionInConstructor( $region, $expected ){ @@ -2415,24 +2440,31 @@ public function testExpiresStringInResult() public function testEmitsWarningWhenExpiresUnparseable() { - $this->expectWarning(); - $this->expectWarningMessage( + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage( "Failed to parse the `expires` header as a timestamp due to " . " an invalid timestamp format.\nPlease refer to `ExpiresString` " . "for the unparsed string format of this header.\n" ); - $client = new S3Client([ - 'region' => 'us-east-1', - 'http_handler' => function (RequestInterface $request) { - return Promise\Create::promiseFor(new Response( - 200, - ['expires' => 'this-is-not-a-timestamp'] - )); - }, - ]); + try { + $client = new S3Client([ + 'region' => 'us-east-1', + 'http_handler' => function (RequestInterface $request) { + return Promise\Create::promiseFor(new Response( + 200, + ['expires' => 'this-is-not-a-timestamp'] + )); + }, + ]); - $client->headObject(['Bucket' => 'foo', 'Key' => 'bar']); + $client->headObject(['Bucket' => 'foo', 'Key' => 'bar']); + } finally { + restore_error_handler(); + } } public function testExpiresRemainsTimestamp() { @@ -2477,7 +2509,7 @@ public function testBucketNotModifiedWithLegacyEndpointProvider() ); } - public function builtinRegionProvider() + public static function builtinRegionProvider() { return [ ['us-east-1' , true], @@ -2489,11 +2521,12 @@ public function builtinRegionProvider() * This test makes sure that not parsable xml errors are retried. * This handling is specified in the s3 parser implementation. * - * @dataProvider clientRetrySettingsProvider * @param array $retrySettings * * @return void - */ + + */ + #[DataProvider('clientRetrySettingsProvider')] public function testS3RetriesOnNotParsableBody(array $retrySettings) { $retries = $retrySettings['max_attempts']; @@ -2519,15 +2552,16 @@ public function testS3RetriesOnNotParsableBody(array $retrySettings) * * @return void * - * @dataProvider directoryBucketProvider - */ + + */ + #[DataProvider('directoryBucketProvider')] public function testIsDirectoryBucket(string $bucketName, bool $expected): void { $client = $this->getTestClient('s3'); $this->assertEquals($expected, $client::isDirectoryBucket($bucketName)); } - public function directoryBucketProvider(): array + public static function directoryBucketProvider(): array { return [ ['bucket-base-name--usw2-az1--x-s3', true], @@ -2563,8 +2597,9 @@ public function testAddCrc32ForDirectoryBucketsAsAppropriate() } /** - * @dataProvider getContentSha256UseCases - */ + + */ + #[DataProvider('getContentSha256UseCases')] public function testAddsContentSHA256AsAppropriate($operation, $args, $hashAdded, $hashValue) { $s3 = $this->getTestClient('s3'); @@ -2579,7 +2614,7 @@ public function testAddsContentSHA256AsAppropriate($operation, $args, $hashAdded $s3->execute($command); } - public function getContentSha256UseCases() + public static function getContentSha256UseCases() { $hash = 'SHA256HASH'; @@ -2609,8 +2644,9 @@ public function getContentSha256UseCases() } /** - * @dataProvider getFlexibleChecksumUseCases - */ + + */ + #[DataProvider('getFlexibleChecksumUseCases')] public function testAddsFlexibleChecksumAsAppropriate($operation, $clientArgs, $operationArgs, $headerAdded, $headerValue) { if (isset($operationArgs['ChecksumAlgorithm']) @@ -2634,7 +2670,7 @@ public function testAddsFlexibleChecksumAsAppropriate($operation, $clientArgs, $ $s3->execute($command); } - public function getFlexibleChecksumUseCases() + public static function getFlexibleChecksumUseCases() { return [ // httpChecksum not modeled @@ -2742,8 +2778,9 @@ public function getFlexibleChecksumUseCases() * @param array $clientConfig * @return void * - * @dataProvider responseChecksumValidationProvider - */ + + */ + #[DataProvider('responseChecksumValidationProvider')] public function testResponseChecksumValidation( array $clientConfig, ?string $checksumAlgorithm, @@ -2774,7 +2811,7 @@ public function testResponseChecksumValidation( $this->assertEquals($checksumAlgorithm, $result['ChecksumValidated']); } - public function responseChecksumValidationProvider(): array + public static function responseChecksumValidationProvider(): array { return [ [ @@ -2814,9 +2851,10 @@ public function responseChecksumValidationProvider(): array } /** - * @dataProvider checksumConfigProvider * @return void - */ + + */ + #[DataProvider('checksumConfigProvider')] public function testChecksumConfigThrowsForInvalidInput( string $option, string $invalidOption @@ -2832,7 +2870,7 @@ public function testChecksumConfigThrowsForInvalidInput( ); } - public function checksumConfigProvider() + public static function checksumConfigProvider() { return [ ['request_checksum_calculation', 'foo'], @@ -2906,8 +2944,9 @@ public function testCreatesPresignedPutRequestsWithChecksumValue() * The purpose of this test is to ensure ApplyChecksumMiddleware is * not invoked twice, ensuring checksum calculation is not repeated. * - * @dataProvider retriesWithoutRecalculatingChecksumProvider - */ + + */ + #[DataProvider('retriesWithoutRecalculatingChecksumProvider')] public function testRetriesWithoutRecalculatingChecksum( string $commandName, array $commandArgs, @@ -2973,7 +3012,7 @@ public function testRetriesWithoutRecalculatingChecksum( ); } - public function retriesWithoutRecalculatingChecksumProvider(): array + public static function retriesWithoutRecalculatingChecksumProvider(): array { return [ 'PutObject legacy' => [ diff --git a/tests/S3/S3EndpointMiddlewareTest.php b/tests/S3/S3EndpointMiddlewareTest.php index 58b6ac7480..1451483c37 100644 --- a/tests/S3/S3EndpointMiddlewareTest.php +++ b/tests/S3/S3EndpointMiddlewareTest.php @@ -12,36 +12,46 @@ use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\Uri; use Psr\Http\Message\RequestInterface; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(S3EndpointMiddleware::class)] class S3EndpointMiddlewareTest extends TestCase { + private static array $excludedOperations = [ + 'ListBuckets', + 'CreateBucket', + 'DeleteBucket' + ]; use UsesServiceTrait; - /** - * @dataProvider includedCommandProvider - * - * @param CommandInterface $command - */ - public function testAppliesAccelerateDualStackEndpointToCommand(CommandInterface $command) + public function testAppliesAccelerateDualStackEndpointToCommand() { - $middleware = new S3EndpointMiddleware( - $this->acceleratePatternAssertingHandler($command, 's3-accelerate.dualstack'), - 'us-west-2', - [ - 'dual_stack' => true, - 'accelerate' => true, - ] - ); + $s3Operations = $this->getTestClient('s3')->getApi()->getOperations(); + foreach (self::$excludedOperations as $excludedOperation) { + unset($s3Operations[$excludedOperation]); + } - $middleware($command, $this->getRequest($command)); + $commands = array_map(function ($commandName) { + return new Command($commandName, ['Bucket' => 'bucket']); + }, array_keys($s3Operations)); + + foreach ($commands as $command) { + $middleware = new S3EndpointMiddleware( + $this->acceleratePatternAssertingHandler($command, 's3-accelerate.dualstack'), + 'us-west-2', + [ + 'dual_stack' => true, + 'accelerate' => true, + ] + ); + + $middleware($command, $this->getRequest($command)); + } } - /** - * @dataProvider excludedCommandProvider - * - * @param CommandInterface $command - */ + #[DataProvider('excludedCommandProvider')] public function testAppliesDualStackToCommandForInvalidOperationsWhenEnableBoth(CommandInterface $command) { $middleware = new S3EndpointMiddleware( @@ -56,11 +66,7 @@ public function testAppliesDualStackToCommandForInvalidOperationsWhenEnableBoth( $middleware($command, $this->getRequest($command)); } - /** - * @dataProvider excludedCommandProvider - * - * @param CommandInterface $command - */ + #[DataProvider('excludedCommandProvider')] public function testAppliesDualStackWithPathStyleToCommandForInvalidOperationsWhenEnableBoth(CommandInterface $command) { $middleware = new S3EndpointMiddleware( @@ -76,56 +82,64 @@ public function testAppliesDualStackWithPathStyleToCommandForInvalidOperationsWh $middleware($command, $this->getPathStyleRequest($command)); } - /** - * @dataProvider includedCommandProvider - * - * @param CommandInterface $command - */ - public function testDoesNothingWithoutOptIn(CommandInterface $command) + public function testDoesNothingWithoutOptIn() { - $middleware = new S3EndpointMiddleware( - $this->noAcceleratePatternAssertingHandler($command, 's3-accelerate.dualstack'), - 'us-west-2', - [] - ); + $s3Operations = $this->getTestClient('s3')->getApi()->getOperations(); + foreach (self::$excludedOperations as $excludedOperation) { + unset($s3Operations[$excludedOperation]); + } - $middleware($command, $this->getRequest($command)); + $commands = array_map(function ($commandName) { + return new Command($commandName, ['Bucket' => 'bucket']); + }, array_keys($s3Operations)); - $middleware = new S3EndpointMiddleware( - $this->noDualStackAssertingHandler($command), - 'us-west-2', - [] - ); + foreach ($commands as $command) { + $middleware = new S3EndpointMiddleware( + $this->noAcceleratePatternAssertingHandler($command, 's3-accelerate.dualstack'), + 'us-west-2', + [] + ); - $middleware($command, $this->getRequest($command)); + $middleware($command, $this->getRequest($command)); + + $middleware = new S3EndpointMiddleware( + $this->noDualStackAssertingHandler($command), + 'us-west-2', + [] + ); + + $middleware($command, $this->getRequest($command)); + } } - /** - * @dataProvider includedCommandProvider - * - * @param CommandInterface $command - */ - public function testAppliesAccelerateDualStackEndpointWithOperationalLevelOptIn(CommandInterface $command) + public function testAppliesAccelerateDualStackEndpointWithOperationalLevelOptIn() { - $middleware = new S3EndpointMiddleware( - $this->acceleratePatternAssertingHandler($command, 's3-accelerate.dualstack'), - 'us-west-2', - [ - 'dual_stack' => false, - 'accelerate' => false, - ] - ); + $s3Operations = $this->getTestClient('s3')->getApi()->getOperations(); + foreach (self::$excludedOperations as $excludedOperation) { + unset($s3Operations[$excludedOperation]); + } - $command['@use_accelerate_endpoint'] = true; - $command['@use_dual_stack_endpoint'] = true; - $middleware($command, $this->getRequest($command)); + $commands = array_map(function ($commandName) { + return new Command($commandName, ['Bucket' => 'bucket']); + }, array_keys($s3Operations)); + + foreach ($commands as $command) { + $middleware = new S3EndpointMiddleware( + $this->acceleratePatternAssertingHandler($command, 's3-accelerate.dualstack'), + 'us-west-2', + [ + 'dual_stack' => false, + 'accelerate' => false, + ] + ); + + $command['@use_accelerate_endpoint'] = true; + $command['@use_dual_stack_endpoint'] = true; + $middleware($command, $this->getRequest($command)); + } } - /** - * @dataProvider excludedCommandProvider - * - * @param CommandInterface $command - */ + #[DataProvider('excludedCommandProvider')] public function testAppliesDualStackForInvalidOperationsWhenEnableBothAtOperationalLevel(CommandInterface $command) { $middleware = new S3EndpointMiddleware( @@ -139,11 +153,7 @@ public function testAppliesDualStackForInvalidOperationsWhenEnableBothAtOperatio $middleware($command, $this->getRequest($command)); } - /** - * @dataProvider excludedCommandProvider - * - * @param CommandInterface $command - */ + #[DataProvider('excludedCommandProvider')] public function testAppliesDualStackForInvalidOperationsWhenEnableBothWithPathStyleAtOperationalLevel(CommandInterface $command) { $middleware = new S3EndpointMiddleware( @@ -158,43 +168,45 @@ public function testAppliesDualStackForInvalidOperationsWhenEnableBothWithPathSt $middleware($command, $this->getPathStyleRequest($command)); } - /** - * @dataProvider includedCommandProvider - * - * @param CommandInterface $command - */ - public function testDoesNothingWhenDisabledBothOnOperationLevel(CommandInterface $command) + public function testDoesNothingWhenDisabledBothOnOperationLevel() { - $middleware = new S3EndpointMiddleware( - $this->noAcceleratePatternAssertingHandler($command, 's3-accelerate.dualstack'), - 'us-west-2', - [ - 'dual_stack' => true, - 'accelerate' => true, - ] - ); - $command['@use_accelerate_endpoint'] = false; - $command['@use_dual_stack_endpoint'] = false; - $middleware($command, $this->getRequest($command)); + $s3Operations = $this->getTestClient('s3')->getApi()->getOperations(); + foreach (self::$excludedOperations as $excludedOperation) { + unset($s3Operations[$excludedOperation]); + } - $middleware = new S3EndpointMiddleware( - $this->noDualStackAssertingHandler($command), - 'us-west-2', - [ - 'dual_stack' => true, - 'accelerate' => true, - ] - ); - $command['@use_accelerate_endpoint'] = false; - $command['@use_dual_stack_endpoint'] = false; - $middleware($command, $this->getRequest($command)); + $commands = array_map(function ($commandName) { + return new Command($commandName, ['Bucket' => 'bucket']); + }, array_keys($s3Operations)); + + foreach ($commands as $command) { + $middleware = new S3EndpointMiddleware( + $this->noAcceleratePatternAssertingHandler($command, 's3-accelerate.dualstack'), + 'us-west-2', + [ + 'dual_stack' => true, + 'accelerate' => true, + ] + ); + $command['@use_accelerate_endpoint'] = false; + $command['@use_dual_stack_endpoint'] = false; + $middleware($command, $this->getRequest($command)); + + $middleware = new S3EndpointMiddleware( + $this->noDualStackAssertingHandler($command), + 'us-west-2', + [ + 'dual_stack' => true, + 'accelerate' => true, + ] + ); + $command['@use_accelerate_endpoint'] = false; + $command['@use_dual_stack_endpoint'] = false; + $middleware($command, $this->getRequest($command)); + } } - /** - * @dataProvider excludedCommandProvider - * - * @param CommandInterface $command - */ + #[DataProvider('excludedCommandProvider')] public function testIgnoresExcludedCommands(CommandInterface $command) { $middleware = new S3EndpointMiddleware( @@ -206,48 +218,71 @@ public function testIgnoresExcludedCommands(CommandInterface $command) $middleware($command, $this->getRequest($command)); } - /** - * @dataProvider includedCommandProvider - * - * @param CommandInterface $command - */ - public function testAppliesAccelerateEndpointToCommands(CommandInterface $command) + public function testAppliesAccelerateEndpointToCommands() { - $middleware = new S3EndpointMiddleware( - $this->acceleratePatternAssertingHandler($command, 's3-accelerate'), - 'us-west-2', - ['accelerate' => true,] - ); + $s3Operations = $this->getTestClient('s3')->getApi()->getOperations(); + foreach (self::$excludedOperations as $excludedOperation) { + unset($s3Operations[$excludedOperation]); + } - $middleware($command, $this->getRequest($command)); + $commands = array_map(function ($commandName) { + return new Command($commandName, ['Bucket' => 'bucket']); + }, array_keys($s3Operations)); + + foreach ($commands as $command) { + $middleware = new S3EndpointMiddleware( + $this->acceleratePatternAssertingHandler($command, 's3-accelerate'), + 'us-west-2', + ['accelerate' => true,] + ); + + $middleware($command, $this->getRequest($command)); + } } - /** - * @dataProvider includedCommandProvider - * - * @param CommandInterface $command - */ - public function testDoesNothingWhenAccelerationDisabledOnOperationLevel(CommandInterface $command) + public function testDoesNothingWhenAccelerationDisabledOnOperationLevel() { - $middleware = new S3EndpointMiddleware( - $this->noAcceleratePatternAssertingHandler($command, 's3-accelerate'), - 'us-west-2', - ['accelerate' => true,] - ); + $s3Operations = $this->getTestClient('s3')->getApi()->getOperations(); + foreach (self::$excludedOperations as $excludedOperation) { + unset($s3Operations[$excludedOperation]); + } - $command['@use_accelerate_endpoint'] = false; - $middleware($command, $this->getRequest($command)); + $commands = array_map(function ($commandName) { + return new Command($commandName, ['Bucket' => 'bucket']); + }, array_keys($s3Operations)); + + foreach ($commands as $command) { + $middleware = new S3EndpointMiddleware( + $this->noAcceleratePatternAssertingHandler($command, 's3-accelerate'), + 'us-west-2', + ['accelerate' => true,] + ); + + $command['@use_accelerate_endpoint'] = false; + $middleware($command, $this->getRequest($command)); + } } public function testAppliesDualStackEndpointToCommand() { - $command = new Command('CreateBucket', ['Bucket' => 'bucket']); - $middleware = new S3EndpointMiddleware( - $this->dualStackAssertingHandler($command), - 'us-west-2', - ['dual_stack' => true,] - ); - $middleware($command, $this->getRequest($command)); + $s3Operations = $this->getTestClient('s3')->getApi()->getOperations(); + foreach (self::$excludedOperations as $excludedOperation) { + unset($s3Operations[$excludedOperation]); + } + + $commands = array_map(function ($commandName) { + return new Command($commandName, ['Bucket' => 'bucket']); + }, array_keys($s3Operations)); + + foreach ($commands as $command) { + $command = new Command('CreateBucket', ['Bucket' => 'bucket']); + $middleware = new S3EndpointMiddleware( + $this->dualStackAssertingHandler($command), + 'us-west-2', + ['dual_stack' => true,] + ); + $middleware($command, $this->getRequest($command)); + } } public function testAppliesDualStackWithPathStyleEndpointToCommand() @@ -354,26 +389,11 @@ public function testApplyingEndpointWhenEndpointOptionAndPathStyleAreSet() $middleware($command, $request); } - public function excludedCommandProvider() - { - return array_map(function ($commandName) { - return [new Command($commandName, ['Bucket' => 'bucket'])]; - }, ['ListBuckets', 'CreateBucket', 'DeleteBucket']); - } - - public function includedCommandProvider() + public static function excludedCommandProvider(): array { - $excludedOperations = array_map(function (array $args) { - return $args[0]->getName(); - }, $this->excludedCommandProvider()); - $s3Operations = $this->getTestClient('s3')->getApi()->getOperations(); - foreach ($excludedOperations as $excludedOperation) { - unset($s3Operations[$excludedOperation]); - } - return array_map(function ($commandName) { return [new Command($commandName, ['Bucket' => 'bucket'])]; - }, array_keys($s3Operations)); + }, self::$excludedOperations); } private function getRequest(CommandInterface $command) @@ -488,7 +508,7 @@ private function ipAddressPathStyleFallbackAssertingHandler(CommandInterface $co }; } - public function jsonCaseProvider() + public static function jsonCaseProvider(): array { return json_decode( file_get_contents(__DIR__ . '/test_cases/uri_addressing.json'), @@ -496,11 +516,7 @@ public function jsonCaseProvider() ); } - /** - * @dataProvider jsonCaseProvider - * - * @param array $testCase - */ + #[DataProvider('jsonCaseProvider')] public function testPassesCompliance( $bucket, $configuredAddressingStyle, @@ -532,16 +548,7 @@ public function testPassesCompliance( ]); } - /** - * @dataProvider objectLambdasSuccessProvider - * - * @param $bucketFieldInput - * @param $clientRegion - * @param $additionalFlags - * @param $useArnRegion - * @param $endpointUrl - * @param $expectedEndpoint - */ + #[DataProvider('objectLambdasSuccessProvider')] public function testObjectLambdaArnSuccess( $bucketFieldInput, $clientRegion, @@ -585,7 +592,7 @@ public function testObjectLambdaArnSuccess( $client->execute($command); } - public function objectLambdasSuccessProvider() + public static function objectLambdasSuccessProvider(): array { return [ ["arn:aws:s3-object-lambda:us-east-1:123456789012:accesspoint/mybanner", "us-east-1", "none", false, null, "mybanner-123456789012.s3-object-lambda.us-east-1.amazonaws.com"], @@ -606,16 +613,7 @@ public function objectLambdasSuccessProvider() ]; } - /** - * @dataProvider objectLambdasFailureProvider - * - * @param $bucketFieldInput - * @param $clientRegion - * @param $additionalFlags - * @param $useArnRegion - * @param $endpointUrl - * @param $expectedException - */ + #[DataProvider('objectLambdasFailureProvider')] public function testObjectLambdaArnFailures( $bucketFieldInput, $clientRegion, @@ -664,7 +662,7 @@ public function testObjectLambdaArnFailures( } } - public function objectLambdasFailureProvider() + public static function objectLambdasFailureProvider(): array { return [ ["arn:aws:s3-object-lambda:us-east-1:123456789012:accesspoint/mybanner", "us-west-2", "none", false, null, @@ -733,15 +731,7 @@ public function objectLambdasFailureProvider() ]; } - - /** - * @dataProvider writeGetObjectResponseProvider - * - * @param $clientRegion - * @param $route - * @param $endpointUrl - * @param $expectedEndpoint - */ + #[DataProvider('writeGetObjectResponseProvider')] public function testWriteGetObjectResponse( $clientRegion, $route, @@ -775,7 +765,7 @@ public function testWriteGetObjectResponse( $client->execute($command); } - public function writeGetObjectResponseProvider() + public static function writeGetObjectResponseProvider(): array { return [ diff --git a/tests/S3/S3MultiRegionClientTest.php b/tests/S3/S3MultiRegionClientTest.php index dde751fff4..7f366a4f99 100644 --- a/tests/S3/S3MultiRegionClientTest.php +++ b/tests/S3/S3MultiRegionClientTest.php @@ -14,9 +14,12 @@ use GuzzleHttp\Psr7\Response; use GuzzleHttp\Promise; use GuzzleHttp\Promise\RejectedPromise; -use Psr\Http\Message\RequestInterface; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use Psr\Http\Message\RequestInterface; +#[CoversClass(S3MultiRegionClient::class)] class S3MultiRegionClientTest extends TestCase { use UsesServiceTrait; @@ -567,11 +570,7 @@ public function testWillDefaultToRegionInPartitionWithPathStyle() $client->getObject(['Bucket' => 'foo', 'Key' => 'bar']); } - /** - * @dataProvider booleanProvider - * - * @param bool $regionalized - */ + #[DataProvider('booleanProvider')] public function testCallbacksAttachedToCommandHandlerListsAreInvoked($regionalized) { /** @var S3ClientInterface $client */ @@ -602,7 +601,7 @@ public function testCallbacksAttachedToCommandHandlerListsAreInvoked($regionaliz $this->assertSame('object!object!', (string) $result['Body']); } - public function booleanProvider() + public static function booleanProvider(): array { return [[true], [false]]; } diff --git a/tests/S3/S3Transfer/AbstractMultipartDownloaderTest.php b/tests/S3/S3Transfer/AbstractMultipartDownloaderTest.php index 0f42fd1c51..6a1a968403 100644 --- a/tests/S3/S3Transfer/AbstractMultipartDownloaderTest.php +++ b/tests/S3/S3Transfer/AbstractMultipartDownloaderTest.php @@ -16,11 +16,13 @@ use Aws\S3\S3Transfer\Utils\StreamDownloadHandler; use GuzzleHttp\Promise\Create; use GuzzleHttp\Psr7\Utils; +use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; /** * Tests MultipartDownloader abstract class implementation. */ +#[CoversClass(AbstractMultipartDownloader::class)] class AbstractMultipartDownloaderTest extends TestCase { /** diff --git a/tests/S3/S3Transfer/MultipartUploaderTest.php b/tests/S3/S3Transfer/MultipartUploaderTest.php index 20876cfba5..9e8d3bc91a 100644 --- a/tests/S3/S3Transfer/MultipartUploaderTest.php +++ b/tests/S3/S3Transfer/MultipartUploaderTest.php @@ -18,10 +18,13 @@ use GuzzleHttp\Promise\Create; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Utils; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\StreamInterface; +#[CoversClass(MultipartUploader::class)] class MultipartUploaderTest extends TestCase { @@ -37,15 +40,7 @@ protected function tearDown(): void restore_error_handler(); } - /** - * @param array $sourceConfig - * @param array $commandArgs - * @param array $config - * @param array $expected - * @return void - * - * @dataProvider multipartUploadProvider - */ + #[DataProvider('multipartUploadProvider')] public function testMultipartUpload( array $sourceConfig, array $commandArgs, @@ -134,10 +129,7 @@ public function testMultipartUpload( } } - /** - * @return array[] - */ - public function multipartUploadProvider(): array { + public static function multipartUploadProvider(): array { return [ '5_parts_upload' => [ 'source_config' => [ @@ -238,9 +230,6 @@ public function multipartUploadProvider(): array { ]; } - /** - * @return S3ClientInterface - */ private function getMultipartUploadS3Client(): S3ClientInterface { return new S3Client([ @@ -271,15 +260,7 @@ private function getMultipartUploadS3Client(): S3ClientInterface ]); } - - /** - * @param int $partSize - * @param bool $expectError - * - * @dataProvider validatePartSizeProvider - * - * @return void - */ + #[DataProvider('validatePartSizeProvider')] public function testValidatePartSize( int $partSize, bool $expectError @@ -307,10 +288,7 @@ public function testValidatePartSize( ); } - /** - * @return array - */ - public function validatePartSizeProvider(): array { + public static function validatePartSizeProvider(): array { return [ 'part_size_over_max' => [ 'part_size' => AbstractMultipartUploader::PART_MAX_SIZE + 1, @@ -331,14 +309,7 @@ public function validatePartSizeProvider(): array { ]; } - /** - * @param string|int $source - * @param bool $expectError - * - * @dataProvider invalidSourceStringProvider - * - * @return void - */ + #[DataProvider('invalidSourceStringProvider')] public function testInvalidSourceStringThrowsException( string|int $source, bool $expectError @@ -382,10 +353,7 @@ public function testInvalidSourceStringThrowsException( } } - /** - * @return array[] - */ - public function invalidSourceStringProvider(): array { + public static function invalidSourceStringProvider(): array { return [ 'invalid_source_file_path_1' => [ 'source' => 'invalid', @@ -406,9 +374,6 @@ public function invalidSourceStringProvider(): array { ]; } - /** - * @return void - */ public function testTransferListenerNotifierNotifiesListenersOnSuccess(): void { $noOfListeners = 3; @@ -475,8 +440,6 @@ public function testTransferListenerNotifierNotifiesListenersOnSuccess(): void /** * Test to make sure createMultipart, uploadPart, and completeMultipart * operations are called. - * - * @return void */ public function testMultipartOperationsAreCalled(): void { $operationsCalled = [ @@ -529,15 +492,7 @@ public function testMultipartOperationsAreCalled(): void { } } - /** - * @param array $sourceConfig - * @param array $checksumConfig - * @param array $expectedOperationHeaders - * - * @dataProvider multipartUploadWithCustomChecksumProvider - * - * @return void - */ + #[DataProvider('multipartUploadWithCustomChecksumProvider')] public function testMultipartUploadWithCustomChecksum( array $sourceConfig, array $checksumConfig, @@ -626,10 +581,7 @@ function (callable $handler) use (&$operationsCalled, $expectedOperationHeaders) } } - /** - * @return array - */ - public function multipartUploadWithCustomChecksumProvider(): array { + public static function multipartUploadWithCustomChecksumProvider(): array { return [ 'custom_checksum_crc32_1' => [ 'source_config' => [ @@ -665,9 +617,6 @@ public function multipartUploadWithCustomChecksumProvider(): array { ]; } - /** - * @return void - */ public function testMultipartUploadAbort() { $this->expectException(S3TransferException::class); $this->expectExceptionMessage('Upload failed'); @@ -724,9 +673,6 @@ public function testMultipartUploadAbort() { } } - /** - * @return void - */ public function testTransferListenerNotifierNotifiesListenersOnFailure(): void { $this->expectException(\Exception::class); @@ -786,9 +732,6 @@ public function testTransferListenerNotifierNotifiesListenersOnFailure(): void $multipartUploader->promise()->wait(); } - /** - * @return void - */ public function testTransferListenerNotifierWithEmptyListeners(): void { $listenerNotifier = new TransferListenerNotifier([]); @@ -841,14 +784,8 @@ public function testTransferListenerNotifierWithEmptyListeners(): void /** * This test makes sure that when full object checksum type is resolved * then, if a custom algorithm provide is not CRC family then it should fail. - * - * @param array $checksumConfig - * @param bool $expectsError - * - * @dataProvider fullObjectChecksumWorksJustWithCRCProvider - * - * @return void */ + #[DataProvider('fullObjectChecksumWorksJustWithCRCProvider')] public function testFullObjectChecksumWorksJustWithCRC( array $checksumConfig, bool $expectsError @@ -890,10 +827,7 @@ public function testFullObjectChecksumWorksJustWithCRC( } } - /** - * @return Generator - */ - public function fullObjectChecksumWorksJustWithCRCProvider(): Generator { + public static function fullObjectChecksumWorksJustWithCRCProvider(): Generator { yield 'sha_256_should_fail' => [ 'checksum_config' => [ 'ChecksumSHA256' => '47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=' @@ -916,15 +850,7 @@ public function fullObjectChecksumWorksJustWithCRCProvider(): Generator { ]; } - /** - * @param array $sourceConfig - * @param array $requestArgs - * @param array $expectedInputArgs - * @param bool $expectsError - * @param int|null $errorOnPartNumber - * @return void - * @dataProvider inputArgumentsPerOperationProvider - */ + #[DataProvider('inputArgumentsPerOperationProvider')] public function testInputArgumentsPerOperation( array $sourceConfig, array $requestArgs, @@ -1017,10 +943,7 @@ function ($commandName, $args) } } - /** - * @return Generator - */ - public function inputArgumentsPerOperationProvider(): Generator + public static function inputArgumentsPerOperationProvider(): Generator { yield 'test_input_fields_are_copied_without_custom_checksums' => [ // Source config to generate a stub body @@ -1326,9 +1249,6 @@ public function inputArgumentsPerOperationProvider(): Generator ]; } - /** - * @return void - */ public function testAbortMultipartUploadShowsWarning(): void { // Convert the warning to an exception diff --git a/tests/S3/S3Transfer/PartGetMultipartDownloaderTest.php b/tests/S3/S3Transfer/PartGetMultipartDownloaderTest.php index c1d3b4d50f..73401369ad 100644 --- a/tests/S3/S3Transfer/PartGetMultipartDownloaderTest.php +++ b/tests/S3/S3Transfer/PartGetMultipartDownloaderTest.php @@ -12,10 +12,13 @@ use GuzzleHttp\Promise\Create; use GuzzleHttp\Psr7\Utils; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; /** * Tests PartGetMultipartDownloader implementation. */ +#[CoversClass(PartGetMultipartDownloader::class)] class PartGetMultipartDownloaderTest extends TestCase { /** @@ -25,10 +28,9 @@ class PartGetMultipartDownloaderTest extends TestCase * @param int $objectSizeInBytes * @param int $targetPartSize * - * @dataProvider partGetMultipartDownloaderProvider - * * @return void */ + #[DataProvider('partGetMultipartDownloaderProvider')] public function testPartGetMultipartDownloader( string $objectKey, int $objectSizeInBytes, @@ -40,7 +42,7 @@ public function testPartGetMultipartDownloader( ->getMock(); $remainingToTransfer = $objectSizeInBytes; $mockClient->method('executeAsync') - -> willReturnCallback(function ($command) + ->willReturnCallback(function ($command) use ( $objectSizeInBytes, $partsCount, @@ -63,7 +65,7 @@ public function testPartGetMultipartDownloader( ])); }); $mockClient->method('getCommand') - -> willReturnCallback(function ($commandName, $args) { + ->willReturnCallback(function ($commandName, $args) { return new Command($commandName, $args); }); @@ -95,7 +97,8 @@ public function testPartGetMultipartDownloader( * * @return array[] */ - public function partGetMultipartDownloaderProvider(): array { + public static function partGetMultipartDownloaderProvider(): array + { return [ [ 'objectKey' => 'ObjectKey_1', @@ -209,10 +212,9 @@ public function testComputeObjectDimensions(): void * @param int $targetPartSize * @param string $eTag * - * @dataProvider ifMatchIsPresentInEachPartRequestAfterFirstProvider - * * @return void */ + #[DataProvider('ifMatchIsPresentInEachPartRequestAfterFirstProvider')] public function testIfMatchIsPresentInEachRangeRequestAfterFirst( int $objectSizeInBytes, int $targetPartSize, @@ -240,7 +242,7 @@ public function testIfMatchIsPresentInEachRangeRequestAfterFirst( return new Command($commandName, $args); }); $s3Client->method('executeAsync') - -> willReturnCallback(function ($command) + ->willReturnCallback(function ($command) use ( $eTag, $objectSizeInBytes, @@ -288,7 +290,7 @@ public function testIfMatchIsPresentInEachRangeRequestAfterFirst( /** * @return Generator */ - public function ifMatchIsPresentInEachPartRequestAfterFirstProvider(): Generator + public static function ifMatchIsPresentInEachPartRequestAfterFirstProvider(): Generator { yield 'multipart_download_with_3_parts_1' => [ 'object_size_in_bytes' => 1024 * 1024 * 20, diff --git a/tests/S3/S3Transfer/Progress/AbstractProgressBarFormatTest.php b/tests/S3/S3Transfer/Progress/AbstractProgressBarFormatTest.php index 8536b47cee..0e12ff5d78 100644 --- a/tests/S3/S3Transfer/Progress/AbstractProgressBarFormatTest.php +++ b/tests/S3/S3Transfer/Progress/AbstractProgressBarFormatTest.php @@ -7,22 +7,21 @@ use Aws\S3\S3Transfer\Progress\AbstractProgressBarFormat; use Aws\S3\S3Transfer\Progress\TransferProgressBarFormat; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(AbstractProgressBarFormat::class)] +#[CoversClass(ColoredTransferProgressBarFormat::class)] +#[CoversClass(PlainProgressBarFormat::class)] +#[CoversClass(TransferProgressBarFormat::class)] class AbstractProgressBarFormatTest extends TestCase { /** * Tests the different implementations of * ProgressBarFormat. Each template and parameter * can be seen in each of the implementations. - * - * @param string $implementationClass - * @param array $args - * @param string $expectedFormat - * - * @return void - * @dataProvider progressBarFormatProvider - * */ + #[DataProvider('progressBarFormatProvider')] public function testProgressBarFormat( string $implementationClass, array $args, @@ -39,7 +38,7 @@ public function testProgressBarFormat( /** * @return array[] */ - public function progressBarFormatProvider(): array + public static function progressBarFormatProvider(): array { return [ 'plain_progress_bar_format_1' => [ diff --git a/tests/S3/S3Transfer/Progress/ConsoleProgressBarTest.php b/tests/S3/S3Transfer/Progress/ConsoleProgressBarTest.php index 83bb3dd028..227fe97158 100644 --- a/tests/S3/S3Transfer/Progress/ConsoleProgressBarTest.php +++ b/tests/S3/S3Transfer/Progress/ConsoleProgressBarTest.php @@ -8,10 +8,13 @@ use Aws\S3\S3Transfer\Progress\AbstractProgressBarFormat; use Aws\S3\S3Transfer\Progress\TransferProgressBarFormat; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; /** * Tests console progress bar. */ +#[CoversClass(ConsoleProgressBar::class)] class ConsoleProgressBarTest extends TestCase { /** @@ -91,14 +94,13 @@ public function testPercentIsNotOverOneHundred(): void * @param string $progressBarChar * @param int $progressBarWidth * @param int $percentCompleted - * @param AbstractProgressBarFormatTest $progressBarFormat + * @param AbstractProgressBarFormat $progressBarFormat * @param array $progressBarFormatArgs * @param string $expectedOutput * * @return void - * @dataProvider progressBarRenderingProvider - * */ + #[DataProvider('progressBarRenderingProvider')] public function testProgressBarRendering( string $progressBarChar, int $progressBarWidth, @@ -124,7 +126,7 @@ public function testProgressBarRendering( * * @return array */ - public function progressBarRenderingProvider(): array + public static function progressBarRenderingProvider(): array { return [ 'plain_progress_bar_format_1' => [ diff --git a/tests/S3/S3Transfer/Progress/MultiProgressTrackerTest.php b/tests/S3/S3Transfer/Progress/MultiProgressTrackerTest.php index 3aaa1d715a..c04380400f 100644 --- a/tests/S3/S3Transfer/Progress/MultiProgressTrackerTest.php +++ b/tests/S3/S3Transfer/Progress/MultiProgressTrackerTest.php @@ -11,7 +11,10 @@ use Aws\S3\S3Transfer\Progress\TransferProgressSnapshot; use Closure; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(MultiProgressTracker::class)] class MultiProgressTrackerTest extends TestCase { /** @@ -28,8 +31,6 @@ public function testDefaultInitialization(): void } /** - * @dataProvider customInitializationProvider - * * @param array $progressTrackers * @param mixed $output * @param int $transferCount @@ -38,14 +39,14 @@ public function testDefaultInitialization(): void * * @return void */ + #[DataProvider('customInitializationProvider')] public function testCustomInitialization( array $progressTrackers, mixed $output, int $transferCount, int $completed, int $failed - ): void - { + ): void { $progressTracker = new MultiProgressTracker( $progressTrackers, $output, @@ -65,15 +66,13 @@ public function testCustomInitialization( * @param array $expectedOutputs * * @return void - * @dataProvider multiProgressTrackerProvider - * */ + #[DataProvider('multiProgressTrackerProvider')] public function testMultiProgressTracker( Closure $progressBarFactory, callable $eventInvoker, array $expectedOutputs, - ): void - { + ): void { $output = fopen("php://temp", "w+"); $progressTracker = new MultiProgressTracker( output: $output, @@ -107,7 +106,7 @@ public function testMultiProgressTracker( /** * @return array */ - public function customInitializationProvider(): array + public static function customInitializationProvider(): array { return [ 'custom_initialization_1' => [ @@ -147,7 +146,7 @@ public function customInitializationProvider(): array /** * @return array */ - public function multiProgressTrackerProvider(): array + public static function multiProgressTrackerProvider(): array { return [ 'multi_progress_tracker_1_single_tracking_object' => [ diff --git a/tests/S3/S3Transfer/Progress/SingleProgressTrackerTest.php b/tests/S3/S3Transfer/Progress/SingleProgressTrackerTest.php index a33abc86e8..15bd0d98de 100644 --- a/tests/S3/S3Transfer/Progress/SingleProgressTrackerTest.php +++ b/tests/S3/S3Transfer/Progress/SingleProgressTrackerTest.php @@ -10,12 +10,12 @@ use Aws\S3\S3Transfer\Progress\AbstractTransferListener; use Aws\S3\S3Transfer\Progress\TransferProgressSnapshot; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(SingleProgressTracker::class)] class SingleProgressTrackerTest extends TestCase { - /** - * @return void - */ public function testDefaultInitialization(): void { $progressTracker = new SingleProgressTracker(); @@ -25,16 +25,7 @@ public function testDefaultInitialization(): void $this->assertNull($progressTracker->getCurrentSnapshot()); } - /** - * @param ProgressBarInterface $progressBar - * @param mixed $output - * @param bool $clear - * @param TransferProgressSnapshot $snapshot - * - * @dataProvider customInitializationProvider - * - * @return void - */ + #[DataProvider('customInitializationProvider')] public function testCustomInitialization( ProgressBarInterface $progressBar, mixed $output, @@ -54,10 +45,7 @@ public function testCustomInitialization( $this->assertSame($snapshot, $progressTracker->getCurrentSnapshot()); } - /** - * @return array[] - */ - public function customInitializationProvider(): array + public static function customInitializationProvider(): array { return [ 'initialization_1' => [ @@ -83,15 +71,7 @@ public function customInitializationProvider(): array ]; } - /** - * @param ProgressBarInterface $progressBar - * @param callable $eventInvoker - * @param array $expectedOutputs - * - * @dataProvider singleProgressTrackingProvider - * - * @return void - */ + #[DataProvider('singleProgressTrackingProvider')] public function testSingleProgressTracking( ProgressBarInterface $progressBar, callable $eventInvoker, @@ -128,10 +108,7 @@ public function testSingleProgressTracking( ); } - /** - * @return array[] - */ - public function singleProgressTrackingProvider(): array + public static function singleProgressTrackingProvider(): array { return [ 'progress_rendering_1_transfer_initiated' => [ diff --git a/tests/S3/S3Transfer/Progress/TransferListenerNotifierTest.php b/tests/S3/S3Transfer/Progress/TransferListenerNotifierTest.php index 4a8c4a732a..64dc1601d2 100644 --- a/tests/S3/S3Transfer/Progress/TransferListenerNotifierTest.php +++ b/tests/S3/S3Transfer/Progress/TransferListenerNotifierTest.php @@ -4,14 +4,14 @@ use Aws\S3\S3Transfer\Progress\AbstractTransferListener; use Aws\S3\S3Transfer\Progress\TransferListenerNotifier; +use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; +#[CoversClass(TransferListenerNotifier::class)] class TransferListenerNotifierTest extends TestCase { - /** - * @return void - */ - public function testListenerNotifier(): void { + public function testListenerNotifier(): void + { $listeners = [ $this->getMockBuilder(AbstractTransferListener::class) ->getMock(), diff --git a/tests/S3/S3Transfer/Progress/TransferProgressSnapshotTest.php b/tests/S3/S3Transfer/Progress/TransferProgressSnapshotTest.php index 5a003a8159..a424a9c917 100644 --- a/tests/S3/S3Transfer/Progress/TransferProgressSnapshotTest.php +++ b/tests/S3/S3Transfer/Progress/TransferProgressSnapshotTest.php @@ -4,12 +4,12 @@ use Aws\S3\S3Transfer\Progress\TransferProgressSnapshot; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(TransferProgressSnapshot::class)] class TransferProgressSnapshotTest extends TestCase { - /** - * @return void - */ public function testInitialization(): void { $snapshot = new TransferProgressSnapshot( @@ -25,15 +25,7 @@ public function testInitialization(): void $this->assertEquals($snapshot->getResponse(), ['Foo' => 'Bar']); } - /** - * @param int $transferredBytes - * @param int $totalBytes - * @param float $expectedRatio - * - * @return void - * @dataProvider ratioTransferredProvider - * - */ + #[DataProvider('ratioTransferredProvider')] public function testRatioTransferred( int $transferredBytes, int $totalBytes, @@ -48,10 +40,7 @@ public function testRatioTransferred( $this->assertEquals($expectedRatio, $snapshot->ratioTransferred()); } - /** - * @return array - */ - public function ratioTransferredProvider(): array + public static function ratioTransferredProvider(): array { return [ 'ratio_1' => [ diff --git a/tests/S3/S3Transfer/RangeGetMultipartDownloaderTest.php b/tests/S3/S3Transfer/RangeGetMultipartDownloaderTest.php index ab6816e014..6d794c994e 100644 --- a/tests/S3/S3Transfer/RangeGetMultipartDownloaderTest.php +++ b/tests/S3/S3Transfer/RangeGetMultipartDownloaderTest.php @@ -13,10 +13,13 @@ use GuzzleHttp\Promise\Create; use GuzzleHttp\Psr7\Utils; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; /** * Tests RangeGetMultipartDownloader implementation. */ +#[CoversClass(RangeGetMultipartDownloader::class)] class RangeGetMultipartDownloaderTest extends TestCase { /** @@ -26,10 +29,9 @@ class RangeGetMultipartDownloaderTest extends TestCase * @param int $objectSizeInBytes * @param int $targetPartSize * - * @dataProvider rangeGetMultipartDownloaderProvider - * * @return void */ + #[DataProvider('rangeGetMultipartDownloaderProvider')] public function testRangeGetMultipartDownloader( string $objectKey, int $objectSizeInBytes, @@ -96,7 +98,8 @@ public function testRangeGetMultipartDownloader( * * @return array[] */ - public function rangeGetMultipartDownloaderProvider(): array { + public static function rangeGetMultipartDownloaderProvider(): array + { return [ [ 'objectKey' => 'ObjectKey_1', @@ -259,10 +262,9 @@ public function testNextCommandIncludesIfMatchWhenETagPresent(): void * @param int $targetPartSize * @param string $eTag * - * @dataProvider ifMatchIsPresentInEachRangeRequestAfterFirstProvider - * * @return void */ + #[DataProvider('ifMatchIsPresentInEachRangeRequestAfterFirstProvider')] public function testIfMatchIsPresentInEachRangeRequestAfterFirst( int $objectSizeInBytes, int $targetPartSize, @@ -336,7 +338,7 @@ public function testIfMatchIsPresentInEachRangeRequestAfterFirst( /** * @return Generator */ - public function ifMatchIsPresentInEachRangeRequestAfterFirstProvider(): Generator + public static function ifMatchIsPresentInEachRangeRequestAfterFirstProvider(): Generator { yield 'multipart_download_with_3_parts_1' => [ 'object_size_in_bytes' => 1024 * 1024 * 20, diff --git a/tests/S3/S3Transfer/S3TransferManagerTest.php b/tests/S3/S3Transfer/S3TransferManagerTest.php index 0bc349d24d..9067c1a0f8 100644 --- a/tests/S3/S3Transfer/S3TransferManagerTest.php +++ b/tests/S3/S3Transfer/S3TransferManagerTest.php @@ -40,6 +40,7 @@ use RecursiveDirectoryIterator; use RuntimeException; use function Aws\filter; +use PHPUnit\Framework\Attributes\DataProvider; class S3TransferManagerTest extends TestCase { @@ -198,13 +199,14 @@ public function testUploadExpectsAReadableSource(): void } /** - * @dataProvider uploadBucketAndKeyProvider * * @param array $bucketKeyArgs * @param string $missingProperty * * @return void - */ + + */ + #[DataProvider('uploadBucketAndKeyProvider')] public function testUploadFailsWhenBucketAndKeyAreNotProvided( array $bucketKeyArgs, string $missingProperty @@ -226,7 +228,7 @@ public function testUploadFailsWhenBucketAndKeyAreNotProvided( /** * @return array[] */ - public function uploadBucketAndKeyProvider(): array + public static function uploadBucketAndKeyProvider(): array { return [ 'bucket_missing' => [ @@ -378,10 +380,10 @@ public function testUploadUsesTransferManagerConfigDefaultMupThreshold(): void * @param int $expectedPartSize * @param bool $isMultipartUpload * - * @dataProvider uploadUsesCustomMupThresholdProvider - * * @return void - */ + + */ + #[DataProvider('uploadUsesCustomMupThresholdProvider')] public function testUploadUsesCustomMupThreshold( int $mupThreshold, int $expectedPartCount, @@ -430,7 +432,7 @@ public function testUploadUsesCustomMupThreshold( /** * @return array */ - public function uploadUsesCustomMupThresholdProvider(): array + public static function uploadUsesCustomMupThresholdProvider(): array { return [ 'mup_threshold_multipart_upload' => [ @@ -547,10 +549,10 @@ public function testUploadUsesDefaultChecksumAlgorithm(): void /** * @param string $checksumAlgorithm * - * @dataProvider uploadUsesCustomChecksumAlgorithmProvider - * * @return void - */ + + */ + #[DataProvider('uploadUsesCustomChecksumAlgorithmProvider')] public function testUploadUsesCustomChecksumAlgorithm( string $checksumAlgorithm, ): void @@ -564,7 +566,7 @@ public function testUploadUsesCustomChecksumAlgorithm( /** * @return array[] */ - public function uploadUsesCustomChecksumAlgorithmProvider(): array + public static function uploadUsesCustomChecksumAlgorithmProvider(): array { return [ 'checksum_crc32c' => [ @@ -631,10 +633,10 @@ private function testUploadResolvedChecksum( * @param string $directory * @param bool $isDirectoryValid * - * @dataProvider uploadDirectoryValidatesProvidedDirectoryProvider - * * @return void - */ + + */ + #[DataProvider('uploadDirectoryValidatesProvidedDirectoryProvider')] public function testUploadDirectoryValidatesProvidedDirectory( string $directory, bool $isDirectoryValid @@ -676,7 +678,7 @@ public function testUploadDirectoryValidatesProvidedDirectory( /** * @return array[] */ - public function uploadDirectoryValidatesProvidedDirectoryProvider(): array + public static function uploadDirectoryValidatesProvidedDirectoryProvider(): array { return [ 'valid_directory' => [ @@ -1549,13 +1551,14 @@ public function testDownloadFailsOnInvalidS3UriSource(): void } /** - * @dataProvider downloadFailsWhenSourceAsArrayMissesBucketOrKeyPropertyProvider * * @param array $sourceAsArray * @param string $expectedExceptionMessage * * @return void - */ + + */ + #[DataProvider('downloadFailsWhenSourceAsArrayMissesBucketOrKeyPropertyProvider')] public function testDownloadFailsWhenSourceAsArrayMissesBucketOrKeyProperty( array $sourceAsArray, string $expectedExceptionMessage, @@ -1575,7 +1578,7 @@ public function testDownloadFailsWhenSourceAsArrayMissesBucketOrKeyProperty( /** * @return array */ - public function downloadFailsWhenSourceAsArrayMissesBucketOrKeyPropertyProvider(): array + public static function downloadFailsWhenSourceAsArrayMissesBucketOrKeyPropertyProvider(): array { return [ 'missing_key' => [ @@ -1673,9 +1676,10 @@ public function testDownloadWorksWithBucketAndKeyAsSource(): void * @param bool $expectedChecksumMode * * @return void - * @dataProvider downloadAppliesChecksumProvider * - */ + + */ + #[DataProvider('downloadAppliesChecksumProvider')] public function testDownloadAppliesChecksumMode( array $transferManagerConfig, array $downloadConfig, @@ -1727,7 +1731,7 @@ public function testDownloadAppliesChecksumMode( /** * @return array */ - public function downloadAppliesChecksumProvider(): array + public static function downloadAppliesChecksumProvider(): array { return [ 'checksum_mode_from_default_transfer_manager_config' => [ @@ -1797,10 +1801,10 @@ public function downloadAppliesChecksumProvider(): array * @param string $multipartDownloadType * @param string $expectedParameter * - * @dataProvider downloadChoosesMultipartDownloadTypeProvider - * * @return void - */ + + */ + #[DataProvider('downloadChoosesMultipartDownloadTypeProvider')] public function testDownloadChoosesMultipartDownloadType( string $multipartDownloadType, string $expectedParameter @@ -1840,7 +1844,7 @@ public function testDownloadChoosesMultipartDownloadType( /** * @return array */ - public function downloadChoosesMultipartDownloadTypeProvider(): array + public static function downloadChoosesMultipartDownloadTypeProvider(): array { return [ 'part_get_multipart_download' => [ @@ -1861,9 +1865,9 @@ public function downloadChoosesMultipartDownloadTypeProvider(): array * * @return void * - * @dataProvider rangeGetMultipartDownloadMinimumPartSizeProvider - * - */ + + */ + #[DataProvider('rangeGetMultipartDownloadMinimumPartSizeProvider')] public function testRangeGetMultipartDownloadMinimumPartSize( int $minimumPartSize, int $objectSize, @@ -1913,7 +1917,7 @@ public function testRangeGetMultipartDownloadMinimumPartSize( /** * @return array */ - public function rangeGetMultipartDownloadMinimumPartSizeProvider(): array + public static function rangeGetMultipartDownloadMinimumPartSizeProvider(): array { return [ 'minimum_part_size_1' => [ @@ -2005,10 +2009,10 @@ public function testDownloadDirectoryCreatesDestinationDirectory(): void * @param array $config * @param string $expectedS3Prefix * - * @dataProvider downloadDirectoryAppliesS3PrefixProvider - * * @return void - */ + + */ + #[DataProvider('downloadDirectoryAppliesS3PrefixProvider')] public function testDownloadDirectoryAppliesS3Prefix( array $config, string $expectedS3Prefix @@ -2077,7 +2081,7 @@ public function testDownloadDirectoryAppliesS3Prefix( /** * @return array */ - public function downloadDirectoryAppliesS3PrefixProvider(): array + public static function downloadDirectoryAppliesS3PrefixProvider(): array { return [ 's3_prefix_from_config' => [ @@ -2294,10 +2298,10 @@ public function testDownloadDirectoryUsesFailurePolicy(): void * @param array $objectList * @param array $expectedObjectList * - * @dataProvider downloadDirectoryAppliesFilterProvider - * * @return void - */ + + */ + #[DataProvider('downloadDirectoryAppliesFilterProvider')] public function testDownloadDirectoryAppliesFilter( Closure $filter, array $objectList, @@ -2398,7 +2402,7 @@ public function testDownloadDirectoryAppliesFilter( /** * @return array[] */ - public function downloadDirectoryAppliesFilterProvider(): array + public static function downloadDirectoryAppliesFilterProvider(): array { return [ 'filter_1' => [ @@ -2611,10 +2615,10 @@ public function testDownloadDirectoryGetObjectRequestCallbackWorks(): void * @param array $listObjectsContent * @param array $expectedFileKeys * - * @dataProvider downloadDirectoryCreateFilesProvider - * * @return void - */ + + */ + #[DataProvider('downloadDirectoryCreateFilesProvider')] public function testDownloadDirectoryCreateFiles( array $listObjectsContent, array $expectedFileKeys, @@ -2688,7 +2692,7 @@ public function testDownloadDirectoryCreateFiles( /** * @return array */ - public function downloadDirectoryCreateFilesProvider(): array + public static function downloadDirectoryCreateFilesProvider(): array { return [ 'files_1' => [ @@ -2726,8 +2730,9 @@ public function downloadDirectoryCreateFilesProvider(): array * @param array $expectedOutput * * @return void - * @dataProvider resolvesOutsideTargetDirectoryProvider - */ + + */ + #[DataProvider('resolvesOutsideTargetDirectoryProvider')] public function testResolvesOutsideTargetDirectory( ?string $prefix, array $objects, @@ -2822,7 +2827,7 @@ public function testResolvesOutsideTargetDirectory( /** * @return array */ - public function resolvesOutsideTargetDirectoryProvider(): array + public static function resolvesOutsideTargetDirectoryProvider(): array { return [ 'download_directory_1_linux' => [ @@ -2929,9 +2934,10 @@ public function resolvesOutsideTargetDirectoryProvider(): array * @param array $outcomes * * @return void - * @dataProvider modeledDownloadCasesProvider * - */ + + */ + #[DataProvider('modeledDownloadCasesProvider')] public function testModeledCasesForDownload( string $testId, array $config, @@ -3104,9 +3110,10 @@ public function bytesTransferred(array $context): bool { * @param array $outcomes * * @return void - * @dataProvider modeledUploadCasesProvider * - */ + + */ + #[DataProvider('modeledUploadCasesProvider')] public function testModeledCasesForUpload( string $testId, array $config, @@ -3253,8 +3260,9 @@ public function bytesTransferred(array $context): bool { * @param array $outcomes * * @return void - * @dataProvider modeledUploadDirectoryCasesProvider - */ + + */ + #[DataProvider('modeledUploadDirectoryCasesProvider')] public function testModeledCasesForUploadDirectory( string $testId, array $config, @@ -3419,9 +3427,10 @@ function (string $operation, ?array $body): StreamInterface { * @param array $outcomes * * @return void - * @dataProvider modeledDownloadDirectoryCasesProvider * - */ + + */ + #[DataProvider('modeledDownloadDirectoryCasesProvider')] public function testModeledCasesForDownloadDirectory( string $testId, array $config, @@ -3682,7 +3691,7 @@ private function parseConfigFromCamelCaseToSnakeCase( /** * @return Generator */ - public function modeledDownloadCasesProvider(): Generator + public static function modeledDownloadCasesProvider(): Generator { $downloadCases = json_decode( file_get_contents( @@ -3704,7 +3713,7 @@ public function modeledDownloadCasesProvider(): Generator /** * @return Generator */ - public function modeledUploadCasesProvider(): Generator + public static function modeledUploadCasesProvider(): Generator { $downloadCases = json_decode( file_get_contents( @@ -3726,7 +3735,7 @@ public function modeledUploadCasesProvider(): Generator /** * @return Generator */ - public function modeledUploadDirectoryCasesProvider(): Generator + public static function modeledUploadDirectoryCasesProvider(): Generator { $uploadDirectoryCases = json_decode( file_get_contents( @@ -3761,7 +3770,7 @@ public function modeledUploadDirectoryCasesProvider(): Generator /** * @return Generator */ - public function modeledDownloadDirectoryCasesProvider(): Generator + public static function modeledDownloadDirectoryCasesProvider(): Generator { $downloadDirectoryCases = json_decode( file_get_contents( diff --git a/tests/S3/S3UriParserTest.php b/tests/S3/S3UriParserTest.php index 39c9b4d864..0ca0cea815 100644 --- a/tests/S3/S3UriParserTest.php +++ b/tests/S3/S3UriParserTest.php @@ -4,13 +4,13 @@ use Aws\Arn\Exception\InvalidArnException; use Aws\S3\S3UriParser; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\S3\S3UriParser - */ +#[CoversClass(S3UriParser::class)] class S3UriParserTest extends TestCase { - public function uriProvider() + public static function uriProvider(): array { return [ ['http://s3.amazonaws.com', ['region' => null, 'bucket' => null, 'key' => null, 'path_style' => true]], @@ -89,9 +89,7 @@ public function uriProvider() ]; } - /** - * @dataProvider uriProvider - */ + #[DataProvider('uriProvider')] public function testParsesUrls($uri, $result, $isError = false) { ksort($result); diff --git a/tests/S3/SSECMiddlewareTest.php b/tests/S3/SSECMiddlewareTest.php index 21dfd1f83d..4d6ebe1f5a 100644 --- a/tests/S3/SSECMiddlewareTest.php +++ b/tests/S3/SSECMiddlewareTest.php @@ -3,19 +3,19 @@ use Aws\Middleware; use Aws\Result; +use Aws\S3\SSECMiddleware; use Aws\Test\UsesServiceTrait; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversNothing; +use PHPUnit\Framework\Attributes\DataProvider; use Yoast\PHPUnitPolyfills\TestCases\TestCase; -/** - * @covers Aws\S3\SSECMiddleware - */ +#[CoversClass(SSECMiddleware::class)] class SSECMiddlewareTest extends TestCase { use UsesServiceTrait; - /** - * @dataProvider getListenerTestCases - */ + #[DataProvider('getListenerTestCases')] public function testSseCpkListener($operation, array $params, array $expectedResults) { $s3 = $this->getTestClient('s3'); @@ -31,7 +31,7 @@ public function testSseCpkListener($operation, array $params, array $expectedRes $s3->execute($cmd); } - public function getListenerTestCases() + public static function getListenerTestCases(): array { return [ [ @@ -85,11 +85,12 @@ public function testCannotUseWithoutHttps() ]); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testCanUseWithoutHttpsForNonSse() { $client = $this->getTestClient('s3', ['scheme' => 'http']); $this->addMockResults($client, [new Result()]); $client->listBuckets(); + $this->assertTrue(true); } } diff --git a/tests/S3/StreamWrapperPathStyleTest.php b/tests/S3/StreamWrapperPathStyleTest.php index b0a4e373dd..47a7f62801 100644 --- a/tests/S3/StreamWrapperPathStyleTest.php +++ b/tests/S3/StreamWrapperPathStyleTest.php @@ -12,10 +12,11 @@ use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversNothing; -/** - * @covers Aws\S3\StreamWrapper - */ +#[CoversClass(StreamWrapper::class)] class StreamWrapperPathStyleTest extends TestCase { use UsesServiceTrait; @@ -36,6 +37,9 @@ public function set_up() 'use_path_style_endpoint' => true ]); $this->client->registerStreamWrapper(); + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }); } public function tear_down() @@ -49,31 +53,32 @@ public function testRegistersStreamWrapperOnlyOnce() StreamWrapper::register($this->client); $this->assertContains('s3', stream_get_wrappers()); StreamWrapper::register($this->client); + restore_error_handler(); } public function testCannotOpenBuckets() { + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage("Cannot open a bucket"); - $this->expectWarning(); fopen('s3://bucket', 'r'); } public function testSupportsOnlyReadWriteXA() { + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage("Mode not supported"); - $this->expectWarning(); fopen('s3://bucket/key', 'c'); } public function testValidatesXMode() { + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage("s3://bucket/key already exists on Amazon S3"); - $this->expectWarning(); $this->addMockResults($this->client, [new Result()]); fopen('s3://bucket/key', 'x'); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testSuccessfulXMode() { $this->addMockResults( @@ -87,6 +92,7 @@ function ($cmd, $request) { ); $r = fopen('s3://bucket/key', 'x'); fclose($r); + $this->assertTrue(true); } public function testOpensNonSeekableReadStream() @@ -171,7 +177,7 @@ public function testCanOpenWriteOnlyStreams() public function testTriggersErrorInsteadOfExceptionWhenWriteFlushFails() { $this->expectExceptionMessage("403 Forbidden"); - $this->expectWarning(); + $this->expectException(\RuntimeException::class); $this->addMockResults($this->client, [ function ($cmd, $req) { return new S3Exception('403 Forbidden', $cmd); } ]); @@ -239,8 +245,8 @@ public function testCanUnlinkFiles() public function testThrowsErrorsWhenUnlinkFails() { + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage("403 Forbidden"); - $this->expectWarning(); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -254,7 +260,7 @@ public function testCreatingBucketWithNoBucketReturnsFalse() public function testCreatingAlreadyExistingBucketRaisesError() { - $this->expectWarning(); + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage("Bucket already exists: s3://already-existing-bucket"); $this->addMockResults($this->client, [new Result()]); mkdir('s3://already-existing-bucket'); @@ -262,7 +268,7 @@ public function testCreatingAlreadyExistingBucketRaisesError() public function testCreatingAlreadyExistingBucketForKeyRaisesError() { - $this->expectWarning(); + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage("Subfolder already exists: s3://already-existing-bucket/key"); $this->addMockResults($this->client, [new Result()]); mkdir('s3://already-existing-bucket/key'); @@ -321,15 +327,15 @@ function ($cmd, $r) { return new S3Exception('404', $cmd); }, public function testCannotDeleteS3() { + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage("specify a bucket"); - $this->expectWarning(); rmdir('s3://'); } public function testRmDirWithExceptionTriggersError() { + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage("403 Forbidden"); - $this->expectWarning(); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -349,7 +355,7 @@ public function testCanDeleteBucketWithRmDir() $this->assertSame('s3.amazonaws.com', $entries[0]['request']->getUri()->getHost()); } - public function rmdirProvider() + public static function rmdirProvider(): array { return [ ['s3://bucket/object/'], @@ -357,9 +363,7 @@ public function rmdirProvider() ]; } - /** - * @dataProvider rmdirProvider - */ + #[DataProvider('rmdirProvider')] public function testCanDeleteObjectWithRmDir($path) { $history = new History(); @@ -396,8 +400,8 @@ public function testCanDeleteNestedFolderWithRmDir() public function testRenameEnsuresProtocolsMatch() { + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage("rename(): Cannot rename a file across wrapper types"); - $this->expectWarning(); StreamWrapper::register($this->client, 'baz'); rename('s3://foo/bar', 'baz://qux/quux'); } @@ -405,14 +409,14 @@ public function testRenameEnsuresProtocolsMatch() public function testRenameEnsuresKeyIsSet() { $this->expectExceptionMessage("The Amazon S3 stream wrapper only supports copying objects"); - $this->expectWarning(); + $this->expectException(\RuntimeException::class); rename('s3://foo/bar', 's3://baz'); } public function testRenameWithExceptionThrowsError() { $this->expectExceptionMessage("Forbidden"); - $this->expectWarning(); + $this->expectException(\RuntimeException::class); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, ]); @@ -512,7 +516,7 @@ public function testCanPullStatDataFromCache() public function testFailingStatTriggersError() { $this->expectExceptionMessage("Forbidden"); - $this->expectWarning(); + $this->expectException(\RuntimeException::class); // Sends one request for HeadObject, then another for ListObjects $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, @@ -525,7 +529,7 @@ function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); } public function testBucketNotFoundTriggersError() { $this->expectExceptionMessage("File or directory not found: s3://bucket"); - $this->expectWarning(); + $this->expectException(\RuntimeException::class); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('404', $cmd); }, ]); @@ -569,8 +573,8 @@ function ($cmd, $r) { return new S3Exception('404', $cmd); }, public function testCannotStatPrefixWithNoResults() { + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage("File or directory not found: s3://bucket/prefix"); - $this->expectWarning(); $this->addMockResults($this->client, [ function ($cmd, $r) { return new S3Exception('404', $cmd); }, new Result() @@ -579,7 +583,7 @@ function ($cmd, $r) { return new S3Exception('404', $cmd); }, stat('s3://bucket/prefix'); } - public function fileTypeProvider() + public static function fileTypeProvider(): array { $err = function ($cmd, $r) { return new S3Exception('404', $cmd); }; @@ -612,9 +616,7 @@ public function fileTypeProvider() ]; } - /** - * @dataProvider fileTypeProvider - */ + #[DataProvider('fileTypeProvider')] public function testDeterminesIfFileOrDir($uri, $queue, $result) { $history = new History(); @@ -642,13 +644,8 @@ public function testDeterminesIfFileOrDir($uri, $queue, $result) public function testStreamCastIsNotPossible() { - if (PHP_VERSION_ID < 80000) { - $this->expectExceptionMessage("cannot represent a stream of type user-space"); - $this->expectWarning(); - } else { - $this->expectExceptionMessage('No stream arrays were passed'); - $this->expectException(\ValueError::class); - } + $this->expectException(\ValueError::class); + $this->expectExceptionMessage('No stream arrays were passed'); $this->addMockResults($this->client, [ new Result(['Body' => Psr7\Utils::streamFor('')]) @@ -661,11 +658,17 @@ public function testStreamCastIsNotPossible() public function testEnsuresClientIsSet() { + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }); $this->expectExceptionMessage("No client in stream context"); - $this->expectWarning(); - fopen('s3://bucket/key', 'r', false, stream_context_create([ - 's3' => ['client' => null] - ])); + try { + fopen('s3://bucket/key', 'r', false, stream_context_create([ + 's3' => ['client' => null] + ])); + } finally { + restore_error_handler(); + } } public function testDoesNotErrorOnIsLink() @@ -766,7 +769,7 @@ public function testProvidesDirectoriesForS3() closedir($r); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testCanSetDelimiterStreamContext() { $this->addMockResults($this->client, [ @@ -792,6 +795,7 @@ public function testCanSetDelimiterStreamContext() $context = stream_context_create(['s3' => ['delimiter' => '']]); $r = opendir('s3://bucket', $context); closedir($r); + $this->assertTrue(true); } public function testCachesReaddirs() diff --git a/tests/S3/StreamWrapperTest.php b/tests/S3/StreamWrapperTest.php index 88840c2c27..6db538b091 100644 --- a/tests/S3/StreamWrapperTest.php +++ b/tests/S3/StreamWrapperTest.php @@ -13,10 +13,11 @@ use GuzzleHttp\Psr7; use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversNothing; -/** - * @covers Aws\S3\StreamWrapper - */ +#[CoversClass(StreamWrapper::class)] class StreamWrapperTest extends TestCase { use UsesServiceTrait; @@ -40,6 +41,7 @@ public function tear_down() { stream_wrapper_unregister('s3'); $this->client = null; + restore_exception_handler(); // In case it was not restored } public function testRegistersStreamWrapperOnlyOnce() @@ -51,37 +53,69 @@ public function testRegistersStreamWrapperOnlyOnce() public function testCannotOpenBuckets() { + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage("Cannot open a bucket"); - $this->expectWarning(); - fopen('s3://bucket', 'r'); + + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + fopen('s3://bucket', 'r'); + } finally { + restore_error_handler(); + } } public function testSupportsOnlyReadWriteXA() { $this->expectExceptionMessage("Mode not supported"); - $this->expectWarning(); - fopen('s3://bucket/key', 'c'); + $this->expectException(\RuntimeException::class); + + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + fopen('s3://bucket/key', 'c'); + } finally { + restore_error_handler(); + } } public function testValidatesXMode() { $this->expectExceptionMessage("s3://bucket/key already exists on Amazon S3"); - $this->expectWarning(); - $this->addMockResults($this->client, [new Result()]); - fopen('s3://bucket/key', 'x'); + $this->expectException(\RuntimeException::class); + + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + $this->addMockResults($this->client, [new Result()]); + fopen('s3://bucket/key', 'x'); + } finally { + restore_error_handler(); + } } public function testValidatesArn() { + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage( "Invalid ARN: Unrecognized format:" . " arn:aws:s3:us-east-1:123456789012:foo:myaccess (type: foo)" ); - $this->expectWarning(); - fopen('s3://arn:aws:s3:us-east-1:123456789012:foo:myaccess/test_key', 'r'); + + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + fopen('s3://arn:aws:s3:us-east-1:123456789012:foo:myaccess/test_key', 'r'); + } finally { + restore_error_handler(); + } } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testSuccessfulXMode() { $this->addMockResults( @@ -95,6 +129,7 @@ function ($cmd, $request) { ); $r = fopen('s3://bucket/key', 'x'); fclose($r); + $this->assertTrue(true); } public function testOpensNonSeekableReadStream() @@ -284,13 +319,21 @@ public function testCanWriteEmptyFileToStream() public function testTriggersErrorInsteadOfExceptionWhenWriteFlushFails() { $this->expectExceptionMessage("403 Forbidden"); - $this->expectWarning(); - $this->addMockResults($this->client, [ - function ($cmd, $req) { return new S3Exception('403 Forbidden', $cmd); } - ]); - $s = fopen('s3://bucket/key', 'w'); - fwrite($s, 'test'); - fclose($s); + $this->expectException(\RuntimeException::class); + + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + $this->addMockResults($this->client, [ + function ($cmd, $req) { return new S3Exception('403 Forbidden', $cmd); } + ]); + $s = fopen('s3://bucket/key', 'w'); + fwrite($s, 'test'); + fclose($s); + } finally { + restore_error_handler(); + } } public function testCanOpenAppendStreamsWithOriginalFile() @@ -353,11 +396,19 @@ public function testCanUnlinkFiles() public function testThrowsErrorsWhenUnlinkFails() { $this->expectExceptionMessage("403 Forbidden"); - $this->expectWarning(); - $this->addMockResults($this->client, [ - function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, - ]); - $this->assertFalse(unlink('s3://bucket/key')); + $this->expectException(\RuntimeException::class); + + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + $this->addMockResults($this->client, [ + function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, + ]); + $this->assertFalse(unlink('s3://bucket/key')); + } finally { + restore_error_handler(); + } } public function testCreatingBucketWithNoBucketReturnsFalse() @@ -367,18 +418,34 @@ public function testCreatingBucketWithNoBucketReturnsFalse() public function testCreatingAlreadyExistingBucketRaisesError() { - $this->expectWarning(); + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage("Bucket already exists: s3://already-existing-bucket"); - $this->addMockResults($this->client, [new Result()]); - mkdir('s3://already-existing-bucket'); + + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + $this->addMockResults($this->client, [new Result()]); + mkdir('s3://already-existing-bucket'); + } finally { + restore_error_handler(); + } } public function testCreatingAlreadyExistingBucketForKeyRaisesError() { - $this->expectWarning(); + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage("Subfolder already exists: s3://already-existing-bucket/key"); - $this->addMockResults($this->client, [new Result()]); - mkdir('s3://already-existing-bucket/key'); + + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + $this->addMockResults($this->client, [new Result()]); + mkdir('s3://already-existing-bucket/key'); + } finally { + restore_error_handler(); + } } public function testCreatingBucketsDoesNotSetAcl() @@ -434,19 +501,34 @@ function ($cmd, $r) { return new S3Exception('404', $cmd); }, public function testCannotDeleteS3() { + $this->expectException(\RuntimeException::class); $this->expectExceptionMessage("specify a bucket"); - $this->expectWarning(); - rmdir('s3://'); + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + rmdir('s3://'); + } finally { + restore_error_handler(); + } } public function testRmDirWithExceptionTriggersError() { $this->expectExceptionMessage("403 Forbidden"); - $this->expectWarning(); - $this->addMockResults($this->client, [ - function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, - ]); - rmdir('s3://bucket'); + $this->expectException(\RuntimeException::class); + + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + $this->addMockResults($this->client, [ + function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, + ]); + rmdir('s3://bucket'); + } finally { + restore_error_handler(); + } } public function testCanDeleteBucketWithRmDir() @@ -462,7 +544,7 @@ public function testCanDeleteBucketWithRmDir() $this->assertSame('bucket.s3.amazonaws.com', $entries[0]['request']->getUri()->getHost()); } - public function rmdirProvider() + public static function rmdirProvider(): array { return [ ['s3://bucket/object/'], @@ -470,9 +552,7 @@ public function rmdirProvider() ]; } - /** - * @dataProvider rmdirProvider - */ + #[DataProvider('rmdirProvider')] public function testCanDeleteObjectWithRmDir($path) { $history = new History(); @@ -511,26 +591,50 @@ public function testCanDeleteNestedFolderWithRmDir() public function testRenameEnsuresProtocolsMatch() { $this->expectExceptionMessage("rename(): Cannot rename a file across wrapper types"); - $this->expectWarning(); - StreamWrapper::register($this->client, 'baz'); - rename('s3://foo/bar', 'baz://qux/quux'); + $this->expectException(\RuntimeException::class); + + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_WARNING); + try { + StreamWrapper::register($this->client, 'baz'); + rename('s3://foo/bar', 'baz://qux/quux'); + } finally { + restore_error_handler(); + } } public function testRenameEnsuresKeyIsSet() { $this->expectExceptionMessage("The Amazon S3 stream wrapper only supports copying objects"); - $this->expectWarning(); - rename('s3://foo/bar', 's3://baz'); + $this->expectException(\RuntimeException::class); + + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + rename('s3://foo/bar', 's3://baz'); + } finally { + restore_error_handler(); + } } public function testRenameWithExceptionThrowsError() { $this->expectExceptionMessage("Forbidden"); - $this->expectWarning(); - $this->addMockResults($this->client, [ - function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, - ]); - rename('s3://foo/bar', 's3://baz/bar'); + $this->expectException(\RuntimeException::class); + + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + $this->addMockResults($this->client, [ + function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, + ]); + rename('s3://foo/bar', 's3://baz/bar'); + } finally { + restore_error_handler(); + } } public function testCanRenameObjects() @@ -627,25 +731,41 @@ public function testCanPullStatDataFromCache() public function testFailingStatTriggersError() { $this->expectExceptionMessage("Forbidden"); - $this->expectWarning(); - // Sends one request for HeadObject, then another for ListObjects - $this->addMockResults($this->client, [ - function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, - function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); } - ]); - clearstatcache('s3://bucket/key'); - stat('s3://bucket/key'); + $this->expectException(\RuntimeException::class); + + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + // Sends one request for HeadObject, then another for ListObjects + $this->addMockResults($this->client, [ + function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, + function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); } + ]); + clearstatcache('s3://bucket/key'); + stat('s3://bucket/key'); + } finally { + restore_error_handler(); + } } public function testBucketNotFoundTriggersError() { $this->expectExceptionMessage("File or directory not found: s3://bucket"); - $this->expectWarning(); - $this->addMockResults($this->client, [ - function ($cmd, $r) { return new S3Exception('404', $cmd); }, - ]); - clearstatcache('s3://bucket'); - stat('s3://bucket'); + $this->expectException(\RuntimeException::class); + + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + $this->addMockResults($this->client, [ + function ($cmd, $r) { return new S3Exception('404', $cmd); }, + ]); + clearstatcache('s3://bucket'); + stat('s3://bucket'); + } finally { + restore_error_handler(); + } } public function testStatsRegularObjects() @@ -708,16 +828,24 @@ function ($cmd, $r) { return new S3Exception('404', $cmd); }, public function testCannotStatPrefixWithNoResults() { $this->expectExceptionMessage("File or directory not found: s3://bucket/prefix"); - $this->expectWarning(); - $this->addMockResults($this->client, [ - function ($cmd, $r) { return new S3Exception('404', $cmd); }, - new Result() - ]); - clearstatcache('s3://bucket/prefix'); - stat('s3://bucket/prefix'); + $this->expectException(\RuntimeException::class); + + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + $this->addMockResults($this->client, [ + function ($cmd, $r) { return new S3Exception('404', $cmd); }, + new Result() + ]); + clearstatcache('s3://bucket/prefix'); + stat('s3://bucket/prefix'); + } finally { + restore_error_handler(); + } } - public function fileTypeProvider() + public static function fileTypeProvider(): array { $err = function ($cmd, $r) { return new S3Exception('404', $cmd); }; @@ -750,9 +878,7 @@ public function fileTypeProvider() ]; } - /** - * @dataProvider fileTypeProvider - */ + #[DataProvider('fileTypeProvider')] public function testDeterminesIfFileOrDir($uri, $queue, $result) { $history = new History(); @@ -780,13 +906,8 @@ public function testDeterminesIfFileOrDir($uri, $queue, $result) public function testStreamCastIsNotPossible() { - if (PHP_VERSION_ID < 80000) { - $this->expectExceptionMessage("cannot represent a stream of type user-space"); - $this->expectWarning(); - } else { - $this->expectExceptionMessage('No stream arrays were passed'); - $this->expectException(\ValueError::class); - } + $this->expectExceptionMessage('No stream arrays were passed'); + $this->expectException(\ValueError::class); $this->addMockResults($this->client, [ new Result(['Body' => Psr7\Utils::streamFor('')]) @@ -800,10 +921,18 @@ public function testStreamCastIsNotPossible() public function testEnsuresClientIsSet() { $this->expectExceptionMessage("No client in stream context"); - $this->expectWarning(); - fopen('s3://bucket/key', 'r', false, stream_context_create([ - 's3' => ['client' => null] - ])); + $this->expectException(\RuntimeException::class); + + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + fopen('s3://bucket/key', 'r', false, stream_context_create([ + 's3' => ['client' => null] + ])); + } finally { + restore_error_handler(); + } } public function testDoesNotErrorOnIsLink() @@ -904,7 +1033,7 @@ public function testProvidesDirectoriesForS3() closedir($r); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testCanSetDelimiterStreamContext() { $this->addMockResults($this->client, [ @@ -930,6 +1059,7 @@ public function testCanSetDelimiterStreamContext() $context = stream_context_create(['s3' => ['delimiter' => '']]); $r = opendir('s3://bucket', $context); closedir($r); + $this->assertTrue(true); } public function testCachesReaddirs() @@ -1025,7 +1155,7 @@ public function testStatDataIsClearedOnWriteUsingCustomProtocol() stream_wrapper_unregister('foo'); } - public function contentProvider() + public static function contentProvider(): array { return [ ['foo'], @@ -1033,14 +1163,15 @@ public function contentProvider() ]; } - /** - * @dataProvider contentProvider - */ - public function testTriggersErrorOnNoFlushOrClose($content) + #[DataProvider('contentProvider')] + public function testTriggersErrorOnNoFlushOrClose(string $content) { - $this->expectWarning(); - $this->expectWarning("Unable to determine stream size. Did you forget to close or flush the stream?"); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage("Unable to determine stream size. Did you forget to close or flush the stream?"); + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_USER_WARNING); $stream = $this->getMockBuilder(Psr7\Stream::class) ->disableOriginalConstructor() ->getMock(); @@ -1087,22 +1218,30 @@ public function testStreamMetadataReturnsFalse() public function testStreamLockReturnsFalse() { - $this->expectWarning(); - $this->expectWarningMessage( + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage( 'stream_lock() is not supported by the Amazon S3 stream wrapper' ); - $stream = $this->getMockBuilder(Psr7\Stream::class) - ->disableOriginalConstructor() - ->getMock(); - $this->addMockResults( - $this->client, - [ - new Result(['Body' => $stream]), - ] - ); - $handle = fopen('s3://bucket/key', 'r'); - $this->assertFalse(flock($handle, LOCK_EX)); + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + $stream = $this->getMockBuilder(Psr7\Stream::class) + ->disableOriginalConstructor() + ->getMock(); + + $this->addMockResults( + $this->client, + [ + new Result(['Body' => $stream]), + ] + ); + $handle = fopen('s3://bucket/key', 'r'); + $this->assertFalse(flock($handle, LOCK_EX)); + } finally { + restore_error_handler(); + } } public function testStreamTruncateReturnsFalse() diff --git a/tests/S3/StreamWrapperV2ExistenceTest.php b/tests/S3/StreamWrapperV2ExistenceTest.php index 2aef340996..2dc4fef839 100644 --- a/tests/S3/StreamWrapperV2ExistenceTest.php +++ b/tests/S3/StreamWrapperV2ExistenceTest.php @@ -12,12 +12,13 @@ use Aws\Test\UsesServiceTrait; use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Response; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversNothing; +use PHPUnit\Framework\Attributes\DataProvider; use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; -/** - * @covers Aws\S3\StreamWrapper - */ +#[CoversClass(StreamWrapper::class)] class StreamWrapperV2ExistenceTest extends TestCase { use UsesServiceTrait; @@ -43,9 +44,7 @@ public function tear_down() $this->client = null; } - /** - * @doesNotPerformAssertions - */ + #[CoversNothing] public function testSuccessfulXMode() { $this->addMockResults( @@ -63,6 +62,7 @@ function ($cmd, $request) { ); $r = fopen('s3://bucket/key', 'x'); fclose($r); + $this->assertTrue(true); } public function testOpensNonSeekableReadStream() @@ -239,14 +239,21 @@ public function testCanWriteEmptyFileToStream() public function testTriggersErrorInsteadOfExceptionWhenWriteFlushFails() { - $this->expectError(); - $this->expectErrorMessage('403 Forbidden'); - $this->addMockResults($this->client, [ - function ($cmd, $req) { return new S3Exception('403 Forbidden', $cmd); } - ]); - $s = fopen('s3://bucket/key', 'w'); - fwrite($s, 'test'); - fclose($s); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('403 Forbidden'); + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + $this->addMockResults($this->client, [ + function ($cmd, $req) { return new S3Exception('403 Forbidden', $cmd); } + ]); + $s = fopen('s3://bucket/key', 'w'); + fwrite($s, 'test'); + fclose($s); + } finally { + restore_error_handler(); + } } public function testCanOpenAppendStreamsWithOriginalFile() @@ -308,12 +315,20 @@ public function testCanUnlinkFiles() public function testThrowsErrorsWhenUnlinkFails() { - $this->expectError(); - $this->expectErrorMessage('403 Forbidden'); - $this->addMockResults($this->client, [ - function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, - ]); - $this->assertFalse(unlink('s3://bucket/key')); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('403 Forbidden'); + + set_error_handler(function ($err, $message){ + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + $this->addMockResults($this->client, [ + function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, + ]); + $this->assertFalse(unlink('s3://bucket/key')); + } finally { + restore_error_handler(); + } } public function testCreatingBucketWithNoBucketReturnsFalse() @@ -323,18 +338,34 @@ public function testCreatingBucketWithNoBucketReturnsFalse() public function testCreatingAlreadyExistingBucketRaisesError() { - $this->expectError(); - $this->expectErrorMessage('Bucket already exists: s3://already-existing-bucket'); - $this->addMockResults($this->client, [new Result()]); - mkdir('s3://already-existing-bucket'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Bucket already exists: s3://already-existing-bucket'); + + set_error_handler(function ($err, $message){ + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + $this->addMockResults($this->client, [new Result()]); + mkdir('s3://already-existing-bucket'); + } finally { + restore_error_handler(); + } } public function testCreatingAlreadyExistingBucketForKeyRaisesError() { - $this->expectError(); - $this->expectErrorMessage('Subfolder already exists: s3://already-existing-bucket/key'); - $this->addMockResults($this->client, [new Result()]); - mkdir('s3://already-existing-bucket/key'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Subfolder already exists: s3://already-existing-bucket/key'); + + set_error_handler(function ($err, $message){ + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + $this->addMockResults($this->client, [new Result()]); + mkdir('s3://already-existing-bucket/key'); + } finally { + restore_error_handler(); + } } public function testCreatingBucketsDoesNotSetAcl() @@ -407,19 +438,35 @@ function ($cmd, $r) { return new S3Exception( public function testCannotDeleteS3() { - $this->expectError(); - $this->expectErrorMessage('specify a bucket'); - rmdir('s3://'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('specify a bucket'); + + set_error_handler(function ($err, $message){ + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + rmdir('s3://'); + } finally { + restore_error_handler(); + } } public function testRmDirWithExceptionTriggersError() { - $this->expectError(); - $this->expectErrorMessage('403 Forbidden'); - $this->addMockResults($this->client, [ - function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, - ]); - rmdir('s3://bucket'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('403 Forbidden'); + + set_error_handler(function ($err, $message){ + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + $this->addMockResults($this->client, [ + function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, + ]); + rmdir('s3://bucket'); + } finally { + restore_error_handler(); + } } public function testCanDeleteBucketWithRmDir() @@ -435,7 +482,10 @@ public function testCanDeleteBucketWithRmDir() $this->assertSame('bucket.s3.amazonaws.com', $entries[0]['request']->getUri()->getHost()); } - public function rmdirProvider() + /** + * @return array> + */ + public static function rmdirProvider(): array { return [ ['s3://bucket/object/'], @@ -443,9 +493,7 @@ public function rmdirProvider() ]; } - /** - * @dataProvider rmdirProvider - */ + #[DataProvider('rmdirProvider')] public function testCanDeleteObjectWithRmDir($path) { $history = new History(); @@ -483,27 +531,52 @@ public function testCanDeleteNestedFolderWithRmDir() public function testRenameEnsuresProtocolsMatch() { - $this->expectError(); - $this->expectErrorMessage('rename(): Cannot rename a file across wrapper types'); - StreamWrapper::register($this->client, 'baz'); - rename('s3://foo/bar', 'baz://qux/quux'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('rename(): Cannot rename a file across wrapper types'); + + set_error_handler(function ($err, $message){ + throw new \RuntimeException($message); + }, E_WARNING); + try { + StreamWrapper::register($this->client, 'baz'); + rename('s3://foo/bar', 'baz://qux/quux'); + } finally { + restore_error_handler(); + } } public function testRenameEnsuresKeyIsSet() { - $this->expectError(); - $this->expectErrorMessage('The Amazon S3 stream wrapper only supports copying objects'); - rename('s3://foo/bar', 's3://baz'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('The Amazon S3 stream wrapper only supports copying objects'); + + set_error_handler(function ($err, $message){ + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + rename('s3://foo/bar', 's3://baz'); + } finally { + restore_error_handler(); + } } public function testRenameWithExceptionThrowsError() { - $this->expectError(); - $this->expectErrorMessage('Forbidden'); - $this->addMockResults($this->client, [ - function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, - ]); - rename('s3://foo/bar', 's3://baz/bar'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Forbidden'); + + set_error_handler(function ($err, $message){ + throw new \RuntimeException($message); + }, E_USER_WARNING); + + try { + $this->addMockResults($this->client, [ + function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, + ]); + rename('s3://foo/bar', 's3://baz/bar'); + } finally { + restore_error_handler(); + } } public function testCanRenameObjects() @@ -599,31 +672,47 @@ public function testCanPullStatDataFromCache() public function testFailingStatTriggersError() { - $this->expectError(); - $this->expectErrorMessage('Forbidden'); - // Sends one request for HeadObject, then another for ListObjects - $this->addMockResults($this->client, [ - function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, - function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); } - ]); - clearstatcache('s3://bucket/key'); - stat('s3://bucket/key'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('Forbidden'); + + set_error_handler(function ($err, $message){ + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + // Sends one request for HeadObject, then another for ListObjects + $this->addMockResults($this->client, [ + function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); }, + function ($cmd, $r) { return new S3Exception('403 Forbidden', $cmd); } + ]); + clearstatcache('s3://bucket/key'); + stat('s3://bucket/key'); + } finally { + restore_error_handler(); + } } public function testBucketNotFoundTriggersError() { - $this->expectError(); - $this->expectErrorMessage('File or directory not found: s3://bucket'); - $this->addMockResults($this->client, [ - function ($cmd, $r) { - return new S3Exception( - '404', - $cmd, - ['response' => new Response(404)] - );}, - ]); - clearstatcache('s3://bucket'); - stat('s3://bucket'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('File or directory not found: s3://bucket'); + + set_error_handler(function ($err, $message){ + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + $this->addMockResults($this->client, [ + function ($cmd, $r) { + return new S3Exception( + '404', + $cmd, + ['response' => new Response(404)] + );}, + ]); + clearstatcache('s3://bucket'); + stat('s3://bucket'); + } finally { + restore_error_handler(); + } } public function testStatsRegularObjects() @@ -667,22 +756,33 @@ function ($cmd, $r) { return new S3Exception( public function testCannotStatPrefixWithNoResults() { - $this->expectError(); - $this->expectErrorMessage('File or directory not found: s3://bucket/prefix'); - $this->addMockResults($this->client, [ - function ($cmd, $r) { return new S3Exception( - '404', - $cmd, - ['response' => new Response(404)] - ); - }, - new Result() - ]); - clearstatcache('s3://bucket/prefix'); - stat('s3://bucket/prefix'); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('File or directory not found: s3://bucket/prefix'); + + set_error_handler(function ($err, $message){ + throw new \RuntimeException($message); + }, E_USER_WARNING); + try { + $this->addMockResults($this->client, [ + function ($cmd, $r) { return new S3Exception( + '404', + $cmd, + ['response' => new Response(404)] + ); + }, + new Result() + ]); + clearstatcache('s3://bucket/prefix'); + stat('s3://bucket/prefix'); + } finally { + restore_error_handler(); + } } - public function fileTypeProvider() + /** + * @return array> + */ + public static function fileTypeProvider(): array { $err = function ($cmd, $r) { return new S3Exception( '404', @@ -720,9 +820,7 @@ public function fileTypeProvider() ]; } - /** - * @dataProvider fileTypeProvider - */ + #[DataProvider('fileTypeProvider')] public function testDeterminesIfFileOrDir($uri, $queue, $result) { $history = new History(); @@ -750,21 +848,24 @@ public function testDeterminesIfFileOrDir($uri, $queue, $result) public function testStreamCastIsNotPossible() { - if (PHP_VERSION_ID < 80000) { - $this->expectExceptionMessage("cannot represent a stream of type user-space"); - $this->expectWarning(); - } else { - $this->expectExceptionMessage('No stream arrays were passed'); - $this->expectException(\ValueError::class); + $this->expectExceptionMessage('No stream arrays were passed'); + $this->expectException(\ValueError::class); + + set_error_handler(function ($err, $message){ + throw new \RuntimeException($message); + }, E_USER_WARNING); + + try { + $this->addMockResults($this->client, [ + new Result(['Body' => Psr7\Utils::streamFor('')]) + ]); + $r = fopen('s3://bucket/key', 'r'); + $read = [$r]; + $write = $except = null; + stream_select($read, $write, $except, 0); + } finally { + restore_error_handler(); } - - $this->addMockResults($this->client, [ - new Result(['Body' => Psr7\Utils::streamFor('')]) - ]); - $r = fopen('s3://bucket/key', 'r'); - $read = [$r]; - $write = $except = null; - stream_select($read, $write, $except, 0); } public function testDoesNotErrorOnIsLink() diff --git a/tests/S3/TransferTest.php b/tests/S3/TransferTest.php index bd95ac2d64..95d9754058 100644 --- a/tests/S3/TransferTest.php +++ b/tests/S3/TransferTest.php @@ -13,10 +13,10 @@ use Psr\Http\Message\RequestInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; use SplFileInfo; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\S3\Transfer - */ +#[CoversClass(Transfer::class)] class TransferTest extends TestCase { use UsesServiceTrait; @@ -378,9 +378,7 @@ function (CommandInterface $cmd, RequestInterface $req) { $this->deleteDirectory($dir); } - /** - * @dataProvider providedPathsOutsideTarget - */ + #[DataProvider('providedPathsOutsideTarget')] public function testCannotDownloadObjectsOutsideTarget($key) { $this->expectException(\Aws\Exception\AwsException::class); @@ -409,7 +407,8 @@ public function testCannotDownloadObjectsOutsideTarget($key) $this->deleteDirectory($dir); } - public function providedPathsOutsideTarget() { + public static function providedPathsOutsideTarget(): array + { return [ ['bar/../a/b'], //ensures if path resolves to target directory @@ -517,9 +516,11 @@ public function testAddContentMd5EmitsDeprecationWarning() { $s3 = $this->getTestClient('s3'); $this->addMockResults($s3, []); - - $this->expectDeprecation(); - $this->expectDeprecationMessage('S3 no longer supports MD5 checksums.'); + set_error_handler(function ($err, $message) { + throw new \RuntimeException($message); + }, E_USER_DEPRECATED); + $this->expectException(\RuntimeException::class); + $this->expectExceptionMessage('S3 no longer supports MD5 checksums.'); $s3->getHandlerList()->appendSign(Middleware::tap( function (CommandInterface $cmd, RequestInterface $req) { $this->assertTrue(isset($command['x-amz-checksum-crc32'])); @@ -548,13 +549,7 @@ function (CommandInterface $cmd, RequestInterface $req) { $this->deleteDirectory($dir); } - /** - * @param $checksumAlgorithm - * @param $value - * @return void - * - * @dataProvider flexibleChecksumsProvider - */ + #[DataProvider('flexibleChecksumsProvider')] public function testAddsFlexibleChecksums($checksumAlgorithm) { if ($checksumAlgorithm === 'crc32c' @@ -612,7 +607,8 @@ function (CommandInterface $cmd, RequestInterface $req) use ($checksumAlgorithm) $this->deleteDirectory($dir); } - public function flexibleChecksumsProvider() { + public static function flexibleChecksumsProvider(): array + { return [ ['sha256'], ['sha1'], diff --git a/tests/S3/UseArnRegion/ConfigurationProviderTest.php b/tests/S3/UseArnRegion/ConfigurationProviderTest.php index 3cfea47ef3..241b02b65b 100644 --- a/tests/S3/UseArnRegion/ConfigurationProviderTest.php +++ b/tests/S3/UseArnRegion/ConfigurationProviderTest.php @@ -8,11 +8,10 @@ use Aws\S3\UseArnRegion\ConfigurationProvider; use Aws\S3\UseArnRegion\Exception\ConfigurationException; use GuzzleHttp\Promise; -use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\S3\UseArnRegion\ConfigurationProvider - */ +#[CoversClass(ConfigurationProvider::class)] class ConfigurationProviderTest extends TestCase { private static $originalEnv; @@ -31,7 +30,7 @@ class ConfigurationProviderTest extends TestCase s3_use_arn_region = true EOT; - public static function set_up_before_class() + public static function setUpBeforeClass(): void { self::$originalEnv = [ 'use_arn_region' => getenv(ConfigurationProvider::ENV_USE_ARN_REGION) ?: '', @@ -56,7 +55,7 @@ private function clearEnv() return $dir; } - public static function tear_down_after_class() + public static function tearDownAfterClass(): void { putenv(ConfigurationProvider::ENV_USE_ARN_REGION . '=' . self::$originalEnv['use_arn_region']); @@ -216,16 +215,15 @@ public function testEnsuresFileIsNotEmpty() public function testEnsuresIniFileIsValid() { $this->expectExceptionMessage("Invalid config file:"); - $this->expectException(\Aws\S3\UseArnRegion\Exception\ConfigurationException::class); + $this->expectException(ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); try { - @call_user_func(ConfigurationProvider::ini())->wait(); - } catch (\Exception $e) { + call_user_func(ConfigurationProvider::ini())->wait(); + } finally { unlink($dir . '/config'); - throw $e; } } @@ -338,7 +336,7 @@ public function testCreatesFromCache() { $expected = new Configuration(true); $cacheBuilder = $this->getMockBuilder(CacheInterface::class); - $cacheBuilder->setMethods(['get', 'set', 'remove']); + $cacheBuilder->onlyMethods(['get', 'set', 'remove']); $cache = $cacheBuilder->getMock(); $cache->expects($this->any()) ->method('get') @@ -352,4 +350,3 @@ public function testCreatesFromCache() $this->assertSame($expected->toArray(), $result->toArray()); } } - diff --git a/tests/S3/UseArnRegion/ConfigurationTest.php b/tests/S3/UseArnRegion/ConfigurationTest.php index 9f05028cee..f2ec7961d4 100644 --- a/tests/S3/UseArnRegion/ConfigurationTest.php +++ b/tests/S3/UseArnRegion/ConfigurationTest.php @@ -3,25 +3,20 @@ use Aws\S3\UseArnRegion\Configuration; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\S3\UseArnRegion\Configuration - */ +#[CoversClass(Configuration::class)] class ConfigurationTest extends TestCase { - /** - * @dataProvider correctValueCases - * - * @param $param - * @param $expected - */ + #[DataProvider('correctValueCases')] public function testGetsCorrectValues($param, $expected) { $config = new Configuration($param); $this->assertEquals($expected, $config->isUseArnRegion()); } - public function correctValueCases() + public static function correctValueCases(): array { return [ [true, true], diff --git a/tests/S3/ValidateResponseChecksumParserTest.php b/tests/S3/ValidateResponseChecksumParserTest.php index e987bbf51a..d30f39c049 100644 --- a/tests/S3/ValidateResponseChecksumParserTest.php +++ b/tests/S3/ValidateResponseChecksumParserTest.php @@ -10,17 +10,15 @@ use Aws\Result; use GuzzleHttp\Psr7\Response; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\S3\ValidateResponseChecksumParser - */ +#[CoversClass(ValidateResponseChecksumParser::class)] class ValidateResponseChecksumParserTest extends TestCase { use UsesServiceTrait; - /** - * @dataProvider getChosenChecksumCases - */ + #[DataProvider('getChosenChecksumCases')] public function testValidatesChoosesRightChecksum( $responseAlgorithms, $checksumHeadersReturned, $expectedChecksum ) { @@ -46,7 +44,7 @@ public function testValidatesChoosesRightChecksum( $this->assertEquals($expectedChecksum, $chosenChecksum); } - public function getChosenChecksumCases() + public static function getChosenChecksumCases(): array { return [ [['crc32', 'crc32c'], [], null], diff --git a/tests/S3Control/EndpointArnMiddlewareTest.php b/tests/S3Control/EndpointArnMiddlewareTest.php index 4b5bb26761..0e5d3970db 100644 --- a/tests/S3Control/EndpointArnMiddlewareTest.php +++ b/tests/S3Control/EndpointArnMiddlewareTest.php @@ -6,31 +6,20 @@ use Aws\Endpoint\PartitionEndpointProvider; use Aws\Exception\InvalidRegionException; use Aws\Middleware; +use Aws\S3Control\EndpointArnMiddleware; use GuzzleHttp\Promise; use GuzzleHttp\Psr7\Response; use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\S3Control\EndpointArnMiddleware - */ +#[CoversClass(EndpointArnMiddleware::class)] class EndpointArnMiddlewareTest extends TestCase { use S3ControlTestingTrait; - /** - * @dataProvider providedSuccessCases - * - * @param $cmdName - * @param $cmdParams - * @param $options - * @param $endpoint - * @param $target - * @param $headers - * @param $signingRegion - * @param $signingService - * @throws \Exception - */ + #[DataProvider('providedSuccessCases')] public function testCorrectlyModifiesRequestAndCommand( $cmdName, $cmdParams, @@ -71,7 +60,7 @@ public function testCorrectlyModifiesRequestAndCommand( $s3control->execute($command); } - public function providedSuccessCases() + public static function providedSuccessCases(): array { return [ // Outposts accesspoint ARN @@ -422,15 +411,7 @@ public function providedSuccessCases() ]; } - /** - * @dataProvider providedFailureCases - * - * @param $cmdName - * @param $cmdParams - * @param $options - * @param $expectedException - * @throws \Exception - */ + #[DataProvider('providedFailureCases')] public function testCorrectlyThrowsForBadInputsOrConfig( $cmdName, $cmdParams, @@ -455,7 +436,7 @@ public function testCorrectlyThrowsForBadInputsOrConfig( } } - public function providedFailureCases() + public static function providedFailureCases(): array { return [ // Outposts accesspoint ARN, different region diff --git a/tests/S3Control/S3ControlClientTest.php b/tests/S3Control/S3ControlClientTest.php index 0f71a5f38d..ba798e7f39 100644 --- a/tests/S3Control/S3ControlClientTest.php +++ b/tests/S3Control/S3ControlClientTest.php @@ -2,14 +2,14 @@ namespace Aws\Test\S3Control; use Aws\Endpoint\PartitionEndpointProvider; +use Aws\S3Control\S3ControlClient; use GuzzleHttp\Promise; use GuzzleHttp\Psr7\Response; use Psr\Http\Message\RequestInterface; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\S3Control\S3ControlClient - */ +#[CoversClass(S3ControlClient::class)] class S3ControlClientTest extends TestCase { use S3ControlTestingTrait; diff --git a/tests/Script/ComposerTest.php b/tests/Script/ComposerTest.php index 9dd8cf436e..8fcc464378 100644 --- a/tests/Script/ComposerTest.php +++ b/tests/Script/ComposerTest.php @@ -6,10 +6,13 @@ use Symfony\Component\Filesystem\Exception\IOException; use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Symfony\Component\Filesystem\Filesystem; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(Composer::class)] class ComposerTest extends TestCase { - public function invalidServiceNameProvider() + public static function invalidServiceNameProvider(): array { return [ [['foo'], 'foo'], @@ -19,12 +22,7 @@ public function invalidServiceNameProvider() ]; } - /** - * @dataProvider invalidServiceNameProvider - * - * @param $serviceList - * @param $invalidService - */ + #[DataProvider('invalidServiceNameProvider')] public function testListInvalidServiceName($serviceList, $invalidService) { $this->expectException(\InvalidArgumentException::class); @@ -45,7 +43,7 @@ public function testNoListedServices() Composer::removeUnusedServices($this->getMockEvent([])); } - public function servicesToKeepProvider() + public static function servicesToKeepProvider(): array { return [ [['S3']], @@ -57,11 +55,7 @@ public function servicesToKeepProvider() ]; } - /** - * @dataProvider servicesToKeepProvider - * - * @param $servicesToKeep - */ + #[DataProvider('servicesToKeepProvider')] public function testRemoveServices($servicesToKeep) { $filesystem = new Filesystem(); @@ -113,9 +107,7 @@ public function testRemoveServices($servicesToKeep) } } - /** - * @dataProvider retryProvider - */ + #[DataProvider('retryProvider')] public function testRetriesOnException($success, $writeCalls) { if (!$success) { @@ -124,17 +116,18 @@ public function testRetriesOnException($success, $writeCalls) 'Removal failed after several attempts. Last error: Simulated Exception' ); } - $exception = new IOException('Simulated Exception'); $filesystem = $this->getMockBuilder(Filesystem::class) ->disableOriginalConstructor() ->getMock(); $filesystem->expects($this->any()) ->method('remove') - ->will($this->onConsecutiveCalls( - $this->throwException($exception), - $this->throwException($exception), - $success ? $this->returnValue(true) : $this->throwException($exception) - )); + ->willReturnCallback(function () use ($success) { + if ($success) { + return true; + } + + throw new IOException('Simulated Exception'); + }); $filesystem->expects($this->any()) ->method('exists') ->willReturn(true); @@ -166,10 +159,10 @@ public function testRetriesOnException($success, $writeCalls) ); } - public function retryProvider() + public static function retryProvider(): array { return [ - 'success' => [true , 3], + 'success' => [true , 1], 'failure' => [false, 2] ]; } @@ -230,4 +223,4 @@ private function getMockEvent( return $mockEvent; } -} \ No newline at end of file +} diff --git a/tests/SdkTest.php b/tests/SdkTest.php index a0db561489..53266adbd6 100644 --- a/tests/SdkTest.php +++ b/tests/SdkTest.php @@ -6,13 +6,11 @@ use Aws\S3\S3MultiRegionClient; use Aws\Sdk; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Sdk - */ +#[CoversClass(Sdk::class)] class SdkTest extends TestCase { - public function testEnsuresMissingMethodThrowsException() { $this->expectException(\BadMethodCallException::class); @@ -22,7 +20,7 @@ public function testEnsuresMissingMethodThrowsException() public function testHasMagicMethods() { $sdk = $this->getMockBuilder(Sdk::class) - ->setMethods(['createClient']) + ->onlyMethods(['createClient']) ->getMock(); $sdk->expects($this->once()) ->method('createClient') diff --git a/tests/Ses/SesClientTest.php b/tests/Ses/SesClientTest.php index de6daa45f6..eeb53fee73 100644 --- a/tests/Ses/SesClientTest.php +++ b/tests/Ses/SesClientTest.php @@ -3,8 +3,10 @@ use Aws\Credentials\Credentials; use Aws\Ses\SesClient; +use PHPUnit\Framework\Attributes\CoversClass; use PHPUnit\Framework\TestCase; +#[CoversClass(SesClient::class)] class SesClientTest extends TestCase { public function testCanGenerateSmtpPasswordFromCredentials() diff --git a/tests/Signature/AnonymousSignatureTest.php b/tests/Signature/AnonymousSignatureTest.php index 40d4a256af..15a913b603 100644 --- a/tests/Signature/AnonymousSignatureTest.php +++ b/tests/Signature/AnonymousSignatureTest.php @@ -5,10 +5,9 @@ use Aws\Signature\AnonymousSignature; use GuzzleHttp\Psr7\Request; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Signature\AnonymousSignature - */ +#[CoversClass(AnonymousSignature::class)] class AnonymousSignatureTest extends TestCase { public function testDoesNotSignsRequests() diff --git a/tests/Signature/DpopSignatureTest.php b/tests/Signature/DpopSignatureTest.php index f2f3c7f201..b151be684b 100644 --- a/tests/Signature/DpopSignatureTest.php +++ b/tests/Signature/DpopSignatureTest.php @@ -4,10 +4,9 @@ use Aws\Signature\DpopSignature; use PHPUnit\Framework\TestCase; use GuzzleHttp\Psr7\Request; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Signature\DpopSignature - */ +#[CoversClass(DpopSignature::class)] class DpopSignatureTest extends TestCase { private function getValidEcKey(): \OpenSSLAsymmetricKey @@ -142,9 +141,6 @@ public function testDerToRawConvertsValidSignature(): void $this->assertEquals(64, strlen($raw)); } - /** - * Test that derToRaw properly handles DER signatures with various R and S lengths - */ public function testDerToRawHandlesVariableLengthComponents(): void { $dpop = new DpopSignature('signin'); @@ -190,9 +186,6 @@ public function testDerToRawHandlesVariableLengthComponents(): void $this->assertEquals(64, strlen($raw4)); } - /** - * Test that derToRaw throws for invalid DER signatures - */ public function testDerToRawThrowsForInvalidSignatures(): void { $dpop = new DpopSignature('signin'); @@ -262,9 +255,6 @@ public function testDerToRawThrowsForLengthMismatch(): void ); } - /** - * Test that the signature can be verified with openssl - */ public function testSignatureCanBeVerified(): void { $dpop = new DpopSignature('signin'); @@ -314,9 +304,6 @@ public function testSignatureCanBeVerified(): void $this->assertEquals(1, $verified); } - /** - * Test that multiple signatures from the same key produce different JWTs (due to jti) - */ public function testMultipleSignaturesProduceDifferentJwts(): void { $dpop = new DpopSignature('signin'); @@ -339,9 +326,6 @@ public function testMultipleSignaturesProduceDifferentJwts(): void $this->assertEquals($parts1[0], $parts2[0]); } - /** - * Test that a key with specifiedCurve parameters works correctly - */ public function testSignRequestWithSpecifiedCurveKey(): void { $dpop = new DpopSignature('signin'); diff --git a/tests/Signature/S3ExpressSignatureTest.php b/tests/Signature/S3ExpressSignatureTest.php index 9c383ca966..90436af315 100644 --- a/tests/Signature/S3ExpressSignatureTest.php +++ b/tests/Signature/S3ExpressSignatureTest.php @@ -6,12 +6,11 @@ use Aws\Signature\S3SignatureV4; use GuzzleHttp\Psr7\Request; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; require_once __DIR__ . '/sig_hack.php'; -/** - * @covers Aws\Signature\S3ExpressSignature - */ +#[CoversClass(S3ExpressSignature::class)] class S3ExpressSignatureTest extends TestCase { private function getFixtures() diff --git a/tests/Signature/S3SignatureV4Test.php b/tests/Signature/S3SignatureV4Test.php index f2f6eb4226..e4b0beaa43 100644 --- a/tests/Signature/S3SignatureV4Test.php +++ b/tests/Signature/S3SignatureV4Test.php @@ -5,11 +5,11 @@ use Aws\Signature\S3SignatureV4; use Yoast\PHPUnitPolyfills\TestCases\TestCase; use GuzzleHttp\Psr7\Request; +use PHPUnit\Framework\Attributes\CoversClass; require_once __DIR__ . '/sig_hack.php'; -/** - * @covers Aws\Signature\S3SignatureV4 - */ + +#[CoversClass(S3SignatureV4::class)] class S3SignatureV4Test extends TestCase { public static function set_up_before_class() diff --git a/tests/Signature/SignatureProviderTest.php b/tests/Signature/SignatureProviderTest.php index 5dc9c498b6..a2d43fcd8a 100644 --- a/tests/Signature/SignatureProviderTest.php +++ b/tests/Signature/SignatureProviderTest.php @@ -9,13 +9,13 @@ use Aws\Signature\SignatureProvider; use Aws\Signature\SignatureV4; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Signature\SignatureProvider - */ +#[CoversClass(SignatureProvider::class)] class SignatureProviderTest extends TestCase { - public function versionProvider() + public static function versionProvider(): array { return [ ['v4', SignatureV4::class, 'foo'], @@ -36,9 +36,7 @@ public function versionProvider() ]; } - /** - * @dataProvider versionProvider - */ + #[DataProvider('versionProvider')] public function testCreatesSignatureFromVersionString($v, $type, $service) { $fn = SignatureProvider::version(); diff --git a/tests/Signature/SignatureV4Test.php b/tests/Signature/SignatureV4Test.php index a101eb8619..fb81a08e15 100644 --- a/tests/Signature/SignatureV4Test.php +++ b/tests/Signature/SignatureV4Test.php @@ -7,12 +7,12 @@ use GuzzleHttp\Psr7; use GuzzleHttp\Psr7\Request; use GuzzleHttp\Psr7\NoSeekStream; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; require_once __DIR__ . '/sig_hack.php'; -/** - * @covers Aws\Signature\SignatureV4 - */ +#[CoversClass(SignatureV4::class)] class SignatureV4Test extends TestCase { const DEFAULT_KEY = 'AKIDEXAMPLE'; @@ -118,7 +118,7 @@ private function decodeQueryPairs(string $query): array return $pairs; } - public function getExpiresDateTimeInterfaceInputs() + public static function getExpiresDateTimeInterfaceInputs(): array { return [ [ @@ -130,9 +130,7 @@ public function getExpiresDateTimeInterfaceInputs() ]; } - /** - * @dataProvider getExpiresDateTimeInterfaceInputs - */ + #[DataProvider('getExpiresDateTimeInterfaceInputs')] public function testCreatesPresignedDatesFromDateTime($dateTime) { $_SERVER['override_v4_time'] = true; @@ -181,7 +179,7 @@ public function testAddsSecurityTokenIfPresentInPresigned() $this->assertStringContainsString('X-Amz-Expires=518400', $url); } - public function getStartDateTimeInterfaceInputs() + public static function getStartDateTimeInterfaceInputs(): array { return [ [ @@ -193,9 +191,7 @@ public function getStartDateTimeInterfaceInputs() ]; } - /** - * @dataProvider getStartDateTimeInterfaceInputs - */ + #[DataProvider('getStartDateTimeInterfaceInputs')] public function testUsesStartDateFromDateTimeIfPresent($dateTime) { $options = ['start_time' => $dateTime]; @@ -392,8 +388,7 @@ public function testEnsuresContentSha256CanBeCalculatedWhenSeekFails() $signature->signRequest($request, $credentials); } - /** @doesNotPerformAssertions */ - public function testUnsignedPayloadProvider() + public static function unsignedPayloadProvider(): array { return [ // POST headers should be signed. @@ -447,9 +442,7 @@ public function testUnsignedPayloadProvider() ]; } - /** - * @dataProvider testUnsignedPayloadProvider - */ + #[DataProvider('unsignedPayloadProvider')] public function testSignRequestUnsignedPayload($req, $sreq, $creq) { $_SERVER['aws_time'] = '20110909T233600Z'; @@ -467,8 +460,7 @@ public function testSignRequestUnsignedPayload($req, $sreq, $creq) $this->assertSame($sreq, Psr7\Message::toString($signature->signRequest($request, $credentials))); } - /** @doesNotPerformAssertions */ - public function testProvider() + public static function provider(): array { return [ // POST headers should be signed. @@ -570,9 +562,7 @@ public function testProvider() ]; } - /** - * @dataProvider testProvider - */ + #[DataProvider('provider')] public function testSignsRequests($req, $sreq, $creq) { $_SERVER['aws_time'] = '20110909T233600Z'; diff --git a/tests/Sqs/SqsClientTest.php b/tests/Sqs/SqsClientTest.php index 7e5944db9a..065dbfad82 100644 --- a/tests/Sqs/SqsClientTest.php +++ b/tests/Sqs/SqsClientTest.php @@ -6,10 +6,10 @@ use Aws\Sqs\SqsClient; use Aws\Test\UsesServiceTrait; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversNothing; -/** - * @covers Aws\Sqs\SqsClient - */ +#[CoversClass(SqsClient::class)] class SqsClientTest extends TestCase { use UsesServiceTrait; @@ -155,7 +155,7 @@ public function testValidatesMessageAttributesExistWithMd5() ]); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testSkipsCommandsThatAreNotReceiveMessage() { $client = new SqsClient([ @@ -164,6 +164,7 @@ public function testSkipsCommandsThatAreNotReceiveMessage() ]); $this->addMockResults($client, [new Result()]); $client->listQueues(); + $this->assertTrue(true); } public function testDoesNotValidateEmptyMessageAttributes() diff --git a/tests/Ssm/SsmClientTest.php b/tests/Ssm/SsmClientTest.php index f072aef541..f61125eca6 100644 --- a/tests/Ssm/SsmClientTest.php +++ b/tests/Ssm/SsmClientTest.php @@ -5,10 +5,9 @@ use Aws\MockHandler; use Aws\Result; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Ssm\SsmClient - */ +#[CoversClass(SsmClient::class)] class SsmClientTest extends TestCase { public function testCanDisableAutoFillPerClient() diff --git a/tests/StreamRequestPayloadMiddlewareTest.php b/tests/StreamRequestPayloadMiddlewareTest.php index ed0443505a..295e780444 100644 --- a/tests/StreamRequestPayloadMiddlewareTest.php +++ b/tests/StreamRequestPayloadMiddlewareTest.php @@ -14,26 +14,26 @@ use GuzzleHttp\Psr7\Request; use Yoast\PHPUnitPolyfills\TestCases\TestCase; use Psr\Http\Message\RequestInterface; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\StreamRequestPayloadMiddleware - */ +#[CoversClass(StreamRequestPayloadMiddleware::class)] class StreamRequestPayloadMiddlewareTest extends TestCase { use ArraySubsetAsserts; - /** - * @dataProvider generateTestCases - * - * @param CommandInterface $command - * @param array $expectedHeaders - * @param array $expectedNonHeaders - */ + #[DataProvider('addsProperHeadersDataProvider')] public function testAddsProperHeaders( - CommandInterface $command, + array $commandDef, array $expectedHeaders, array $expectedNonHeaders ) { + $service = $this->generateTestService(); + $client = $this->generateTestClient($service); + $command = $client->getCommand( + $commandDef['command_name'], + $commandDef['command_args'] + ); $list = $this->generateTestHandlerList(); $list->setHandler(function ( @@ -54,50 +54,48 @@ public function testAddsProperHeaders( $handler($command, new Request('POST', 'https://foo.com')); } - public function generateTestCases() + public static function addsProperHeadersDataProvider(): array { - $service = $this->generateTestService(); - $client = $this->generateTestClient($service); $inputStream = Psr7\Utils::streamFor('test'); return [ [ - $client->getCommand( - 'NonStreamingOp', - [ + [ + 'command_name' => 'NonStreamingOp', + 'command_args' => [ 'InputString' => 'teststring', ] - ), + ], [], [ 'transfer-encoding'], ], [ - $client->getCommand( - 'StreamingOp', - [ + [ + 'command_name' => 'StreamingOp', + 'command_args' => [ 'InputStream' => $inputStream, ] - ), + ], [ 'Content-Length' => [26] ], [ 'transfer-encoding' ], ], [ - $client->getCommand( - 'StreamingLengthOp', - [ + [ + 'command_name' => 'StreamingLengthOp', + 'command_args' => [ 'InputStream' => $inputStream, ] - ), + ], [ 'Content-Length' => [26] ], [ 'transfer-encoding' ], ], [ - $client->getCommand( - 'StreamingLengthUnsignedOp', - [ + [ + 'command_name' => 'StreamingLengthUnsignedOp', + 'command_args' => [ 'InputStream' => $inputStream, ] - ), + ], [ 'Content-Length' => [26] ], [ 'transfer-encoding' ], ], @@ -129,7 +127,7 @@ public function testThrowsExceptionOnIncalculableSize() ->willReturn(null); $requestMock = $this->getMockBuilder(Request::class) ->setConstructorArgs(['POST', 'https://foo.com']) - ->setMethods(['getBody']) + ->onlyMethods(['getBody']) ->getMock(); $requestMock->expects($this->any()) ->method('getBody') @@ -282,5 +280,4 @@ private function generateTestService() function () { return []; } ); } - } diff --git a/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php b/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php index 0406271cc6..70c59afa03 100644 --- a/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php +++ b/tests/Sts/RegionalEndpoints/ConfigurationProviderTest.php @@ -10,10 +10,10 @@ use Aws\Sts\RegionalEndpoints\Exception\ConfigurationException; use GuzzleHttp\Promise; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; -/** - * git\Sts\RegionalEndpoints\ConfigurationProvider - */ +#[CoversClass(ConfigurationProvider::class)] class ConfigurationProviderTest extends TestCase { private static $originalEnv; @@ -216,16 +216,15 @@ public function testEnsuresFileIsNotEmpty() public function testEnsuresIniFileIsValid() { $this->expectExceptionMessage("Invalid config file:"); - $this->expectException(\Aws\Sts\RegionalEndpoints\Exception\ConfigurationException::class); + $this->expectException(ConfigurationException::class); $dir = $this->clearEnv(); file_put_contents($dir . '/config', "wef \n=\nwef"); putenv('HOME=' . dirname($dir)); try { - @call_user_func(ConfigurationProvider::ini())->wait(); - } catch (\Exception $e) { + call_user_func(ConfigurationProvider::ini())->wait(); + } finally { unlink($dir . '/config'); - throw $e; } } @@ -338,7 +337,7 @@ public function testCreatesFromCache() { $expected = new Configuration('regional'); $cacheBuilder = $this->getMockBuilder(CacheInterface::class); - $cacheBuilder->setMethods(['get', 'set', 'remove']); + $cacheBuilder->onlyMethods(['get', 'set', 'remove']); $cache = $cacheBuilder->getMock(); $cache->expects($this->any()) ->method('get') @@ -352,7 +351,7 @@ public function testCreatesFromCache() $this->assertSame($expected->toArray(), $result->toArray()); } - public function getSuccessfulUnwrapData() + public static function getSuccessfulUnwrapData(): array { $expected = new Configuration('regional'); return [ @@ -383,11 +382,7 @@ function () use ($expected) { ]; } - /** - * @dataProvider getSuccessfulUnwrapData - * @param $toUnwrap - * @param ConfigurationInterface $expected - */ + #[DataProvider('getSuccessfulUnwrapData')] public function testSuccessfulUnwraps($toUnwrap, ConfigurationInterface $expected) { $this->assertSame( diff --git a/tests/Sts/RegionalEndpoints/ConfigurationTest.php b/tests/Sts/RegionalEndpoints/ConfigurationTest.php index ec4120c89e..29f2b9aab8 100644 --- a/tests/Sts/RegionalEndpoints/ConfigurationTest.php +++ b/tests/Sts/RegionalEndpoints/ConfigurationTest.php @@ -4,10 +4,9 @@ use Aws\Sts\RegionalEndpoints\Configuration; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\Sts\RegionalEndpoints\Configuration - */ +#[CoversClass(Configuration::class)] class ConfigurationTest extends TestCase { public function testGetsCorrectValues() diff --git a/tests/Sts/StsClientTest.php b/tests/Sts/StsClientTest.php index 04369a93e3..4b6bc3eb9d 100644 --- a/tests/Sts/StsClientTest.php +++ b/tests/Sts/StsClientTest.php @@ -15,10 +15,10 @@ use GuzzleHttp\Promise\Create; use GuzzleHttp\Psr7\Uri; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Sts\StsClient - */ +#[CoversClass(StsClient::class)] class StsClientTest extends TestCase { private $originalEnv = []; @@ -183,11 +183,7 @@ public function testCanCreateCredentialsObjectFromStsResultWithFederatedUser() $this->assertFalse($credentials->isExpired()); } - /** - * @dataProvider stsAssumeRoleOperationsDataProvider - * - * @return void - */ + #[DataProvider('stsAssumeRoleOperationsDataProvider')] public function testStsAssumeRoleOperationsWithAccountId($response, $expected) { $operation = 'assumeRole'; @@ -206,7 +202,7 @@ public function testStsAssumeRoleOperationsWithAccountId($response, $expected) self::assertSame($expected->toArray(), $response->toArray()); } - public function stsAssumeRoleOperationsDataProvider(): array + public static function stsAssumeRoleOperationsDataProvider(): array { return [ 'Sts::AssumeRole' => [ @@ -232,9 +228,7 @@ public function stsAssumeRoleOperationsDataProvider(): array ]; } - /** - * @dataProvider stsAssumeRoleWithSAMLOperationsDataProvider - */ + #[DataProvider('stsAssumeRoleWithSAMLOperationsDataProvider')] public function testStsAssumeRoleWithSAMLOperationsWithAccountId( $response, $expected @@ -266,7 +260,7 @@ public function testStsAssumeRoleWithSAMLOperationsWithAccountId( self::assertSame($expected->toArray(), $response->toArray()); } - public function stsAssumeRoleWithSAMLOperationsDataProvider(): array + public static function stsAssumeRoleWithSAMLOperationsDataProvider(): array { return [ 'Sts::AssumeRoleWithSaml' => [ @@ -291,9 +285,7 @@ public function stsAssumeRoleWithSAMLOperationsDataProvider(): array ]; } - /** - * @dataProvider stsAssumeRoleWithWebIdentityOperationsDataProvider - */ + #[DataProvider('stsAssumeRoleWithWebIdentityOperationsDataProvider')] public function testStsAssumeRoleWithWebIdentityOperationsWithAccountId( $response, $expected @@ -321,7 +313,7 @@ public function testStsAssumeRoleWithWebIdentityOperationsWithAccountId( self::assertSame($expected->toArray(), $response->toArray()); } - public function stsAssumeRoleWithWebIdentityOperationsDataProvider(): array + public static function stsAssumeRoleWithWebIdentityOperationsDataProvider(): array { return [ 'Sts::AssumeRoleWithWebIdentity' => [ @@ -347,9 +339,7 @@ public function stsAssumeRoleWithWebIdentityOperationsDataProvider(): array ]; } - /** - * @dataProvider stsGetFederationTokenOperationsDataProvider - */ + #[DataProvider('stsGetFederationTokenOperationsDataProvider')] public function testStsGetFederationTokenOperationsWithAccountId( $response, $expected @@ -379,7 +369,7 @@ public function testStsGetFederationTokenOperationsWithAccountId( self::assertSame($expected->toArray(), $response->toArray()); } - public function stsGetFederationTokenOperationsDataProvider(): array + public static function stsGetFederationTokenOperationsDataProvider(): array { return [ 'Sts::GetFederationToken' => [ @@ -430,7 +420,7 @@ private function getTestStsClient($operation, $response) { $stsClient = $this->getMockBuilder(StsClient::class) -> disableOriginalConstructor() - -> setMethods(['__call']) + -> onlyMethods(['__call']) -> getMock(); $stsClient->method('__call') -> willReturnCallback(function ($callOperation) use ($operation, $response) { diff --git a/tests/Token/BearerTokenAuthorizationTest.php b/tests/Token/BearerTokenAuthorizationTest.php index 9ee33c603f..2957934f1c 100644 --- a/tests/Token/BearerTokenAuthorizationTest.php +++ b/tests/Token/BearerTokenAuthorizationTest.php @@ -1,16 +1,18 @@ [ @@ -30,14 +32,13 @@ public function bearerTestProvider() { "token" => "mF_9.B5f-4.1JqM", "expectedHeaders" => ["Authorization" => "Bearer mF_9.B5f-4.1JqM",], ], - ]; + ]; } - /** - * @dataProvider bearerTestProvider - */ - public function testBearerSuccessCases($headers, $tokenString, $expectedHeaders) { - $authorizer = new \Aws\Token\BearerTokenAuthorization(); + #[DataProvider('bearerTestProvider')] + public function testBearerSuccessCases($headers, $tokenString, $expectedHeaders) + { + $authorizer = new BearerTokenAuthorization(); $request = new Request('GET', 'http://foo.com'); foreach ($headers as $header => $value) { $request = $request->withHeader($header, $value); @@ -49,12 +50,13 @@ public function testBearerSuccessCases($headers, $tokenString, $expectedHeaders) } } - public function testBearerNullToken() { - $authorizer = new \Aws\Token\BearerTokenAuthorization(); + public function testBearerNullToken() + { + $authorizer = new BearerTokenAuthorization(); $request = new Request('GET', 'http://foo.com'); $token = new Token(null); $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage("Cannot authorize a request with an empty token"); $authorizer->authorizeRequest($request, $token); } -} \ No newline at end of file +} diff --git a/tests/Token/BedrockTokenProviderTest.php b/tests/Token/BedrockTokenProviderTest.php index d4dd36e757..dc2ed554f5 100644 --- a/tests/Token/BedrockTokenProviderTest.php +++ b/tests/Token/BedrockTokenProviderTest.php @@ -13,7 +13,10 @@ use Aws\Token\TokenSource; use GuzzleHttp\Promise; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\DataProvider; +#[CoversClass(BedrockTokenProvider::class)] class BedrockTokenProviderTest extends TestCase { use UsesServiceTrait; @@ -237,15 +240,8 @@ public function testMemoization(): void /** * Test integration with Bedrock Clients - * - * @param $serviceName - * @param $envVars - * @param $clientArgs - * @param $expectations - * @param $iniConfig - * - * @dataProvider integrationWithClientProvider */ + #[DataProvider('integrationWithClientProvider')] public function testIntegrationWithClient( $serviceName, $envVars, @@ -315,9 +311,9 @@ public function testIntegrationWithClient( } } - public function integrationWithClientProvider(): \Generator + public static function integrationWithClientProvider(): \Generator { - static $services = [ + $services = [ 'bedrock', 'bedrock-agent', 'bedrock-agent-runtime', @@ -394,9 +390,8 @@ public function integrationWithClientProvider(): \Generator /** * Test that token source is added to user agent header - * - * @dataProvider tokenSourceUserAgentProvider */ + #[DataProvider('tokenSourceUserAgentProvider')] public function testTokenSourceInUserAgent( string $service, string $operation, @@ -440,7 +435,7 @@ function (callable $handler) { $client->{$operation}($args); } - public function tokenSourceUserAgentProvider(): \Generator + public static function tokenSourceUserAgentProvider(): \Generator { yield 'bedrock' => [ 'service' => 'bedrock', diff --git a/tests/Token/SsoTokenProviderTest.php b/tests/Token/SsoTokenProviderTest.php index 9372b80280..9286fad54c 100644 --- a/tests/Token/SsoTokenProviderTest.php +++ b/tests/Token/SsoTokenProviderTest.php @@ -1,19 +1,17 @@ homepath); } - public function testSsoTokenProviderSuccess() { $dir = $this->clearEnv(); diff --git a/tests/Token/TokenProviderTest.php b/tests/Token/TokenProviderTest.php index 534b934b2d..a95dc97d17 100644 --- a/tests/Token/TokenProviderTest.php +++ b/tests/Token/TokenProviderTest.php @@ -1,4 +1,5 @@ assertEquals($token->getExpiration(), $found->getExpiration()); } - public function tokenProviderSuccessCases() { + public static function tokenProviderSuccessCases(): array + { return [ "Valid token with all fields" => [ @@ -157,9 +161,7 @@ public function tokenProviderSuccessCases() { ]; } - /** - * @dataProvider tokenProviderSuccessCases - */ + #[DataProvider('tokenProviderSuccessCases')] public function testTokenProviderCachedSuccess($cachedToken, $expectedToken) { $_SERVER['aws_time'] = 1640466950; @@ -187,7 +189,8 @@ public function testTokenProviderCachedSuccess($cachedToken, $expectedToken) $this->assertEquals(strtotime($expectedToken['expiration']), $found->getExpiration()); } - public function tokenProviderSuccessCasesWithRefresh() { + public static function tokenProviderSuccessCasesWithRefresh(): array + { return [ "Expired token refresh with refresh token" => [ @@ -258,9 +261,7 @@ public function tokenProviderSuccessCasesWithRefresh() { ]; } - /** - * @dataProvider tokenProviderSuccessCasesWithRefresh - */ + #[DataProvider('tokenProviderSuccessCasesWithRefresh')] public function testTokenProviderCachedSuccessWithRefresh( $currentTime, $cachedToken, @@ -327,7 +328,7 @@ public function testTokenProviderCachedSuccessWithRefresh( isset($cachedToken['registrationExpiresAt']) ? strToTime($cachedToken['registrationExpiresAt']) : null, isset($cachedToken['region']) ? $cachedToken['region'] : null, isset($cachedToken['startUrl']) ? $cachedToken['startUrl'] : null - ); + ); $saved = [ 'token' => $token, 'refreshMethod' => function () use ($ssoTokenProvider) { @@ -350,7 +351,8 @@ public function testTokenProviderCachedSuccessWithRefresh( } } - public function tokenProviderFailureCases() { + public static function tokenProviderFailureCases(): array + { return [ "Minimal expired cached token" => [ @@ -391,9 +393,7 @@ public function tokenProviderFailureCases() { ]; } - /** - * @dataProvider tokenProviderFailureCases - */ + #[DataProvider('tokenProviderFailureCases')] public function testTokenProviderFailureCases($cachedToken, $expectedException) { $cache = new LruArrayCache; @@ -430,7 +430,7 @@ public function testCacheWritesAndReadsCorrectFormat() $token = new Token('test-token', strtotime('+1 hour')); $providerCallCount = 0; - $provider = function() use ($token, &$providerCallCount) { + $provider = function () use ($token, &$providerCallCount) { $providerCallCount++; return Promise\Create::promiseFor($token); }; diff --git a/tests/Token/TokenTest.php b/tests/Token/TokenTest.php index 286a6c511f..b72ada235f 100644 --- a/tests/Token/TokenTest.php +++ b/tests/Token/TokenTest.php @@ -6,10 +6,9 @@ use Aws\Token\Token; use Aws\Identity\IdentityInterface; use PHPUnit\Framework\TestCase; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\Token\Token - */ +#[CoversClass(Token::class)] class TokenTest extends TestCase { public function testHasGetters() diff --git a/tests/TraceMiddlewareTest.php b/tests/TraceMiddlewareTest.php index 6fb5190bc6..57abeb6708 100644 --- a/tests/TraceMiddlewareTest.php +++ b/tests/TraceMiddlewareTest.php @@ -15,10 +15,10 @@ use GuzzleHttp\Psr7\Response; use GuzzleHttp\Promise; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\TraceMiddleware - */ +#[CoversClass(TraceMiddleware::class)] class TraceMiddlewareTest extends TestCase { public function testEmitsDebugInfo() @@ -128,13 +128,7 @@ public function testTracksAwsSpecificExceptions() $this->assertStringContainsString('string(5) "error"', $str); } - /** - * @dataProvider authStringProvider - * - * @param string $key - * @param string $signature - * @param array $headers - */ + #[DataProvider('authStringProvider')] public function testScrubsAuthStrings($key, $signature, array $headers) { $str = ''; @@ -239,7 +233,7 @@ public function testEmitsForMiddlewareThatDoesNotReturnRequest() $this->assertEquals('success', $result[0]); } - public function authStringProvider() + public static function authStringProvider(): array { return [ // v4 signature example from http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-auth-using-authorization-header.html diff --git a/tests/UserAgentMiddlewareTest.php b/tests/UserAgentMiddlewareTest.php index 0565e19a8f..1c3848d27a 100644 --- a/tests/UserAgentMiddlewareTest.php +++ b/tests/UserAgentMiddlewareTest.php @@ -38,14 +38,15 @@ use GuzzleHttp\Promise\Create; use GuzzleHttp\Psr7\Response; use GuzzleHttp\Psr7\Utils; +use PHPUnit\Framework\Attributes\RunClassInSeparateProcess; use Psr\Http\Message\RequestInterface; use GuzzleHttp\Psr7\Request; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers \Aws\UserAgentMiddleware - * @runInSeparateProcess - */ +#[CoversClass(\Aws\UserAgentMiddleware::class)] +#[RunClassInSeparateProcess] class UserAgentMiddlewareTest extends TestCase { use MetricsBuilderTestTrait; @@ -133,12 +134,13 @@ public function testAppendsUserAgentHeader() * Tests the user agent header value contains the expected * component. * - * @dataProvider userAgentCasesDataProvider * @param array $args * @param string $expected * * @return void - */ + + */ + #[DataProvider('userAgentCasesDataProvider')] public function testUserAgentContainsValue(array $args, string $expected) { $handler = UserAgentMiddleware::wrap($args); @@ -165,7 +167,7 @@ public function testUserAgentContainsValue(array $args, string $expected) * * @return \Generator */ - public function userAgentCasesDataProvider(): \Generator + public static function userAgentCasesDataProvider(): \Generator { yield 'sdkVersion' => [[], 'aws-sdk-php/' . Sdk::VERSION]; @@ -173,11 +175,11 @@ public function userAgentCasesDataProvider(): \Generator yield 'hhvmVersion' => [[], defined('HHVM_VERSION') ? 'HHVM/' . HHVM_VERSION : ""]; - yield 'osName' => [[], $this->getOsNameForUserAgent()]; + yield 'osName' => [[], self::getOsNameForUserAgent()]; yield 'langVersion' => [[], 'lang/php#' . phpversion()]; - yield 'execEnv' => [[], $this->getExecEnvForUserAgent()]; + yield 'execEnv' => [[], self::getExecEnvForUserAgent()]; yield 'appId' => [['app_id' => 'FooAppId'], 'app/FooAppId']; @@ -227,7 +229,7 @@ public function userAgentCasesDataProvider(): \Generator ]; } - private function getOsNameForUserAgent(): string + private static function getOsNameForUserAgent(): string { $disabledFunctions = explode(',', ini_get('disable_functions')); if (function_exists('php_uname') @@ -243,7 +245,7 @@ private function getOsNameForUserAgent(): string return ""; } - private function getExecEnvForUserAgent(): string + private static function getExecEnvForUserAgent(): string { $expectedEnv = "LambdaFooEnvironment"; putenv("AWS_EXECUTION_ENV={$expectedEnv}"); @@ -321,10 +323,10 @@ public function testUserAgentCapturePaginatorMetric() /** * Tests user agent captures retry config metric. * - * @dataProvider retryConfigMetricProvider - * * @return void - */ + + */ + #[DataProvider('retryConfigMetricProvider')] public function testUserAgentCaptureRetryConfigMetric( $retryMode, $expectedMetric @@ -355,7 +357,7 @@ public function testUserAgentCaptureRetryConfigMetric( * * @return array[] */ - public function retryConfigMetricProvider(): array + public static function retryConfigMetricProvider(): array { return [ 'retryAdaptive' => [ @@ -405,70 +407,75 @@ public function testUserAgentCaptureS3TransferMetric() */ public function testUserAgentCaptureS3CryptoV1Metric() { - $kms = $this->getTestKmsClient(); - $list = $kms->getHandlerList(); - $list->setHandler(function ($cmd, $req) { - // Verify decryption command has correct parameters - $this->assertSame('cek', $cmd['CiphertextBlob']); - $this->assertEquals( - [ - 'kms_cmk_id' => '11111111-2222-3333-4444-555555555555' - ], - $cmd['EncryptionContext'] - ); - return Create::promiseFor( - new Result(['Plaintext' => random_bytes(32)]) - ); - }); - $provider = new KmsMaterialsProvider($kms, 'foo'); + set_error_handler(function ($errno, $errstr) {}, E_USER_WARNING); + try { + $kms = $this->getTestKmsClient(); + $list = $kms->getHandlerList(); + $list->setHandler(function ($cmd, $req) { + // Verify decryption command has correct parameters + $this->assertSame('cek', $cmd['CiphertextBlob']); + $this->assertEquals( + [ + 'kms_cmk_id' => '11111111-2222-3333-4444-555555555555' + ], + $cmd['EncryptionContext'] + ); + return Create::promiseFor( + new Result(['Plaintext' => random_bytes(32)]) + ); + }); + $provider = new KmsMaterialsProvider($kms, 'foo'); - $responded = false; - $s3Client = new S3Client([ - 'region' => 'us-east-2', - 'handler' => function ( - CommandInterface $_, - RequestInterface $request - ) { + $responded = false; + $s3Client = new S3Client([ + 'region' => 'us-east-2', + 'handler' => function ( + CommandInterface $_, + RequestInterface $request + ) { - $metrics = $this->getMetricsAsArray($request); + $metrics = $this->getMetricsAsArray($request); - $this->assertTrue( - in_array(MetricsBuilder::S3_CRYPTO_V2, $metrics) - ); + $this->assertTrue( + in_array(MetricsBuilder::S3_CRYPTO_V2, $metrics) + ); - return new Result([ - 'Body' => 'This is a test body' - ]); - }, - 'http_handler' => function () use ($provider, &$responded) { - if ($responded) { + return new Result([ + 'Body' => 'This is a test body' + ]); + }, + 'http_handler' => function () use ($provider, &$responded) { + if ($responded) { + return new FulfilledPromise(new Response( + 200, + [], + json_encode( + $this->getValidV1GcmMetadataFields($provider) + ) + )); + } + + $responded = true; return new FulfilledPromise(new Response( 200, [], - json_encode( - $this->getValidV1GcmMetadataFields($provider) - ) + 'test' )); - } - - $responded = true; - return new FulfilledPromise(new Response( - 200, - [], - 'test' - )); - }, - ]); - $encryptionClient = @new S3EncryptionClient( - $s3Client, - InstructionFileMetadataStrategy::DEFAULT_FILE_SUFFIX - ); - $result = $encryptionClient->getObject([ - 'Bucket' => 'foo', - 'Key' => 'foo', - '@MaterialsProvider' => $provider, - ]); - $this->assertInstanceOf(AesGcmDecryptingStream::class, $result['Body']); + }, + ]); + $encryptionClient = @new S3EncryptionClient( + $s3Client, + InstructionFileMetadataStrategy::DEFAULT_FILE_SUFFIX + ); + $result = $encryptionClient->getObject([ + 'Bucket' => 'foo', + 'Key' => 'foo', + '@MaterialsProvider' => $provider, + ]); + $this->assertInstanceOf(AesGcmDecryptingStream::class, $result['Body']); + } finally { + restore_error_handler(); + } } /** @@ -478,72 +485,77 @@ public function testUserAgentCaptureS3CryptoV1Metric() */ public function testUserAgentCaptureS3CryptoV2Metric() { - $kms = $this->getTestKmsClient(); - $list = $kms->getHandlerList(); - $list->setHandler(function ($cmd, $req) { - // Verify decryption command has correct parameters - $this->assertSame('cek', $cmd['CiphertextBlob']); - $this->assertEquals( - [ - 'aws:x-amz-cek-alg' => 'AES/GCM/NoPadding' - ], - $cmd['EncryptionContext'] - ); - return Create::promiseFor( - new Result(['Plaintext' => random_bytes(32)]) - ); - }); - $provider = new KmsMaterialsProviderV2($kms, 'foo'); + set_error_handler(function ($errno, $errstr) {}, E_USER_WARNING); + try { + $kms = $this->getTestKmsClient(); + $list = $kms->getHandlerList(); + $list->setHandler(function ($cmd, $req) { + // Verify decryption command has correct parameters + $this->assertSame('cek', $cmd['CiphertextBlob']); + $this->assertEquals( + [ + 'aws:x-amz-cek-alg' => 'AES/GCM/NoPadding' + ], + $cmd['EncryptionContext'] + ); + return Create::promiseFor( + new Result(['Plaintext' => random_bytes(32)]) + ); + }); + $provider = new KmsMaterialsProviderV2($kms, 'foo'); - $responded = false; - $s3Client = new S3Client([ - 'region' => 'us-east-2', - 'handler' => function ( - CommandInterface $_, - RequestInterface $request - ) { + $responded = false; + $s3Client = new S3Client([ + 'region' => 'us-east-2', + 'handler' => function ( + CommandInterface $_, + RequestInterface $request + ) { - $metrics = $this->getMetricsAsArray($request); + $metrics = $this->getMetricsAsArray($request); - $this->assertTrue( - in_array(MetricsBuilder::S3_CRYPTO_V2, $metrics) - ); + $this->assertTrue( + in_array(MetricsBuilder::S3_CRYPTO_V2, $metrics) + ); - return new Result([ - 'Body' => 'This is a test body' - ]); - }, - 'http_handler' => function () use ($provider, &$responded) { - if ($responded) { + return new Result([ + 'Body' => 'This is a test body' + ]); + }, + 'http_handler' => function () use ($provider, &$responded) { + if ($responded) { + return new FulfilledPromise(new Response( + 200, + [], + json_encode( + $this->getValidV2GcmMetadataFields($provider) + ) + )); + } + + $responded = true; return new FulfilledPromise(new Response( 200, [], - json_encode( - $this->getValidV2GcmMetadataFields($provider) - ) + 'test' )); - } - - $responded = true; - return new FulfilledPromise(new Response( - 200, - [], - 'test' - )); - }, - ]); - $encryptionClient = @new S3EncryptionClientV2( - $s3Client, - InstructionFileMetadataStrategy::DEFAULT_FILE_SUFFIX - ); - $result = $encryptionClient->getObject([ - 'Bucket' => 'foo', - 'Key' => 'foo', - '@MaterialsProvider' => $provider, - '@SecurityProfile' => 'V2', - '@CommitmentPolicy' => 'FORBID_ENCRYPT_ALLOW_DECRYPT' - ]); - $this->assertInstanceOf(AesGcmDecryptingStream::class, $result['Body']); + }, + ]); + $encryptionClient = @new S3EncryptionClientV2( + $s3Client, + InstructionFileMetadataStrategy::DEFAULT_FILE_SUFFIX + ); + $result = $encryptionClient->getObject([ + 'Bucket' => 'foo', + 'Key' => 'foo', + '@MaterialsProvider' => $provider, + '@SecurityProfile' => 'V2', + '@CommitmentPolicy' => 'FORBID_ENCRYPT_ALLOW_DECRYPT' + ]); + $this->assertInstanceOf(AesGcmDecryptingStream::class, $result['Body']); + } finally { + restore_error_handler(); + } } /** @@ -827,10 +839,10 @@ private function getDynamoDBTestRuleSet(): array * @param string $checksumMetric * @param bool $supported * - * @dataProvider flexibleChecksumTestProvider - * * @return void - */ + + */ + #[DataProvider('flexibleChecksumTestProvider')] public function testUserAgentCaptureFlexibleChecksumMetric( string $algorithm, string $checksumMetric, @@ -874,7 +886,7 @@ public function testUserAgentCaptureFlexibleChecksumMetric( * * @return array[] */ - public function flexibleChecksumTestProvider(): array + public static function flexibleChecksumTestProvider(): array { return [ 'metric_checksum_crc32' => [ diff --git a/tests/UsesServiceTrait.php b/tests/UsesServiceTrait.php index faf4133087..0372420480 100644 --- a/tests/UsesServiceTrait.php +++ b/tests/UsesServiceTrait.php @@ -109,7 +109,7 @@ private function createMockAwsException( $type = $type ?: AwsException::class; $client = $this->getMockBuilder(AwsClientInterface::class) - ->setMethods(['getApi']) + ->onlyMethods(['getApi']) ->getMockForAbstractClass(); $client->expects($this->any()) diff --git a/tests/WaiterTest.php b/tests/WaiterTest.php index b5c5dc3dca..b4f25baf55 100644 --- a/tests/WaiterTest.php +++ b/tests/WaiterTest.php @@ -20,10 +20,11 @@ use GuzzleHttp\Psr7; use Psr\Http\Message\RequestInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; +use PHPUnit\Framework\Attributes\CoversNothing; -/** - * @covers Aws\Waiter - */ +#[CoversClass(Waiter::class)] class WaiterTest extends TestCase { use UsesServiceTrait; @@ -61,7 +62,7 @@ public function testErrorOnBadBeforeCallback() ); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testContinueWaitingOnHandlerError() { $retries = 10; @@ -92,9 +93,10 @@ public function testContinueWaitingOnHandlerError() $client->waitUntil('TableExists', [ 'TableName' => 'table', ]); + $this->assertTrue(true); } - /** @doesNotPerformAssertions */ + #[CoversNothing] public function testCanCancel() { $client = $this->getTestClient('DynamoDb'); @@ -104,6 +106,7 @@ public function testCanCancel() '@http' => ['debug' => true] ])->promise()->cancel(); sleep(1); + $this->assertTrue(true); } public function testCanWait() @@ -146,11 +149,20 @@ public function testCanWait() $this->assertSame(6000, $waitTime, 'Did not delay long enough.'); } - /** - * @dataProvider getWaiterWorkflowTestCases - */ + #[DataProvider('waiterWorkflowDataProvider')] public function testWaiterWorkflow($results, $expectedException) { + // Normalize results + foreach ($results as &$result) { + if (is_array($result)) { + $result = $this->createMockAwsException( + $result['code'], + $result['type'], + $result['message'] + ); + } + } + // Prepare a client $client = $this->getTestClient('DynamoDb', [ 'api_provider' => $this->getApiProvider() @@ -178,12 +190,16 @@ public function testWaiterWorkflow($results, $expectedException) $this->assertEquals($expectedException, $actualException); } - public function getWaiterWorkflowTestCases() + public static function waiterWorkflowDataProvider(): array { return [ [ [ - $this->createMockAwsException('ResourceNotFoundException'), + [ + 'code' => 'ResourceNotFoundException', + 'type' => null, + 'message' => null + ], new Result(['Table' => ['TableStatus' => 'CREATING']]), new Result(['Table' => ['TableStatus' => 'CREATING']]), new Result(['Table' => ['TableStatus' => 'ACTIVE']]), @@ -209,7 +225,11 @@ public function getWaiterWorkflowTestCases() ], [ [ - $this->createMockAwsException(null, null, 'foo'), + [ + 'code' => null, + 'type' => null, + 'message' => 'foo' + ], ], 'The TableExists waiter entered a failure state. Reason: foo' ], @@ -260,22 +280,22 @@ private function getApiProvider() }; } - /** - * @dataProvider getMatchersTestCases - */ + #[DataProvider('matcherDataProvider')] public function testMatchers($matcher, $result, $acceptor, $expected) { + $waiter = new \ReflectionClass(Waiter::class); $matcher = $waiter->getMethod($matcher); $waiter = $waiter->newInstanceWithoutConstructor(); - $this->assertEquals($expected, $matcher->invoke($waiter, $result, $acceptor)); + $this->assertEquals($expected, $matcher->invoke( + $waiter, + $result === null ? null : $this->getMockResult($result), + $acceptor + )); } - /** - * @return array - */ - public function getMatchersTestCases(): array + public static function matcherDataProvider(): array { return [ 'matches_path_1' => [ @@ -286,31 +306,31 @@ public function getMatchersTestCases(): array ], 'matches_path_2' => [ 'matcher' => 'matchesPath', - 'result' => $this->getMockResult(['a' => ['b' => 'c']]), + 'result' => ['a' => ['b' => 'c']], 'acceptor' => ['argument' => 'a.b', 'expected' => 'c'], 'expected' => true ], 'matches_path_3' => [ 'matcher' => 'matchesPath', - 'result' => $this->getMockResult(['a' => ['b' => 'c']]), + 'result' => ['a' => ['b' => 'c']], 'acceptor' => ['argument' => 'a', 'expected' => 'z'], 'expected' => false ], 'matches_path_4_same_value_different_type' => [ 'matcher' => 'matchesPath', - 'result' => $this->getMockResult(['a' => ['b' => 'false']]), + 'result' => ['a' => ['b' => 'false']], 'acceptor' => ['argument' => 'a.b', 'expected' => false], 'expected' => false ], 'matches_path_5_same_value_same_type' => [ 'matcher' => 'matchesPath', - 'result' => $this->getMockResult(['a' => ['b' => false]]), + 'result' => ['a' => ['b' => false]], 'acceptor' => ['argument' => 'a.b', 'expected' => false], 'expected' => true ], 'matches_path_6_same_value_same_type' => [ 'matcher' => 'matchesPath', - 'result' => $this->getMockResult(['a' => ['b' => 'false']]), + 'result' => ['a' => ['b' => 'false']], 'acceptor' => ['argument' => 'a.b', 'expected' => 'false'], 'expected' => true ], @@ -322,35 +342,35 @@ public function getMatchersTestCases(): array ], 'matches_path_all_2' => [ 'matcher' => 'matchesPathAll', - 'result' => $this->getMockResult([ + 'result' => [ 'a' => [ ['b' => 'c'], ['b' => 'c'], ['b' => 'c'] ] - ]), + ], 'acceptor' => ['argument' => 'a[].b', 'expected' => 'c'], 'expected' => true, ], 'matches_path_all_3' => [ 'matcher' => 'matchesPathAll', - 'result' => $this->getMockResult(['a' => [ + 'result' => ['a' => [ ['b' => 'c'], ['b' => 'z'], ['b' => 'c'] - ]]), + ]], 'acceptor' => ['argument' => 'a[].b', 'expected' => 'c'], 'expected' => false, ], 'matches_path_all_4_empty_array_as_result' => [ 'matcher' => 'matchesPathAll', - 'result' => $this->getMockResult(), + 'result' => [], 'acceptor' => ['argument' => 'a', 'expected' => 'c'], 'expected' => false, ], 'matches_path_all_4_non_array_value_as_result' => [ 'matcher' => 'matchesPathAll', - 'result' => $this->getMockResult(['a' => 'FooValue']), + 'result' => ['a' => 'FooValue'], 'acceptor' => ['argument' => 'a[].b', 'expected' => 'c'], 'expected' => false, ], @@ -362,37 +382,37 @@ public function getMatchersTestCases(): array ], 'matches_path_any_2' => [ 'matcher' => 'matchesPathAny', - 'result' => $this->getMockResult([ + 'result' => [ 'a' => [ ['b' => 'c'], ['b' => 'd'], ['b' => 'e'] ] - ]), + ], 'acceptor' => ['argument' => 'a[].b', 'expected' => 'c'], 'expected' => true, ], 'matches_path_any_3' => [ 'matcher' => 'matchesPathAny', - 'result' => $this->getMockResult([ + 'result' => [ 'a' => [ ['b' => 'x'], ['b' => 'y'], ['b' => 'z'] ] - ]), + ], 'acceptor' => ['argument' => 'a[].b', 'expected' => 'c'], 'expected' => false, ], 'matches_path_any_4_empty_array_as_result' => [ 'matcher' => 'matchesPathAny', - 'result' => $this->getMockResult(), + 'result' => [], 'acceptor' => ['argument' => 'a', 'expected' => 'c'], 'expected' => false, ], 'matches_path_any_5_non_array_value_as_result' => [ 'matcher' => 'matchesPathAll', - 'result' => $this->getMockResult(['a' => 'FooValue']), + 'result' => ['a' => 'FooValue'], 'acceptor' => ['argument' => 'a[].b', 'expected' => 'c'], 'expected' => false, ], @@ -404,13 +424,13 @@ public function getMatchersTestCases(): array ], 'matches_status_2' => [ 'matcher' => 'matchesStatus', - 'result' => $this->getMockResult(), + 'result' => [], 'acceptor' => ['expected' => 200], 'expected' => true, ], 'matches_status_3' => [ 'matcher' => 'matchesStatus', - 'result' => $this->getMockResult(), + 'result' => [], 'acceptor' => ['expected' => 400], 'expected' => false, ], @@ -422,13 +442,13 @@ public function getMatchersTestCases(): array ], 'matches_error_2' => [ 'matcher' => 'matchesError', - 'result' => $this->getMockResult('InvalidData'), + 'result' => 'InvalidData', 'acceptor' => ['expected' => 'InvalidData'], 'expected' => true, ], 'matches_error_3' => [ 'matcher' => 'matchesError', - 'result' => $this->getMockResult('InvalidData'), + 'result' => 'InvalidData', 'acceptor' => ['expected' => 'Foo'], 'expected' => false, ], @@ -450,7 +470,6 @@ private function getMockResult($data = []) return new Result($data + ['@metadata' => ['statusCode' => 200]]); } - /** * Tests the waiter expects not error. * This means the operation should succeed. diff --git a/tests/WrappedHttpHandlerTest.php b/tests/WrappedHttpHandlerTest.php index 9311b47ae6..dd2bcde89c 100644 --- a/tests/WrappedHttpHandlerTest.php +++ b/tests/WrappedHttpHandlerTest.php @@ -16,10 +16,10 @@ use GuzzleHttp\Psr7\Response; use Psr\Http\Message\ResponseInterface; use Yoast\PHPUnitPolyfills\TestCases\TestCase; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\CoversClass; -/** - * @covers Aws\WrappedHttpHandler - */ +#[CoversClass(WrappedHttpHandler::class)] class WrappedHttpHandlerTest extends TestCase { use TestServiceTrait; @@ -91,24 +91,18 @@ public function testCanRejectWithoutResponse() } } - /** - * @dataProvider responseAndParserProvider - * - * @param Response $res - * @param $errorParser - * @param $expectedCode - * @param $expectedId - * @param $expectedArray - */ + #[DataProvider('responseAndParserProvider')] public function testCanRejectWithAndParseResponse( Response $res, - Service $service, - $errorParser, - $expectedCode, - $expectedId, - $expectedArray + string $serviceName, + string $errorParserClass, + ?string $expectedCode, + ?string $expectedId, + array $expectedArray ) { + $service = $this->generateTestService($serviceName); + $errorParser = new $errorParserClass($service); $client = $this->generateTestClient($service, []); $cmd = $client->getCommand('TestOperation', []); $e = new \Exception('a'); @@ -133,69 +127,59 @@ public function testCanRejectWithAndParseResponse( } } - public function responseAndParserProvider() + public static function responseAndParserProvider(): \Generator { - $services = [ - 'ec2' => $this->generateTestService('ec2'), - 'json' => $this->generateTestService('json'), - 'query' => $this->generateTestService('query'), - 'rest-json' => $this->generateTestService('rest-json'), - 'rest-xml' => $this->generateTestService('rest-xml'), - ]; - - - yield [ - new Response( + $cases = [ + 'json_rpc_error_parser' => [ + 'response' => new Response( 400, ['X-Amzn-RequestId' => '123'], json_encode(['__type' => 'foo#bar']) ), - $services['json'], - new JsonRpcErrorParser($services['json']), - 'bar', - '123', - [], - ]; - yield [ - new Response( + 'service_name' => 'json', + 'error_parser' => JsonRpcErrorParser::class, + 'expected_code' => 'bar', + 'expected_id' => '123', + 'expected_array' => [] + ], + 'rest_json' => [ + 'response' => new Response( 400, - [ - 'X-Amzn-RequestId' => '123', - ], + ['X-Amzn-RequestId' => '123'], json_encode(['message' => 'sorry!']) ), - $services['rest-json'], - new RestJsonErrorParser($services['rest-json']), - null, - '123', - [], - ]; - yield [ - new Response( + 'service_name' => 'rest-json', + 'error_parser' => RestJsonErrorParser::class, + 'expected_code' => null, + 'expected_id' => '123', + 'expected_array' => [] + ], + 'rest_xml' => [ + 'response' => new Response( 400, [], 'InternalError656c76696e6727732072657175657374' ), - $services['rest-xml'], - new XmlErrorParser($services['rest-xml']), - 'InternalError', - '656c76696e6727732072657175657374', - [], - ]; - [ - new Response( + 'service_name' => 'rest-xml', + 'error_parser' => XmlErrorParser::class, + 'expected_code' => 'InternalError', + 'expected_id' => '656c76696e6727732072657175657374', + 'expected_array' => [] + ], + 'query' => [ + 'response' => new Response( 400, ['X-Amzn-RequestId' => '123'], openssl_random_pseudo_bytes(1024) ), - $services['query'], - new XmlErrorParser($services['query']), - null, - null, - [], - ]; - yield 'Rest-json with modeled exception from header error type' => [ - new Response( + 'service_name' => 'query', + 'error_parser' => XmlErrorParser::class, + 'expected_code' => null, + 'expected_id' => null, + 'expected_array' => [] + ], + 'rest_json_with_modeled_exception_from_header_error_type' => [ + 'response' => new Response( 400, [ 'X-Amzn-RequestId' => '123', @@ -207,19 +191,19 @@ public function responseAndParserProvider() 'NotModeled' => 'bar' ]) ), - $services['rest-json'], - new RestJsonErrorParser($services['rest-json']), - 'TestException', - '123', - [ + 'service_name' => 'rest-json', + 'error_parser' => RestJsonErrorParser::class, + 'expected_code' => 'TestException', + 'expected_id' => '123', + 'expected_array' => [ 'TestString' => 'foo-string', 'TestInt' => 456, 'TestHeaders' => [], 'TestStatus' => 400 - ], - ]; - yield 'Rest-json with modeled exception from body error code' => [ - new Response( + ] + ], + 'rest_json_with_modeled_exception_from_body_error_code' => [ + 'response' => new Response( 400, [ 'X-Amzn-RequestId' => '123' @@ -231,19 +215,19 @@ public function responseAndParserProvider() 'code' => 'TestException' ]) ), - $services['rest-json'], - new RestJsonErrorParser($services['rest-json']), - 'TestException', - '123', - [ + 'service_name' => 'rest-json', + 'error_parser' => RestJsonErrorParser::class, + 'expected_code' => 'TestException', + 'expected_id' => '123', + 'expected_array' => [ 'TestString' => 'foo-string', 'TestInt' => 456, 'TestHeaders' => [], 'TestStatus' => 400 - ], - ]; - yield 'Ec2 with modeled exception' => [ - new Response( + ] + ], + 'ec2_with_modeled_exception' => [ + 'response' => new Response( 400, [], '' . "\n" . @@ -259,19 +243,19 @@ public function responseAndParserProvider() ' xyz' . '' ), - $services['ec2'], - new XmlErrorParser($services['ec2']), - 'TestException', - 'xyz', - [ + 'service_name' => 'ec2', + 'error_parser' => XmlErrorParser::class, + 'expected_code' => 'TestException', + 'expected_id' => 'xyz', + 'expected_array' => [ 'TestString' => 'SomeString', 'TestInt' => 456, 'TestHeaders' => [], 'TestStatus' => 400, - ], - ]; - yield 'Query with modeled exception' => [ - new Response( + ] + ], + 'query_with_modeled_exception' => [ + 'response' => new Response( 400, [], '' . @@ -285,19 +269,19 @@ public function responseAndParserProvider() ' xyz' . '' ), - $services['query'], - new XmlErrorParser($services['query']), - 'TestException', - 'xyz', - [ + 'service_name' => 'query', + 'error_parser' => XmlErrorParser::class, + 'expected_code' => 'TestException', + 'expected_id' => 'xyz', + 'expected_array' => [ 'TestString' => 'SomeString', 'TestInt' => 456, 'TestHeaders' => [], 'TestStatus' => 400, - ], - ]; - yield 'Rest-xml with modeled exception' => [ - new Response( + ] + ], + 'rest_xml_with_modeled_exception' => [ + 'response' => new Response( 400, [], '' . @@ -311,17 +295,22 @@ public function responseAndParserProvider() ' xyz' . '' ), - $services['rest-xml'], - new XmlErrorParser($services['rest-xml']), - 'TestException', - 'xyz', - [ + 'service_name' => 'rest-xml', + 'error_parser' => XmlErrorParser::class, + 'expected_code' => 'TestException', + 'expected_id' => 'xyz', + 'expected_array' => [ 'TestString' => 'SomeString', 'TestInt' => 456, 'TestHeaders' => [], 'TestStatus' => 400, - ], - ]; + ] + ] + ]; + + foreach ($cases as $key => $case) { + yield $key => $case; + } } public function testCanRejectWithException() diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 3591ad7425..0dbfa771e3 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -9,18 +9,6 @@ define('PHPUNIT_COMPOSER_INSTALL', __DIR__ . '/../vendor/autoload.php'); } -if (!class_exists('\PHPUnit\Framework\Constraint\RegularExpression')) { - class_alias('\PHPUnit_Framework_Constraint_PCREMatch', '\PHPUnit\Framework\Constraint\RegularExpression'); -} - -if (!class_exists('\PHPUnit\Framework\Constraint\Callback')) { - class_alias('\PHPUnit_Framework_Constraint_Callback', '\PHPUnit\Framework\Constraint\Callback'); -} - -if (!class_exists('\PHPUnit\Framework\Error\Warning')) { - class_alias('\PHPUnit_Framework_Error_Warning', '\PHPUnit\Framework\Error\Warning'); -} - // Clear out any previously compiled JMESPath files. JmesPath\Env::cleanCompileDir();